From 24e63bc62617f9d5621500b5c4d148429549ef75 Mon Sep 17 00:00:00 2001 From: Micah Acinapura Date: Sun, 22 Nov 2020 16:54:51 -0500 Subject: [PATCH 01/43] move glfw init after macos window is ready --- apps/OpenSpace/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index d074fc737a..c85a62eedc 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -1012,7 +1012,6 @@ std::string selectedSgctProfileFromLauncher(LauncherWindow& lw, bool hasCliSGCTC } int main(int argc, char** argv) { - glfwInit(); #ifdef WIN32 SetUnhandledExceptionFilter(generateMiniDump); @@ -1182,6 +1181,7 @@ int main(int argc, char** argv) { if (!win.wasLaunchSelected()) { exit(EXIT_SUCCESS); } + glfwInit(); global::configuration->profile = win.selectedProfile(); windowConfiguration = selectedSgctProfileFromLauncher( @@ -1191,6 +1191,8 @@ int main(int argc, char** argv) { labelFromCfgFile, xmlExt ); + } else { + glfwInit(); } if (global::configuration->profile.empty()) { LFATAL("Cannot launch with an empty profile"); From 4786201fd9584ad5c15b84e0e5e97c8a89303e82 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Wed, 25 Nov 2020 15:56:38 +0100 Subject: [PATCH 02/43] MacOS fixes for BigSur --- apps/OpenSpace/main.cpp | 3 + include/openspace/engine/globalscallbacks.h | 77 +++-------- modules/cefwebgui/cefwebguimodule.cpp | 6 +- modules/cefwebgui/src/guikeyboardhandler.cpp | 2 +- modules/globebrowsing/globebrowsingmodule.cpp | 8 +- modules/imgui/imguimodule.cpp | 26 ++-- modules/server/servermodule.cpp | 2 +- modules/webbrowser/CMakeLists.txt | 2 +- .../webbrowser/cmake/webbrowser_helpers.cmake | 3 +- modules/webbrowser/src/eventhandler.cpp | 16 +-- modules/webbrowser/webbrowsermodule.cpp | 2 +- src/engine/globals.cpp | 5 + src/engine/globalscallbacks.cpp | 130 ++++++------------ src/engine/openspaceengine.cpp | 34 ++--- 14 files changed, 121 insertions(+), 195 deletions(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index c85a62eedc..e9dffbc665 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -224,6 +224,8 @@ void mainInitFunc(GLFWwindow*) { global::openSpaceEngine->initialize(); LDEBUG("Initializing OpenSpace Engine finished"); +#ifndef __APPLE__ + // Apparently: "Cocoa: Regular windows do not have icons on macOS" { std::string path = absPath("${DATA}/openspace-icon.png"); int x; @@ -242,6 +244,7 @@ void mainInitFunc(GLFWwindow*) { stbi_image_free(icons[0].pixels); } +#endif // __APPLE__ currentWindow = Engine::instance().windows().front().get(); currentViewport = currentWindow->viewports().front().get(); diff --git a/include/openspace/engine/globalscallbacks.h b/include/openspace/engine/globalscallbacks.h index 9131294139..cc06979e97 100644 --- a/include/openspace/engine/globalscallbacks.h +++ b/include/openspace/engine/globalscallbacks.h @@ -31,62 +31,26 @@ #include #include -namespace openspace::global { +namespace openspace::global::callback { -namespace detail { - -std::vector>& gInitialize(); -std::vector>& gDeinitialize(); - -std::vector>& gInitializeGL(); -std::vector>& gDeinitializeGL(); - -std::vector>& gPreSync(); -std::vector>& gPostSyncPreDraw(); -std::vector>& gRender(); -std::vector>& gDraw2D(); -std::vector>& gPostDraw(); - -std::vector>& gKeyboard(); -std::vector>& gCharacter(); - -std::vector>& gMouseButton(); -std::vector>& gMousePosition(); -std::vector>& gMouseScrollWheel(); - -std::vector>& gTouchDetected(); -std::vector>& gTouchUpdated(); -std::vector>& gTouchExit(); - -} // namespace detail - -namespace callback { - -static std::vector>& initialize = detail::gInitialize(); -static std::vector>& deinitialize = detail::gDeinitialize(); -static std::vector>& initializeGL = detail::gInitializeGL(); -static std::vector>& deinitializeGL = detail::gDeinitializeGL(); -static std::vector>& preSync = detail::gPreSync(); -static std::vector>& postSyncPreDraw = detail::gPostSyncPreDraw(); -static std::vector>& render = detail::gRender(); -static std::vector>& draw2D = detail::gDraw2D(); -static std::vector>& postDraw = detail::gPostDraw(); -static std::vector>& keyboard = - detail::gKeyboard(); -static std::vector>& character = - detail::gCharacter(); -static std::vector>& - mouseButton = detail::gMouseButton(); -static std::vector>& mousePosition = - detail::gMousePosition(); -static std::vector>& mouseScrollWheel = - detail::gMouseScrollWheel(); -static std::vector>& touchDetected = - detail::gTouchDetected(); -static std::vector>& touchUpdated = - detail::gTouchUpdated(); -static std::vector>& touchExit = - detail::gTouchExit(); +inline std::vector>* initialize; +inline std::vector>* deinitialize; +inline std::vector>* initializeGL; +inline std::vector>* deinitializeGL; +inline std::vector>* preSync; +inline std::vector>* postSyncPreDraw; +inline std::vector>* render; +inline std::vector>* draw2D; +inline std::vector>* postDraw; +inline std::vector>* keyboard; +inline std::vector>* character; +inline std::vector>* + mouseButton; +inline std::vector>* mousePosition; +inline std::vector>* mouseScrollWheel; +inline std::vector>* touchDetected; +inline std::vector>* touchUpdated; +inline std::vector>* touchExit; /** * If the framerate becomes slow, Chromium Embedded Framework (used in Web Browser Module) @@ -99,7 +63,8 @@ static std::vector>& touchExit = */ extern void (*webBrowserPerformanceHotfix)(); -} // namespace callback +void create(); +void destroy(); } // namespace openspace::global diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index ceecc0e650..71b0967697 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -206,11 +206,11 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) _visible = configuration.hasValue(VisibleInfo.identifier) && configuration.value(VisibleInfo.identifier); - global::callback::initializeGL.emplace_back([this]() { + global::callback::initializeGL->emplace_back([this]() { startOrStopGui(); }); - global::callback::draw2D.emplace_back([this](){ + global::callback::draw2D->emplace_back([this](){ ZoneScopedN("CefWebGuiModule") const bool isGuiWindow = @@ -233,7 +233,7 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) } }); - global::callback::deinitializeGL.emplace_back([this]() { + global::callback::deinitializeGL->emplace_back([this]() { ZoneScopedN("CefWebGuiModule") if (_endpointCallback != -1) { diff --git a/modules/cefwebgui/src/guikeyboardhandler.cpp b/modules/cefwebgui/src/guikeyboardhandler.cpp index ef534d0095..3711fa0629 100644 --- a/modules/cefwebgui/src/guikeyboardhandler.cpp +++ b/modules/cefwebgui/src/guikeyboardhandler.cpp @@ -31,7 +31,7 @@ namespace openspace { GUIKeyboardHandler::GUIKeyboardHandler() { _keyConsumed = false; - global::callback::keyboard.emplace_back( + global::callback::keyboard->emplace_back( [&](Key, KeyModifier, KeyAction) -> bool { const bool previous = _keyConsumed; _keyConsumed = false; diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index e7e36ddaa1..6a36997952 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -216,7 +216,7 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { // Initialize - global::callback::initializeGL.emplace_back([&]() { + global::callback::initializeGL->emplace_back([&]() { ZoneScopedN("GlobeBrowsingModule") _tileCache = std::make_unique(_tileCacheSizeMB); @@ -232,7 +232,7 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { addPropertySubOwner(GdalWrapper::ref()); }); - global::callback::deinitializeGL.emplace_back([]() { + global::callback::deinitializeGL->emplace_back([]() { ZoneScopedN("GlobeBrowsingModule") tileprovider::deinitializeDefaultTile(); @@ -240,14 +240,14 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { // Render - global::callback::render.emplace_back([&]() { + global::callback::render->emplace_back([&]() { ZoneScopedN("GlobeBrowsingModule") _tileCache->update(); }); // Deinitialize - global::callback::deinitialize.emplace_back([&]() { + global::callback::deinitialize->emplace_back([&]() { ZoneScopedN("GlobeBrowsingModule") GdalWrapper::destroy(); diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index 50bc8dbe78..02ce4f908e 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -44,7 +44,7 @@ namespace openspace { ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { addPropertySubOwner(gui); - global::callback::initialize.emplace_back([&]() { + global::callback::initialize->emplace_back([&]() { LDEBUGC("ImGUIModule", "Initializing GUI"); gui.initialize(); @@ -130,28 +130,28 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { ); }); - global::callback::deinitialize.emplace_back([&]() { + global::callback::deinitialize->emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Deinitialize GUI"); gui.deinitialize(); }); - global::callback::initializeGL.emplace_back([&]() { + global::callback::initializeGL->emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Initializing GUI OpenGL"); gui.initializeGL(); }); - global::callback::deinitializeGL.emplace_back([&]() { + global::callback::deinitializeGL->emplace_back([&]() { ZoneScopedN("ImGUI") LDEBUGC("ImGui", "Deinitialize GUI OpenGL"); gui.deinitializeGL(); }); - global::callback::draw2D.emplace_back([&]() { + global::callback::draw2D->emplace_back([&]() { ZoneScopedN("ImGUI") WindowDelegate& delegate = *global::windowDelegate; @@ -179,7 +179,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } }); - global::callback::keyboard.emplace_back( + global::callback::keyboard->emplace_back( [&](Key key, KeyModifier mod, KeyAction action) -> bool { ZoneScopedN("ImGUI") @@ -193,7 +193,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::character.emplace_back( + global::callback::character->emplace_back( [&](unsigned int codepoint, KeyModifier modifier) -> bool { ZoneScopedN("ImGUI") @@ -207,13 +207,13 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::mousePosition.emplace_back( + global::callback::mousePosition->emplace_back( [&](double x, double y) { _mousePosition = glm::vec2(static_cast(x), static_cast(y)); } ); - global::callback::mouseButton.emplace_back( + global::callback::mouseButton->emplace_back( [&](MouseButton button, MouseAction action, KeyModifier) -> bool { ZoneScopedN("ImGUI") @@ -234,7 +234,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::mouseScrollWheel.emplace_back( + global::callback::mouseScrollWheel->emplace_back( [&](double, double posY) -> bool { ZoneScopedN("ImGUI") @@ -248,19 +248,19 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::touchDetected.emplace_back( + global::callback::touchDetected->emplace_back( [&](TouchInput input) -> bool { return gui.touchDetectedCallback(input); } ); - global::callback::touchUpdated.emplace_back( + global::callback::touchUpdated->emplace_back( [&](TouchInput input) -> bool { return gui.touchUpdatedCallback(input); } ); - global::callback::touchExit.emplace_back( + global::callback::touchExit->emplace_back( [&](TouchInput input) { gui.touchExitCallback(input); } diff --git a/modules/server/servermodule.cpp b/modules/server/servermodule.cpp index 84910594da..a7a3df6ae3 100644 --- a/modules/server/servermodule.cpp +++ b/modules/server/servermodule.cpp @@ -73,7 +73,7 @@ ServerInterface* ServerModule::serverInterfaceByIdentifier(const std::string& id } void ServerModule::internalInitialize(const ghoul::Dictionary& configuration) { - global::callback::preSync.emplace_back([this]() { + global::callback::preSync->emplace_back([this]() { ZoneScopedN("ServerModule") preSync(); diff --git a/modules/webbrowser/CMakeLists.txt b/modules/webbrowser/CMakeLists.txt index c914689fda..55f88c9be4 100644 --- a/modules/webbrowser/CMakeLists.txt +++ b/modules/webbrowser/CMakeLists.txt @@ -156,7 +156,7 @@ if (OS_MACOSX) # Helper executable target. add_executable(${CEF_HELPER_TARGET} MACOSX_BUNDLE ${WEBBROWSER_HELPER_SOURCES}) SET_EXECUTABLE_TARGET_PROPERTIES(${CEF_HELPER_TARGET}) - add_cef_logical_target("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") + # add_cef_logical_target("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") add_dependencies(${CEF_HELPER_TARGET} libcef_dll_wrapper) target_link_libraries(${CEF_HELPER_TARGET} libcef_dll_wrapper ${CEF_STANDARD_LIBS}) set_target_properties(${CEF_HELPER_TARGET} PROPERTIES diff --git a/modules/webbrowser/cmake/webbrowser_helpers.cmake b/modules/webbrowser/cmake/webbrowser_helpers.cmake index ac082325ba..c9b6242ba8 100644 --- a/modules/webbrowser/cmake/webbrowser_helpers.cmake +++ b/modules/webbrowser/cmake/webbrowser_helpers.cmake @@ -77,7 +77,8 @@ function(run_cef_macosx_config CEF_ROOT module_path) add_dependencies(${CEF_TARGET} libcef_dll_wrapper "${CEF_HELPER_TARGET}") - target_link_libraries(${CEF_TARGET} PUBLIC libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + # target_link_libraries(${CEF_TARGET} PUBLIC libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + target_link_libraries(${CEF_TARGET} PUBLIC libcef_dll_wrapper ${CEF_STANDARD_LIBS}) set_target_properties(${CEF_TARGET} PROPERTIES RESOURCE "${WEBBROWSER_RESOURCES_SRCS}" MACOSX_BUNDLE_INFO_PLIST ${module_path}/mac/Info.plist diff --git a/modules/webbrowser/src/eventhandler.cpp b/modules/webbrowser/src/eventhandler.cpp index da9ca87185..aa65c1f64d 100644 --- a/modules/webbrowser/src/eventhandler.cpp +++ b/modules/webbrowser/src/eventhandler.cpp @@ -152,7 +152,7 @@ namespace { namespace openspace { void EventHandler::initialize() { - global::callback::character.emplace_back( + global::callback::character->emplace_back( [this](unsigned int charCode, KeyModifier mod) -> bool { if (_browserInstance) { return charCallback(charCode, mod); @@ -160,7 +160,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::keyboard.emplace_back( + global::callback::keyboard->emplace_back( [this](Key key, KeyModifier mod, KeyAction action) -> bool { if (_browserInstance) { return keyboardCallback(key, mod, action); @@ -168,7 +168,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mousePosition.emplace_back( + global::callback::mousePosition->emplace_back( [this](double x, double y) -> bool { if (_browserInstance) { return mousePositionCallback(x, y); @@ -176,7 +176,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mouseButton.emplace_back( + global::callback::mouseButton->emplace_back( [this](MouseButton button, MouseAction action, KeyModifier mods) -> bool { if (_browserInstance) { return mouseButtonCallback(button, action, mods); @@ -184,7 +184,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mouseScrollWheel.emplace_back( + global::callback::mouseScrollWheel->emplace_back( [this](double x, double y) -> bool { if (_browserInstance) { const glm::ivec2 delta(x, y); @@ -194,7 +194,7 @@ void EventHandler::initialize() { } ); - global::callback::touchDetected.emplace_back( + global::callback::touchDetected->emplace_back( [&](TouchInput input) -> bool { if (!_browserInstance) { return false; @@ -236,7 +236,7 @@ void EventHandler::initialize() { } ); - global::callback::touchUpdated.emplace_back( + global::callback::touchUpdated->emplace_back( [&](TouchInput input) -> bool { if (!_browserInstance) { return false; @@ -278,7 +278,7 @@ void EventHandler::initialize() { } ); - global::callback::touchExit.emplace_back( + global::callback::touchExit->emplace_back( [&](TouchInput input) { if (!_browserInstance) { return; diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index 33a5fe0f46..cdcc85faeb 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -73,7 +73,7 @@ WebBrowserModule::WebBrowserModule() , _updateBrowserBetweenRenderables(UpdateBrowserBetweenRenderablesInfo, true) , _browserUpdateInterval(BrowserUpdateIntervalInfo, 1.f, 1.0f, 1000.f) { - global::callback::deinitialize.emplace_back([this]() { + global::callback::deinitialize->emplace_back([this]() { ZoneScopedN("WebBrowserModule") deinitialize(); diff --git a/src/engine/globals.cpp b/src/engine/globals.cpp index 1a008a11ca..10317f366f 100644 --- a/src/engine/globals.cpp +++ b/src/engine/globals.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -104,6 +105,8 @@ namespace openspace::global { void create() { ZoneScoped + callback::create(); + std::byte* currentPos = DataStorage.data(); fontManager = new (currentPos) ghoul::fontrendering::FontManager({ 1536, 1536, 1 }); @@ -355,6 +358,8 @@ void destroy() { fontManager->~FontManager(); std::fill(DataStorage.begin(), DataStorage.end(), std::byte(0)); + + callback::destroy(); } void deinitialize() { diff --git a/src/engine/globalscallbacks.cpp b/src/engine/globalscallbacks.cpp index a6dba4bc19..bc373d8f25 100644 --- a/src/engine/globalscallbacks.cpp +++ b/src/engine/globalscallbacks.cpp @@ -24,97 +24,49 @@ #include -namespace openspace::global::detail { - -std::vector>& gInitialize() { - static std::vector> g; - return g; -} - -std::vector>& gDeinitialize() { - static std::vector> g; - return g; -} - -std::vector>& gInitializeGL() { - static std::vector> g; - return g; -} - -std::vector>& gDeinitializeGL() { - static std::vector> g; - return g; -} - -std::vector>& gPreSync() { - static std::vector> g; - return g; -} - -std::vector>& gPostSyncPreDraw() { - static std::vector> g; - return g; -} - -std::vector>& gRender() { - static std::vector> g; - return g; -} - -std::vector>& gDraw2D() { - static std::vector> g; - return g; -} - -std::vector>& gPostDraw() { - static std::vector> g; - return g; -} - -std::vector>& gKeyboard() { - static std::vector> g; - return g; -} - -std::vector>& gCharacter() { - static std::vector> g; - return g; -} - -std::vector>& gMouseButton() { - static std::vector> g; - return g; -} - -std::vector>& gMousePosition() { - static std::vector> g; - return g; -} - -std::vector>& gMouseScrollWheel() { - static std::vector> g; - return g; -} - -std::vector>& gTouchDetected() { - static std::vector> g; - return g; -} - -std::vector>& gTouchUpdated() { - static std::vector> g; - return g; -} - -std::vector>& gTouchExit() { - static std::vector> g; - return g; -} - -} // namespace openspace::global::detail - namespace openspace::global::callback { +void create() { + initialize = new std::vector>; + deinitialize = new std::vector>; + initializeGL = new std::vector>; + deinitializeGL = new std::vector>; + preSync = new std::vector> ; + postSyncPreDraw = new std::vector> ; + render = new std::vector>; + draw2D = new std::vector>; + postDraw = new std::vector>; + keyboard = new std::vector>; + character = new std::vector>; + mouseButton = + new std::vector>; + mousePosition = new std::vector>; + mouseScrollWheel = new std::vector>; + touchDetected = new std::vector>; + touchUpdated = new std::vector>; + touchExit = new std::vector>; +} + +void destroy() { + delete touchExit; + delete touchUpdated; + delete touchDetected; + delete mouseScrollWheel; + delete mousePosition; + delete mouseButton; + delete character; + delete keyboard; + delete postDraw; + delete draw2D; + delete render; + delete postSyncPreDraw; + delete preSync; + delete deinitializeGL; + delete initializeGL; + delete deinitialize; + delete initialize; +} + void(*webBrowserPerformanceHotfix)() = nullptr; } // namespace openspace::global::callback diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index cedd6501b7..d51f322e91 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -370,7 +370,7 @@ void OpenSpaceEngine::initialize() { global::renderEngine->initialize(); - for (const std::function& func : global::callback::initialize) { + for (const std::function& func : *global::callback::initialize) { ZoneScopedN("[Module] initialize") func(); @@ -663,7 +663,7 @@ void OpenSpaceEngine::initializeGL() { global::moduleEngine->initializeGL(); - for (const std::function& func : global::callback::initializeGL) { + for (const std::function& func : *global::callback::initializeGL) { ZoneScopedN("[Module] initializeGL") func(); } @@ -865,7 +865,7 @@ void OpenSpaceEngine::deinitialize() { LTRACE("OpenSpaceEngine::deinitialize(begin)"); - for (const std::function& func : global::callback::deinitialize) { + for (const std::function& func : *global::callback::deinitialize) { func(); } @@ -914,7 +914,7 @@ void OpenSpaceEngine::deinitializeGL() { global::openSpaceEngine->_scene = nullptr; global::renderEngine->setScene(nullptr); - for (const std::function& func : global::callback::deinitializeGL) { + for (const std::function& func : *global::callback::deinitializeGL) { func(); } @@ -1125,7 +1125,7 @@ void OpenSpaceEngine::preSynchronization() { global::interactionMonitor->updateActivityState(); } - for (const std::function& func : global::callback::preSync) { + for (const std::function& func : *global::callback::preSync) { ZoneScopedN("[Module] preSync") func(); @@ -1180,7 +1180,7 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { _scene->camera()->invalidateCache(); } - for (const std::function& func : global::callback::postSyncPreDraw) { + for (const std::function& func : *global::callback::postSyncPreDraw) { ZoneScopedN("[Module] postSyncPreDraw") func(); @@ -1226,7 +1226,7 @@ void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& view global::renderEngine->render(sceneMatrix, viewMatrix, projectionMatrix); - for (const std::function& func : global::callback::render) { + for (const std::function& func : *global::callback::render) { ZoneScopedN("[Module] render") func(); @@ -1251,7 +1251,7 @@ void OpenSpaceEngine::drawOverlays() { global::sessionRecording->render(); } - for (const std::function& func : global::callback::draw2D) { + for (const std::function& func : *global::callback::draw2D) { ZoneScopedN("[Module] draw2D") func(); @@ -1267,7 +1267,7 @@ void OpenSpaceEngine::postDraw() { global::renderEngine->postDraw(); - for (const std::function& func : global::callback::postDraw) { + for (const std::function& func : *global::callback::postDraw) { ZoneScopedN("[Module] postDraw") func(); @@ -1317,7 +1317,7 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio } using F = std::function; - for (const F& func : global::callback::keyboard) { + for (const F& func : *global::callback::keyboard) { const bool isConsumed = func(key, mod, action); if (isConsumed) { return; @@ -1340,7 +1340,7 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier) ZoneScoped using F = std::function; - for (const F& func : global::callback::character) { + for (const F& func : *global::callback::character) { bool isConsumed = func(codepoint, modifier); if (isConsumed) { return; @@ -1358,7 +1358,7 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, ZoneScoped using F = std::function; - for (const F& func : global::callback::mouseButton) { + for (const F& func : *global::callback::mouseButton) { bool isConsumed = func(button, action, mods); if (isConsumed) { // If the mouse was released, we still want to forward it to the navigation @@ -1390,7 +1390,7 @@ void OpenSpaceEngine::mousePositionCallback(double x, double y) { ZoneScoped using F = std::function; - for (const F& func : global::callback::mousePosition) { + for (const F& func : *global::callback::mousePosition) { func(x, y); } @@ -1404,7 +1404,7 @@ void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY) { ZoneScoped using F = std::function; - for (const F& func : global::callback::mouseScrollWheel) { + for (const F& func : *global::callback::mouseScrollWheel) { bool isConsumed = func(posX, posY); if (isConsumed) { return; @@ -1419,7 +1419,7 @@ void OpenSpaceEngine::touchDetectionCallback(TouchInput input) { ZoneScoped using F = std::function; - for (const F& func : global::callback::touchDetected) { + for (const F& func : *global::callback::touchDetected) { bool isConsumed = func(input); if (isConsumed) { return; @@ -1431,7 +1431,7 @@ void OpenSpaceEngine::touchUpdateCallback(TouchInput input) { ZoneScoped using F = std::function; - for (const F& func : global::callback::touchUpdated) { + for (const F& func : *global::callback::touchUpdated) { bool isConsumed = func(input); if (isConsumed) { return; @@ -1443,7 +1443,7 @@ void OpenSpaceEngine::touchExitCallback(TouchInput input) { ZoneScoped using F = std::function; - for (const F& func : global::callback::touchExit) { + for (const F& func : *global::callback::touchExit) { func(input); } } From eeb61d02b5385fb69087feeea34d61f66871171d Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Wed, 25 Nov 2020 17:15:01 +0100 Subject: [PATCH 03/43] Compile fix --- modules/iswa/iswamodule.cpp | 2 +- modules/touch/touchmodule.cpp | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/iswa/iswamodule.cpp b/modules/iswa/iswamodule.cpp index fa2869a174..59b222fb71 100644 --- a/modules/iswa/iswamodule.cpp +++ b/modules/iswa/iswamodule.cpp @@ -43,7 +43,7 @@ namespace openspace { IswaModule::IswaModule() : OpenSpaceModule(Name) { - global::callback::initialize.push_back([]() { + global::callback::initialize->push_back([]() { ZoneScopedN("IswaModule") IswaManager::initialize(); }); diff --git a/modules/touch/touchmodule.cpp b/modules/touch/touchmodule.cpp index dc80b46fac..a5ace0268b 100644 --- a/modules/touch/touchmodule.cpp +++ b/modules/touch/touchmodule.cpp @@ -191,7 +191,7 @@ TouchModule::~TouchModule() { void TouchModule::internalInitialize(const ghoul::Dictionary& /*dictionary*/){ _ear.reset(new TuioEar()); - global::callback::initializeGL.push_back([&]() { + global::callback::initializeGL->push_back([&]() { LDEBUGC("TouchModule", "Initializing TouchMarker OpenGL"); _markers.initialize(); #ifdef WIN32 @@ -204,33 +204,33 @@ void TouchModule::internalInitialize(const ghoul::Dictionary& /*dictionary*/){ #endif }); - global::callback::deinitializeGL.push_back([&]() { + global::callback::deinitializeGL->push_back([&]() { LDEBUGC("TouchMarker", "Deinitialize TouchMarker OpenGL"); _markers.deinitialize(); }); // These are handled in UI thread, which (as of 20th dec 2019) is in main/rendering // thread so we don't need a mutex here - global::callback::touchDetected.push_back( + global::callback::touchDetected->push_back( [this](TouchInput i) { addTouchInput(i); return true; } ); - global::callback::touchUpdated.push_back( + global::callback::touchUpdated->push_back( [this](TouchInput i) { updateOrAddTouchInput(i); return true; } ); - global::callback::touchExit.push_back( + global::callback::touchExit->push_back( std::bind(&TouchModule::removeTouchInput, this, std::placeholders::_1) ); - global::callback::preSync.push_back([&]() { + global::callback::preSync->push_back([&]() { _touch.setCamera(global::navigationHandler->camera()); _touch.setFocusNode(global::navigationHandler->orbitalNavigator().anchorNode()); @@ -251,7 +251,7 @@ void TouchModule::internalInitialize(const ghoul::Dictionary& /*dictionary*/){ clearInputs(); }); - global::callback::render.push_back([&]() { + global::callback::render->push_back([&]() { _markers.render(_touchPoints); }); } From 4d9e6bc650ae883675003503351be476b5710c56 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Wed, 2 Dec 2020 13:55:25 -0700 Subject: [PATCH 04/43] Rename hirise.asset since linux filenames are case-sensitive --- .../mars/layers/colorlayers/{HiRISE.asset => hirise.asset} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data/assets/scene/solarsystem/planets/mars/layers/colorlayers/{HiRISE.asset => hirise.asset} (100%) diff --git a/data/assets/scene/solarsystem/planets/mars/layers/colorlayers/HiRISE.asset b/data/assets/scene/solarsystem/planets/mars/layers/colorlayers/hirise.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/mars/layers/colorlayers/HiRISE.asset rename to data/assets/scene/solarsystem/planets/mars/layers/colorlayers/hirise.asset From 284efb48e37c6a3eb47ca1b9424c3e8bea1cb064 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Wed, 2 Dec 2020 13:56:11 -0700 Subject: [PATCH 05/43] Modified globals DataStorage method to make gcc happy on linux --- src/engine/globals.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/engine/globals.cpp b/src/engine/globals.cpp index 10317f366f..31d62713ba 100644 --- a/src/engine/globals.cpp +++ b/src/engine/globals.cpp @@ -96,7 +96,7 @@ namespace { sizeof(scripting::ScriptScheduler) + sizeof(Profile); - std::array DataStorage; + std::vector DataStorage; } // namespace } // namespace openspace @@ -106,6 +106,7 @@ void create() { ZoneScoped callback::create(); + DataStorage.resize(TotalSize); std::byte* currentPos = DataStorage.data(); @@ -357,7 +358,7 @@ void destroy() { LDEBUGC("Globals", "Destroying 'FontManager'"); fontManager->~FontManager(); - std::fill(DataStorage.begin(), DataStorage.end(), std::byte(0)); + DataStorage.clear(); callback::destroy(); } From fd9fdc430aebddef2c417f29c51aa8a56387a7a8 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Thu, 3 Dec 2020 09:24:27 -0700 Subject: [PATCH 06/43] Switched to unsecure http URLs for satellites due to httprequest problem --- .../scene/solarsystem/planets/earth/satellites/misc/iss.asset | 2 +- .../solarsystem/planets/earth/satellites/weather/aqua.asset | 2 +- .../solarsystem/planets/earth/satellites/weather/snpp.asset | 2 +- .../solarsystem/planets/earth/satellites/weather/terra.asset | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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 635c56d9f0..2a91bf1261 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset @@ -3,7 +3,7 @@ local satelliteHelper = asset.require('util/tle_helper') local transforms = asset.require('scene/solarsystem/planets/earth/transforms') local sunTransforms = asset.require('scene/solarsystem/sun/transforms') -local url = "https://celestrak.com/satcat/tle.php?CATNR=25544" +local url = "http://celestrak.com/satcat/tle.php?CATNR=25544" local identifier = "ISS" local filename = "ISS.txt" local nodes = {} diff --git a/data/assets/scene/solarsystem/planets/earth/satellites/weather/aqua.asset b/data/assets/scene/solarsystem/planets/earth/satellites/weather/aqua.asset index 9d2587e1fd..9ebe43df49 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/weather/aqua.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/weather/aqua.asset @@ -3,7 +3,7 @@ local satelliteHelper = asset.require('util/tle_helper') local transforms = asset.require('scene/solarsystem/planets/earth/transforms') local sunTransforms = asset.require('scene/solarsystem/sun/transforms') -local url = "https://celestrak.com/satcat/tle.php?CATNR=27424" +local url = "http://celestrak.com/satcat/tle.php?CATNR=27424" local identifier = "Aqua" local filename = "Aqua.txt" local nodes = {} diff --git a/data/assets/scene/solarsystem/planets/earth/satellites/weather/snpp.asset b/data/assets/scene/solarsystem/planets/earth/satellites/weather/snpp.asset index ff812053a1..2b251d229d 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/weather/snpp.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/weather/snpp.asset @@ -3,7 +3,7 @@ local satelliteHelper = asset.require('util/tle_helper') local transforms = asset.require('scene/solarsystem/planets/earth/transforms') local sunTransforms = asset.require('scene/solarsystem/sun/transforms') -local url = "https://celestrak.com/satcat/tle.php?CATNR=37849" +local url = "http://celestrak.com/satcat/tle.php?CATNR=37849" local identifier = "SNPP" local filename = "SNPP.txt" local nodes = {} diff --git a/data/assets/scene/solarsystem/planets/earth/satellites/weather/terra.asset b/data/assets/scene/solarsystem/planets/earth/satellites/weather/terra.asset index 0cdae52344..3d064550ee 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/weather/terra.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/weather/terra.asset @@ -3,7 +3,7 @@ local satelliteHelper = asset.require('util/tle_helper') local transforms = asset.require('scene/solarsystem/planets/earth/transforms') local sunTransforms = asset.require('scene/solarsystem/sun/transforms') -local url = "https://celestrak.com/satcat/tle.php?CATNR=25994" +local url = "http://celestrak.com/satcat/tle.php?CATNR=25994" local identifier = "Terra" local filename = "Terra.txt" local nodes = {} From ba4e47b54e3488b199bf10d24b25421fdf42c446 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Tue, 8 Dec 2020 19:55:09 -0700 Subject: [PATCH 07/43] First pass at interpolation fix during playback with screenshots --- .../openspace/interaction/sessionrecording.h | 18 ++++++++++++++++++ src/interaction/sessionrecording.cpp | 14 ++++++++++++++ src/scene/scene.cpp | 17 ++++++++++++++--- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 4e2ce1faef..c71c528975 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -30,6 +30,7 @@ #include #include #include +#include namespace openspace::interaction { @@ -117,6 +118,20 @@ public: */ double fixedDeltaTimeDuringFrameOutput() const; + /** + * Returns the number of microseconds that have elapsed since playback started, if + * playback is set to be in the mode where a screenshot is captured with every + * rendered frame (enableTakeScreenShotDuringPlayback() is used to enable this mode). + * At the start of playback, this timer is set to the current steady_clock value. + * However, during playback it is incremented by the fixed framerate of the playback + * rather than the actual clock value (as in normal operation). + * + * \returns number of microseconds elapsed since playback started in terms of the + * number of rendered frames multiplied by the fixed time increment per + * frame + */ + std::chrono::steady_clock::time_point currentPlaybackInterpolationTime() const; + /** * Starts a recording session, which will save data to the provided filename * according to the data format specified, and will continue until recording is @@ -627,6 +642,9 @@ protected: bool _saveRenderingDuringPlayback = false; double _saveRenderingDeltaTime = 1.0 / 30.0; double _saveRenderingCurrentRecordedTime; + std::chrono::steady_clock::duration _saveRenderingDeltaTime_interpolation_usec; + std::chrono::steady_clock::time_point _saveRenderingCurrentRecordedTime_interpolation; + long long _saveRenderingClockInterpolation_countsPerSec; unsigned char _keyframeBuffer[_saveBufferMaxSize_bytes]; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 4e5b9d8a93..0d83cf4f99 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -324,11 +324,15 @@ bool SessionRecording::startPlayback(std::string& filename, return false; } //Set time reference mode + using namespace std::chrono; double now = global::windowDelegate->applicationTime(); _timestampPlaybackStarted_application = now; _timestampPlaybackStarted_simulation = global::timeManager->time().j2000Seconds(); _timestampApplicationStarted_simulation = _timestampPlaybackStarted_simulation - now; _playbackTimeReferenceMode = timeMode; + _saveRenderingCurrentRecordedTime_interpolation = steady_clock::now(); + _saveRenderingClockInterpolation_countsPerSec = + system_clock::duration::period::den / system_clock::duration::period::num; //Set playback flags to true for all modes _playbackActive_camera = true; @@ -407,6 +411,8 @@ void SessionRecording::signalPlaybackFinishedForComponent(RecordedType type) { void SessionRecording::enableTakeScreenShotDuringPlayback(int fps) { _saveRenderingDuringPlayback = true; _saveRenderingDeltaTime = 1.0 / fps; + _saveRenderingDeltaTime_interpolation_usec = + std::chrono::microseconds(static_cast(_saveRenderingDeltaTime * 1000000)); } void SessionRecording::disableTakeScreenShotDuringPlayback() { @@ -907,6 +913,10 @@ double SessionRecording::fixedDeltaTimeDuringFrameOutput() const { } } +std::chrono::steady_clock::time_point SessionRecording::currentPlaybackInterpolationTime() const { + return _saveRenderingCurrentRecordedTime_interpolation; +} + bool SessionRecording::playbackCamera() { Timestamps times; datamessagestructures::CameraKeyframe kf; @@ -1388,6 +1398,8 @@ bool SessionRecording::addKeyframeToTimeline(RecordedType type, } void SessionRecording::moveAheadInTime() { + using namespace std::chrono; + double currTime = currentTime(); lookForNonCameraKeyframesThatHaveComeDue(currTime); updateCameraWithOrWithoutNewKeyframes(currTime); @@ -1398,6 +1410,8 @@ void SessionRecording::moveAheadInTime() { global::navigationHandler->orbitalNavigator().anchorNode(); const Renderable* focusRenderable = focusNode->renderable(); if (!focusRenderable || focusRenderable->renderedWithDesiredData()) { + _saveRenderingCurrentRecordedTime_interpolation += + _saveRenderingDeltaTime_interpolation_usec; _saveRenderingCurrentRecordedTime += _saveRenderingDeltaTime; global::renderEngine->takeScreenshot(); } diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index d364354be3..ababedeea9 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -494,9 +495,14 @@ 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 = ( + global::sessionRecording->isSavingFramesDuringPlayback() ? + global::sessionRecording->currentPlaybackInterpolationTime() : + std::chrono::steady_clock::now() + ); for (PropertyInterpolationInfo& info : _propertyInterpolationInfos) { if (info.prop == prop) { - info.beginTime = std::chrono::steady_clock::now(); + info.beginTime = now; info.durationSeconds = durationSeconds; info.easingFunction = func; // If we found it, we can break since we make sure that each property is only @@ -543,8 +549,13 @@ void Scene::updateInterpolations() { using namespace std::chrono; - auto now = steady_clock::now(); - + steady_clock::time_point now; + if (global::sessionRecording->isSavingFramesDuringPlayback()) { + now = global::sessionRecording->currentPlaybackInterpolationTime(); + } + else { + now = steady_clock::now(); + } // First, let's update the properties for (PropertyInterpolationInfo& i : _propertyInterpolationInfos) { long long usPassed = duration_cast( From 5ed85d8fcdaea2ce5536c7724b149824f1279501 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Fri, 11 Dec 2020 12:40:22 -0700 Subject: [PATCH 08/43] Fix for property change interpolation during playback with screenshots --- include/openspace/interaction/sessionrecording.h | 1 + src/interaction/sessionrecording.cpp | 8 ++++++++ src/scene/scene.cpp | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index c71c528975..baba89dfdb 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -645,6 +645,7 @@ protected: std::chrono::steady_clock::duration _saveRenderingDeltaTime_interpolation_usec; std::chrono::steady_clock::time_point _saveRenderingCurrentRecordedTime_interpolation; long long _saveRenderingClockInterpolation_countsPerSec; + bool _saveRendering_isFirstFrame = true; unsigned char _keyframeBuffer[_saveBufferMaxSize_bytes]; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 0d83cf4f99..d80997d38b 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -333,6 +333,7 @@ bool SessionRecording::startPlayback(std::string& filename, _saveRenderingCurrentRecordedTime_interpolation = steady_clock::now(); _saveRenderingClockInterpolation_countsPerSec = system_clock::duration::period::den / system_clock::duration::period::num; + _saveRendering_isFirstFrame = true; //Set playback flags to true for all modes _playbackActive_camera = true; @@ -457,6 +458,7 @@ void SessionRecording::cleanUpPlayback() { _idxTimeline_cameraPtrPrev = 0; _hasHitEndOfCameraKeyframes = false; _saveRenderingDuringPlayback = false; + _saveRendering_isFirstFrame = true; _cleanupNeeded = false; } @@ -1403,6 +1405,12 @@ void SessionRecording::moveAheadInTime() { double currTime = currentTime(); lookForNonCameraKeyframesThatHaveComeDue(currTime); updateCameraWithOrWithoutNewKeyframes(currTime); + //Unfortunately the first frame is sometimes rendered because globebrowsing reports + // that all chunks are rendered when they apparently are not. + if (_saveRendering_isFirstFrame) { + _saveRendering_isFirstFrame = false; + return; + } if (isSavingFramesDuringPlayback()) { // Check if renderable in focus is still resolving tile loading // do not adjust time while we are doing this, or take screenshot diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index ababedeea9..37080bb352 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -513,7 +513,7 @@ void Scene::addPropertyInterpolation(properties::Property* prop, float durationS PropertyInterpolationInfo i = { prop, - std::chrono::steady_clock::now(), + now, durationSeconds, func }; From 61aaf60825a6ca90fbd5efac6b38c63a0bd37389 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Sun, 13 Dec 2020 16:23:19 -0700 Subject: [PATCH 09/43] Implemented pause-during-playback feature --- .../openspace/interaction/sessionrecording.h | 3 ++ src/interaction/sessionrecording.cpp | 32 +++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index baba89dfdb..483ae02695 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -638,6 +638,9 @@ protected: bool _playbackActive_script = false; bool _hasHitEndOfCameraKeyframes = false; bool _setSimulationTimeWithNextCameraKeyframe = false; + bool _playbackStartedPaused = false; + double _playbackPauseOffset = 0.0; + double _previousTime = 0.0; bool _saveRenderingDuringPlayback = false; double _saveRenderingDeltaTime = 1.0 / 30.0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index d80997d38b..f1f71c3897 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -334,6 +334,8 @@ bool SessionRecording::startPlayback(std::string& filename, _saveRenderingClockInterpolation_countsPerSec = system_clock::duration::period::den / system_clock::duration::period::num; _saveRendering_isFirstFrame = true; + _playbackPauseOffset = 0.0; + _playbackStartedPaused = global::timeManager->isPaused(); //Set playback flags to true for all modes _playbackActive_camera = true; @@ -459,6 +461,8 @@ void SessionRecording::cleanUpPlayback() { _hasHitEndOfCameraKeyframes = false; _saveRenderingDuringPlayback = false; _saveRendering_isFirstFrame = true; + _playbackPauseOffset = 0.0; + _playbackStartedPaused = false; _cleanupNeeded = false; } @@ -891,13 +895,13 @@ double SessionRecording::currentTime() const { } else if (_playbackTimeReferenceMode == KeyframeTimeRef::Relative_recordedStart) { return (global::windowDelegate->applicationTime() - - _timestampPlaybackStarted_application); + _timestampPlaybackStarted_application) - _playbackPauseOffset; } else if (_playbackTimeReferenceMode == KeyframeTimeRef::Absolute_simTimeJ2000) { return global::timeManager->time().j2000Seconds(); } else { - return global::windowDelegate->applicationTime(); + return global::windowDelegate->applicationTime() - _playbackPauseOffset; } } @@ -1402,6 +1406,20 @@ bool SessionRecording::addKeyframeToTimeline(RecordedType type, void SessionRecording::moveAheadInTime() { using namespace std::chrono; + bool paused = global::timeManager->isPaused(); + if (paused) { + if (_playbackStartedPaused) { + return; + } + else { + _playbackPauseOffset += global::windowDelegate->applicationTime() - _previousTime; + } + } + else { + _playbackStartedPaused = false; + } + _previousTime = global::windowDelegate->applicationTime(); + double currTime = currentTime(); lookForNonCameraKeyframesThatHaveComeDue(currTime); updateCameraWithOrWithoutNewKeyframes(currTime); @@ -1418,10 +1436,12 @@ void SessionRecording::moveAheadInTime() { global::navigationHandler->orbitalNavigator().anchorNode(); const Renderable* focusRenderable = focusNode->renderable(); if (!focusRenderable || focusRenderable->renderedWithDesiredData()) { - _saveRenderingCurrentRecordedTime_interpolation += - _saveRenderingDeltaTime_interpolation_usec; - _saveRenderingCurrentRecordedTime += _saveRenderingDeltaTime; - global::renderEngine->takeScreenshot(); + if (!paused) { + _saveRenderingCurrentRecordedTime_interpolation += + _saveRenderingDeltaTime_interpolation_usec; + _saveRenderingCurrentRecordedTime += _saveRenderingDeltaTime; + global::renderEngine->takeScreenshot(); + } } } } From d060780f99d7962b5990c2965cba5fe3b88ee63d Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Mon, 22 Mar 2021 12:21:32 -0600 Subject: [PATCH 10/43] Added method for saving current value of a property while recording --- include/openspace/interaction/sessionrecording.h | 13 +++++++++++++ src/interaction/sessionrecording.cpp | 8 ++++++++ src/scene/scene_lua.inl | 6 ++++++ 3 files changed, 27 insertions(+) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 3f52d346a6..a27f6711c6 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -420,6 +420,18 @@ public: void saveScriptKeyframeAscii(Timestamps& times, datamessagestructures::ScriptMessage& sm, std::ofstream& file); + /** + * Since session recordings only record changes, the initial conditions aren't + * preserved when a playback starts. This function is called whenever a property + * value is set and a recording is in progress. Before the set happens, this + * function will read the current value of the property and store it so that when + * the recording is finished, the initial state will be added as a set property + * command at the beginning of the recording file, to be applied when playback + * starts. + * + * \param prop The property being set + */ + void savePropertyBaseline(properties::Property& prop); /** * Reads header information from a session recording file * @@ -658,6 +670,7 @@ protected: std::vector _keyframesTime; std::vector _keyframesScript; std::vector _timeline; + std::vector _keyframesSavePropertiesBaseline; unsigned int _idxTimeline_nonCamera = 0; unsigned int _idxTime = 0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index b5c418708d..10d067480b 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -701,6 +701,14 @@ void SessionRecording::saveScriptKeyframeAscii(Timestamps& times, saveKeyframeToFile(keyframeLine.str(), file); } +void SessionRecording::savePropertyBaseline(properties::Property& prop) { + std::string initialScriptCommand = fmt::format( + "openspace.setPropertyValueSingle(\"{}\", {})", + prop.fullyQualifiedIdentifier(), prop.getStringValue() + ); + _keyframesSavePropertiesBaseline.push_back(initialScriptCommand); +} + void SessionRecording::preSynchronization() { ZoneScoped diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index ca45fad370..6092fba38c 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -194,6 +194,9 @@ void applyRegularExpression(lua_State* L, const std::string& regex, // value change if the types agree foundMatching = true; + if (global::sessionRecording->isRecording()) { + global::sessionRecording->savePropertyBaseline(*prop); + } if (interpolationDuration == 0.0) { global::renderEngine->scene()->removePropertyInterpolation(prop); prop->setLuaValue(L); @@ -265,6 +268,9 @@ int setPropertyCall_single(properties::Property& prop, const std::string& uri, ); } else { + if (global::sessionRecording->isRecording()) { + global::sessionRecording->savePropertyBaseline(prop); + } if (duration == 0.0) { global::renderEngine->scene()->removePropertyInterpolation(&prop); prop.setLuaValue(L); From b00e1cc5ab99bc8bcf55968b98d3272e807cdb6e Mon Sep 17 00:00:00 2001 From: GPayne Date: Fri, 9 Apr 2021 11:28:15 -0600 Subject: [PATCH 11/43] Switched to using timeline in memory during recording --- .../openspace/interaction/sessionrecording.h | 36 ++- src/interaction/sessionrecording.cpp | 281 ++++++++++-------- src/scripting/scriptengine.cpp | 2 +- 3 files changed, 186 insertions(+), 133 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index a27f6711c6..4b448cdbfe 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -220,13 +220,13 @@ public: * whether it is following the rotation of a node, and timestamp). The data will be * saved to the recording file only if a recording is currently in progress. */ - void saveCameraKeyframe(); + void saveCameraKeyframeToTimeline(); /** * Used to trigger a save of the current timing states. The data will be saved to the * recording file only if a recording is currently in progress. */ - void saveTimeKeyframe(); + void saveTimeKeyframeToTimeline(); /** * Used to trigger a save of a script to the recording file, but only if a recording @@ -234,7 +234,7 @@ public: * * \param scriptToSave String of the Lua command to be saved */ - void saveScriptKeyframe(std::string scriptToSave); + void saveScriptKeyframeToTimeline(std::string scriptToSave); /** * \return The Lua library that contains all Lua functions available to affect the @@ -551,7 +551,7 @@ protected: struct timelineEntry { RecordedType keyframeType; unsigned int idxIntoKeyframeTypeArray; - double timestamp; + Timestamps t3stamps; }; ExternInteraction _externInteract; double _timestampRecordStarted = 0.0; @@ -559,9 +559,11 @@ protected: double _timestampPlaybackStarted_simulation = 0.0; double _timestampApplicationStarted_simulation = 0.0; bool hasCameraChangedFromPrev(datamessagestructures::CameraKeyframe kfNew); - double appropriateTimestamp(double timeOs, double timeRec, double timeSim); + double appropriateTimestamp(Timestamps t3stamps); double equivalentSimulationTime(double timeOs, double timeRec, double timeSim); double equivalentApplicationTime(double timeOs, double timeRec, double timeSim); + void recordCurrentTimePauseState(const Timestamps tripleTimestamp); + void recordCurrentTimeRate(const Timestamps tripleTimestamp); bool handleRecordingFile(std::string filenameIn); static bool isPath(std::string& filename); void removeTrailingPathSlashes(std::string& filename); @@ -572,18 +574,21 @@ protected: bool playbackAddEntriesToTimeline(); void signalPlaybackFinishedForComponent(RecordedType type); void findFirstCameraKeyframeInTimeline(); + Timestamps generateCurrentTimestamp3(double keyframeTime); 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, std::ofstream& file); - bool addKeyframe(double timestamp, + bool addKeyframe(Timestamps t3stamps, interaction::KeyframeNavigator::CameraPose keyframe, int lineNum); - bool addKeyframe(double timestamp, datamessagestructures::TimeKeyframe keyframe, - int lineNum); - bool addKeyframe(double timestamp, std::string scriptToQueue, int lineNum); - bool addKeyframeToTimeline(RecordedType type, size_t indexIntoTypeKeyframes, - double timestamp, int lineNum); + bool addKeyframe(Timestamps t3stamps, + datamessagestructures::TimeKeyframe keyframe, int lineNum); + bool addKeyframe(Timestamps t3stamps, + std::string scriptToQueue, int lineNum); + bool addKeyframeToTimeline(std::vector& timeline, RecordedType type, + size_t indexIntoTypeKeyframes, Timestamps t3stamps, int lineNum); + void moveAheadInTime(); void lookForNonCameraKeyframesThatHaveComeDue(double currTime); void updateCameraWithOrWithoutNewKeyframes(double currTime); @@ -607,6 +612,7 @@ protected: const int lineNum); void saveSingleKeyframeScript(datamessagestructures::ScriptMessage& kf, Timestamps& times, DataMode mode, std::ofstream& file, unsigned char* buffer); + void saveScriptKeyframeToPropertiesBaseline(std::string script); unsigned int findIndexOfLastCameraKeyframeInTimeline(); bool doesTimelineEntryContainCamera(unsigned int index) const; std::vector> _stateChangeCallbacks; @@ -643,6 +649,7 @@ protected: std::string _playbackLineParsing; std::ofstream _recordFile; int _playbackLineNum = 1; + int _recordingEntryNum = 1; KeyframeTimeRef _playbackTimeReferenceMode; datamessagestructures::CameraKeyframe _prevRecordedCameraKeyframe; bool _playbackActive_camera = false; @@ -670,7 +677,12 @@ protected: std::vector _keyframesTime; std::vector _keyframesScript; std::vector _timeline; - std::vector _keyframesSavePropertiesBaseline; + + std::vector _keyframesSavePropertiesBaseline_scripts; + std::vector _keyframesSavePropertiesBaseline_timeline; + + std::vector _keyframesSavePropertiesTripleTimestamps; + std::vector _propertyBaselinesSaved; unsigned int _idxTimeline_nonCamera = 0; unsigned int _idxTime = 0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 10d067480b..ae4a4d98fa 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -188,6 +188,7 @@ bool SessionRecording::handleRecordingFile(std::string filenameIn) { } bool SessionRecording::startRecording(const std::string& filename) { + _timeline.clear(); if (_state == SessionState::Recording) { LERROR("Unable to start recording while already in recording mode"); return false; @@ -210,6 +211,9 @@ bool SessionRecording::startRecording(const std::string& filename) { _playbackActive_camera = false; _playbackActive_time = false; _playbackActive_script = false; + _propertyBaselinesSaved.clear(); + _keyframesSavePropertiesBaseline.clear(); + _recordingEntryNum = 1; _recordFile << FileHeaderTitle; _recordFile.write(FileHeaderVersion, FileHeaderVersionLength); @@ -223,20 +227,44 @@ bool SessionRecording::startRecording(const std::string& filename) { _timestampRecordStarted = global::windowDelegate->applicationTime(); - //Record the current delta time so this is preserved in recording - double currentDeltaTime = global::timeManager->deltaTime(); - std::string scriptCommandForInitializingDeltaTime = - "openspace.time.setDeltaTime(" + std::to_string(currentDeltaTime) + ")"; - saveScriptKeyframe(scriptCommandForInitializingDeltaTime); + //Record the current delta time as the first property to save in the file. + //This needs to be saved as a baseline whether or not it changes during recording. + Timestamps timestampsRecStarted = { + _timestampRecordStarted, + 0.0, + global::timeManager->time().j2000Seconds() + }; + recordCurrentTimePauseState(timestampsRecStarted); + recordCurrentTimeRate(timestampsRecStarted); LINFO("Session recording started"); } return recordingFileOK; } +void SessionRecording::recordCurrentTimePauseState(const Timestamps tripleTimestamp) { + bool isPaused = global::timeManager->isPaused(); + std::string initialTimePausedCommand = "openspace.setPause(" + + isPaused ? "true" : "false" + ")"; + saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand); +} + +void SessionRecording::recordCurrentTimeRate(const Timestamps tripleTimestamp) { + std::string initialTimeRateCommand = fmt::format( + "openspace.setDeltaTime({})", global::timeManager->deltaTime() + ); + saveScriptKeyframeToPropertiesBaseline(initialTimeRateCommand); +} + void SessionRecording::stopRecording() { if (_state == SessionState::Recording) { + for (std::string initPropScripts : _keyframesSavePropertiesBaseline) { + saveScriptKeyframeToTimeline(initPropScripts); + } + for (timelineEntry entry : _timeline) { +//TODO: Write each keyframe here + } _state = SessionState::Idle; LINFO("Session recording stopped"); } @@ -383,8 +411,8 @@ void SessionRecording::findFirstCameraKeyframeInTimeline() { _idxTimeline_cameraFirstInTimeline = i; _idxTimeline_cameraPtrPrev = _idxTimeline_cameraFirstInTimeline; _idxTimeline_cameraPtrNext = _idxTimeline_cameraFirstInTimeline; - _cameraFirstInTimeline_timestamp - = _timeline[_idxTimeline_cameraFirstInTimeline].timestamp; + _cameraFirstInTimeline_timestamp = appropriateTimestamp( + _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps); foundCameraKeyframe = true; break; } @@ -545,11 +573,15 @@ bool SessionRecording::hasCameraChangedFromPrev( return hasChanged; } -void SessionRecording::saveCameraKeyframe() { - if (_state != SessionState::Recording) { - return; - } +SessionRecording::Timestamps SessionRecording::generateCurrentTimestamp3(double kfTime) { + return { + kfTime, + kfTime - _timestampRecordStarted, + global::timeManager->time().j2000Seconds() + }; +} +void SessionRecording::saveCameraKeyframeToTimeline() { const SceneGraphNode* an = global::navigationHandler->orbitalNavigator().anchorNode(); if (!an) { return; @@ -559,12 +591,9 @@ void SessionRecording::saveCameraKeyframe() { // & orientation of camera datamessagestructures::CameraKeyframe kf = _externInteract.generateCameraKeyframe(); - Timestamps times = { - kf._timestamp, - kf._timestamp - _timestampRecordStarted, - global::timeManager->time().j2000Seconds() - }; - saveSingleKeyframeCamera(kf, times, _recordingDataMode, _recordFile, _keyframeBuffer); + Timestamps times = generateCurrentTimestamp3(kf._timestamp); + interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); + addKeyframe(times, pbFrame, _recordingEntryNum++); } void SessionRecording::saveHeaderBinary(Timestamps& times, @@ -613,20 +642,12 @@ void SessionRecording::saveCameraKeyframeAscii(Timestamps& times, saveKeyframeToFile(keyframeLine.str(), file); } -void SessionRecording::saveTimeKeyframe() { - if (_state != SessionState::Recording) { - return; - } - +void SessionRecording::saveTimeKeyframeToTimeline() { //Create a time keyframe, then call to populate it with current time props datamessagestructures::TimeKeyframe kf = _externInteract.generateTimeKeyframe(); - Timestamps times = { - kf._timestamp, - kf._timestamp - _timestampRecordStarted, - global::timeManager->time().j2000Seconds() - }; - saveSingleKeyframeTime(kf, times, _recordingDataMode, _recordFile, _keyframeBuffer); + Timestamps times = generateCurrentTimestamp3(kf._timestamp); + addKeyframe(times, kf, _recordingEntryNum++); } void SessionRecording::saveTimeKeyframeBinary(Timestamps& times, @@ -652,27 +673,28 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, saveKeyframeToFile(keyframeLine.str(), file); } -void SessionRecording::saveScriptKeyframe(std::string scriptToSave) +void SessionRecording::saveScriptKeyframeToTimeline(std::string scriptToSave) { - if (_state != SessionState::Recording) { - return; - } - datamessagestructures::ScriptMessage sm = _externInteract.generateScriptMessage(scriptToSave); - Timestamps times = { - sm._timestamp, - sm._timestamp - _timestampRecordStarted, - global::timeManager->time().j2000Seconds() - }; + Timestamps times = generateCurrentTimestamp3(sm._timestamp); + addKeyframe(times, sm._script, _playbackLineNum); +} - saveSingleKeyframeScript( - sm, +void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script) +{ + Timestamps times + = generateCurrentTimestamp3(global::windowDelegate->applicationTime()); + size_t indexIntoScriptKeyframesFromMainTimeline + = _keyframesSavePropertiesBaseline_scripts.size(); + _keyframesSavePropertiesBaseline_scripts.push_back(std::move(script)); + addKeyframeToTimeline( + _keyframesSavePropertiesBaseline_timeline, + RecordedType::Script, + indexIntoScriptKeyframesFromMainTimeline, times, - _recordingDataMode, - _recordFile, - _keyframeBuffer + 0 ); } @@ -702,20 +724,29 @@ void SessionRecording::saveScriptKeyframeAscii(Timestamps& times, } void SessionRecording::savePropertyBaseline(properties::Property& prop) { - std::string initialScriptCommand = fmt::format( - "openspace.setPropertyValueSingle(\"{}\", {})", - prop.fullyQualifiedIdentifier(), prop.getStringValue() + bool isPropAlreadySaved = ( + std::find( + _propertyBaselinesSaved.begin(), + _propertyBaselinesSaved.end(), + prop.fullyQualifiedIdentifier() + ) != _propertyBaselinesSaved.end() ); - _keyframesSavePropertiesBaseline.push_back(initialScriptCommand); + if( !isPropAlreadySaved ) { + std::string initialScriptCommand = fmt::format( + "openspace.setPropertyValueSingle(\"{}\", {})", + prop.fullyQualifiedIdentifier(), prop.getStringValue() + ); + saveScriptKeyframeToPropertiesBaseline(initialScriptCommand); + } } void SessionRecording::preSynchronization() { ZoneScoped if (_state == SessionState::Recording) { - saveCameraKeyframe(); + saveCameraKeyframeToTimeline(); if (UsingTimeKeyframes) { - saveTimeKeyframe(); + saveTimeKeyframeToTimeline(); } } else if (_state == SessionState::Playback) { @@ -855,18 +886,16 @@ bool SessionRecording::playbackAddEntriesToTimeline() { return parsingStatusOk; } -double SessionRecording::appropriateTimestamp(double timeOs, - double timeRec, - double timeSim) +double SessionRecording::appropriateTimestamp(Timestamps t3stamps) { if (_playbackTimeReferenceMode == KeyframeTimeRef::Relative_recordedStart) { - return timeRec; + return t3stamps.timeRec; } else if (_playbackTimeReferenceMode == KeyframeTimeRef::Absolute_simTimeJ2000) { - return timeSim; + return t3stamps.timeSim; } else { - return timeOs; + return t3stamps.timeOs; } } @@ -952,11 +981,13 @@ bool SessionRecording::playbackCamera() { _setSimulationTimeWithNextCameraKeyframe = false; _saveRenderingCurrentRecordedTime = times.timeRec; } - double timeRef = appropriateTimestamp(times.timeOs, times.timeRec, times.timeSim); - interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); if (success) { - success = addKeyframe(timeRef, pbFrame, _playbackLineNum); + success = addKeyframe( + {times.timeOs, times.timeRec, times.timeSim}, + pbFrame, + _playbackLineNum + ); } return success; } @@ -1086,12 +1117,13 @@ bool SessionRecording::playbackTimeChange() { _playbackLineNum ); kf._timestamp = equivalentApplicationTime(times.timeOs, times.timeRec, times.timeSim); - kf._time = kf._timestamp + _timestampApplicationStarted_simulation; - //global::timeManager.addKeyframe(timeRef, pbFrame._timestamp); - //_externInteract.timeInteraction(pbFrame); if (success) { - success = addKeyframe(kf._timestamp, kf, _playbackLineNum); + success = addKeyframe( + {times.timeOs, times.timeRec, times.timeSim}, + kf, + _playbackLineNum + ); } return success; } @@ -1231,9 +1263,12 @@ bool SessionRecording::playbackScript() { _playbackLineNum ); - double timeRef = appropriateTimestamp(times.timeOs, times.timeRec, times.timeSim); if (success) { - success = addKeyframe(timeRef, kf._script, _playbackLineNum); + success = addKeyframe( + {times.timeOs, times.timeRec, times.timeSim}, + kf._script, + _playbackLineNum + ); } return success; } @@ -1350,57 +1385,16 @@ bool SessionRecording::readScriptKeyframeAscii(Timestamps& times, return true; } -bool SessionRecording::addKeyframe(double timestamp, - interaction::KeyframeNavigator::CameraPose keyframe, - int lineNum) -{ - size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size(); - _keyframesCamera.push_back(std::move(keyframe)); - return addKeyframeToTimeline( - RecordedType::Camera, - indexIntoCameraKeyframesFromMainTimeline, - timestamp, - lineNum - ); -} - -bool SessionRecording::addKeyframe(double timestamp, - datamessagestructures::TimeKeyframe keyframe, - int lineNum) -{ - size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size(); - _keyframesTime.push_back(std::move(keyframe)); - return addKeyframeToTimeline( - RecordedType::Time, - indexIntoTimeKeyframesFromMainTimeline, - timestamp, - lineNum - ); -} - -bool SessionRecording::addKeyframe(double timestamp, - std::string scriptToQueue, - int lineNum) -{ - size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size(); - _keyframesScript.push_back(std::move(scriptToQueue)); - return addKeyframeToTimeline( - RecordedType::Script, - indexIntoScriptKeyframesFromMainTimeline, - timestamp, - lineNum - ); -} - -bool SessionRecording::addKeyframeToTimeline(RecordedType type, +bool SessionRecording::addKeyframeToTimeline(std::vector& timeline, + RecordedType type, size_t indexIntoTypeKeyframes, - double timestamp, int lineNum) + Timestamps t3stamps, int lineNum) { try { - _timeline.push_back({ + timeline.push_back({ type, static_cast(indexIntoTypeKeyframes), - timestamp + t3stamps }); } catch(...) { @@ -1414,6 +1408,51 @@ bool SessionRecording::addKeyframeToTimeline(RecordedType type, return true; } +bool SessionRecording::addKeyframe(Timestamps t3stamps, + interaction::KeyframeNavigator::CameraPose keyframe, + int lineNum) +{ + size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size(); + _keyframesCamera.push_back(std::move(keyframe)); + return addKeyframeToTimeline( + _timeline, + RecordedType::Camera, + indexIntoCameraKeyframesFromMainTimeline, + t3stamps, + lineNum + ); +} + +bool SessionRecording::addKeyframe(Timestamps t3stamps, + datamessagestructures::TimeKeyframe keyframe, + int lineNum) +{ + size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size(); + _keyframesTime.push_back(std::move(keyframe)); + return addKeyframeToTimeline( + _timeline, + RecordedType::Time, + indexIntoTimeKeyframesFromMainTimeline, + t3stamps, + lineNum + ); +} + +bool SessionRecording::addKeyframe(Timestamps t3stamps, + std::string scriptToQueue, + int lineNum) +{ + size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size(); + _keyframesScript.push_back(std::move(scriptToQueue)); + return addKeyframeToTimeline( + _timeline, + RecordedType::Script, + indexIntoScriptKeyframesFromMainTimeline, + t3stamps, + lineNum + ); +} + void SessionRecording::moveAheadInTime() { using namespace std::chrono; @@ -1423,7 +1462,8 @@ void SessionRecording::moveAheadInTime() { return; } else { - _playbackPauseOffset += global::windowDelegate->applicationTime() - _previousTime; + _playbackPauseOffset + += global::windowDelegate->applicationTime() - _previousTime; } } else { @@ -1512,7 +1552,8 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) { if (doesTimelineEntryContainCamera(seekAheadIndex)) { unsigned int indexIntoCameraKeyframes = _timeline[seekAheadIndex].idxIntoKeyframeTypeArray; - double seekAheadKeyframeTimestamp = _timeline[seekAheadIndex].timestamp; + double seekAheadKeyframeTimestamp + = appropriateTimestamp(_timeline[seekAheadIndex].t3stamps); if (indexIntoCameraKeyframes >= (_keyframesCamera.size() - 1)) { _hasHitEndOfCameraKeyframes = true; @@ -1532,7 +1573,7 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) { } double interpolationUpperBoundTimestamp = - _timeline[_idxTimeline_cameraPtrNext].timestamp; + appropriateTimestamp(_timeline[_idxTimeline_cameraPtrNext].t3stamps); if ((currTime > interpolationUpperBoundTimestamp) && _hasHitEndOfCameraKeyframes) { _idxTimeline_cameraPtrPrev = _idxTimeline_cameraPtrNext; @@ -1607,9 +1648,9 @@ bool SessionRecording::processCameraKeyframe(double now) { } // getPrevTimestamp(); - double prevTime = _timeline[_idxTimeline_cameraPtrPrev].timestamp; + double prevTime = appropriateTimestamp(_timeline[_idxTimeline_cameraPtrPrev].t3stamps); // getNextTimestamp(); - double nextTime = _timeline[_idxTimeline_cameraPtrNext].timestamp; + double nextTime = appropriateTimestamp(_timeline[_idxTimeline_cameraPtrNext].t3stamps); double t; if ((nextTime - prevTime) < 1e-7) { @@ -1672,10 +1713,10 @@ double SessionRecording::getNextTimestamp() { return 0.0; } else if (_idxTimeline_nonCamera < _timeline.size()) { - return _timeline[_idxTimeline_nonCamera].timestamp; + return appropriateTimestamp(_timeline[_idxTimeline_nonCamera].t3stamps); } else { - return _timeline.back().timestamp; + return appropriateTimestamp(_timeline.back().t3stamps); } } @@ -1684,13 +1725,13 @@ double SessionRecording::getPrevTimestamp() { return 0.0; } else if (_idxTimeline_nonCamera == 0) { - return _timeline.front().timestamp; + return appropriateTimestamp(_timeline.front().t3stamps); } else if (_idxTimeline_nonCamera < _timeline.size()) { - return _timeline[_idxTimeline_nonCamera - 1].timestamp; + return appropriateTimestamp(_timeline[_idxTimeline_nonCamera - 1].t3stamps); } else { - return _timeline.back().timestamp; + return appropriateTimestamp(_timeline.back().t3stamps); } } diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index 7ea69ac42d..068a778177 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -694,7 +694,7 @@ void ScriptEngine::preSync(bool isMaster) { global::parallelPeer->sendScript(item.script); } if (global::sessionRecording->isRecording()) { - global::sessionRecording->saveScriptKeyframe(item.script); + global::sessionRecording->saveScriptKeyframeToTimeline(item.script); } } } From fbec2fe71340a12c5507ce1bf4bf0a89af200197 Mon Sep 17 00:00:00 2001 From: GPayne Date: Tue, 13 Apr 2021 14:21:33 -0600 Subject: [PATCH 12/43] Updated save-to-disk when recording ends --- .../openspace/interaction/sessionrecording.h | 2 - include/openspace/network/messagestructures.h | 8 ++ src/interaction/sessionrecording.cpp | 83 +++++++++++++++++-- 3 files changed, 86 insertions(+), 7 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 4b448cdbfe..7f3240eaff 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -680,8 +680,6 @@ protected: std::vector _keyframesSavePropertiesBaseline_scripts; std::vector _keyframesSavePropertiesBaseline_timeline; - - std::vector _keyframesSavePropertiesTripleTimestamps; std::vector _propertyBaselinesSaved; unsigned int _idxTimeline_nonCamera = 0; diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index f9e7492ebf..b2dec16915 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -49,6 +49,14 @@ struct CameraKeyframe { CameraKeyframe(const std::vector& buffer) { deserialize(buffer); } + CameraKeyframe(glm::dvec3&& pos, glm::dquat&& rot, std::string&& focusNode, + bool&& followNodeRot, float&& scale) + : _position(pos) + , _rotation(rot) + , _focusNode(focusNode) + , _scale(scale) + , _followNodeRotation(followNodeRot) + {} glm::dvec3 _position = glm::dvec3(0.0); glm::dquat _rotation = glm::dquat(1.0, 0.0, 0.0, 0.0); diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index ae4a4d98fa..720dd4664e 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -212,7 +212,8 @@ bool SessionRecording::startRecording(const std::string& filename) { _playbackActive_time = false; _playbackActive_script = false; _propertyBaselinesSaved.clear(); - _keyframesSavePropertiesBaseline.clear(); + _keyframesSavePropertiesBaseline_scripts.clear(); + _keyframesSavePropertiesBaseline_timeline.clear(); _recordingEntryNum = 1; _recordFile << FileHeaderTitle; @@ -246,7 +247,7 @@ bool SessionRecording::startRecording(const std::string& filename) { void SessionRecording::recordCurrentTimePauseState(const Timestamps tripleTimestamp) { bool isPaused = global::timeManager->isPaused(); std::string initialTimePausedCommand = "openspace.setPause(" + - isPaused ? "true" : "false" + ")"; + std::string(isPaused ? "true" : "false") + ")"; saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand); } @@ -259,17 +260,86 @@ void SessionRecording::recordCurrentTimeRate(const Timestamps tripleTimestamp) { void SessionRecording::stopRecording() { if (_state == SessionState::Recording) { - for (std::string initPropScripts : _keyframesSavePropertiesBaseline) { - saveScriptKeyframeToTimeline(initPropScripts); + //Add all property baseline scripts to the beginning of the recording file + datamessagestructures::ScriptMessage smTmp; + for (timelineEntry initPropScripts : _keyframesSavePropertiesBaseline_timeline) { + if (initPropScripts.keyframeType == RecordedType::Script) { + smTmp._script = _keyframesSavePropertiesBaseline_scripts + [initPropScripts.idxIntoKeyframeTypeArray]; + saveSingleKeyframeScript( + smTmp, + initPropScripts.t3stamps, + _recordingDataMode, + _recordFile, + _keyframeBuffer + ); + } } for (timelineEntry entry : _timeline) { -//TODO: Write each keyframe here + switch (entry.keyframeType) { + case RecordedType::Camera: + { + interaction::KeyframeNavigator::CameraPose kf + = _keyframesCamera[entry.idxIntoKeyframeTypeArray]; + glm::dquat tmpRotation( + std::move(kf.rotation.w), + std::move(kf.rotation.x), + std::move(kf.rotation.y), + std::move(kf.rotation.z) + ); + datamessagestructures::CameraKeyframe kfMsg( + std::move(kf.position), + std::move(tmpRotation), + std::move(kf.focusNode), + std::move(kf.followFocusNodeRotation), + std::move(kf.scale) + ); + saveSingleKeyframeCamera( + kfMsg, + entry.t3stamps, + _recordingDataMode, + _recordFile, + _keyframeBuffer + ); + break; + } + case RecordedType::Time: + { + datamessagestructures::TimeKeyframe tf + = _keyframesTime[entry.idxIntoKeyframeTypeArray]; + saveSingleKeyframeTime( + tf, + entry.t3stamps, + _recordingDataMode, + _recordFile, + _keyframeBuffer + ); + break; + } + case RecordedType::Script: + { + smTmp._script = _keyframesScript[entry.idxIntoKeyframeTypeArray]; + saveSingleKeyframeScript( + smTmp, + entry.t3stamps, + _recordingDataMode, + _recordFile, + _keyframeBuffer + ); + break; + } + default: + { + break; + } + } } _state = SessionState::Idle; LINFO("Session recording stopped"); } // Close the recording file _recordFile.close(); + _cleanupNeeded = true; } bool SessionRecording::startPlayback(std::string& filename, @@ -486,6 +556,9 @@ void SessionRecording::cleanUpPlayback() { _keyframesCamera.clear(); _keyframesTime.clear(); _keyframesScript.clear(); + _keyframesSavePropertiesBaseline_scripts.clear(); + _keyframesSavePropertiesBaseline_timeline.clear(); + _propertyBaselinesSaved.clear(); _idxTimeline_nonCamera = 0; _idxTime = 0; _idxScript = 0; From e94fbb2adff5a38705a1dde843c37cea20237afb Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 15 Apr 2021 16:57:20 -0600 Subject: [PATCH 13/43] Added reject lists for property and scripts during playback --- .../openspace/interaction/sessionrecording.h | 14 +++++ src/interaction/sessionrecording.cpp | 59 +++++++++++++------ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 7f3240eaff..e2fa60ba80 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -613,6 +613,7 @@ protected: void saveSingleKeyframeScript(datamessagestructures::ScriptMessage& kf, Timestamps& times, DataMode mode, std::ofstream& file, unsigned char* buffer); void saveScriptKeyframeToPropertiesBaseline(std::string script); + bool isPropertyAllowedForBaseline(const std::string& propString); unsigned int findIndexOfLastCameraKeyframeInTimeline(); bool doesTimelineEntryContainCamera(unsigned int index) const; std::vector> _stateChangeCallbacks; @@ -681,6 +682,19 @@ protected: std::vector _keyframesSavePropertiesBaseline_scripts; std::vector _keyframesSavePropertiesBaseline_timeline; std::vector _propertyBaselinesSaved; + std::vector _propertyBaselineRejects = { + "NavigationHandler.OrbitalNavigator.Anchor", + "NavigationHandler.OrbitalNavigator.Aim", + "NavigationHandler.OrbitalNavigator.RetargetAnchor", + "NavigationHandler.OrbitalNavigator.RetargetAim" + }; + std::vector _scriptRejects = { + "openspace.sessionRecording", + "openspace.time.interpolatePause", + "openspace.time.interpolateTogglePause", + "openspace.time.setPause", + "openspace.time.togglePause" + }; unsigned int _idxTimeline_nonCamera = 0; unsigned int _idxTime = 0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 720dd4664e..f6bc74cccd 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -236,7 +236,6 @@ bool SessionRecording::startRecording(const std::string& filename) { global::timeManager->time().j2000Seconds() }; - recordCurrentTimePauseState(timestampsRecStarted); recordCurrentTimeRate(timestampsRecStarted); LINFO("Session recording started"); } @@ -246,14 +245,14 @@ bool SessionRecording::startRecording(const std::string& filename) { void SessionRecording::recordCurrentTimePauseState(const Timestamps tripleTimestamp) { bool isPaused = global::timeManager->isPaused(); - std::string initialTimePausedCommand = "openspace.setPause(" + + std::string initialTimePausedCommand = "openspace.time.setPause(" + std::string(isPaused ? "true" : "false") + ")"; saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand); } void SessionRecording::recordCurrentTimeRate(const Timestamps tripleTimestamp) { std::string initialTimeRateCommand = fmt::format( - "openspace.setDeltaTime({})", global::timeManager->deltaTime() + "openspace.time.setDeltaTime({})", global::timeManager->deltaTime() ); saveScriptKeyframeToPropertiesBaseline(initialTimeRateCommand); } @@ -262,13 +261,14 @@ void SessionRecording::stopRecording() { if (_state == SessionState::Recording) { //Add all property baseline scripts to the beginning of the recording file datamessagestructures::ScriptMessage smTmp; + Timestamps timeRecStart = generateCurrentTimestamp3(_timestampRecordStarted); for (timelineEntry initPropScripts : _keyframesSavePropertiesBaseline_timeline) { if (initPropScripts.keyframeType == RecordedType::Script) { smTmp._script = _keyframesSavePropertiesBaseline_scripts [initPropScripts.idxIntoKeyframeTypeArray]; saveSingleKeyframeScript( smTmp, - initPropScripts.t3stamps, + timeRecStart, _recordingDataMode, _recordFile, _keyframeBuffer @@ -748,6 +748,16 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, void SessionRecording::saveScriptKeyframeToTimeline(std::string scriptToSave) { + const std::string returnPrefix = "return "; + size_t substringStartIdx = 0; + if (scriptToSave.substr(0, returnPrefix.length()) == returnPrefix) { + substringStartIdx += returnPrefix.length(); + } + for (auto reject : _scriptRejects) { + if (scriptToSave.substr(substringStartIdx, reject.length()) == reject) { + return; + } + } datamessagestructures::ScriptMessage sm = _externInteract.generateScriptMessage(scriptToSave); @@ -797,22 +807,37 @@ void SessionRecording::saveScriptKeyframeAscii(Timestamps& times, } void SessionRecording::savePropertyBaseline(properties::Property& prop) { - bool isPropAlreadySaved = ( - std::find( - _propertyBaselinesSaved.begin(), - _propertyBaselinesSaved.end(), - prop.fullyQualifiedIdentifier() - ) != _propertyBaselinesSaved.end() - ); - if( !isPropAlreadySaved ) { - std::string initialScriptCommand = fmt::format( - "openspace.setPropertyValueSingle(\"{}\", {})", - prop.fullyQualifiedIdentifier(), prop.getStringValue() - ); - saveScriptKeyframeToPropertiesBaseline(initialScriptCommand); + std::string propIdentifier = prop.fullyQualifiedIdentifier(); + if (isPropertyAllowedForBaseline(propIdentifier)) { + bool isPropAlreadySaved = ( + std::find( + _propertyBaselinesSaved.begin(), + _propertyBaselinesSaved.end(), + propIdentifier + ) + != _propertyBaselinesSaved.end() + ); + if (!isPropAlreadySaved) { + std::string initialScriptCommand = fmt::format( + "openspace.setPropertyValueSingle(\"{}\", {})", + propIdentifier, prop.getStringValue() + ); + saveScriptKeyframeToPropertiesBaseline(initialScriptCommand); + _propertyBaselinesSaved.push_back(propIdentifier); + } } } +bool SessionRecording::isPropertyAllowedForBaseline(const std::string& propString) { + for (auto reject : _propertyBaselineRejects) { + if (propString.substr(0, reject.length()) == reject) + { + return false; + } + } + return true; +} + void SessionRecording::preSynchronization() { ZoneScoped From d012ee2fbb2720daabab6f04e138606daca72053 Mon Sep 17 00:00:00 2001 From: GPayne Date: Tue, 20 Apr 2021 16:22:01 -0600 Subject: [PATCH 14/43] Added preprocessing to reject recording if used scenegraphnodes are not loaded --- .../openspace/interaction/sessionrecording.h | 15 +++ src/interaction/sessionrecording.cpp | 103 +++++++++++++++++- 2 files changed, 115 insertions(+), 3 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index e2fa60ba80..c78da14611 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -634,6 +634,13 @@ protected: DataMode readModeFromHeader(std::string filename); void readPlaybackHeader_stream(std::stringstream& conversionInStream, std::string& version, DataMode& mode); + void getListofLoadedSceneGraphNodes(); + + bool checkIfScriptUsesScenegraphNode(std::string s); + std::string checkForScenegraphNodeAccess_Scene(std::string& s, std::string& result); + std::string checkForScenegraphNodeAccess_Nav(std::string& s, std::string& result); + void eraseSpacesFromString(std::string& s, size_t pos); + std::string getNameFromSurroundingQuotes(std::string& s, char quote); static void writeToFileBuffer(unsigned char* buf, size_t& idx, double src); static void writeToFileBuffer(unsigned char* buf, size_t& idx, std::vector& cv); @@ -673,6 +680,12 @@ protected: unsigned char _keyframeBuffer[_saveBufferMaxSize_bytes]; bool _cleanupNeeded = false; + const std::string scriptReturnPrefix = "return "; + std::vector scriptsUsingScenegraphNodesNavAccess = { + "RetargetAnchor", + "Anchor", + "Aim" + }; std::vector _keyframesCamera; std::vector _keyframesTime; @@ -690,11 +703,13 @@ protected: }; std::vector _scriptRejects = { "openspace.sessionRecording", + "openspace.scriptScheduler.clear", "openspace.time.interpolatePause", "openspace.time.interpolateTogglePause", "openspace.time.setPause", "openspace.time.togglePause" }; + std::vector _loadedSceneGraphNodes; unsigned int _idxTimeline_nonCamera = 0; unsigned int _idxTime = 0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index f6bc74cccd..ab4b6c93c3 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -748,10 +748,9 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, void SessionRecording::saveScriptKeyframeToTimeline(std::string scriptToSave) { - const std::string returnPrefix = "return "; size_t substringStartIdx = 0; - if (scriptToSave.substr(0, returnPrefix.length()) == returnPrefix) { - substringStartIdx += returnPrefix.length(); + if (scriptToSave.substr(0, scriptReturnPrefix.length()) == scriptReturnPrefix) { + substringStartIdx += scriptReturnPrefix.length(); } for (auto reject : _scriptRejects) { if (scriptToSave.substr(substringStartIdx, reject.length()) == reject) { @@ -1361,6 +1360,8 @@ bool SessionRecording::playbackScript() { _playbackLineNum ); + success = checkIfScriptUsesScenegraphNode(kf._script); + if (success) { success = addKeyframe( {times.timeOs, times.timeRec, times.timeSim}, @@ -1371,6 +1372,102 @@ bool SessionRecording::playbackScript() { return success; } +void SessionRecording::getListofLoadedSceneGraphNodes() { + std::vector nodes = + global::renderEngine->scene()->allSceneGraphNodes(); + for (SceneGraphNode* n : nodes) { + _loadedSceneGraphNodes.push_back(n->guiName()); + } +} + +bool SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { + if (s.rfind(scriptReturnPrefix, 0) == 0) { + s.erase(0, scriptReturnPrefix.length()); + } + //This works for both setPropertyValue and setPropertyValueSingle + if (s.rfind("openspace.setPropertyValue", 0) == 0) { + std::string found; + if (s.find("(\"") != std::string::npos) { + std::string subj = s.substr(s.find("(\"") + 2); + checkForScenegraphNodeAccess_Scene(subj, found); + checkForScenegraphNodeAccess_Nav(subj, found); + if (found != "") { + if (std::find(_loadedSceneGraphNodes.begin(), + _loadedSceneGraphNodes.end(), + found) + == _loadedSceneGraphNodes.end()) + { + LERROR(fmt::format( + "Playback file requires scenegraph node {}, which is " + "not currently loaded", subj + )); + return false; + } + } + } + } + return true; +} + +std::string SessionRecording::checkForScenegraphNodeAccess_Scene(std::string& s, + std::string& result) +{ + const std::string scene = "Scene."; + auto posScene = s.find(scene); + if (posScene != std::string::npos) { + auto posDot = s.rfind(".", posScene + scene.length()); + result = s.substr(posScene + scene.length(), posDot - posScene); + } +} + +std::string SessionRecording::checkForScenegraphNodeAccess_Nav(std::string& s, + std::string& result) +{ + std::string nextTerm = "NavigationHandler.OrbitalNavigator."; + std::vector navScriptsUsingNodes = { + ".RetargetAnchor", + ".Anchor", + ".Aim" + }; + auto posNav = s.find(nextTerm); + if (posNav != std::string::npos) { + auto posDot = s.rfind(".", posNav + nextTerm.length()); + if (posDot != std::string::npos) { + for (std::string accessName : navScriptsUsingNodes) { + if (s.substr(posDot).rfind(accessName) == 0) { + std::string postName = s.substr(posDot + accessName.length() + 1); + eraseSpacesFromString(postName, 0); + result = getNameFromSurroundingQuotes(postName, s.at(0)); + } + } + } + } +} + +void SessionRecording::eraseSpacesFromString(std::string& s, size_t pos) { + s.erase( + s.begin(), + std::find_if( + s.begin(), + s.end(), + std::not1(std::ptr_fun(std::isspace)) + ) + ); +} + +std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s, char quote) { + std::string result; + //Handle either ' or " marks + if (quote == '\'' || quote == '\"') { + size_t quoteCount = std::count(s.begin(), s.end(), s); + //Must be an opening and closing quote char + if (quoteCount == 2) { + result = s.substr(1, s.rfind(2, quote)); + } + } + return result; +} + bool SessionRecording::convertScript(std::stringstream& inStream, DataMode mode, int lineNum, std::string& inputLine, std::ofstream& outFile, unsigned char* buffer) From 7371c5bd09cf79f6d3db5547d3cf9d5f4fbae3c0 Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 22 Apr 2021 21:58:18 -0600 Subject: [PATCH 15/43] Fixes for tracking nodes that are used in a recording --- .../openspace/interaction/sessionrecording.h | 30 ++-- src/interaction/sessionrecording.cpp | 149 ++++++++++-------- 2 files changed, 103 insertions(+), 76 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index c78da14611..0d80f2b973 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -562,8 +562,8 @@ protected: double appropriateTimestamp(Timestamps t3stamps); double equivalentSimulationTime(double timeOs, double timeRec, double timeSim); double equivalentApplicationTime(double timeOs, double timeRec, double timeSim); - void recordCurrentTimePauseState(const Timestamps tripleTimestamp); - void recordCurrentTimeRate(const Timestamps tripleTimestamp); + void recordCurrentTimePauseState(); + void recordCurrentTimeRate(); bool handleRecordingFile(std::string filenameIn); static bool isPath(std::string& filename); void removeTrailingPathSlashes(std::string& filename); @@ -573,7 +573,7 @@ protected: bool playbackScript(); bool playbackAddEntriesToTimeline(); void signalPlaybackFinishedForComponent(RecordedType type); - void findFirstCameraKeyframeInTimeline(); + bool findFirstCameraKeyframeInTimeline(); Timestamps generateCurrentTimestamp3(double keyframeTime); static void saveStringToFile(const std::string& s, unsigned char* kfBuffer, size_t& idx, std::ofstream& file); @@ -634,13 +634,14 @@ protected: DataMode readModeFromHeader(std::string filename); void readPlaybackHeader_stream(std::stringstream& conversionInStream, std::string& version, DataMode& mode); - void getListofLoadedSceneGraphNodes(); + void populateListofLoadedSceneGraphNodes(); bool checkIfScriptUsesScenegraphNode(std::string s); - std::string checkForScenegraphNodeAccess_Scene(std::string& s, std::string& result); - std::string checkForScenegraphNodeAccess_Nav(std::string& s, std::string& result); - void eraseSpacesFromString(std::string& s, size_t pos); - std::string getNameFromSurroundingQuotes(std::string& s, char quote); + void checkForScenegraphNodeAccess_Scene(std::string& s, std::string& result); + void checkForScenegraphNodeAccess_Nav(std::string& s, std::string& result); + bool checkIfInitialFocusNodeIsLoaded(unsigned int firstCamIndex); + void eraseSpacesFromString(std::string& s); + std::string getNameFromSurroundingQuotes(std::string& s); static void writeToFileBuffer(unsigned char* buf, size_t& idx, double src); static void writeToFileBuffer(unsigned char* buf, size_t& idx, std::vector& cv); @@ -681,7 +682,7 @@ protected: bool _cleanupNeeded = false; const std::string scriptReturnPrefix = "return "; - std::vector scriptsUsingScenegraphNodesNavAccess = { + std::vector scriptsUsingScenegraphNodesNavAccess = { "RetargetAnchor", "Anchor", "Aim" @@ -695,13 +696,13 @@ protected: std::vector _keyframesSavePropertiesBaseline_scripts; std::vector _keyframesSavePropertiesBaseline_timeline; std::vector _propertyBaselinesSaved; - std::vector _propertyBaselineRejects = { + const std::vector _propertyBaselineRejects = { "NavigationHandler.OrbitalNavigator.Anchor", "NavigationHandler.OrbitalNavigator.Aim", "NavigationHandler.OrbitalNavigator.RetargetAnchor", "NavigationHandler.OrbitalNavigator.RetargetAim" }; - std::vector _scriptRejects = { + const std::vector _scriptRejects = { "openspace.sessionRecording", "openspace.scriptScheduler.clear", "openspace.time.interpolatePause", @@ -709,7 +710,12 @@ protected: "openspace.time.setPause", "openspace.time.togglePause" }; - std::vector _loadedSceneGraphNodes; + const std::vector _navScriptsUsingNodes = { + "RetargetAnchor", + "Anchor", + "Aim" + }; + std::vector _loadedNodes; unsigned int _idxTimeline_nonCamera = 0; unsigned int _idxTime = 0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index ab4b6c93c3..36c577f2f8 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -236,21 +236,21 @@ bool SessionRecording::startRecording(const std::string& filename) { global::timeManager->time().j2000Seconds() }; - recordCurrentTimeRate(timestampsRecStarted); + recordCurrentTimeRate(); LINFO("Session recording started"); } return recordingFileOK; } -void SessionRecording::recordCurrentTimePauseState(const Timestamps tripleTimestamp) { +void SessionRecording::recordCurrentTimePauseState() { bool isPaused = global::timeManager->isPaused(); std::string initialTimePausedCommand = "openspace.time.setPause(" + std::string(isPaused ? "true" : "false") + ")"; saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand); } -void SessionRecording::recordCurrentTimeRate(const Timestamps tripleTimestamp) { +void SessionRecording::recordCurrentTimeRate() { std::string initialTimeRateCommand = fmt::format( "openspace.time.setDeltaTime({})", global::timeManager->deltaTime() ); @@ -449,6 +449,8 @@ bool SessionRecording::startPlayback(std::string& filename, global::navigationHandler->keyframeNavigator().setTimeReferenceMode(timeMode, now); global::scriptScheduler->setTimeReferenceMode(timeMode); + _loadedNodes.clear(); + populateListofLoadedSceneGraphNodes(); _setSimulationTimeWithNextCameraKeyframe = forceSimTimeAtStart; if (!playbackAddEntriesToTimeline()) { @@ -457,7 +459,10 @@ bool SessionRecording::startPlayback(std::string& filename, } _hasHitEndOfCameraKeyframes = false; - findFirstCameraKeyframeInTimeline(); + if (!findFirstCameraKeyframeInTimeline()) { + cleanUpPlayback(); + return false; + } LINFO(fmt::format( "Playback session started: ({:8.3f},0.0,{:13.3f}) with {}/{}/{} entries, " @@ -474,7 +479,7 @@ bool SessionRecording::startPlayback(std::string& filename, return true; } -void SessionRecording::findFirstCameraKeyframeInTimeline() { +bool SessionRecording::findFirstCameraKeyframeInTimeline() { bool foundCameraKeyframe = false; for (unsigned int i = 0; i < _timeline.size(); i++) { if (doesTimelineEntryContainCamera(i)) { @@ -490,6 +495,10 @@ void SessionRecording::findFirstCameraKeyframeInTimeline() { if (!foundCameraKeyframe) { signalPlaybackFinishedForComponent(RecordedType::Camera); + return true; + } + else { + return checkIfInitialFocusNodeIsLoaded(_idxTimeline_cameraFirstInTimeline); } } @@ -541,10 +550,17 @@ void SessionRecording::cleanUpPlayback() { ghoul_assert(camera != nullptr, "Camera must not be nullptr"); Scene* scene = camera->parent()->scene(); if (!_timeline.empty()) { - unsigned int p = _timeline[_idxTimeline_cameraPtrPrev].idxIntoKeyframeTypeArray; - const SceneGraphNode* n = scene->sceneGraphNode(_keyframesCamera[p].focusNode); - if (n) { - global::navigationHandler->orbitalNavigator().setFocusNode(n->identifier()); + if (_timeline.size() > 0) { + unsigned int p = + _timeline[_idxTimeline_cameraPtrPrev].idxIntoKeyframeTypeArray; + if (_keyframesCamera.size() > 0) { + const SceneGraphNode* n = scene->sceneGraphNode( + _keyframesCamera[p].focusNode); + if (n) { + global::navigationHandler->orbitalNavigator().setFocusNode( + n->identifier()); + } + } } } global::scriptScheduler->stopPlayback(); @@ -559,6 +575,7 @@ void SessionRecording::cleanUpPlayback() { _keyframesSavePropertiesBaseline_scripts.clear(); _keyframesSavePropertiesBaseline_timeline.clear(); _propertyBaselinesSaved.clear(); + _loadedNodes.clear(); _idxTimeline_nonCamera = 0; _idxTime = 0; _idxScript = 0; @@ -746,19 +763,19 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, saveKeyframeToFile(keyframeLine.str(), file); } -void SessionRecording::saveScriptKeyframeToTimeline(std::string scriptToSave) +void SessionRecording::saveScriptKeyframeToTimeline(std::string script) { size_t substringStartIdx = 0; - if (scriptToSave.substr(0, scriptReturnPrefix.length()) == scriptReturnPrefix) { + if (script.substr(0, scriptReturnPrefix.length()).compare(scriptReturnPrefix) == 0) { substringStartIdx += scriptReturnPrefix.length(); } - for (auto reject : _scriptRejects) { - if (scriptToSave.substr(substringStartIdx, reject.length()) == reject) { + for (std::string reject : _scriptRejects) { + if (script.substr(substringStartIdx, reject.length()).compare(reject) == 0) { return; } } datamessagestructures::ScriptMessage sm - = _externInteract.generateScriptMessage(scriptToSave); + = _externInteract.generateScriptMessage(script); Timestamps times = generateCurrentTimestamp3(sm._timestamp); addKeyframe(times, sm._script, _playbackLineNum); @@ -828,8 +845,8 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) { } bool SessionRecording::isPropertyAllowedForBaseline(const std::string& propString) { - for (auto reject : _propertyBaselineRejects) { - if (propString.substr(0, reject.length()) == reject) + for (std::string reject : _propertyBaselineRejects) { + if (propString.substr(0, reject.length()).compare(reject) == 0) { return false; } @@ -1372,11 +1389,11 @@ bool SessionRecording::playbackScript() { return success; } -void SessionRecording::getListofLoadedSceneGraphNodes() { +void SessionRecording::populateListofLoadedSceneGraphNodes() { std::vector nodes = global::renderEngine->scene()->allSceneGraphNodes(); for (SceneGraphNode* n : nodes) { - _loadedSceneGraphNodes.push_back(n->guiName()); + _loadedNodes.push_back(n->identifier()); } } @@ -1391,15 +1408,13 @@ bool SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { std::string subj = s.substr(s.find("(\"") + 2); checkForScenegraphNodeAccess_Scene(subj, found); checkForScenegraphNodeAccess_Nav(subj, found); - if (found != "") { - if (std::find(_loadedSceneGraphNodes.begin(), - _loadedSceneGraphNodes.end(), - found) - == _loadedSceneGraphNodes.end()) + if (found.length() > 0) { + auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), found); + if (it == _loadedNodes.end()) { LERROR(fmt::format( - "Playback file requires scenegraph node {}, which is " - "not currently loaded", subj + "Playback file requires scenegraph node '{}', which is " + "not currently loaded", found )); return false; } @@ -1409,65 +1424,71 @@ bool SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { return true; } -std::string SessionRecording::checkForScenegraphNodeAccess_Scene(std::string& s, - std::string& result) +void SessionRecording::checkForScenegraphNodeAccess_Scene(std::string& s, + std::string& result) { const std::string scene = "Scene."; auto posScene = s.find(scene); if (posScene != std::string::npos) { - auto posDot = s.rfind(".", posScene + scene.length()); - result = s.substr(posScene + scene.length(), posDot - posScene); - } -} - -std::string SessionRecording::checkForScenegraphNodeAccess_Nav(std::string& s, - std::string& result) -{ - std::string nextTerm = "NavigationHandler.OrbitalNavigator."; - std::vector navScriptsUsingNodes = { - ".RetargetAnchor", - ".Anchor", - ".Aim" - }; - auto posNav = s.find(nextTerm); - if (posNav != std::string::npos) { - auto posDot = s.rfind(".", posNav + nextTerm.length()); - if (posDot != std::string::npos) { - for (std::string accessName : navScriptsUsingNodes) { - if (s.substr(posDot).rfind(accessName) == 0) { - std::string postName = s.substr(posDot + accessName.length() + 1); - eraseSpacesFromString(postName, 0); - result = getNameFromSurroundingQuotes(postName, s.at(0)); - } - } + auto posDot = s.find(".", posScene + scene.length() + 1); + if (posDot > posScene && posDot != std::string::npos) { + result = s.substr(posScene + scene.length(), posDot + - (posScene + scene.length())); } } } -void SessionRecording::eraseSpacesFromString(std::string& s, size_t pos) { - s.erase( - s.begin(), - std::find_if( - s.begin(), - s.end(), - std::not1(std::ptr_fun(std::isspace)) - ) - ); +void SessionRecording::checkForScenegraphNodeAccess_Nav(std::string& s, + std::string& result) +{ + const std::string nextTerm = "NavigationHandler.OrbitalNavigator."; + auto posNav = s.find(nextTerm); + for (std::string accessName : _navScriptsUsingNodes) { + if (s.substr(posNav + nextTerm.length()).rfind(accessName) == 0) { + std::string postName = s.substr(posNav + nextTerm.length() + + accessName.length() + 2); + eraseSpacesFromString(postName); + result = getNameFromSurroundingQuotes(postName); + } + } } -std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s, char quote) { +void SessionRecording::eraseSpacesFromString(std::string& s) { + s.erase(std::remove_if(s.begin(), s.end(), std::isspace), s.end()); +} + +std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) { std::string result; + char quote = s.at(0); //Handle either ' or " marks if (quote == '\'' || quote == '\"') { - size_t quoteCount = std::count(s.begin(), s.end(), s); + 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(2, quote)); + result = s.substr(1, s.rfind(quote) - 1); } } 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; + } + } + return true; +} + + bool SessionRecording::convertScript(std::stringstream& inStream, DataMode mode, int lineNum, std::string& inputLine, std::ofstream& outFile, unsigned char* buffer) From 08118ba7bb236fc8c0f35f5fa4158dc73775a19c Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Fri, 23 Apr 2021 10:52:31 +0200 Subject: [PATCH 16/43] Add initial support for SpaceMouse as joystick input --- data/assets/util/default_joystick.asset | 161 +++++++++++------- .../interaction/joystickcamerastates.h | 14 +- .../interaction/joystickinputstate.h | 10 ++ .../openspace/interaction/navigationhandler.h | 3 +- src/interaction/joystickcamerastates.cpp | 49 ++++-- src/interaction/joystickinputstate.cpp | 11 ++ src/interaction/navigationhandler.cpp | 8 +- src/interaction/navigationhandler_lua.inl | 8 +- 8 files changed, 184 insertions(+), 80 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 2c55c2dc42..de8c9be609 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -4,6 +4,7 @@ local propertyHelper = asset.require('./property_helper') -- "None" -- "Orbit X" -- "Orbit Y" +-- "Zoom" -- both in and out -- "Zoom In" -- "Zoom Out" -- "LocalRoll X" @@ -62,6 +63,14 @@ local PS4Controller = { } } +local SpaceMouse = { + Push = {0, 1, 2}, -- left/right, back/forth, up/down + Twist = {5}, -- left/right + Tilt = {4, 3}, -- left/right, back/forth + LeftButton = 0, + RightButton = 1 +} + -- Variables to store the state of the joystick between frames Joystick = {} Joystick.State = {} @@ -105,70 +114,102 @@ end asset.onInitialize(function() -- Set the controller to the connected controller - -- Currently: XBoxController or PS4Controller + -- Currently: XBoxController, PS4Controller or SpaceMouse local controller = XBoxController; - openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[1], 0.15) - openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[2], 0.15) - openspace.navigation.setAxisDeadZone(controller.RightThumbStick[1], 0.15) - openspace.navigation.setAxisDeadZone(controller.RightThumbStick[2], 0.15) - openspace.navigation.setAxisDeadZone(controller.LeftTrigger, 0.15) - openspace.navigation.setAxisDeadZone(controller.RightTrigger, 0.15) + if(controller.A ~= nil) then + openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[1], 0.15) + openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[2], 0.15) + openspace.navigation.setAxisDeadZone(controller.RightThumbStick[1], 0.15) + openspace.navigation.setAxisDeadZone(controller.RightThumbStick[2], 0.15) + openspace.navigation.setAxisDeadZone(controller.LeftTrigger, 0.15) + openspace.navigation.setAxisDeadZone(controller.RightTrigger, 0.15) - openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[1], "Orbit X"); - openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[2], "Orbit Y", true); - openspace.navigation.bindJoystickAxis(controller.RightThumbStick[1], "Pan X", true); - openspace.navigation.bindJoystickAxis(controller.RightThumbStick[2], "Pan Y", true); - openspace.navigation.bindJoystickAxis(controller.LeftTrigger, "Zoom Out", false, true); - openspace.navigation.bindJoystickAxis(controller.RightTrigger, "Zoom In", false, true); + openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[1], "Orbit X"); + openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[2], "Orbit Y", true); + openspace.navigation.bindJoystickAxis(controller.RightThumbStick[1], "Pan X", true); + openspace.navigation.bindJoystickAxis(controller.RightThumbStick[2], "Pan Y", true); + openspace.navigation.bindJoystickAxis(controller.LeftTrigger, "Zoom Out", false, true); + openspace.navigation.bindJoystickAxis(controller.RightTrigger, "Zoom In", false, true); - openspace.navigation.bindJoystickButton( - controller.LB, - bindLocalRoll(controller.RightThumbStick[1]), - "Switch to local roll mode" - ) - openspace.navigation.bindJoystickButton( - controller.LB, - unbindRoll(controller.RightThumbStick[1]), - "Switch back to normal mode", - "Release" - ) - openspace.navigation.bindJoystickButton( - controller.RB, - bindGlobalRoll(controller.RightThumbStick[1]), - "Switch to global roll mode" - ) - openspace.navigation.bindJoystickButton( - controller.RB, - unbindRoll(controller.RightThumbStick[1]), - "Switch back to normal mode", - "Release" - ) + openspace.navigation.bindJoystickButton( + controller.LB, + bindLocalRoll(controller.RightThumbStick[1]), + "Switch to local roll mode" + ) + openspace.navigation.bindJoystickButton( + controller.LB, + unbindRoll(controller.RightThumbStick[1]), + "Switch back to normal mode", + "Release" + ) + openspace.navigation.bindJoystickButton( + controller.RB, + bindGlobalRoll(controller.RightThumbStick[1]), + "Switch to global roll mode" + ) + openspace.navigation.bindJoystickButton( + controller.RB, + unbindRoll(controller.RightThumbStick[1]), + "Switch back to normal mode", + "Release" + ) - openspace.navigation.bindJoystickButton( - controller.A, - propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.ZoomFriction'), - "Toggle zoom friction" - ) - openspace.navigation.bindJoystickButton( - controller.B, - propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RotationalFriction'), - "Toggle rotational friction" - ) - openspace.navigation.bindJoystickButton( - controller.DPad.Left, - propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RollFriction'), - "Toggle roll friction" - ) + openspace.navigation.bindJoystickButton( + controller.A, + propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.ZoomFriction'), + "Toggle zoom friction" + ) + openspace.navigation.bindJoystickButton( + controller.B, + propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RotationalFriction'), + "Toggle rotational friction" + ) + openspace.navigation.bindJoystickButton( + controller.DPad.Left, + propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RollFriction'), + "Toggle roll friction" + ) - openspace.navigation.bindJoystickButton( - controller.X, - "openspace.setPropertyValue('NavigationHandler.Origin', 'Earth')", - "Switch target to Earth" - ) - openspace.navigation.bindJoystickButton( - controller.Y, - "openspace.setPropertyValue('NavigationHandler.Origin', 'Mars')", - "Switch target to Mars" - ) + openspace.navigation.bindJoystickButton( + controller.X, + "openspace.setPropertyValue('NavigationHandler.Origin', 'Earth')", + "Switch target to Earth" + ) + openspace.navigation.bindJoystickButton( + controller.Y, + "openspace.setPropertyValue('NavigationHandler.Origin', 'Mars')", + "Switch target to Mars" + ) + elseif (controller.LeftButton ~= nil) then + openspace.navigation.bindJoystickAxis(controller.Push[1], "Orbit X", false, false, true, 25.0); + openspace.navigation.bindJoystickAxis(controller.Push[2], "Orbit Y", false, false, true, 25.0); + openspace.navigation.bindJoystickAxis(controller.Twist[1], "Pan X", true, false, true, 25.0); + openspace.navigation.bindJoystickAxis(controller.Tilt[2], "Pan Y", false, false, true, 25.0); + openspace.navigation.bindJoystickAxis(controller.Push[3], "Zoom", false, false, true, 25.0); + + openspace.navigation.bindJoystickButton( + controller.LeftButton, + bindLocalRoll(controller.Twist[1]), + "Switch to local roll mode" + ) + openspace.navigation.bindJoystickButton( + controller.LeftButton, + unbindRoll(controller.Twist[1]), + "Switch back to normal mode", + "Release" + ) + + openspace.navigation.bindJoystickButton( + controller.RightButton, + bindGlobalRoll(controller.Twist[1]), + "Switch to global roll mode" + ) + openspace.navigation.bindJoystickButton( + controller.RightButton, + unbindRoll(controller.Twist[1]), + "Switch back to normal mode", + "Release" + ) + end end) diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index fd0098e933..da12dc7081 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -43,6 +43,7 @@ public: OrbitY, ZoomIn, ZoomOut, + Zoom, LocalRollX, LocalRollY, GlobalRollX, @@ -60,7 +61,14 @@ public: AxisInvert invert = AxisInvert::No; AxisNormalize normalize = AxisNormalize::No; + // The axis values can either go back to 0 when the joystick is released or it can + // stay at the value it was. The latter is static + bool isStatic = false; + float deadzone = 0.f; + + // Every axis can have their own sensitivity + double sensitivity = 0.0; }; JoystickCameraStates(double sensitivity, double velocityScaleFactor); @@ -69,7 +77,8 @@ public: void setAxisMapping(int axis, AxisType mapping, AxisInvert shouldInvert = AxisInvert::No, - AxisNormalize shouldNormalize = AxisNormalize::No + AxisNormalize shouldNormalize = AxisNormalize::No, + bool isStatic = false, double sensitivity = 0.0 ); AxisInformation axisMapping(int axis) const; @@ -91,6 +100,8 @@ private: std::array _axisMapping; + std::array _prevAxisValues; + struct ButtonInformation { std::string command; JoystickAction action; @@ -135,6 +146,7 @@ from_string(std::string_view string) if (string == "None") { return T::None; } if (string == "Orbit X") { return T::OrbitX; } if (string == "Orbit Y") { return T::OrbitY; } + if (string == "Zoom") { return T::Zoom; } if (string == "Zoom In") { return T::ZoomIn; } if (string == "Zoom Out") { return T::ZoomOut; } if (string == "LocalRoll X") { return T::LocalRollX; } diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index ced81f4013..48586c84ff 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -71,6 +71,10 @@ struct JoystickInputState { /// \c nAxes values are defined values, the rest are undefined std::array axes; + /// The axis values can either go back to 0 when the joystick is released or it can + /// stay at the value it was. The latter is static + bool isStatic = false; + /// The number of buttons that this joystick possesses int nButtons = 0; /// The status of each button. Only the first \c nButtons values are defined, the rest @@ -95,6 +99,12 @@ struct JoystickInputStates : public std::array */ float axis(int axis) const; + /** + * This function checks whether this joystick input has static axis or not + * \return If this joystick input has static axis or not + */ + bool isStatic() const; + /** * This functions checks whether any connected joystick has its \p button in the * passed \p action. Any joystick that does not posses the \p button, it will be diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index 68d34498b2..a6b06b2633 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -115,7 +115,8 @@ public: JoystickCameraStates::AxisInvert shouldInvert = JoystickCameraStates::AxisInvert::No, JoystickCameraStates::AxisNormalize shouldNormalize = - JoystickCameraStates::AxisNormalize::No + JoystickCameraStates::AxisNormalize::No, + bool isStatic = false, double sensitivity = 0.0 ); JoystickCameraStates::AxisInformation joystickAxisMapping(int axis) const; diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 78a9f97506..fe09ecc85c 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -52,8 +52,13 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, continue; } - bool hasValue = true; - float value = inputState.joystickAxis(i); + float rawValue = inputState.joystickAxis(i); + float value = rawValue; + + if (t.isStatic) { + value = rawValue - _prevAxisValues[i]; + _prevAxisValues[i] = rawValue; + } if (std::fabs(value) <= t.deadzone) { continue; @@ -67,49 +72,55 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, value *= -1.f; } - value = static_cast(value * _sensitivity); + if (std::fabs(t.sensitivity) > std::numeric_limits().epsilon()) { + value = static_cast(value * t.sensitivity); + } + else { + value = static_cast(value * _sensitivity); + } switch (t.type) { case AxisType::None: break; case AxisType::OrbitX: - globalRotation.first = hasValue; + globalRotation.first = true; globalRotation.second.x = value; break; case AxisType::OrbitY: - globalRotation.first = hasValue; + globalRotation.first = true; globalRotation.second.y = value; break; + case AxisType::Zoom: case AxisType::ZoomIn: - zoom.first = hasValue; + zoom.first = true; zoom.second += value; break; case AxisType::ZoomOut: - zoom.first = hasValue; + zoom.first = true; zoom.second -= value; break; case AxisType::LocalRollX: - localRoll.first = hasValue; + localRoll.first = true; localRoll.second.x = value; break; case AxisType::LocalRollY: - localRoll.first = hasValue; + localRoll.first = true; localRoll.second.y = value; break; case AxisType::GlobalRollX: - globalRoll.first = hasValue; + globalRoll.first = true; globalRoll.second.x = value; break; case AxisType::GlobalRollY: - globalRoll.first = hasValue; + globalRoll.first = true; globalRoll.second.y = value; break; case AxisType::PanX: - localRotation.first = hasValue; + localRotation.first = true; localRotation.second.x = value; break; case AxisType::PanY: - localRotation.first = hasValue; + localRotation.first = true; localRotation.second.y = value; break; } @@ -167,13 +178,23 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, void JoystickCameraStates::setAxisMapping(int axis, AxisType mapping, AxisInvert shouldInvert, - AxisNormalize shouldNormalize) + AxisNormalize shouldNormalize, + bool isStatic, + double sensitivity) { ghoul_assert(axis < JoystickInputState::MaxAxes, "axis must be < MaxAxes"); _axisMapping[axis].type = mapping; _axisMapping[axis].invert = shouldInvert; _axisMapping[axis].normalize = shouldNormalize; + _axisMapping[axis].isStatic = isStatic; + _axisMapping[axis].sensitivity = sensitivity; + + if (isStatic) { + global::joystickInputStates->at(axis).isStatic = true; + } + + _prevAxisValues[axis] = 0.f; } JoystickCameraStates::AxisInformation JoystickCameraStates::axisMapping(int axis) const { diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp index 4a5537a353..c052806523 100644 --- a/src/interaction/joystickinputstate.cpp +++ b/src/interaction/joystickinputstate.cpp @@ -54,6 +54,17 @@ float JoystickInputStates::axis(int axis) const { return res; } +bool JoystickInputStates::isStatic() const { + bool res = std::any_of( + begin(), + end(), + [](const JoystickInputState& state) { + return state.isStatic; + } + ); + return res; +} + bool JoystickInputStates::button(int button, JoystickAction action) const { ghoul_precondition(button >= 0, "button must be 0 or positive"); diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 203a674f1e..b22b321940 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -492,13 +492,17 @@ void NavigationHandler::loadNavigationState(const std::string& filepath) { void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, JoystickCameraStates::AxisInvert shouldInvert, - JoystickCameraStates::AxisNormalize shouldNormalize) + JoystickCameraStates::AxisNormalize shouldNormalize, + bool isStatic, + double sensitivity) { _orbitalNavigator.joystickStates().setAxisMapping( axis, mapping, shouldInvert, - shouldNormalize + shouldNormalize, + isStatic, + sensitivity ); } diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 34f6531f51..504526ab2c 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -190,7 +190,7 @@ int retargetAim(lua_State* L) { int bindJoystickAxis(lua_State* L) { const int n = ghoul::lua::checkArgumentsAndThrow( L, - { 2, 4 }, + { 2, 6 }, "lua::bindJoystickAxis" ); @@ -199,12 +199,16 @@ int bindJoystickAxis(lua_State* L) { const bool shouldInvert = n > 2 ? ghoul::lua::value(L, 3) : false; const bool shouldNormalize = n > 3 ? ghoul::lua::value(L, 4) : false; + const bool isStatic = n > 4 ? ghoul::lua::value(L, 5) : false; + const double sensitivity = n > 5 ? ghoul::lua::value(L, 6) : 0.0; global::navigationHandler->setJoystickAxisMapping( axis, ghoul::from_string(axisType), interaction::JoystickCameraStates::AxisInvert(shouldInvert), - interaction::JoystickCameraStates::AxisNormalize(shouldNormalize) + interaction::JoystickCameraStates::AxisNormalize(shouldNormalize), + isStatic, + sensitivity ); lua_settop(L, 0); From d93d367e7493a9fd9f73d5f80dadf6740fad8775 Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Fri, 23 Apr 2021 11:33:14 +0200 Subject: [PATCH 17/43] Add roll axis for SpaceMouse --- data/assets/util/default_joystick.asset | 43 +++++++++---------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index de8c9be609..805924b944 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -182,34 +182,23 @@ asset.onInitialize(function() "Switch target to Mars" ) elseif (controller.LeftButton ~= nil) then - openspace.navigation.bindJoystickAxis(controller.Push[1], "Orbit X", false, false, true, 25.0); - openspace.navigation.bindJoystickAxis(controller.Push[2], "Orbit Y", false, false, true, 25.0); - openspace.navigation.bindJoystickAxis(controller.Twist[1], "Pan X", true, false, true, 25.0); - openspace.navigation.bindJoystickAxis(controller.Tilt[2], "Pan Y", false, false, true, 25.0); - openspace.navigation.bindJoystickAxis(controller.Push[3], "Zoom", false, false, true, 25.0); + openspace.navigation.bindJoystickAxis(controller.Push[1], "Orbit X", false, false, true, 40.0); + openspace.navigation.bindJoystickAxis(controller.Push[2], "Orbit Y", false, false, true, 40.0); + openspace.navigation.bindJoystickAxis(controller.Twist[1], "Pan X", true, false, true, 40.0); + openspace.navigation.bindJoystickAxis(controller.Tilt[2], "Pan Y", false, false, true, 35.0); + openspace.navigation.bindJoystickAxis(controller.Push[3], "Zoom", false, false, true, 40.0); + openspace.navigation.bindJoystickAxis(controller.Tilt[1], "LocalRoll X", false, false, true, 35.0); - openspace.navigation.bindJoystickButton( - controller.LeftButton, - bindLocalRoll(controller.Twist[1]), - "Switch to local roll mode" - ) - openspace.navigation.bindJoystickButton( - controller.LeftButton, - unbindRoll(controller.Twist[1]), - "Switch back to normal mode", - "Release" - ) + --openspace.navigation.bindJoystickButton( + --controller.LeftButton, + --bindLocalRoll(controller.Tilt[1]), + --"Switch to local roll mode" + --) - openspace.navigation.bindJoystickButton( - controller.RightButton, - bindGlobalRoll(controller.Twist[1]), - "Switch to global roll mode" - ) - openspace.navigation.bindJoystickButton( - controller.RightButton, - unbindRoll(controller.Twist[1]), - "Switch back to normal mode", - "Release" - ) + --openspace.navigation.bindJoystickButton( + --controller.RightButton, + --bindGlobalRoll(controller.Tilt[1]), + --"Switch to global roll mode" + --) end end) From b9441cc6186777e01ef7c3815a5e736dd12d9634 Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Fri, 23 Apr 2021 15:45:24 +0200 Subject: [PATCH 18/43] Correct PS4Controller mapping --- data/assets/util/default_joystick.asset | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 805924b944..0aee25e63e 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -45,10 +45,10 @@ local PS4Controller = { RightThumbStick = { 2, 5 }, LeftTrigger = 3, RightTrigger = 4, - A = 3, -- Triangle - B = 0, -- Square - X = 2, -- Circle - Y = 1, -- Cross + A = 1, -- Cross + B = 2, -- Circle + X = 0, -- Square + Y = 3, -- Triangle LB = 4, RB = 5, Select = 9, -- options @@ -117,13 +117,12 @@ asset.onInitialize(function() -- Currently: XBoxController, PS4Controller or SpaceMouse local controller = XBoxController; + -- Case of XBoxController or PS4Controller if(controller.A ~= nil) then openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[1], 0.15) openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[2], 0.15) openspace.navigation.setAxisDeadZone(controller.RightThumbStick[1], 0.15) openspace.navigation.setAxisDeadZone(controller.RightThumbStick[2], 0.15) - openspace.navigation.setAxisDeadZone(controller.LeftTrigger, 0.15) - openspace.navigation.setAxisDeadZone(controller.RightTrigger, 0.15) openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[1], "Orbit X"); openspace.navigation.bindJoystickAxis(controller.LeftThumbStick[2], "Orbit Y", true); @@ -173,14 +172,19 @@ asset.onInitialize(function() openspace.navigation.bindJoystickButton( controller.X, - "openspace.setPropertyValue('NavigationHandler.Origin', 'Earth')", + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.Aim', '');" .. + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.Anchor', 'Earth');" .. + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.RetargetAnchor', nil);", "Switch target to Earth" ) openspace.navigation.bindJoystickButton( controller.Y, - "openspace.setPropertyValue('NavigationHandler.Origin', 'Mars')", + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.Aim', '');" .. + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.Anchor', 'Mars');" .. + "openspace.setPropertyValueSingle('NavigationHandler.OrbitalNavigator.RetargetAnchor', nil);", "Switch target to Mars" ) + -- Case of SpaceMouse elseif (controller.LeftButton ~= nil) then openspace.navigation.bindJoystickAxis(controller.Push[1], "Orbit X", false, false, true, 40.0); openspace.navigation.bindJoystickAxis(controller.Push[2], "Orbit Y", false, false, true, 40.0); From 7ceb4850c64a3d931a2b21c5e8e26b651426c1df Mon Sep 17 00:00:00 2001 From: GPayne Date: Sun, 25 Apr 2021 21:47:04 -0600 Subject: [PATCH 19/43] Fix for ascii-to-binary in conversion task --- src/interaction/tasks/convertrecformattask.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/interaction/tasks/convertrecformattask.cpp b/src/interaction/tasks/convertrecformattask.cpp index 3651d49868..ad6cf99d88 100644 --- a/src/interaction/tasks/convertrecformattask.cpp +++ b/src/interaction/tasks/convertrecformattask.cpp @@ -123,6 +123,11 @@ void ConvertRecFormatTask::convert() { } if (_fileFormatType == SessionRecording::DataMode::Ascii) { + _iFile.close(); + _iFile.open(_inFilePath, std::ifstream::in); + //Throw out first line + std::string throw_out; + std::getline(_iFile, throw_out); _oFile.open(_outFilePath); } else if (_fileFormatType == SessionRecording::DataMode::Binary) { From e95ca6c3e824da2d60d084459dc8e353c3c88cc4 Mon Sep 17 00:00:00 2001 From: GPayne Date: Mon, 26 Apr 2021 21:29:52 -0600 Subject: [PATCH 20/43] Fixed minor timing bugs while running full test of record/playback --- .../openspace/interaction/sessionrecording.h | 3 ++- src/interaction/sessionrecording.cpp | 18 ++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 0d80f2b973..10e7d6b601 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -555,6 +555,7 @@ protected: }; ExternInteraction _externInteract; double _timestampRecordStarted = 0.0; + Timestamps _timestamps3RecordStarted; double _timestampPlaybackStarted_application = 0.0; double _timestampPlaybackStarted_simulation = 0.0; double _timestampApplicationStarted_simulation = 0.0; @@ -665,7 +666,6 @@ protected: bool _playbackActive_time = false; bool _playbackActive_script = false; bool _hasHitEndOfCameraKeyframes = false; - bool _setSimulationTimeWithNextCameraKeyframe = false; bool _playbackStartedPaused = false; double _playbackPauseOffset = 0.0; double _previousTime = 0.0; @@ -702,6 +702,7 @@ protected: "NavigationHandler.OrbitalNavigator.RetargetAnchor", "NavigationHandler.OrbitalNavigator.RetargetAim" }; + //A script that begins with an exact match of any of the strings contained in _scriptRejects will not be recorded const std::vector _scriptRejects = { "openspace.sessionRecording", "openspace.scriptScheduler.clear", diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 36c577f2f8..cb7d8bcf83 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -230,7 +230,7 @@ bool SessionRecording::startRecording(const std::string& filename) { //Record the current delta time as the first property to save in the file. //This needs to be saved as a baseline whether or not it changes during recording. - Timestamps timestampsRecStarted = { + _timestamps3RecordStarted = { _timestampRecordStarted, 0.0, global::timeManager->time().j2000Seconds() @@ -261,14 +261,13 @@ void SessionRecording::stopRecording() { if (_state == SessionState::Recording) { //Add all property baseline scripts to the beginning of the recording file datamessagestructures::ScriptMessage smTmp; - Timestamps timeRecStart = generateCurrentTimestamp3(_timestampRecordStarted); for (timelineEntry initPropScripts : _keyframesSavePropertiesBaseline_timeline) { if (initPropScripts.keyframeType == RecordedType::Script) { smTmp._script = _keyframesSavePropertiesBaseline_scripts [initPropScripts.idxIntoKeyframeTypeArray]; saveSingleKeyframeScript( smTmp, - timeRecStart, + _timestamps3RecordStarted, _recordingDataMode, _recordFile, _keyframeBuffer @@ -452,7 +451,6 @@ bool SessionRecording::startPlayback(std::string& filename, _loadedNodes.clear(); populateListofLoadedSceneGraphNodes(); - _setSimulationTimeWithNextCameraKeyframe = forceSimTimeAtStart; if (!playbackAddEntriesToTimeline()) { cleanUpPlayback(); return false; @@ -463,6 +461,11 @@ bool SessionRecording::startPlayback(std::string& filename, cleanUpPlayback(); return false; } + if (forceSimTimeAtStart) { + Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps; + global::timeManager->setTimeNextFrame(Time(times.timeSim)); + _saveRenderingCurrentRecordedTime = times.timeRec; + } LINFO(fmt::format( "Playback session started: ({:8.3f},0.0,{:13.3f}) with {}/{}/{} entries, " @@ -1090,11 +1093,6 @@ bool SessionRecording::playbackCamera() { _playbackLineNum ); - if (_setSimulationTimeWithNextCameraKeyframe) { - global::timeManager->setTimeNextFrame(Time(times.timeSim)); - _setSimulationTimeWithNextCameraKeyframe = false; - _saveRenderingCurrentRecordedTime = times.timeRec; - } interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); if (success) { success = addKeyframe( @@ -1184,7 +1182,7 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times, )); return false; } - times.timeOs = kf._timestamp; + //times.timeOs = kf._timestamp; if (!file) { LINFO(fmt::format( From 64985614bf074ff79cf6f4ac13c57b280f2e8dd9 Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Wed, 12 May 2021 17:43:29 +0200 Subject: [PATCH 21/43] Make SpaceMouse respond to sensitivity slider --- src/interaction/joystickcamerastates.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index fe09ecc85c..3952f1ae42 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -73,7 +73,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, } if (std::fabs(t.sensitivity) > std::numeric_limits().epsilon()) { - value = static_cast(value * t.sensitivity); + value = static_cast(value * t.sensitivity * _sensitivity); } else { value = static_cast(value * _sensitivity); From 9cdd2527814cb9acf77c284f6dfd1a9027ffddcf Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Fri, 14 May 2021 17:09:06 +0200 Subject: [PATCH 22/43] Make buttons on SpaceMouse to switch between local and global roll --- data/assets/util/default_joystick.asset | 38 +++++++++++++++++------ src/interaction/joystickcamerastates.cpp | 2 +- src/interaction/navigationhandler_lua.inl | 8 +++-- 3 files changed, 35 insertions(+), 13 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 47436e9adc..1519bc54ff 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -82,11 +82,11 @@ local bindLocalRoll = function(axis) -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup if not Joystick.State.IsInRollMode then -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) end -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); Joystick.State.IsInRollMode = true ]] end @@ -96,19 +96,39 @@ local bindGlobalRoll = function(axis) -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup if not Joystick.State.IsInRollMode then -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) end -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); Joystick.State.IsInRollMode = true ]] end +local permaBindLocalRoll = function(axis) + return [[ + -- Save current axis state + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + + -- Set new axis state + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + ]] +end + +local permaBindGlobalRoll = function(axis) + return [[ + -- Save current axis state + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + + -- Set new axis state + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + ]] +end + local unbindRoll = function(axis) return [[ -- Reset previous state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); ]] end @@ -193,16 +213,16 @@ asset.onInitialize(function() openspace.navigation.bindJoystickAxis(controller.Push[3], "Zoom", false, false, true, 40.0); openspace.navigation.bindJoystickAxis(controller.Tilt[1], "LocalRoll X", false, false, true, 35.0); - --[[openspace.navigation.bindJoystickButton( + openspace.navigation.bindJoystickButton( controller.LeftButton, - bindLocalRoll(controller.Tilt[1]), + permaBindLocalRoll(controller.Tilt[1]), "Switch to local roll mode" ) openspace.navigation.bindJoystickButton( controller.RightButton, - bindGlobalRoll(controller.Tilt[1]), + permaBindGlobalRoll(controller.Tilt[1]), "Switch to global roll mode" - )]]-- + ) end end) diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 3952f1ae42..7583c941e2 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -194,7 +194,7 @@ void JoystickCameraStates::setAxisMapping(int axis, AxisType mapping, global::joystickInputStates->at(axis).isStatic = true; } - _prevAxisValues[axis] = 0.f; + _prevAxisValues[axis] = global::joystickInputStates->axis(axis); } JoystickCameraStates::AxisInformation JoystickCameraStates::axisMapping(int axis) const { diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 504526ab2c..74dc1afa8d 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -227,10 +227,12 @@ int joystickAxis(lua_State* L) { lua_settop(L, 0); const bool invert = info.invert; const bool normalize = info.normalize; - ghoul::lua::push(L, ghoul::to_string(info.type), invert, normalize); + const bool isStatic = info.isStatic; + const float sensitivity = info.sensitivity; + ghoul::lua::push(L, ghoul::to_string(info.type), invert, normalize, isStatic, sensitivity); - ghoul_assert(lua_gettop(L) == 3, "Incorrect number of items left on stack"); - return 3; + ghoul_assert(lua_gettop(L) == 5, "Incorrect number of items left on stack"); + return 5; } int setJoystickAxisDeadzone(lua_State* L) { From 0f6423c2ccf1e3993febefb49c8eabfe52982f13 Mon Sep 17 00:00:00 2001 From: Emma Broman Date: Tue, 18 May 2021 12:45:55 +0200 Subject: [PATCH 23/43] Update documentation for time.interpolateTime Now also includes info about the optional second property --- src/util/time.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/util/time.cpp b/src/util/time.cpp index bd886aa9aa..84c677d36b 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -175,20 +175,21 @@ scripting::LuaLibrary Time::luaLibrary() { &luascriptfunctions::time_togglePause, {}, "", - "Toggles the pause function, i.e. temporarily setting the delta time to 0" - " and restoring it afterwards" + "Toggles the pause function, i.e. temporarily setting the delta time to " + "0 and restoring it afterwards" }, { "interpolateTime", &luascriptfunctions::time_interpolateTime, {}, "{number, string} [, number]", - "Sets the current simulation time to the " - "specified value. If the parameter is a number, the value is the number " + "Sets the current simulation time to the specified value. " + "If the first parameter is a number, the target is the number " "of seconds past the J2000 epoch. If it is a string, it has to be a " - "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS. " - "Note: providing time zone using the Z format is not supported. UTC is " - "assumed." + "valid ISO 8601-like date string of the format YYYY-MM-DDTHH:MN:SS " + "(Note: providing time zone using the Z format is not supported. UTC is " + "assumed). If a second input value is given, the interpolation is done " + "over the specified number of seconds." }, { "interpolateTimeRelative", From 107ed9f51cecd0ad80583a6da88a8610295891c9 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 18 May 2021 13:16:53 +0200 Subject: [PATCH 24/43] Fix issue when trying to print non-ascii character --- src/rendering/renderengine.cpp | 50 +++++++++++++++++----------------- src/util/screenlog.cpp | 4 +-- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 54fc03cfc2..5dcea92e9a 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -556,7 +556,10 @@ void RenderEngine::initializeGL() { { ZoneScopedN("Log") LINFO("Initializing Log"); - std::unique_ptr log = std::make_unique(ScreenLogTimeToLive); + std::unique_ptr log = std::make_unique( + ScreenLogTimeToLive, + ghoul::logging::LogLevel::Warning + ); _log = log.get(); ghoul::logging::LogManager::ref().addLog(std::move(log)); } @@ -1406,32 +1409,29 @@ void RenderEngine::renderScreenLog() { _log->removeExpiredEntries(); - constexpr const int MaxNumberMessages = 20; + constexpr const size_t MaxNumberMessages = 20; constexpr const int CategoryLength = 30; constexpr const int MessageLength = 280; constexpr const std::chrono::seconds FadeTime(5); const std::vector& entries = _log->entries(); - auto lastEntries = - entries.size() > MaxNumberMessages ? - std::make_pair(entries.rbegin(), entries.rbegin() + MaxNumberMessages) : - std::make_pair(entries.rbegin(), entries.rend()); - const glm::ivec2 fontRes = fontResolution(); - size_t nr = 1; + size_t nRows = 1; const auto now = std::chrono::steady_clock::now(); - for (auto& it = lastEntries.first; it != lastEntries.second; ++it) { + for (size_t i = 1; i <= std::min(MaxNumberMessages, entries.size()); i += 1) { ZoneScopedN("Entry") - std::chrono::duration diff = now - it->timeStamp; + const ScreenLog::LogEntry& it = entries[entries.size() - i]; + + const std::chrono::duration diff = now - it.timeStamp; float alpha = 1.f; - std::chrono::duration ttf = ScreenLogTimeToLive - FadeTime; + const std::chrono::duration ttf = ScreenLogTimeToLive - FadeTime; if (diff > ttf) { - double d = (diff - ttf).count(); - float t = static_cast(d) / static_cast(FadeTime.count()); - float p = 0.8f - t; + 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); } @@ -1439,8 +1439,8 @@ void RenderEngine::renderScreenLog() { if (alpha <= 0.f) { break; } - std::string_view message = std::string_view(it->message).substr(0, MessageLength); - nr += std::count(message.begin(), message.end(), '\n'); + 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); @@ -1450,9 +1450,9 @@ void RenderEngine::renderScreenLog() { char* end = fmt::format_to( buf.data(), "{:<15} {}{}", - it->timeString, - std::string_view(it->category).substr(0, CategoryLength), - it->category.length() > CategoryLength ? "..." : "" + 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()); @@ -1460,7 +1460,7 @@ void RenderEngine::renderScreenLog() { *_fontLog, glm::vec2( 10.f, - _fontLog->pointSize() * nr * 2 + fontRes.y * _verticalLogOffset + _fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset ), text, white @@ -1481,9 +1481,9 @@ void RenderEngine::renderScreenLog() { default: return white; } - }(it->level); + }(it.level); - const std::string_view lvl = ghoul::to_string(it->level); + 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()); @@ -1491,7 +1491,7 @@ void RenderEngine::renderScreenLog() { *_fontLog, glm::vec2( 10 + (30 + 3) * _fontLog->pointSize(), - _fontLog->pointSize() * nr * 2 + fontRes.y * _verticalLogOffset + _fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset ), levelText, color @@ -1502,12 +1502,12 @@ void RenderEngine::renderScreenLog() { *_fontLog, glm::vec2( 10 + 44 * _fontLog->pointSize(), - _fontLog->pointSize() * nr * 2 + fontRes.y * _verticalLogOffset + _fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset ), message, white ); - ++nr; + ++nRows; } } diff --git a/src/util/screenlog.cpp b/src/util/screenlog.cpp index 40e42f679e..95e9d099f5 100644 --- a/src/util/screenlog.cpp +++ b/src/util/screenlog.cpp @@ -36,7 +36,7 @@ ScreenLog::ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel) } void ScreenLog::removeExpiredEntries() { - std::lock_guard guard(_mutex); + 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); + std::lock_guard guard(_mutex); if (level >= _logLevel) { _entries.push_back({ level, From b9a8ec93de4c746c2f8839bc61e7cba3e145849d Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 18 May 2021 14:19:54 +0200 Subject: [PATCH 25/43] Update Ghoul version --- apps/OpenSpace/main.cpp | 2 +- ext/ghoul | 2 +- src/rendering/renderengine.cpp | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index b4a2d5bc6f..65dbd607a0 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -1078,7 +1078,7 @@ int main(int argc, char* argv[]) { bool showHelp = parser.execute(); if (showHelp) { - parser.displayHelp(std::cout); + std::cout << parser.helpText(); exit(EXIT_SUCCESS); } // Take an actual copy of the arguments diff --git a/ext/ghoul b/ext/ghoul index d85c1597e4..91b391e1ac 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit d85c1597e436898b67a6ebc9f98885032bec44bb +Subproject commit 91b391e1ac382786b4636a8340f9d8216455f4be diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 5dcea92e9a..e0ea8c6aa6 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -48,6 +48,7 @@ #include #include #include +#include #include #include #include From 0d06c68f6f38d9c1f5b09d436a9e7be5a0b83d04 Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Tue, 18 May 2021 16:41:15 +0200 Subject: [PATCH 26/43] Clean up --- data/assets/util/default_joystick.asset | 2 +- include/openspace/interaction/joystickcamerastates.h | 5 ++++- include/openspace/interaction/joystickinputstate.h | 9 ++------- src/interaction/joystickinputstate.cpp | 11 ----------- 4 files changed, 7 insertions(+), 20 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 1519bc54ff..96d28e8b33 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -135,7 +135,7 @@ end asset.onInitialize(function() -- Set the controller to the connected controller -- Currently: XBoxController, PS4Controller or SpaceMouse - local controller = SpaceMouse; + local controller = XBoxController; -- Case of XBoxController or PS4Controller if(controller.A ~= nil) then diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index da12dc7081..6b6d0a565a 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -62,7 +62,8 @@ public: AxisNormalize normalize = AxisNormalize::No; // The axis values can either go back to 0 when the joystick is released or it can - // stay at the value it was. The latter is static + // stay at the value it was before the joystick was released. + // The latter is called a static axis, when the values don't go back to 0. bool isStatic = false; float deadzone = 0.f; @@ -100,6 +101,8 @@ private: std::array _axisMapping; + // This array is used to store the old axis values from the previous frame, + // it is used to calculate the difference in the values in the case of a static axis std::array _prevAxisValues; struct ButtonInformation { diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index 48586c84ff..1384ed6293 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -72,7 +72,8 @@ struct JoystickInputState { std::array axes; /// The axis values can either go back to 0 when the joystick is released or it can - /// stay at the value it was. The latter is static + /// stay at the value it was before the joystick was released. + /// The latter is called a static axis, when the values don't go back to 0. bool isStatic = false; /// The number of buttons that this joystick possesses @@ -99,12 +100,6 @@ struct JoystickInputStates : public std::array */ float axis(int axis) const; - /** - * This function checks whether this joystick input has static axis or not - * \return If this joystick input has static axis or not - */ - bool isStatic() const; - /** * This functions checks whether any connected joystick has its \p button in the * passed \p action. Any joystick that does not posses the \p button, it will be diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp index c052806523..4a5537a353 100644 --- a/src/interaction/joystickinputstate.cpp +++ b/src/interaction/joystickinputstate.cpp @@ -54,17 +54,6 @@ float JoystickInputStates::axis(int axis) const { return res; } -bool JoystickInputStates::isStatic() const { - bool res = std::any_of( - begin(), - end(), - [](const JoystickInputState& state) { - return state.isStatic; - } - ); - return res; -} - bool JoystickInputStates::button(int button, JoystickAction action) const { ghoul_precondition(button >= 0, "button must be 0 or positive"); From 413639e9feef74eb56f23487898ef5cc1483e2eb Mon Sep 17 00:00:00 2001 From: GPayne Date: Wed, 19 May 2021 19:47:51 -0600 Subject: [PATCH 27/43] Fixed problems with pausing time and time management --- data/assets/util/default_keybindings.asset | 2 +- .../openspace/interaction/sessionrecording.h | 75 +++++++--- src/interaction/sessionrecording.cpp | 130 +++++++++++++----- src/interaction/sessionrecording_lua.inl | 59 ++++++++ src/util/time.cpp | 9 ++ src/util/time_lua.inl | 39 ++++++ 6 files changed, 264 insertions(+), 50 deletions(-) diff --git a/data/assets/util/default_keybindings.asset b/data/assets/util/default_keybindings.asset index 57d90ddaa2..158e5f623d 100644 --- a/data/assets/util/default_keybindings.asset +++ b/data/assets/util/default_keybindings.asset @@ -36,7 +36,7 @@ local Keybindings = { { Key = "SPACE", Name = "Toggle Pause (Interpolated)", - Command = "openspace.time.interpolateTogglePause()", + Command = "openspace.time.pauseToggleViaKeyboard()", Documentation = "Smoothly starts and stops the simulation time.", GuiPath = "/Simulation Speed", Local = true diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 10e7d6b601..7cce41be01 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -70,6 +70,18 @@ public: double timeSim; }; + /* + * Struct for storing a script substring that, if found in a saved script, + * will be replaced by its substringReplacement counterpart. + */ + struct ScriptSubstringReplace { + std::string substringFound; + std::string substringReplacement; + ScriptSubstringReplace(std::string found, std::string replace) + : substringFound(found) + , substringReplacement(replace) {}; + }; + static const size_t FileHeaderVersionLength = 5; char FileHeaderVersion[FileHeaderVersionLength+1] = "01.00"; char TargetConvertVersion[FileHeaderVersionLength+1] = "01.00"; @@ -186,6 +198,22 @@ public: */ void stopPlayback(); + /** + * Returns playback pause status. + * + * \return \c true if playback is paused + */ + bool isPlaybackPaused(); + + /** + * Pauses a playback session. This does both the normal pause functionality of + * setting simulation delta time to zero, and pausing the progression through the + * timeline. + * + * \param pause if true, then will set playback timeline progression to zero + */ + void setPlaybackPause(bool pause); + /** * Enables that rendered frames should be saved during playback * \param fps Number of frames per second. @@ -618,6 +646,9 @@ protected: unsigned int findIndexOfLastCameraKeyframeInTimeline(); bool doesTimelineEntryContainCamera(unsigned int index) const; std::vector> _stateChangeCallbacks; + bool doesStartWithSubstring(const std::string& s, const std::string& matchSubstr); + void trimCommandsFromScriptIfFound(std::string& script); + void replaceCommandsFromScriptIfFound(std::string& script); RecordedType getNextKeyframeType(); RecordedType getPrevKeyframeType(); @@ -666,7 +697,8 @@ protected: bool _playbackActive_time = false; bool _playbackActive_script = false; bool _hasHitEndOfCameraKeyframes = false; - bool _playbackStartedPaused = false; + bool _playbackPaused = false; + bool _playbackPausedWithinDeltaTimePause = false; double _playbackPauseOffset = 0.0; double _previousTime = 0.0; @@ -682,11 +714,6 @@ protected: bool _cleanupNeeded = false; const std::string scriptReturnPrefix = "return "; - std::vector scriptsUsingScenegraphNodesNavAccess = { - "RetargetAnchor", - "Anchor", - "Aim" - }; std::vector _keyframesCamera; std::vector _keyframesTime; @@ -702,19 +729,35 @@ protected: "NavigationHandler.OrbitalNavigator.RetargetAnchor", "NavigationHandler.OrbitalNavigator.RetargetAim" }; - //A script that begins with an exact match of any of the strings contained in _scriptRejects will not be recorded + //A script that begins with an exact match of any of the strings contained in + // _scriptRejects will not be recorded const std::vector _scriptRejects = { - "openspace.sessionRecording", - "openspace.scriptScheduler.clear", - "openspace.time.interpolatePause", - "openspace.time.interpolateTogglePause", - "openspace.time.setPause", - "openspace.time.togglePause" + "openspace.sessionRecording.enableTakeScreenShotDuringPlayback", + "openspace.sessionRecording.startPlayback", + "openspace.sessionRecording.stopPlayback", + "openspace.sessionRecording.startRecording", + "openspace.sessionRecording.stopRecording", + "openspace.scriptScheduler.clear" }; const std::vector _navScriptsUsingNodes = { - "RetargetAnchor", - "Anchor", - "Aim" + "RetargetAnchor", + "Anchor", + "Aim" + }; + //Any script snippet included in this vector will be trimmed from any script + // from the script manager, before it is recorded in the session recording file. + // The remainder of the script will be retained. + const std::vector _scriptsToBeTrimmed = { + "openspace.sessionRecording.togglePlaybackPause" + }; + //Any script snippet included in this vector will be trimmed from any script + // from the script manager, before it is recorded in the session recording file. + // The remainder of the script will be retained. + const std::vector _scriptsToBeReplaced = { + { + "openspace.time.pauseToggleViaKeyboard", + "openspace.time.interpolateTogglePause" + } }; std::vector _loadedNodes; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index cb7d8bcf83..bb4675b160 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -236,6 +236,7 @@ bool SessionRecording::startRecording(const std::string& filename) { global::timeManager->time().j2000Seconds() }; + recordCurrentTimePauseState(); recordCurrentTimeRate(); LINFO("Session recording started"); } @@ -252,7 +253,7 @@ void SessionRecording::recordCurrentTimePauseState() { void SessionRecording::recordCurrentTimeRate() { std::string initialTimeRateCommand = fmt::format( - "openspace.time.setDeltaTime({})", global::timeManager->deltaTime() + "openspace.time.setDeltaTime({})", global::timeManager->targetDeltaTime() ); saveScriptKeyframeToPropertiesBaseline(initialTimeRateCommand); } @@ -437,7 +438,7 @@ bool SessionRecording::startPlayback(std::string& filename, system_clock::duration::period::den / system_clock::duration::period::num; _saveRendering_isFirstFrame = true; _playbackPauseOffset = 0.0; - _playbackStartedPaused = global::timeManager->isPaused(); + _playbackPaused = false; //Set playback flags to true for all modes _playbackActive_camera = true; @@ -482,6 +483,27 @@ bool SessionRecording::startPlayback(std::string& filename, return true; } +bool SessionRecording::isPlaybackPaused() { + return (_state == SessionState::Playback && _playbackPaused); +} + +void SessionRecording::setPlaybackPause(bool pause) { + if (_state == SessionState::Playback) { + if (pause && !_playbackPaused) { + _playbackPausedWithinDeltaTimePause = global::timeManager->isPaused(); + if (!_playbackPausedWithinDeltaTimePause) { + global::timeManager->setPause(true); + } + } + else if (!pause && _playbackPaused) { + if (!_playbackPausedWithinDeltaTimePause) { + global::timeManager->setPause(false); + } + } + _playbackPaused = pause; + } +} + bool SessionRecording::findFirstCameraKeyframeInTimeline() { bool foundCameraKeyframe = false; for (unsigned int i = 0; i < _timeline.size(); i++) { @@ -588,7 +610,7 @@ void SessionRecording::cleanUpPlayback() { _saveRenderingDuringPlayback = false; _saveRendering_isFirstFrame = true; _playbackPauseOffset = 0.0; - _playbackStartedPaused = false; + _playbackPaused = false; _cleanupNeeded = false; } @@ -768,15 +790,16 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, void SessionRecording::saveScriptKeyframeToTimeline(std::string script) { - size_t substringStartIdx = 0; - if (script.substr(0, scriptReturnPrefix.length()).compare(scriptReturnPrefix) == 0) { - substringStartIdx += scriptReturnPrefix.length(); + if (doesStartWithSubstring(script, scriptReturnPrefix)) { + script = script.substr(scriptReturnPrefix.length()); } for (std::string reject : _scriptRejects) { - if (script.substr(substringStartIdx, reject.length()).compare(reject) == 0) { + if (doesStartWithSubstring(script, reject)) { return; } } + trimCommandsFromScriptIfFound(script); + replaceCommandsFromScriptIfFound(script); datamessagestructures::ScriptMessage sm = _externInteract.generateScriptMessage(script); @@ -784,8 +807,13 @@ void SessionRecording::saveScriptKeyframeToTimeline(std::string script) addKeyframe(times, sm._script, _playbackLineNum); } -void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script) +bool SessionRecording::doesStartWithSubstring(const std::string& s, + const std::string& matchSubstr) { + return (s.substr(0, matchSubstr.length()).compare(matchSubstr) == 0); +} + +void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script) { Timestamps times = generateCurrentTimestamp3(global::windowDelegate->applicationTime()); size_t indexIntoScriptKeyframesFromMainTimeline @@ -800,6 +828,28 @@ void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script ); } +void SessionRecording::trimCommandsFromScriptIfFound(std::string& script) +{ + for (std::string trimSnippet : _scriptsToBeTrimmed) { + auto findIdx = script.find(trimSnippet); + if (findIdx != std::string::npos) { + auto findClosingParens = script.find_first_of(')', findIdx); + script.erase(findIdx, findClosingParens + 1); + } + } +} + +void SessionRecording::replaceCommandsFromScriptIfFound(std::string& script) +{ + for (ScriptSubstringReplace replacementSnippet : _scriptsToBeReplaced) { + auto findIdx = script.find(replacementSnippet.substringFound); + if (findIdx != std::string::npos) { + script.erase(findIdx, replacementSnippet.substringFound.length()); + script.insert(findIdx, replacementSnippet.substringReplacement); + } + } +} + void SessionRecording::saveScriptKeyframeBinary(Timestamps& times, datamessagestructures::ScriptMessage& sm, unsigned char* smBuffer, @@ -849,8 +899,7 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) { bool SessionRecording::isPropertyAllowedForBaseline(const std::string& propString) { for (std::string reject : _propertyBaselineRejects) { - if (propString.substr(0, reject.length()).compare(reject) == 0) - { + if (doesStartWithSubstring(propString, reject)) { return false; } } @@ -1076,7 +1125,9 @@ double SessionRecording::fixedDeltaTimeDuringFrameOutput() const { } } -std::chrono::steady_clock::time_point SessionRecording::currentPlaybackInterpolationTime() const { +std::chrono::steady_clock::time_point +SessionRecording::currentPlaybackInterpolationTime() const +{ return _saveRenderingCurrentRecordedTime_interpolation; } @@ -1182,7 +1233,6 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times, )); return false; } - //times.timeOs = kf._timestamp; if (!file) { LINFO(fmt::format( @@ -1408,8 +1458,7 @@ bool SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { checkForScenegraphNodeAccess_Nav(subj, found); if (found.length() > 0) { auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), found); - if (it == _loadedNodes.end()) - { + if (it == _loadedNodes.end()) { LERROR(fmt::format( "Playback file requires scenegraph node '{}', which is " "not currently loaded", found @@ -1441,12 +1490,14 @@ void SessionRecording::checkForScenegraphNodeAccess_Nav(std::string& s, { const std::string nextTerm = "NavigationHandler.OrbitalNavigator."; auto posNav = s.find(nextTerm); - for (std::string accessName : _navScriptsUsingNodes) { - if (s.substr(posNav + nextTerm.length()).rfind(accessName) == 0) { - std::string postName = s.substr(posNav + nextTerm.length() - + accessName.length() + 2); - eraseSpacesFromString(postName); - result = getNameFromSurroundingQuotes(postName); + if (posNav != std::string::npos) { + for (std::string accessName : _navScriptsUsingNodes) { + if (s.substr(posNav + nextTerm.length()).rfind(accessName) == 0) { + std::string postName = s.substr(posNav + nextTerm.length() + + accessName.length() + 2); + eraseSpacesFromString(postName); + result = getNameFromSurroundingQuotes(postName); + } } } } @@ -1474,8 +1525,7 @@ bool SessionRecording::checkIfInitialFocusNodeIsLoaded(unsigned int camIdx1) { std::string startFocusNode = _keyframesCamera[_timeline[camIdx1].idxIntoKeyframeTypeArray].focusNode; auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), startFocusNode); - if (it == _loadedNodes.end()) - { + if (it == _loadedNodes.end()) { LERROR(fmt::format( "Playback file requires scenegraph node '{}', which is " "not currently loaded", startFocusNode @@ -1671,17 +1721,9 @@ void SessionRecording::moveAheadInTime() { using namespace std::chrono; bool paused = global::timeManager->isPaused(); - if (paused) { - if (_playbackStartedPaused) { - return; - } - else { - _playbackPauseOffset - += global::windowDelegate->applicationTime() - _previousTime; - } - } - else { - _playbackStartedPaused = false; + if (_playbackPaused) { + _playbackPauseOffset + += global::windowDelegate->applicationTime() - _previousTime; } _previousTime = global::windowDelegate->applicationTime(); @@ -2529,6 +2571,28 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "Performs a conversion of the specified file to the most most recent " "file format, creating a copy of the recording file." }, + { + "setPlaybackPause", + &luascriptfunctions::setPlaybackPause, + {}, + "bool", + "Pauses or resumes the playback progression through keyframes" + }, + { + "togglePlaybackPause", + &luascriptfunctions::togglePlaybackPause, + {}, + "", + "Toggles the pause function, i.e. temporarily setting the delta time to 0" + " and restoring it afterwards" + }, + { + "isPlayingBack", + & luascriptfunctions::isPlayingBack, + {}, + "", + "Returns true if session recording is currently playing back a recording" + } } }; } diff --git a/src/interaction/sessionrecording_lua.inl b/src/interaction/sessionrecording_lua.inl index fe457ce3df..89f30ad370 100644 --- a/src/interaction/sessionrecording_lua.inl +++ b/src/interaction/sessionrecording_lua.inl @@ -185,4 +185,63 @@ int fileFormatConversion(lua_State* L) { return 0; } +int setPlaybackPause(lua_State* L) { + const int nArguments = lua_gettop(L); + + if (nArguments == 1) { + const bool pause = lua_toboolean(L, 1) == 1; + global::sessionRecording->setPlaybackPause(pause); + } + else { + lua_settop(L, 0); + return luaL_error( + L, + "bad number of arguments, expected 1, got %i", + nArguments + ); + } + + lua_settop(L, 0); + ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); + return 0; +} + +int togglePlaybackPause(lua_State* L) { + const int nArguments = lua_gettop(L); + + if (nArguments == 0) { + bool isPlaybackPaused = global::sessionRecording->isPlaybackPaused(); + global::sessionRecording->setPlaybackPause(!isPlaybackPaused); + } + else { + lua_settop(L, 0); + return luaL_error( + L, + "bad number of arguments, expected 0, got %i", + nArguments + ); + } + + lua_settop(L, 0); + ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); + return 0; +} + +int isPlayingBack(lua_State* L) { + const int nArguments = lua_gettop(L); + + if (nArguments != 0) { + lua_settop(L, 0); + return luaL_error( + L, + "bad number of arguments, expected 0, got %i", + nArguments + ); + } + + ghoul::lua::push(L, global::sessionRecording->isPlayingBack()); + ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); + return 1; +} + } // namespace openspace::luascriptfunctions diff --git a/src/util/time.cpp b/src/util/time.cpp index bd886aa9aa..189238e8b3 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -264,6 +264,15 @@ scripting::LuaLibrary Time::luaLibrary() { " and restoring it afterwards. If an input value is given, the " "interpolation is done over the specified number of seconds." }, + { + "pauseToggleViaKeyboard", + &luascriptfunctions::time_pauseToggleViaKeyboard, + {}, + "", + "Toggles the pause function from a keypress. This function behaves like" + " interpolateTogglePause during normal mode, and behaves like" + " sessionRecording.pausePlayback when playing-back a recording." + }, { "currentTime", &luascriptfunctions::time_currentTime, diff --git a/src/util/time_lua.inl b/src/util/time_lua.inl index 95ebcd4d11..185567f97b 100644 --- a/src/util/time_lua.inl +++ b/src/util/time_lua.inl @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -379,6 +380,44 @@ int time_interpolateTogglePause(lua_State* L) { return 0; } +/** +* \ingroup LuaScripts +* time_pauseToggleViaKeyboard(): +* This allows for a keypress (via keybinding) to have dual functionality. In normal +* operational mode it will behave just like time_interpolateTogglePause, but +* during playback of a session recording it will pause the playback without manipulating +* the delta time. +*/ +int time_pauseToggleViaKeyboard(lua_State* L) { + const int nArguments = lua_gettop(L); + + if (nArguments == 0) { + if (global::sessionRecording->isPlayingBack()) { + bool isPlaybackPaused = global::sessionRecording->isPlaybackPaused(); + global::sessionRecording->setPlaybackPause(!isPlaybackPaused); + } + else { + const bool pause = !global::timeManager->isPaused(); + global::timeManager->interpolatePause(pause, + pause ? + global::timeManager->defaultPauseInterpolationDuration() : + global::timeManager->defaultUnpauseInterpolationDuration() + ); + } + } + else { + lua_settop(L, 0); + return luaL_error( + L, + "bad number of arguments, expected 0 or 1, got %i", + nArguments + ); + } + + lua_settop(L, 0); + ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); + return 0; +} /** * \ingroup LuaScripts From 80eba3bdd98d62eab396d21b35e5f0549456a016 Mon Sep 17 00:00:00 2001 From: Malin Ejdbo Date: Thu, 20 May 2021 13:44:45 +0200 Subject: [PATCH 28/43] Address PR comments --- data/assets/util/default_joystick.asset | 18 +++++++++--------- .../interaction/joystickcamerastates.h | 8 ++++---- .../openspace/interaction/joystickinputstate.h | 4 ++-- .../openspace/interaction/navigationhandler.h | 2 +- src/interaction/joystickcamerastates.cpp | 12 ++++++------ src/interaction/navigationhandler.cpp | 4 ++-- src/interaction/navigationhandler_lua.inl | 8 ++++---- 7 files changed, 28 insertions(+), 28 deletions(-) diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 96d28e8b33..8ecce48410 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -82,11 +82,11 @@ local bindLocalRoll = function(axis) -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup if not Joystick.State.IsInRollMode then -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) end -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity); Joystick.State.IsInRollMode = true ]] end @@ -96,11 +96,11 @@ local bindGlobalRoll = function(axis) -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup if not Joystick.State.IsInRollMode then -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) end -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity); Joystick.State.IsInRollMode = true ]] end @@ -108,27 +108,27 @@ end local permaBindLocalRoll = function(axis) return [[ -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity); ]] end local permaBindGlobalRoll = function(axis) return [[ -- Save current axis state - Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity = openspace.navigation.joystickAxis(]] .. axis .. [[) -- Set new axis state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity); ]] end local unbindRoll = function(axis) return [[ -- Reset previous state - openspace.navigation.bindJoystickAxis(]] .. axis .. [[, Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Static, Joystick.State.Axis.Sensitivity); + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized, Joystick.State.Axis.Sticky, Joystick.State.Axis.Sensitivity); ]] end diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index 6b6d0a565a..15188faf26 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -63,8 +63,8 @@ public: // 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 static axis, when the values don't go back to 0. - bool isStatic = false; + // The latter is called a sticky axis, when the values don't go back to 0. + bool isSticky = false; float deadzone = 0.f; @@ -79,7 +79,7 @@ public: void setAxisMapping(int axis, AxisType mapping, AxisInvert shouldInvert = AxisInvert::No, AxisNormalize shouldNormalize = AxisNormalize::No, - bool isStatic = false, double sensitivity = 0.0 + bool isSticky = false, double sensitivity = 0.0 ); AxisInformation axisMapping(int axis) const; @@ -102,7 +102,7 @@ private: std::array _axisMapping; // This array is used to store the old axis values from the previous frame, - // it is used to calculate the difference in the values in the case of a static axis + // it is used to calculate the difference in the values in the case of a sticky axis std::array _prevAxisValues; struct ButtonInformation { diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index 1384ed6293..c5d320c7b8 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -73,8 +73,8 @@ struct JoystickInputState { /// 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 static axis, when the values don't go back to 0. - bool isStatic = false; + /// The latter is called a sticky axis, when the values don't go back to 0. + bool isSticky = false; /// The number of buttons that this joystick possesses int nButtons = 0; diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index a6b06b2633..15d080330b 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -116,7 +116,7 @@ public: JoystickCameraStates::AxisInvert::No, JoystickCameraStates::AxisNormalize shouldNormalize = JoystickCameraStates::AxisNormalize::No, - bool isStatic = false, double sensitivity = 0.0 + bool isSticky = false, double sensitivity = 0.0 ); JoystickCameraStates::AxisInformation joystickAxisMapping(int axis) const; diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 7583c941e2..91d89fe274 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -55,7 +55,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, float rawValue = inputState.joystickAxis(i); float value = rawValue; - if (t.isStatic) { + if (t.isSticky) { value = rawValue - _prevAxisValues[i]; _prevAxisValues[i] = rawValue; } @@ -72,7 +72,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, value *= -1.f; } - if (std::fabs(t.sensitivity) > std::numeric_limits().epsilon()) { + if (std::abs(t.sensitivity) > std::numeric_limits::epsilon()) { value = static_cast(value * t.sensitivity * _sensitivity); } else { @@ -179,7 +179,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, void JoystickCameraStates::setAxisMapping(int axis, AxisType mapping, AxisInvert shouldInvert, AxisNormalize shouldNormalize, - bool isStatic, + bool isSticky, double sensitivity) { ghoul_assert(axis < JoystickInputState::MaxAxes, "axis must be < MaxAxes"); @@ -187,11 +187,11 @@ void JoystickCameraStates::setAxisMapping(int axis, AxisType mapping, _axisMapping[axis].type = mapping; _axisMapping[axis].invert = shouldInvert; _axisMapping[axis].normalize = shouldNormalize; - _axisMapping[axis].isStatic = isStatic; + _axisMapping[axis].isSticky = isSticky; _axisMapping[axis].sensitivity = sensitivity; - if (isStatic) { - global::joystickInputStates->at(axis).isStatic = true; + if (isSticky) { + global::joystickInputStates->at(axis).isSticky = true; } _prevAxisValues[axis] = global::joystickInputStates->axis(axis); diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index b22b321940..93831d330a 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -493,7 +493,7 @@ void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, JoystickCameraStates::AxisInvert shouldInvert, JoystickCameraStates::AxisNormalize shouldNormalize, - bool isStatic, + bool isSticky, double sensitivity) { _orbitalNavigator.joystickStates().setAxisMapping( @@ -501,7 +501,7 @@ void NavigationHandler::setJoystickAxisMapping(int axis, mapping, shouldInvert, shouldNormalize, - isStatic, + isSticky, sensitivity ); } diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 74dc1afa8d..58ca4737f2 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -199,7 +199,7 @@ int bindJoystickAxis(lua_State* L) { const bool shouldInvert = n > 2 ? ghoul::lua::value(L, 3) : false; const bool shouldNormalize = n > 3 ? ghoul::lua::value(L, 4) : false; - const bool isStatic = n > 4 ? ghoul::lua::value(L, 5) : false; + const bool isSticky = n > 4 ? ghoul::lua::value(L, 5) : false; const double sensitivity = n > 5 ? ghoul::lua::value(L, 6) : 0.0; global::navigationHandler->setJoystickAxisMapping( @@ -207,7 +207,7 @@ int bindJoystickAxis(lua_State* L) { ghoul::from_string(axisType), interaction::JoystickCameraStates::AxisInvert(shouldInvert), interaction::JoystickCameraStates::AxisNormalize(shouldNormalize), - isStatic, + isSticky, sensitivity ); @@ -227,9 +227,9 @@ int joystickAxis(lua_State* L) { lua_settop(L, 0); const bool invert = info.invert; const bool normalize = info.normalize; - const bool isStatic = info.isStatic; + const bool isSticky = info.isSticky; const float sensitivity = info.sensitivity; - ghoul::lua::push(L, ghoul::to_string(info.type), invert, normalize, isStatic, sensitivity); + ghoul::lua::push(L, ghoul::to_string(info.type), invert, normalize, isSticky, sensitivity); ghoul_assert(lua_gettop(L) == 5, "Incorrect number of items left on stack"); return 5; From 5dfe4cb5c26d0bc44b47ad9c69277e961f31670a Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 20 May 2021 12:09:11 -0600 Subject: [PATCH 29/43] Added topic for new session recording pausing within playback --- .../openspace/interaction/sessionrecording.h | 4 +- .../src/topics/sessionrecordingtopic.cpp | 3 ++ src/interaction/sessionrecording.cpp | 40 +++++++++---------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 7cce41be01..633b38377e 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -61,7 +61,8 @@ public: enum class SessionState { Idle = 0, Recording, - Playback + Playback, + PlaybackPaused }; struct Timestamps { @@ -697,7 +698,6 @@ protected: bool _playbackActive_time = false; bool _playbackActive_script = false; bool _hasHitEndOfCameraKeyframes = false; - bool _playbackPaused = false; bool _playbackPausedWithinDeltaTimePause = false; double _playbackPauseOffset = 0.0; double _previousTime = 0.0; diff --git a/modules/server/src/topics/sessionrecordingtopic.cpp b/modules/server/src/topics/sessionrecordingtopic.cpp index 9b39e739c5..1a724b24fd 100644 --- a/modules/server/src/topics/sessionrecordingtopic.cpp +++ b/modules/server/src/topics/sessionrecordingtopic.cpp @@ -124,6 +124,9 @@ void SessionRecordingTopic::sendJsonData() { case SessionRecording::SessionState::Playback: stateString = "playing"; break; + case SessionRecording::SessionState::PlaybackPaused: + stateString = "playing-paused"; + break; default: stateString = "idle"; break; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index bb4675b160..e02ab90fa4 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -193,7 +193,7 @@ bool SessionRecording::startRecording(const std::string& filename) { LERROR("Unable to start recording while already in recording mode"); return false; } - else if (_state == SessionState::Playback) { + else if (_state == SessionState::Playback || _state == SessionState::PlaybackPaused) { LERROR("Unable to start recording while in session playback mode"); return false; } @@ -365,7 +365,7 @@ bool SessionRecording::startPlayback(std::string& filename, LERROR("Unable to start playback while in session recording mode"); return false; } - else if (_state == SessionState::Playback) { + else if (_state == SessionState::Playback || _state == SessionState::PlaybackPaused) { LERROR("Unable to start new playback while in session playback mode"); return false; } @@ -438,7 +438,6 @@ bool SessionRecording::startPlayback(std::string& filename, system_clock::duration::period::den / system_clock::duration::period::num; _saveRendering_isFirstFrame = true; _playbackPauseOffset = 0.0; - _playbackPaused = false; //Set playback flags to true for all modes _playbackActive_camera = true; @@ -484,23 +483,22 @@ bool SessionRecording::startPlayback(std::string& filename, } bool SessionRecording::isPlaybackPaused() { - return (_state == SessionState::Playback && _playbackPaused); + return (_state == SessionState::PlaybackPaused); } void SessionRecording::setPlaybackPause(bool pause) { - if (_state == SessionState::Playback) { - if (pause && !_playbackPaused) { - _playbackPausedWithinDeltaTimePause = global::timeManager->isPaused(); - if (!_playbackPausedWithinDeltaTimePause) { - global::timeManager->setPause(true); - } + if (pause && _state == SessionState::Playback) { + _playbackPausedWithinDeltaTimePause = global::timeManager->isPaused(); + if (!_playbackPausedWithinDeltaTimePause) { + global::timeManager->setPause(true); } - else if (!pause && _playbackPaused) { - if (!_playbackPausedWithinDeltaTimePause) { - global::timeManager->setPause(false); - } + _state = SessionState::PlaybackPaused; + } + else if (!pause && _state == SessionState::PlaybackPaused) { + if (!_playbackPausedWithinDeltaTimePause) { + global::timeManager->setPause(false); } - _playbackPaused = pause; + _state = SessionState::Playback; } } @@ -560,7 +558,7 @@ void SessionRecording::disableTakeScreenShotDuringPlayback() { } void SessionRecording::stopPlayback() { - if (_state == SessionState::Playback) { + if (_state == SessionState::Playback || _state == SessionState::PlaybackPaused) { _state = SessionState::Idle; _cleanupNeeded = true; LINFO("Session playback stopped"); @@ -610,7 +608,6 @@ void SessionRecording::cleanUpPlayback() { _saveRenderingDuringPlayback = false; _saveRendering_isFirstFrame = true; _playbackPauseOffset = 0.0; - _playbackPaused = false; _cleanupNeeded = false; } @@ -915,7 +912,7 @@ void SessionRecording::preSynchronization() { saveTimeKeyframeToTimeline(); } } - else if (_state == SessionState::Playback) { + else if (_state == SessionState::Playback || _state == SessionState::PlaybackPaused) { moveAheadInTime(); } else if (_cleanupNeeded) { @@ -960,11 +957,12 @@ bool SessionRecording::isRecording() const { } bool SessionRecording::isPlayingBack() const { - return (_state == SessionState::Playback); + return (_state == SessionState::Playback || _state == SessionState::PlaybackPaused); } bool SessionRecording::isSavingFramesDuringPlayback() const { - return (_state == SessionState::Playback && _saveRenderingDuringPlayback); + return ((_state == SessionState::Playback || _state == SessionState::PlaybackPaused) + && _saveRenderingDuringPlayback); } SessionRecording::SessionState SessionRecording::state() const { @@ -1721,7 +1719,7 @@ void SessionRecording::moveAheadInTime() { using namespace std::chrono; bool paused = global::timeManager->isPaused(); - if (_playbackPaused) { + if (_state == SessionState::PlaybackPaused) { _playbackPauseOffset += global::windowDelegate->applicationTime() - _previousTime; } From fb739d719ec4126e0b79875da8e3f58d8cb8604c Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 20 May 2021 12:44:29 -0600 Subject: [PATCH 30/43] Restored support for session recording files in any directory --- .../openspace/interaction/sessionrecording.h | 5 ++++- src/interaction/sessionrecording.cpp | 21 +++++++++---------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 633b38377e..06dc144c4c 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -182,7 +182,9 @@ public: /** * Starts a playback session, which can run in one of three different time modes. * - * \param filename file containing recorded keyframes to play back + * \param filename file containing recorded keyframes to play back. The file path + * is relative to the base recordings directory specified in the + * config file by the RECORDINGS variable * \param timeMode which of the 3 time modes to use for time reference during * \param forceSimTimeAtStart if true simulation time is forced to that of playback * playback: recorded time, application time, or simulation time. See the @@ -461,6 +463,7 @@ public: * \param prop The property being set */ void savePropertyBaseline(properties::Property& prop); + /** * Reads header information from a session recording file * diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index e02ab90fa4..9961b8db74 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -346,10 +346,6 @@ bool SessionRecording::startPlayback(std::string& filename, KeyframeTimeRef timeMode, bool forceSimTimeAtStart) { - if (isPath(filename)) { - LERROR("Playback filename must not contain path (/) elements"); - return false; - } std::string absFilename; //Run through conversion in case file is older. Does nothing if the file format // is up-to-date @@ -2135,9 +2131,6 @@ void SessionRecording::readFileIntoStringStream(std::string filename, std::ifstream& inputFstream, std::stringstream& stream) { - if (isPath(filename)) { - throw ConversionError("Playback filename must not contain path (/) elements"); - } std::string conversionInFilename = absPath("${RECORDINGS}/" + filename); if (!FileSys.fileExists(conversionInFilename)) { throw ConversionError(fmt::format( @@ -2508,7 +2501,9 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "the time since the recording was started (the same relative time " "applies to the playback). When playback starts, the simulation time " "is automatically set to what it was at recording time. The string " - "argument is the filename to pull playback keyframes from." + "argument is the filename to pull playback keyframes from (the file " + "path is relative to the RECORDINGS variable specified in the config " + "file)." }, { "startPlaybackApplicationTime", @@ -2517,7 +2512,9 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "string", "Starts a playback session with keyframe times that are relative to " "application time (seconds since OpenSpace application started). " - "The string argument is the filename to pull playback keyframes from." + "The string argument is the filename to pull playback keyframes from " + "(the file path is relative to the RECORDINGS variable specified in the " + "config file)." }, { "startPlaybackRecordedTime", @@ -2527,7 +2524,8 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "Starts a playback session with keyframe times that are relative to " "the time since the recording was started (the same relative time " "applies to the playback). The string argument is the filename to pull " - "playback keyframes from." + "playback keyframes from (the file path is relative to the RECORDINGS " + "variable specified in the config file)." }, { "startPlaybackSimulationTime", @@ -2536,7 +2534,8 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "string", "Starts a playback session with keyframe times that are relative to " "the simulated date & time. The string argument is the filename to pull " - "playback keyframes from." + "playback keyframes from (the file path is relative to the RECORDINGS " + "variable specified in the config file)." }, { "stopPlayback", From 3f9ae245c71da22f98ee7fc482f20fc845d5aa87 Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 20 May 2021 19:06:39 -0600 Subject: [PATCH 31/43] Added loop playback option to repeat playback file --- .../openspace/interaction/sessionrecording.h | 10 +- src/interaction/sessionrecording.cpp | 116 ++++++++++++------ src/interaction/sessionrecording_lua.inl | 19 ++- 3 files changed, 104 insertions(+), 41 deletions(-) diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index 06dc144c4c..749f7badfe 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -189,11 +189,13 @@ public: * \param forceSimTimeAtStart if true simulation time is forced to that of playback * playback: recorded time, application time, or simulation time. See the * LuaLibrary entry for SessionRecording for details on these time modes + * \param loop if true then the file will playback in loop mode, continuously + * looping back to the beginning until it is manually stopped * * \return \c true if recording to file starts without errors */ bool startPlayback(std::string& filename, KeyframeTimeRef timeMode, - bool forceSimTimeAtStart); + bool forceSimTimeAtStart, bool loop); /** * Used to stop a playback in progress. If open, the playback file will be closed, @@ -622,6 +624,10 @@ protected: bool addKeyframeToTimeline(std::vector& timeline, RecordedType type, size_t indexIntoTypeKeyframes, Timestamps t3stamps, int lineNum); + void initializePlayback_time(double now); + void initializePlayback_modeFlags(); + bool initializePlayback_timeline(); + void initializePlayback_triggerStart(); void moveAheadInTime(); void lookForNonCameraKeyframesThatHaveComeDue(double currTime); void updateCameraWithOrWithoutNewKeyframes(double currTime); @@ -702,6 +708,8 @@ protected: bool _playbackActive_script = false; bool _hasHitEndOfCameraKeyframes = false; bool _playbackPausedWithinDeltaTimePause = false; + bool _playbackLoopMode = false; + bool _playbackForceSimTimeAtStart = false; double _playbackPauseOffset = 0.0; double _previousTime = 0.0; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 9961b8db74..0adee7253f 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -344,7 +344,8 @@ void SessionRecording::stopRecording() { bool SessionRecording::startPlayback(std::string& filename, KeyframeTimeRef timeMode, - bool forceSimTimeAtStart) + bool forceSimTimeAtStart, + bool loop) { std::string absFilename; //Run through conversion in case file is older. Does nothing if the file format @@ -374,6 +375,7 @@ bool SessionRecording::startPlayback(std::string& filename, _playbackLineNum = 1; _playbackFilename = absFilename; + _playbackLoopMode = loop; // Open in ASCII first _playbackFile.open(_playbackFilename, std::ifstream::in); @@ -422,27 +424,13 @@ bool SessionRecording::startPlayback(std::string& filename, cleanUpPlayback(); return false; } - //Set time reference mode - using namespace std::chrono; - double now = global::windowDelegate->applicationTime(); - _timestampPlaybackStarted_application = now; - _timestampPlaybackStarted_simulation = global::timeManager->time().j2000Seconds(); - _timestampApplicationStarted_simulation = _timestampPlaybackStarted_simulation - now; - _playbackTimeReferenceMode = timeMode; - _saveRenderingCurrentRecordedTime_interpolation = steady_clock::now(); - _saveRenderingClockInterpolation_countsPerSec = - system_clock::duration::period::den / system_clock::duration::period::num; _saveRendering_isFirstFrame = true; - _playbackPauseOffset = 0.0; + //Set time reference mode + _playbackForceSimTimeAtStart = forceSimTimeAtStart; + double now = global::windowDelegate->applicationTime(); + _playbackTimeReferenceMode = timeMode; + initializePlayback_time(now); - //Set playback flags to true for all modes - _playbackActive_camera = true; - _playbackActive_script = true; - if (UsingTimeKeyframes) { - _playbackActive_time = true; - } - - global::navigationHandler->keyframeNavigator().setTimeReferenceMode(timeMode, now); global::scriptScheduler->setTimeReferenceMode(timeMode); _loadedNodes.clear(); populateListofLoadedSceneGraphNodes(); @@ -452,30 +440,69 @@ bool SessionRecording::startPlayback(std::string& filename, return false; } - _hasHitEndOfCameraKeyframes = false; - if (!findFirstCameraKeyframeInTimeline()) { + initializePlayback_modeFlags(); + if (!initializePlayback_timeline()) { cleanUpPlayback(); return false; } - if (forceSimTimeAtStart) { - Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps; - global::timeManager->setTimeNextFrame(Time(times.timeSim)); - _saveRenderingCurrentRecordedTime = times.timeRec; - } LINFO(fmt::format( "Playback session started: ({:8.3f},0.0,{:13.3f}) with {}/{}/{} entries, " "forceTime={}", now, _timestampPlaybackStarted_simulation, _keyframesCamera.size(), - _keyframesTime.size(), _keyframesScript.size(), (forceSimTimeAtStart ? 1 : 0) + _keyframesTime.size(), _keyframesScript.size(), + (_playbackForceSimTimeAtStart ? 1 : 0) )); + initializePlayback_triggerStart(); + + return true; +} + +void SessionRecording::initializePlayback_time(double now) { + using namespace std::chrono; + _timestampPlaybackStarted_application = now; + _timestampPlaybackStarted_simulation = global::timeManager->time().j2000Seconds(); + _timestampApplicationStarted_simulation = _timestampPlaybackStarted_simulation - now; + _saveRenderingCurrentRecordedTime_interpolation = steady_clock::now(); + _saveRenderingClockInterpolation_countsPerSec = + system_clock::duration::period::den / system_clock::duration::period::num; + _playbackPauseOffset = 0.0; + global::navigationHandler->keyframeNavigator().setTimeReferenceMode( + _playbackTimeReferenceMode, now); +} + +void SessionRecording::initializePlayback_modeFlags() { + _playbackActive_camera = true; + _playbackActive_script = true; + if (UsingTimeKeyframes) { + _playbackActive_time = true; + } + _hasHitEndOfCameraKeyframes = false; +} + +bool SessionRecording::initializePlayback_timeline() { + if (!findFirstCameraKeyframeInTimeline()) { + return false; + } + if (_playbackForceSimTimeAtStart) { + Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps; + global::timeManager->setTimeNextFrame(Time(times.timeSim)); + _saveRenderingCurrentRecordedTime = times.timeRec; + } + _idxTimeline_nonCamera = 0; + _idxTime = 0; + _idxScript = 0; + _idxTimeline_cameraPtrNext = 0; + _idxTimeline_cameraPtrPrev = 0; + return true; +} + +void SessionRecording::initializePlayback_triggerStart() { global::navigationHandler->triggerPlaybackStart(); global::scriptScheduler->triggerPlaybackStart(); global::timeManager->triggerPlaybackStart(); _state = SessionState::Playback; - - return true; } bool SessionRecording::isPlaybackPaused() { @@ -536,9 +563,19 @@ void SessionRecording::signalPlaybackFinishedForComponent(RecordedType type) { } if (!_playbackActive_camera && !_playbackActive_time && !_playbackActive_script) { - _state = SessionState::Idle; - _cleanupNeeded = true; - LINFO("Playback session finished"); + if (_playbackLoopMode) { + //Loop back to the beginning to replay + _saveRenderingDuringPlayback = false; + initializePlayback_time(global::windowDelegate->applicationTime()); + initializePlayback_modeFlags(); + initializePlayback_timeline(); + initializePlayback_triggerStart(); + } + else { + _state = SessionState::Idle; + _cleanupNeeded = true; + LINFO("Playback session finished"); + } } } @@ -604,6 +641,8 @@ void SessionRecording::cleanUpPlayback() { _saveRenderingDuringPlayback = false; _saveRendering_isFirstFrame = true; _playbackPauseOffset = 0.0; + _playbackLoopMode = false; + _playbackForceSimTimeAtStart = false; _cleanupNeeded = false; } @@ -2496,14 +2535,15 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "startPlayback", &luascriptfunctions::startPlaybackDefault, {}, - "string", + "string [, bool]", "Starts a playback session with keyframe times that are relative to " "the time since the recording was started (the same relative time " "applies to the playback). When playback starts, the simulation time " "is automatically set to what it was at recording time. The string " "argument is the filename to pull playback keyframes from (the file " "path is relative to the RECORDINGS variable specified in the config " - "file)." + "file). If a second input value of true is given, then playback will " + "continually loop until it is manually stopped." }, { "startPlaybackApplicationTime", @@ -2520,12 +2560,14 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { "startPlaybackRecordedTime", &luascriptfunctions::startPlaybackRecordedTime, {}, - "string", + "string [, bool]", "Starts a playback session with keyframe times that are relative to " "the time since the recording was started (the same relative time " "applies to the playback). The string argument is the filename to pull " "playback keyframes from (the file path is relative to the RECORDINGS " - "variable specified in the config file)." + "variable specified in the config file). If a second input value of " + "true is given, then playback will continually loop until it is " + "manually stopped." }, { "startPlaybackSimulationTime", diff --git a/src/interaction/sessionrecording_lua.inl b/src/interaction/sessionrecording_lua.inl index 89f30ad370..dab45d5bce 100644 --- a/src/interaction/sessionrecording_lua.inl +++ b/src/interaction/sessionrecording_lua.inl @@ -84,6 +84,20 @@ int startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode, bool forceSimTimeAtStart) { using ghoul::lua::luaTypeToString; + const int nArguments = lua_gettop(L); + bool loop = false; + + if (nArguments == 2) { + loop = lua_toboolean(L, 2) == 1; + } + else if (nArguments != 1) { + lua_settop(L, 0); + return luaL_error( + L, + "bad number of arguments, expected 1 or 2, got %i", + nArguments + ); + } const std::string playbackFilePath = ghoul::lua::value( L, @@ -98,7 +112,8 @@ int startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode, global::sessionRecording->startPlayback( const_cast(playbackFilePath), timeMode, - forceSimTimeAtStart + forceSimTimeAtStart, + loop ); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -106,7 +121,6 @@ int startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode, } int startPlaybackDefault(lua_State* L) { - ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::startPlaybackDefault"); using interaction::KeyframeNavigator; return startPlayback(L, interaction::KeyframeTimeRef::Relative_recordedStart, true); @@ -120,7 +134,6 @@ int startPlaybackApplicationTime(lua_State* L) { } int startPlaybackRecordedTime(lua_State* L) { - ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::startPlaybackRecordedTime"); using interaction::KeyframeNavigator; return startPlayback(L, interaction::KeyframeTimeRef::Relative_recordedStart, false); From 2513a5d2e37746025786a85f8eda370bb0fd1830 Mon Sep 17 00:00:00 2001 From: GPayne Date: Thu, 20 May 2021 20:28:18 -0600 Subject: [PATCH 32/43] Fix for call to remove_if --- src/interaction/sessionrecording.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 54e4e84bb7..b29a37bf07 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -1532,7 +1533,7 @@ void SessionRecording::checkForScenegraphNodeAccess_Nav(std::string& s, } void SessionRecording::eraseSpacesFromString(std::string& s) { - s.erase(std::remove_if(s.begin(), s.end(), std::isspace), s.end()); + s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end()); } std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) { From 1c85e327e41bec8433bf380faa318f7ebf1e68ff Mon Sep 17 00:00:00 2001 From: Emma Broman Date: Fri, 21 May 2021 15:21:40 +0200 Subject: [PATCH 33/43] Add RenderableGlobe docs to documentation page --- modules/globebrowsing/globebrowsingmodule.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index c8618ad63f..912efc92f2 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -454,6 +454,7 @@ std::vector GlobeBrowsingModule::documentations() globebrowsing::LayerAdjustment::Documentation(), globebrowsing::LayerManager::Documentation(), globebrowsing::GlobeTranslation::Documentation(), + globebrowsing::RenderableGlobe::Documentation(), GlobeLabelsComponent::Documentation(), RingsComponent::Documentation(), ShadowComponent::Documentation() From 3154d370434a0b5926b4ad7fcd860d113713c0d2 Mon Sep 17 00:00:00 2001 From: Micah Acinapura Date: Fri, 21 May 2021 13:04:24 -0400 Subject: [PATCH 34/43] filesystem fixes --- ext/ghoul | 2 +- src/util/httprequest.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ext/ghoul b/ext/ghoul index 91b391e1ac..d8430b5ac9 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 91b391e1ac382786b4636a8340f9d8216455f4be +Subproject commit d8430b5ac92329716f78093e5e8ff9a5cc63652e diff --git a/src/util/httprequest.cpp b/src/util/httprequest.cpp index 7e1ba8d541..2250aa80f9 100644 --- a/src/util/httprequest.cpp +++ b/src/util/httprequest.cpp @@ -406,21 +406,21 @@ bool HttpFileDownload::initDownload() { char buffer[255]; LERROR(fmt::format( "Cannot open file '{}': {}", - std::string(destinationFile), + std::string(_destination), std::string(strerror_r(errno, buffer, sizeof(buffer))) )); return false; #else LERROR(fmt::format( "Cannot open file '{}': {}", - std::string(destinationFile), + std::string(_destination), std::string(strerror(errno)) )); return false; #endif } - LERROR(fmt::format("Cannot open file {}", std::string(destinationFile))); + LERROR(fmt::format("Cannot open file {}", std::string(_destination))); return false; #endif } From 63e9deab5f40ea1d07e1ee08fffaa5d690786df0 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sun, 23 May 2021 00:42:44 +0200 Subject: [PATCH 35/43] Feature/stars (#1598) * Add the ability to remap SPECK variables to usage values --- data/assets/scene/digitaluniverse/stars.asset | 31 ++- .../digitaluniverse/stars_colormap.asset | 12 +- .../milkyway/exoplanets/exoplanets_data.asset | 4 +- data/assets/scene/milkyway/gaia/apogee.asset | 12 +- data/assets/scene/milkyway/gaia/galah.asset | 12 +- .../objects/orionnebula/cluster.asset | 12 +- data/assets/scene/milkyway/stars/denver.asset | 12 +- modules/space/rendering/renderablestars.cpp | 148 ++++++++++- modules/space/rendering/renderablestars.h | 12 + modules/space/shaders/star_fs.glsl | 44 ++-- modules/space/shaders/star_ge.glsl | 239 ++++++++++-------- modules/space/shaders/star_vs.glsl | 6 +- 12 files changed, 386 insertions(+), 158 deletions(-) diff --git a/data/assets/scene/digitaluniverse/stars.asset b/data/assets/scene/digitaluniverse/stars.asset index 3103cd6c9a..35a3565535 100644 --- a/data/assets/scene/digitaluniverse/stars.asset +++ b/data/assets/scene/digitaluniverse/stars.asset @@ -1,6 +1,6 @@ local assetHelper = asset.require('util/asset_helper') -local colorLUT = asset.require('./stars_colormap').BvColorLUT +local colormaps = asset.require('./stars_colormap').ColorMaps local textures = asset.syncedResource({ Name = "Stars Textures", @@ -30,10 +30,21 @@ local stars = { File = speck .. "/stars.speck", Texture = textures .. "/halo.png", --ShapeTexture = textures .. "/disc.png", - ColorMap = colorLUT .. "/colorbv.cmap", + ColorMap = colormaps .. "/colorbv.cmap", + OtherDataColorMap = colormaps .. "/viridis.cmap", MagnitudeExponent = 6.2, SizeComposition = "Distance Modulus", - RenderMethod = "Texture Based" -- or PSF + RenderMethod = "Texture Based", -- or PSF + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed" + } }, GUI = { Name = "Stars", @@ -55,12 +66,22 @@ local sunstar = { File = sunspeck .. "/sunstar.speck", Texture = textures .. "/halo.png", --ShapeTexture = textures .. "/disc.png", - ColorMap = colorLUT .. "/colorbv.cmap", + ColorMap = colormaps .. "/colorbv.cmap", MagnitudeExponent = 6.2, SizeComposition = "Distance Modulus", RenderMethod = "Texture Based", -- or PSF FadeInDistances = { 0.0001, 0.1 }, - RenderableType = "PostDeferredTransparent" + RenderableType = "PostDeferredTransparent", + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed", + } }, GUI = { Name = "Sun", diff --git a/data/assets/scene/digitaluniverse/stars_colormap.asset b/data/assets/scene/digitaluniverse/stars_colormap.asset index eb4cbc22e3..d8aaa83f1d 100644 --- a/data/assets/scene/digitaluniverse/stars_colormap.asset +++ b/data/assets/scene/digitaluniverse/stars_colormap.asset @@ -1,20 +1,20 @@ local assetHelper = asset.require('util/asset_helper') -local BvColorLUT = asset.syncedResource({ +local colormaps = asset.syncedResource({ Name = "Stars Color Table", Type = "HttpSynchronization", Identifier = "stars_colormap", Version = 2 }) -asset.export("BvColorLUT", BvColorLUT) +asset.export("ColorMaps", colormaps) asset.meta = { - Name = "Stars B-V Colormap", + Name = "Star Colormaps", Version = "2.0", - Description = [[A lookup table that maps a B-V color index to an RGB color. - The B-V values are in the range (-0.4, 2.0) and each line maps a value - in that range to a color]], + Description = [[Lookup tables used for star datasets, one of the tables map a B-V color + index to an RGB color. The B-V values are in the range (-0.4, 2.0) and each line maps + a value in that range to a color. The other table is the commonly used viridis map]], Author = "OpenSpace Team", URL = "https://www.amnh.org/research/hayden-planetarium/digital-universe", License = "AMNH Digital Universe" diff --git a/data/assets/scene/milkyway/exoplanets/exoplanets_data.asset b/data/assets/scene/milkyway/exoplanets/exoplanets_data.asset index 73d4f033a5..45597c4302 100644 --- a/data/assets/scene/milkyway/exoplanets/exoplanets_data.asset +++ b/data/assets/scene/milkyway/exoplanets/exoplanets_data.asset @@ -1,4 +1,4 @@ -local bvColorLUT = asset.require('scene/digitaluniverse/stars_colormap').BvColorLUT +local colormaps = asset.require('scene/digitaluniverse/stars_colormap').ColorMaps local DataPath = asset.syncedResource({ Name = "Exoplanet Data Files", @@ -15,7 +15,7 @@ asset.onInitialize(function () p = "Modules.Exoplanets.BvColormap"; if (openspace.getPropertyValue(p) == "") then - openspace.setPropertyValueSingle(p, bvColorLUT .. "/colorbv.cmap") + openspace.setPropertyValueSingle(p, colormaps .. "/colorbv.cmap") end end) diff --git a/data/assets/scene/milkyway/gaia/apogee.asset b/data/assets/scene/milkyway/gaia/apogee.asset index efa58038ff..12c495264a 100644 --- a/data/assets/scene/milkyway/gaia/apogee.asset +++ b/data/assets/scene/milkyway/gaia/apogee.asset @@ -39,7 +39,17 @@ local gaia_abundance_apogee = { ColorMap = colorLUT .. "/colorbv.cmap", OtherDataColorMap = colorLUT .. "/viridis.cmap", StaticFilter = -9999, - StaticFilterReplacement = 0.0 + StaticFilterReplacement = 0.0, + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed" + } }, GUI = { Path = "/Milky Way/Gaia" diff --git a/data/assets/scene/milkyway/gaia/galah.asset b/data/assets/scene/milkyway/gaia/galah.asset index c9163b2ff3..121ee8f510 100644 --- a/data/assets/scene/milkyway/gaia/galah.asset +++ b/data/assets/scene/milkyway/gaia/galah.asset @@ -39,7 +39,17 @@ local gaia_abundance_galah = { ColorMap = colorLUT .. "/colorbv.cmap", OtherDataColorMap = colorLUT .. "/viridis.cmap", StaticFilter = -9999, - StaticFilterReplacement = 0.0 + StaticFilterReplacement = 0.0, + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed" + } }, GUI = { Path = "/Milky Way/Gaia" diff --git a/data/assets/scene/milkyway/objects/orionnebula/cluster.asset b/data/assets/scene/milkyway/objects/orionnebula/cluster.asset index 2325788c80..0abd320818 100644 --- a/data/assets/scene/milkyway/objects/orionnebula/cluster.asset +++ b/data/assets/scene/milkyway/objects/orionnebula/cluster.asset @@ -19,7 +19,17 @@ local OrionClusterStars = { ColorMap = sync .. "/colorbv.cmap", MagnitudeExponent = 5.02, SizeComposition = "Distance Modulus", - RenderMethod = "Texture Based" + RenderMethod = "Texture Based", + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed" + } }, GUI = { Name = "Orion Nebula Star Cluster", diff --git a/data/assets/scene/milkyway/stars/denver.asset b/data/assets/scene/milkyway/stars/denver.asset index a1c2fbef55..4dc1621909 100644 --- a/data/assets/scene/milkyway/stars/denver.asset +++ b/data/assets/scene/milkyway/stars/denver.asset @@ -32,7 +32,17 @@ local object = { ColorMap = colorLUT .. "/denver_colorbv.cmap", MagnitudeExponent = 6.2, SizeComposition = "Distance Modulus", - RenderMethod = "Texture Based" -- or PSF + RenderMethod = "Texture Based", -- or PSF + DataMapping = { + Bv = "colorb_v", + Luminance = "lum", + AbsoluteMagnitude = "absmag", + ApparentMagnitude = "appmag", + Vx = "vx", + Vy = "vy", + Vz = "vz", + Speed = "speed" + } }, GUI = { Name = "Stars (Denver)", diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index d2af7317ab..f5c747ed1a 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -120,6 +120,61 @@ namespace { "to its color. The texture is used as a one dimensional lookup function." }; + constexpr openspace::properties::Property::PropertyInfo MappingBvInfo = { + "MappingBV", + "Mapping (bv-color)", + "The name of the variable in the speck file that is used as the b-v color " + "variable" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingLuminanceInfo = { + "MappingLuminance", + "Mapping (luminance)", + "The name of the variable in the speck file that is used as the luminance " + "variable" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingAbsMagnitudeInfo = { + "MappingAbsMagnitude", + "Mapping (absolute magnitude)", + "The name of the variable in the speck file that is used as the absolute " + "magnitude variable" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingAppMagnitudeInfo = { + "MappingAppMagnitude", + "Mapping (apparent magnitude)", + "The name of the variable in the speck file that is used as the apparent " + "magnitude variable" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingVxInfo = { + "MappingVx", + "Mapping (vx)", + "The name of the variable in the speck file that is used as the star velocity " + "along the x-axis" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingVyInfo = { + "MappingVy", + "Mapping (vy)", + "The name of the variable in the speck file that is used as the star velocity " + "along the y-axis" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingVzInfo = { + "MappingVz", + "Mapping (vz)", + "The name of the variable in the speck file that is used as the star velocity " + "along the z-axis" + }; + + constexpr openspace::properties::Property::PropertyInfo MappingSpeedInfo = { + "MappingSpeed", + "Mapping (speed)", + "The name of the variable in the speck file that is used as the speed" + }; + constexpr openspace::properties::Property::PropertyInfo ColorOptionInfo = { "ColorOption", "Color Option", @@ -361,11 +416,33 @@ namespace { // [[codegen::verbatim(SizeCompositionOptionInfo.description)]] std::optional sizeComposition; + struct DataMapping { + // [[codegen::verbatim(MappingBvInfo.description)]] + std::optional bv; + // [[codegen::verbatim(MappingLuminanceInfo.description)]] + std::optional luminance; + // [[codegen::verbatim(MappingAbsMagnitudeInfo.description)]] + std::optional absoluteMagnitude; + // [[codegen::verbatim(MappingAppMagnitudeInfo.description)]] + std::optional apparentMagnitude; + // [[codegen::verbatim(MappingVxInfo.description)]] + std::optional vx; + // [[codegen::verbatim(MappingVyInfo.description)]] + std::optional vy; + // [[codegen::verbatim(MappingVzInfo.description)]] + std::optional vz; + // [[codegen::verbatim(MappingSpeedInfo.description)]] + std::optional speed; + }; + // The mappings between data values and the variable names specified in the speck + // file + DataMapping dataMapping; + // [[codegen::verbatim(FadeInDistancesInfo.description)]] std::optional fadeInDistances; // [[codegen::verbatim(DisableFadeInInfo.description)]] - std::optional distableFadeIn; + std::optional disableFadeIn; }; #include "renderablestars_codegen.cpp" } // namespace @@ -383,6 +460,17 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) , _speckFile(SpeckFileInfo) , _colorTexturePath(ColorTextureInfo) //, _shapeTexturePath(ShapeTextureInfo) + , _dataMappingContainer({ "DataMapping", "Data Mapping" }) + , _dataMapping{ + properties::StringProperty(MappingBvInfo), + properties::StringProperty(MappingLuminanceInfo), + properties::StringProperty(MappingAbsMagnitudeInfo), + properties::StringProperty(MappingAppMagnitudeInfo), + properties::StringProperty(MappingVxInfo), + properties::StringProperty(MappingVyInfo), + properties::StringProperty(MappingVzInfo), + properties::StringProperty(MappingSpeedInfo) + } , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _otherDataOption( OtherDataOptionInfo, @@ -416,7 +504,7 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) , _p2Param(P2ParamInfo, 0.138f, 0.f, 1.f) , _spencerAlphaConst(AlphaConstInfo, 0.02f, 0.000001f, 5.f) , _moffatPSFParamOwner(MoffatPSFParamOwnerInfo) - , _FWHMConst(FWHMInfo, 10.4f, -100.f, 1000.f) + , _FWHMConst(FWHMInfo, 10.4f, 0.f, 100.f) , _moffatBetaConst(BetaInfo, 4.765f, 0.f, 100.f) , _renderingMethodOption( RenderMethodOptionInfo, @@ -440,6 +528,40 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) addProperty(_opacity); registerUpdateRenderBinFromOpacity(); + _dataMapping.bvColor = p.dataMapping.bv.value_or(""); + _dataMapping.bvColor.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.bvColor); + + _dataMapping.luminance = p.dataMapping.luminance.value_or(""); + _dataMapping.luminance.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.luminance); + + _dataMapping.absoluteMagnitude = p.dataMapping.absoluteMagnitude.value_or(""); + _dataMapping.absoluteMagnitude.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.absoluteMagnitude); + + _dataMapping.apparentMagnitude = p.dataMapping.apparentMagnitude.value_or(""); + _dataMapping.apparentMagnitude.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.apparentMagnitude); + + _dataMapping.vx = p.dataMapping.vx.value_or(""); + _dataMapping.vx.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.vx); + + _dataMapping.vy = p.dataMapping.vy.value_or(""); + _dataMapping.vy.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.vy); + + _dataMapping.vz = p.dataMapping.vz.value_or(""); + _dataMapping.vz.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.vz); + + _dataMapping.speed = p.dataMapping.speed.value_or(""); + _dataMapping.speed.onChange([this]() { _dataIsDirty = true; }); + _dataMappingContainer.addProperty(_dataMapping.speed); + + addPropertySubOwner(_dataMappingContainer); + _speckFile = p.speckFile.string(); _speckFile.onChange([&]() { _speckFileIsDirty = true; }); addProperty(_speckFile); @@ -1212,14 +1334,20 @@ void RenderableStars::loadData() { } std::vector RenderableStars::createDataSlice(ColorOption option) { - const int bvIdx = std::max(_dataset.index("colorb_v"), 0); - const int lumIdx = std::max(_dataset.index("lum"), 0); - const int absMagIdx = std::max(_dataset.index("absmag"), 0); - const int appMagIdx = std::max(_dataset.index("appmag"), 0); - const int vxIdx = std::max(_dataset.index("vx"), 0); - const int vyIdx = std::max(_dataset.index("vy"), 0); - const int vzIdx = std::max(_dataset.index("vz"), 0); - const int speedIdx = std::max(_dataset.index("speed"), 0); + const int bvIdx = std::max(_dataset.index(_dataMapping.bvColor.value()), 0); + const int lumIdx = std::max(_dataset.index(_dataMapping.luminance.value()), 0); + const int absMagIdx = std::max( + _dataset.index(_dataMapping.absoluteMagnitude.value()), + 0 + ); + const int appMagIdx = std::max( + _dataset.index(_dataMapping.apparentMagnitude.value()), + 0 + ); + const int vxIdx = std::max(_dataset.index(_dataMapping.vx.value()), 0); + const int vyIdx = std::max(_dataset.index(_dataMapping.vy.value()), 0); + const int vzIdx = std::max(_dataset.index(_dataMapping.vz.value()), 0); + const int speedIdx = std::max(_dataset.index(_dataMapping.speed.value()), 0); _otherDataRange = glm::vec2( std::numeric_limits::max(), diff --git a/modules/space/rendering/renderablestars.h b/modules/space/rendering/renderablestars.h index 663dd0ac06..0b6eb73a53 100644 --- a/modules/space/rendering/renderablestars.h +++ b/modules/space/rendering/renderablestars.h @@ -84,6 +84,18 @@ private: std::unique_ptr _colorTexture; std::unique_ptr _colorTextureFile; + properties::PropertyOwner _dataMappingContainer; + struct { + properties::StringProperty bvColor; + properties::StringProperty luminance; + properties::StringProperty absoluteMagnitude; + properties::StringProperty apparentMagnitude; + properties::StringProperty vx; + properties::StringProperty vy; + properties::StringProperty vz; + properties::StringProperty speed; + } _dataMapping; + properties::OptionProperty _colorOption; properties::OptionProperty _otherDataOption; properties::StringProperty _otherDataColorMapPath; diff --git a/modules/space/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl index a38dd238b1..24ac77cf6f 100644 --- a/modules/space/shaders/star_fs.glsl +++ b/modules/space/shaders/star_fs.glsl @@ -23,14 +23,13 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "floatoperations.glsl" // keep in sync with renderablestars.h:ColorOption enum -const int COLOROPTION_COLOR = 0; -const int COLOROPTION_VELOCITY = 1; -const int COLOROPTION_SPEED = 2; -const int COLOROPTION_OTHERDATA = 3; -const int COLOROPTION_FIXEDCOLOR = 4; +const int ColorOptionColor = 0; +const int ColorOptionVelocity = 1; +const int ColorOptionSpeed = 2; +const int ColorOptionOtherData = 3; +const int ColorOptionFixedColor = 4; uniform sampler1D colorTexture; uniform sampler2D psfTexture; @@ -44,12 +43,11 @@ uniform sampler1D otherDataTexture; uniform vec2 otherDataRange; uniform bool filterOutOfRange; -in vec4 vs_position; -in vec2 psfCoords; -flat in vec4 ge_bvLumAbsMagAppMag; +in vec3 vs_position; +in vec2 texCoords; +flat in float ge_bv; flat in vec3 ge_velocity; flat in float ge_speed; -flat in float ge_observationDistance; flat in float gs_screenSpaceDepth; vec4 bv2rgb(float bv) { @@ -59,32 +57,29 @@ vec4 bv2rgb(float bv) { } bool isOtherDataValueInRange() { - float t = (ge_bvLumAbsMagAppMag.x - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); + float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); return t >= 0.0 && t <= 1.0; } vec4 otherDataValue() { - float t = (ge_bvLumAbsMagAppMag.x - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); + float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); t = clamp(t, 0.0, 1.0); return texture(otherDataTexture, t); } Fragment getFragment() { - // Something in the color calculations need to be changed because before it was dependent - // on the gl blend functions since the abuffer was not involved - vec4 color = vec4(0.0); switch (colorOption) { - case COLOROPTION_COLOR: - color = bv2rgb(ge_bvLumAbsMagAppMag.x); + case ColorOptionColor: + color = bv2rgb(ge_bv); break; - case COLOROPTION_VELOCITY: + case ColorOptionVelocity: color = vec4(abs(ge_velocity), 0.5); break; - case COLOROPTION_SPEED: + case ColorOptionSpeed: // @TODO Include a transfer function here ---abock color = vec4(vec3(ge_speed), 0.5); break; - case COLOROPTION_OTHERDATA: + case ColorOptionOtherData: if (filterOutOfRange && !isOtherDataValueInRange()) { discard; } @@ -92,14 +87,13 @@ Fragment getFragment() { color = otherDataValue(); } break; - case COLOROPTION_FIXEDCOLOR: + case ColorOptionFixedColor: color = vec4(fixedColor, 1.0); break; } - vec4 textureColor = texture(psfTexture, 0.5 * psfCoords + 0.5); - vec4 fullColor = vec4(color.rgb, textureColor.a); - fullColor.a *= alphaValue; + vec4 textureColor = texture(psfTexture, texCoords); + vec4 fullColor = vec4(color.rgb, textureColor.a * alphaValue); if (fullColor.a < 0.001) { discard; @@ -108,7 +102,7 @@ Fragment getFragment() { Fragment frag; frag.color = fullColor; frag.depth = gs_screenSpaceDepth; - frag.gPosition = vs_position; + frag.gPosition = vec4(vs_position, 1.0); frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); frag.disableLDR2HDR = true; diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index 759927b7f1..0c832f69f6 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -24,7 +24,6 @@ #version __CONTEXT__ -#include "floatoperations.glsl" #include "PowerScaling/powerScalingMath.hglsl" layout(points) in; @@ -32,25 +31,20 @@ layout(triangle_strip, max_vertices = 4) out; in vec4 vs_bvLumAbsMagAppMag[]; in vec3 vs_velocity[]; -in vec4 vs_gPosition[]; in float vs_speed[]; -out vec4 vs_position; -out vec2 psfCoords; +out vec3 vs_position; +out vec2 texCoords; -flat out vec4 ge_bvLumAbsMagAppMag; +flat out float ge_bv; flat out vec3 ge_velocity; flat out float ge_speed; -flat out float ge_observationDistance; flat out float gs_screenSpaceDepth; uniform float magnitudeExponent; uniform dvec3 eyePosition; uniform dvec3 cameraUp; -// uniform float FWHM; -// uniform float betaConstant; - uniform int psfParamConf; uniform float lumCent; uniform float radiusCent; @@ -62,127 +56,168 @@ uniform dmat4 modelMatrix; const double PARSEC = 3.08567756E16; //const double PARSEC = 3.08567782E16; -const vec2 corners[4] = vec2[4]( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(1.0, 1.0), - vec2(0.0, 1.0) -); +// FRAGILE +// All of these values have to be synchronized with the values in the optionproperty +const int SizeCompositionOptionAppBrightness = 0; +const int SizeCompositionOptionLumSize = 1; +const int SizeCompositionOptionLumSizeAppBrightness = 2; +const int SizeCompositionOptionLumSizeAbsMagnitude = 3; +const int SizeCompositionOptionLumSizeAppMagnitude = 4; +const int SizeCompositionOptionLumSizeDistanceModulus = 5; -const float SunTemperature = 5800.0f; -const float SunAbsMagnitude = 4.83f; +const float SunTemperature = 5800.0; +const float SunAbsMagnitude = 4.83; const float SunRadius = 6.957E8; // meters float bvToKelvin(float bv) { - float tmp = 0.92f * bv; - return 4600.f * (1.f/(tmp+1.7f) +1.f/(tmp+0.62f)); + float tmp = 0.92 * bv; + return 4600 * (1.f / (tmp + 1.7) + 1.f / (tmp + 0.62)); +} + +double scaleForApparentBrightness(dvec3 dpos, float luminance) { + // Working like Partiview + double pSize = pow(10, 29.0 + magnitudeExponent); + float luminosity = luminance * 10.0; + double distanceToStar = length(dpos - eyePosition); + return (pSize * luminosity) / distanceToStar; +} + +double scaleForLuminositySize(float bv, float luminance, float absMagnitude) { + double adjustedLuminance = luminance + 5E9; + float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); + float temperature = bvToKelvin(bv); + float relativeTemperature = SunTemperature / temperature; + double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); + return (lumCent * adjustedLuminance + (radiusCent * starRadius)) * pow(10.0, magnitudeExponent); +} + +double scaleForLuminositySizeAppBrightness(dvec3 dpos, float bv, float luminance, float absMagnitude) { + double luminosity = double(1.0 - luminance); + double distanceToStarInParsecs = trunc(length(dpos - eyePosition) / PARSEC); + double apparentBrightness = luminosity / distanceToStarInParsecs; + float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); + float temperature = bvToKelvin(bv); + float relativeTemperature = SunTemperature / temperature; + double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); + + double scaledLuminance = lumCent * (luminance + 5E9); + double scaledStarRadius = radiusCent * starRadius; + double scaledBrightness = brightnessCent * apparentBrightness * 5E15; + return (scaledLuminance + scaledStarRadius + scaledBrightness) * pow(10.0, magnitudeExponent); +} + +double scaleForAbsoluteMagnitude(float absMagnitude) { + return (-absMagnitude + 35) * pow(10.0, magnitudeExponent + 8.5); +} + +double scaleForApparentMagnitude(dvec3 dpos, float absMag) { + double distanceToStarInMeters = length(dpos - eyePosition); + double distanceToCenterInMeters = length(eyePosition); + float distanceToStarInParsecs = float(distanceToStarInMeters/PARSEC); + //float appMag = absMag + 5*log(distanceToStarInParsecs) - 5.0; + float appMag = absMag + 5.0 * (log(distanceToStarInParsecs/10.0)/log(2.0)); + //appMag = vs_bvLumAbsMagAppMag[0].w; + + //scaleMultiply = (30.623 - appMag) * pow(10.0, magnitudeExponent + 7.0);// * + //float(distanceToStarInMeters/distanceToCenterInMeters); + + return (-appMag + 50.f) * pow(10.0, magnitudeExponent + 7.5f); + // return log(35.f + appMag) * pow(10.0, magnitudeExponent + 6.5f); + // return exp((35.f - appMag) * 0.2) * pow(10.0, magnitudeExponent + 2.5f); + // return appMag * pow(10.0, magnitudeExponent + 8.5f); + // return exp((-30.0 - appMag) * 0.45) * pow(10.0, magnitudeExponent + 8.f); + // return pow(10.0, (appMag - absMag)*(1.0/5.0) + 1.0) * pow(10.0, magnitudeExponent + 3.f); +} + +double scaleForDistanceModulus(float absMag) { + return exp((-30.623 - absMag) * 0.462) * pow(10.0, magnitudeExponent + 12.5) * 2000; } void main() { - vs_position = gl_in[0].gl_Position; // in object space - dvec4 dpos = modelMatrix * dvec4(vs_position); + vec3 pos = gl_in[0].gl_Position.xyz; + vs_position = pos; // in object space + dvec4 dpos = modelMatrix * dvec4(pos, 1.0); + + ge_bv = vs_bvLumAbsMagAppMag[0].x; + ge_velocity = vs_velocity[0]; + ge_speed = vs_speed[0]; - ge_bvLumAbsMagAppMag = vs_bvLumAbsMagAppMag[0]; - ge_velocity = vs_velocity[0]; - ge_speed = vs_speed[0]; - double scaleMultiply = 1.0; - if (psfParamConf == 0) { - // Working like Partiview - double luminosity = double(ge_bvLumAbsMagAppMag.y) * 10.0; - double pSize = pow(10, magnitudeExponent + 29.0); - double distanceToStar = length((dpos.xyz - eyePosition)); - double apparentBrightness = pSize * luminosity / (distanceToStar); - scaleMultiply = apparentBrightness; + if (psfParamConf == SizeCompositionOptionAppBrightness) { + float luminance = vs_bvLumAbsMagAppMag[0].y; + + scaleMultiply = scaleForApparentBrightness(dpos.xyz, luminance); } - else if (psfParamConf == 1) { - float L_over_Lsun = pow(2.51f, SunAbsMagnitude - ge_bvLumAbsMagAppMag.z); - float starTemperature = bvToKelvin(ge_bvLumAbsMagAppMag.x); - float starRadius = SunRadius * pow(SunTemperature/starTemperature, 2.f) * sqrt(L_over_Lsun); - scaleMultiply = ((lumCent * (ge_bvLumAbsMagAppMag.y + 5E9)) + - (radiusCent * double(starRadius))) * pow(10.0, magnitudeExponent); + else if (psfParamConf == SizeCompositionOptionLumSize) { + float bv = vs_bvLumAbsMagAppMag[0].x; + float luminance = vs_bvLumAbsMagAppMag[0].y; + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + + scaleMultiply = scaleForLuminositySize(bv, luminance, absMagnitude); } - else if (psfParamConf == 2) { - double luminosity = double(1.0 - ge_bvLumAbsMagAppMag.y); - double distanceToStarInParsecs = trunc(length(dpos.xyz - eyePosition) / PARSEC); - double apparentBrightness = luminosity / distanceToStarInParsecs; - float L_over_Lsun = pow(2.51f, SunAbsMagnitude - ge_bvLumAbsMagAppMag.z); - float starTemperature = bvToKelvin(ge_bvLumAbsMagAppMag.x); - float starRadius = SunRadius * pow(SunTemperature/starTemperature, 2.f) * - sqrt(L_over_Lsun); - scaleMultiply = ((lumCent * (ge_bvLumAbsMagAppMag.y + 5E9)) + - (radiusCent * double(starRadius)) + - (brightnessCent * apparentBrightness * 5E15)) * - pow(10.0, magnitudeExponent); + else if (psfParamConf == SizeCompositionOptionLumSizeAppBrightness) { + float bv = vs_bvLumAbsMagAppMag[0].x; + float luminance = vs_bvLumAbsMagAppMag[0].y; + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + + scaleMultiply = scaleForLuminositySizeAppBrightness(dpos.xyz, bv, luminance, absMagnitude); } - else if (psfParamConf == 3) { - float absMag = ge_bvLumAbsMagAppMag.z; - scaleMultiply = (-absMag + 35.f) * pow(10.0, magnitudeExponent + 8.5f); + else if (psfParamConf == SizeCompositionOptionLumSizeAbsMagnitude) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + + scaleMultiply = scaleForAbsoluteMagnitude(absMagnitude); } - else if (psfParamConf == 4) { - float absMag = vs_bvLumAbsMagAppMag[0].z; - double distanceToStarInMeters = length(dpos.xyz - eyePosition); - double distanceToCenterInMeters = length(eyePosition); - float distanceToStarInParsecs = float(distanceToStarInMeters/PARSEC); - //float appMag = absMag + 5*log(distanceToStarInParsecs) - 5.0; - float appMag = absMag + 5.0 * (log(distanceToStarInParsecs/10.0)/log(2.0)); - //appMag = vs_bvLumAbsMagAppMag[0].w; + else if (psfParamConf == SizeCompositionOptionLumSizeAppMagnitude) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + + scaleMultiply = scaleForApparentMagnitude(dpos.xyz, absMagnitude); + } + else if (psfParamConf == SizeCompositionOptionLumSizeDistanceModulus) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - //scaleMultiply = (30.623 - appMag) * pow(10.0, magnitudeExponent + 7.0);// * - //float(distanceToStarInMeters/distanceToCenterInMeters); - - //scaleMultiply = (-appMag + 50.f) * pow(10.0, magnitudeExponent + 7.5f); - //scaleMultiply = log(35.f + appMag) * pow(10.0, magnitudeExponent + 6.5f); - //scaleMultiply = exp((35.f - appMag) * 0.2) * pow(10.0, magnitudeExponent + 2.5f); - //scaleMultiply = appMag * pow(10.0, magnitudeExponent + 8.5f); - scaleMultiply = exp((-30.0 - appMag) * 0.45) * pow(10.0, magnitudeExponent + 8.f); - //scaleMultiply = pow(10.0, (appMag - absMag)*(1.0/5.0) + 1.0) * pow(10.0, magnitudeExponent + 3.f); - } - else if (psfParamConf == 5) { - float absMag = ge_bvLumAbsMagAppMag.z; - scaleMultiply = exp((-30.623 - absMag) * 0.462) * pow(10.0, magnitudeExponent + 12.5f) * 2000; + scaleMultiply = scaleForDistanceModulus(absMagnitude); } - dvec3 scaledRight = dvec3(0.0); - dvec3 scaledUp = dvec3(0.0); - vec4 bottomLeftVertex, bottomRightVertex, topLeftVertex, topRightVertex; - - dvec3 normal = normalize(eyePosition - dpos.xyz); + dvec3 normal = eyePosition - dpos.xyz; dvec3 newRight = normalize(cross(cameraUp, normal)); - dvec3 newUp = cross(normal, newRight); - scaledRight = scaleMultiply * newRight; - scaledUp = scaleMultiply * newUp; + dvec3 newUp = normalize(cross(normal, newRight)); + dvec3 scaledRight = scaleMultiply * newRight; + dvec3 scaledUp = scaleMultiply * newUp; - bottomLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - gs_screenSpaceDepth = bottomLeftVertex.w; + vec4 lowerLeft = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w)) + ); - topRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + vec4 upperRight = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w)) + ); - bottomRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); + vec4 lowerRight = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w)) + ); - topLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); - - // Build primitive - - gl_Position = bottomLeftVertex; - psfCoords = vec2(-1.0, -1.0); + vec4 upperLeft = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w)) + ); + + gs_screenSpaceDepth = lowerLeft.w; + + // Build primitive + gl_Position = lowerLeft; + texCoords = vec2(0.0, 0.0); EmitVertex(); - gl_Position = bottomRightVertex; - psfCoords = vec2(1.0, -1.0); + gl_Position = lowerRight; + texCoords = vec2(1.0,0.0); EmitVertex(); - gl_Position = topLeftVertex; - psfCoords = vec2(-1.0, 1.0); + gl_Position = upperLeft; + texCoords = vec2(0.0, 1.0); EmitVertex(); - gl_Position = topRightVertex; - psfCoords = vec2(1.0, 1.0); + gl_Position = upperRight; + texCoords = vec2(1.0, 1.0); EmitVertex(); EndPrimitive(); diff --git a/modules/space/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl index 754deb5ea5..3213cbc96a 100644 --- a/modules/space/shaders/star_vs.glsl +++ b/modules/space/shaders/star_vs.glsl @@ -24,8 +24,6 @@ #version __CONTEXT__ -#include "PowerScaling/powerScaling_vs.hglsl" - in vec3 in_position; in vec4 in_bvLumAbsMagAppMag; in vec3 in_velocity; @@ -37,8 +35,8 @@ out float vs_speed; void main() { vs_bvLumAbsMagAppMag = in_bvLumAbsMagAppMag; - vs_velocity = in_velocity; - vs_speed = in_speed; + vs_velocity = in_velocity; + vs_speed = in_speed; gl_Position = vec4(in_position, 1.0); } From 72a3c29160d636edb2e7a895266a1aea1cb995fd Mon Sep 17 00:00:00 2001 From: GPayne Date: Mon, 24 May 2021 23:36:45 -0600 Subject: [PATCH 36/43] Restored a few asserts on lua commands --- src/interaction/sessionrecording_lua.inl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/interaction/sessionrecording_lua.inl b/src/interaction/sessionrecording_lua.inl index dab45d5bce..520f074dd5 100644 --- a/src/interaction/sessionrecording_lua.inl +++ b/src/interaction/sessionrecording_lua.inl @@ -122,6 +122,7 @@ int startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode, int startPlaybackDefault(lua_State* L) { using interaction::KeyframeNavigator; + ghoul::lua::checkArgumentsAndThrow(L, {1, 2}, "lua::startPlaybackDefault"); return startPlayback(L, interaction::KeyframeTimeRef::Relative_recordedStart, true); } @@ -135,6 +136,7 @@ int startPlaybackApplicationTime(lua_State* L) { int startPlaybackRecordedTime(lua_State* L) { using interaction::KeyframeNavigator; + ghoul::lua::checkArgumentsAndThrow(L, {1, 2}, "lua::startPlaybackRecordedTime"); return startPlayback(L, interaction::KeyframeTimeRef::Relative_recordedStart, false); } From c3ba532bdb1bfe3732848eec9b2a01f2fa3bd54a Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 25 May 2021 14:08:33 +0200 Subject: [PATCH 37/43] Feature/cleanup (#1608) * Revert screenlog back to showing Info and above messages * Various code cleanup --- include/openspace/rendering/deferredcaster.h | 20 +- .../rendering/screenspacerenderable.h | 2 +- modules/atmosphere/CMakeLists.txt | 17 +- .../rendering/atmospheredeferredcaster.cpp | 1003 ++++++++--------- .../rendering/atmospheredeferredcaster.h | 77 +- .../rendering/renderableatmosphere.cpp | 39 +- .../rendering/renderableatmosphere.h | 12 - .../atmosphere/shaders/atmosphere_common.glsl | 369 +++--- .../shaders/atmosphere_deferred_fs.glsl | 976 +++++++--------- .../shaders/atmosphere_deferred_vs.glsl | 6 +- ...g_sup_calc_gs.glsl => calculation_gs.glsl} | 12 +- ...iance_calc_vs.glsl => calculation_vs.glsl} | 2 +- .../atmosphere/shaders/deltaE_calc_vs.glsl | 31 - .../atmosphere/shaders/deltaJ_calc_fs.glsl | 122 +- .../atmosphere/shaders/deltaJ_calc_gs.glsl | 39 - .../atmosphere/shaders/deltaJ_calc_vs.glsl | 31 - .../atmosphere/shaders/deltaS_calc_fs.glsl | 19 +- .../atmosphere/shaders/deltaS_calc_gs.glsl | 39 - .../atmosphere/shaders/deltaS_calc_vs.glsl | 31 - .../shaders/deltaS_sup_calc_fs.glsl | 19 +- .../shaders/deltaS_sup_calc_gs.glsl | 39 - .../shaders/deltaS_sup_calc_vs.glsl | 31 - .../shaders/inScattering_calc_fs.glsl | 87 +- .../shaders/inScattering_calc_gs.glsl | 39 - .../shaders/inScattering_calc_vs.glsl | 31 - .../shaders/inScattering_sup_calc_fs.glsl | 31 +- .../shaders/inScattering_sup_calc_vs.glsl | 31 - .../shaders/irradiance_calc_fs.glsl | 20 +- .../shaders/irradiance_final_fs.glsl | 2 +- .../shaders/irradiance_final_vs.glsl | 31 - .../shaders/irradiance_sup_calc_fs.glsl | 54 +- .../shaders/irradiance_sup_calc_vs.glsl | 31 - .../shaders/transmittance_calc_fs.glsl | 63 +- .../shaders/transmittance_calc_vs.glsl | 31 - modules/base/shaders/axes_fs.glsl | 2 +- modules/base/shaders/axes_vs.glsl | 2 +- modules/base/shaders/grid_fs.glsl | 5 +- modules/base/shaders/grid_vs.glsl | 4 +- modules/base/shaders/line_fs.glsl | 1 - modules/base/shaders/plane_fs.glsl | 8 +- modules/base/shaders/plane_vs.glsl | 6 +- modules/base/shaders/screenspace_fs.glsl | 23 +- modules/base/shaders/screenspace_vs.glsl | 13 +- modules/base/shaders/sphere_fs.glsl | 2 - modules/base/shaders/sphere_vs.glsl | 2 +- modules/cefwebgui/shaders/gui_fs.glsl | 5 +- modules/cefwebgui/shaders/gui_vs.glsl | 5 +- modules/digitaluniverse/CMakeLists.txt | 8 +- .../digitaluniverse/shaders/billboard_fs.glsl | 61 +- .../digitaluniverse/shaders/billboard_gs.glsl | 168 ++- .../digitaluniverse/shaders/billboard_vs.glsl | 6 +- .../shaders/billboardpolygon_gs.glsl | 48 +- .../shaders/billboardpolygon_vs.glsl | 2 +- .../digitaluniverse/shaders/dumesh_fs.glsl | 20 +- .../digitaluniverse/shaders/dumesh_vs.glsl | 18 +- modules/digitaluniverse/shaders/plane_fs.glsl | 35 +- modules/digitaluniverse/shaders/plane_vs.glsl | 11 +- .../digitaluniverse/shaders/points_fs.glsl | 55 - .../digitaluniverse/shaders/points_gs.glsl | 63 -- .../shaders/points_sprite_fs.glsl | 20 +- .../digitaluniverse/shaders/points_vs.glsl | 22 +- .../shaders/pointssprite_fs.glsl | 53 - .../shaders/pointssprite_vs.glsl | 48 - modules/exoplanets/shaders/orbitdisc_fs.glsl | 129 ++- modules/exoplanets/shaders/orbitdisc_vs.glsl | 13 +- modules/galaxy/rendering/renderablegalaxy.cpp | 4 +- modules/galaxy/shaders/billboard_fs.glsl | 29 +- modules/galaxy/shaders/billboard_ge.glsl | 95 +- modules/galaxy/shaders/billboard_vs.glsl | 4 +- modules/galaxy/shaders/galaxyraycast.glsl | 72 +- modules/galaxy/shaders/points_fs.glsl | 27 +- modules/galaxy/shaders/points_vs.glsl | 8 +- .../galaxy/shaders/raycasterbounds_fs.glsl | 18 +- .../galaxy/shaders/raycasterbounds_vs.glsl | 11 +- modules/globebrowsing/CMakeLists.txt | 10 +- .../shaders/advanced_rings_fs.glsl | 149 ++- .../shaders/advanced_rings_vs.glsl | 15 +- .../shaders/{blending.hglsl => blending.glsl} | 107 +- .../shaders/globalrenderer_vs.glsl | 129 ++- .../shaders/localrenderer_vs.glsl | 102 +- .../globebrowsing/shaders/renderer_fs.glsl | 303 +++-- modules/globebrowsing/shaders/rings_fs.glsl | 153 ++- .../globebrowsing/shaders/rings_geom_fs.glsl | 68 +- .../globebrowsing/shaders/rings_geom_vs.glsl | 13 +- modules/globebrowsing/shaders/rings_vs.glsl | 15 +- .../globebrowsing/shaders/smviewer_fs.glsl | 40 - .../globebrowsing/shaders/smviewer_vs.glsl | 51 - .../shaders/texturetilemapping.glsl | 457 ++++++++ .../shaders/texturetilemapping.hglsl | 461 -------- .../shaders/{tile.hglsl => tile.glsl} | 52 +- .../{tileheight.hglsl => tileheight.glsl} | 63 +- ...vertexskirt.hglsl => tilevertexskirt.glsl} | 10 +- modules/globebrowsing/src/renderableglobe.cpp | 2 - modules/globebrowsing/src/ringscomponent.cpp | 4 +- modules/globebrowsing/src/shadowcomponent.cpp | 31 - modules/globebrowsing/src/shadowcomponent.h | 5 - modules/imgui/shaders/gui_fs.glsl | 2 +- modules/imgui/shaders/gui_vs.glsl | 6 +- modules/imgui/src/guifilepathcomponent.cpp | 2 +- .../space/shaders/constellationbounds_fs.glsl | 12 +- .../space/shaders/constellationbounds_vs.glsl | 12 +- modules/space/shaders/convolution_fs.glsl | 52 +- modules/space/shaders/convolution_vs.glsl | 8 +- modules/space/shaders/debrisViz_fs.glsl | 95 +- modules/space/shaders/debrisViz_vs.glsl | 89 +- modules/space/shaders/habitablezone_fs.glsl | 68 +- modules/space/shaders/habitablezone_vs.glsl | 12 +- modules/space/shaders/psfToTexture_fs.glsl | 53 +- modules/space/shaders/psfToTexture_vs.glsl | 4 +- modules/space/shaders/rings_fs.glsl | 95 +- modules/space/shaders/rings_vs.glsl | 12 +- modules/space/shaders/star_fs.glsl | 92 +- modules/space/shaders/star_ge.glsl | 228 ++-- modules/space/shaders/star_vs.glsl | 8 +- .../dashboard/dashboarditeminstruments.cpp | 82 +- .../dashboard/dashboarditeminstruments.h | 13 +- .../rendering/renderablecrawlingline.cpp | 22 +- .../rendering/renderablecrawlingline.h | 2 - .../rendering/renderablefov.cpp | 210 ++-- .../rendering/renderablefov.h | 26 +- .../rendering/renderablemodelprojection.cpp | 150 ++- .../rendering/renderablemodelprojection.h | 14 +- .../rendering/renderableplaneprojection.cpp | 86 +- .../rendering/renderableplaneprojection.h | 1 - .../rendering/renderableplanetprojection.cpp | 289 ++--- .../rendering/renderableplanetprojection.h | 19 +- .../rendering/renderableshadowcylinder.cpp | 10 +- .../rendering/renderableshadowcylinder.h | 1 - .../shaders/crawlingline_fs.glsl | 13 +- .../shaders/crawlingline_vs.glsl | 12 +- .../shaders/dilation_fs.glsl | 92 +- .../shaders/dilation_vs.glsl | 4 +- .../spacecraftinstruments/shaders/fov_fs.glsl | 10 +- .../spacecraftinstruments/shaders/fov_vs.glsl | 78 +- .../shaders/renderableModelDepth_fs.glsl | 3 +- .../shaders/renderableModelDepth_vs.glsl | 4 +- .../shaders/renderableModelProjection_fs.glsl | 64 +- .../shaders/renderableModelProjection_vs.glsl | 20 +- .../shaders/renderableModel_fs.glsl | 93 +- .../shaders/renderableModel_vs.glsl | 24 +- .../renderablePlanetProjection_fs.glsl | 70 +- .../renderablePlanetProjection_vs.glsl | 4 +- .../shaders/renderablePlanet_fs.glsl | 66 +- .../shaders/renderablePlanet_vs.glsl | 55 +- .../shaders/terminatorshadow_fs.glsl | 12 +- .../shaders/terminatorshadow_vs.glsl | 28 +- .../spacecraftinstrumentsmodule.cpp | 7 +- .../util/hongkangparser.cpp | 47 +- .../util/hongkangparser.h | 1 - .../util/imagesequencer.cpp | 225 ++-- .../util/imagesequencer.h | 92 +- .../util/instrumentdecoder.cpp | 2 +- .../util/instrumenttimesparser.cpp | 104 +- .../util/labelparser.cpp | 47 +- .../spacecraftinstruments/util/labelparser.h | 13 - .../util/projectioncomponent.cpp | 172 +-- .../util/projectioncomponent.h | 2 +- .../util/scannerdecoder.cpp | 8 +- .../util/scannerdecoder.h | 2 - .../util/sequenceparser.cpp | 11 +- .../util/sequenceparser.h | 12 +- .../util/targetdecoder.cpp | 11 +- .../util/targetdecoder.h | 1 - modules/touch/shaders/marker_fs.glsl | 38 +- modules/touch/shaders/marker_vs.glsl | 7 +- modules/webbrowser/include/browserclient.h | 1 - modules/webbrowser/include/browserinstance.h | 14 +- modules/webbrowser/include/eventhandler.h | 16 +- modules/webbrowser/src/browserclient.cpp | 9 +- modules/webbrowser/src/browserinstance.cpp | 17 +- modules/webbrowser/src/cefhost.cpp | 23 +- .../webbrowser/src/defaultbrowserlauncher.cpp | 19 +- modules/webbrowser/src/eventhandler.cpp | 66 +- modules/webbrowser/src/screenspacebrowser.cpp | 33 +- modules/webbrowser/src/webbrowserapp.cpp | 1 - modules/webbrowser/webbrowsermodule.cpp | 24 +- modules/webbrowser/webbrowsermodule.h | 3 +- modules/webgui/webguimodule.cpp | 96 +- modules/webgui/webguimodule.h | 2 +- src/documentation/documentationengine.cpp | 2 +- src/rendering/framebufferrenderer.cpp | 14 +- src/rendering/renderengine.cpp | 5 +- src/rendering/screenspacerenderable.cpp | 12 +- 183 files changed, 4267 insertions(+), 6072 deletions(-) rename modules/atmosphere/shaders/{inScattering_sup_calc_gs.glsl => calculation_gs.glsl} (92%) rename modules/atmosphere/shaders/{irradiance_calc_vs.glsl => calculation_vs.glsl} (98%) delete mode 100644 modules/atmosphere/shaders/deltaE_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/deltaJ_calc_gs.glsl delete mode 100644 modules/atmosphere/shaders/deltaJ_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/deltaS_calc_gs.glsl delete mode 100644 modules/atmosphere/shaders/deltaS_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl delete mode 100644 modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/inScattering_calc_gs.glsl delete mode 100644 modules/atmosphere/shaders/inScattering_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/irradiance_final_vs.glsl delete mode 100644 modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl delete mode 100644 modules/atmosphere/shaders/transmittance_calc_vs.glsl delete mode 100644 modules/digitaluniverse/shaders/points_fs.glsl delete mode 100644 modules/digitaluniverse/shaders/points_gs.glsl delete mode 100644 modules/digitaluniverse/shaders/pointssprite_fs.glsl delete mode 100644 modules/digitaluniverse/shaders/pointssprite_vs.glsl rename modules/globebrowsing/shaders/{blending.hglsl => blending.glsl} (56%) delete mode 100644 modules/globebrowsing/shaders/smviewer_fs.glsl delete mode 100644 modules/globebrowsing/shaders/smviewer_vs.glsl create mode 100644 modules/globebrowsing/shaders/texturetilemapping.glsl delete mode 100644 modules/globebrowsing/shaders/texturetilemapping.hglsl rename modules/globebrowsing/shaders/{tile.hglsl => tile.glsl} (78%) rename modules/globebrowsing/shaders/{tileheight.hglsl => tileheight.glsl} (66%) rename modules/globebrowsing/shaders/{tilevertexskirt.hglsl => tilevertexskirt.glsl} (89%) diff --git a/include/openspace/rendering/deferredcaster.h b/include/openspace/rendering/deferredcaster.h index 0f33e1894e..3d9f476848 100644 --- a/include/openspace/rendering/deferredcaster.h +++ b/include/openspace/rendering/deferredcaster.h @@ -25,6 +25,7 @@ #ifndef __OPENSPACE_CORE___DEFERREDCASTER___H #define __OPENSPACE_CORE___DEFERREDCASTER___H +#include #include namespace ghoul::opengl { @@ -46,31 +47,30 @@ public: const DeferredcastData& /*deferredData*/, ghoul::opengl::ProgramObject& /*program*/) {}; - virtual void postRaycast(const RenderData & /*renderData*/, + virtual void postRaycast(const RenderData& /*renderData*/, const DeferredcastData& /*deferredData*/, ghoul::opengl::ProgramObject& /*program*/) {}; - virtual std::string deferredcastPath() const = 0; + virtual std::filesystem::path deferredcastPath() const = 0; - virtual std::string deferredcastVSPath() const = 0; + virtual std::filesystem::path deferredcastVSPath() const = 0; - virtual std::string deferredcastFSPath() const = 0; + virtual std::filesystem::path deferredcastFSPath() const = 0; virtual void initializeCachedVariables(ghoul::opengl::ProgramObject&) = 0; virtual void update(const UpdateData&) = 0; /** - * Return a path to a glsl file with helper functions required for the - * transformation and raycast steps. - * This file will be included once per shader program generated, - * regardless of how many volumes say they require the file. - * Ideal to avoid redefinitions of helper functions. + * Return a path to a GLSL file with helper functions required for the transformation + * and raycast steps. This file will be included once per shader program generated, + * regardless of how many volumes say they require the file. Ideal to avoid + * redefinitions of helper functions. * * The shader preprocessor will have access to the #{namespace} variable (unique per * helper file) which should be a prefix to all symbols defined by the helper */ - virtual std::string helperPath() const = 0; + virtual std::filesystem::path helperPath() const = 0; }; } // namespace openspace diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index bffec324c4..87154bd7b8 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -109,7 +109,7 @@ protected: properties::TriggerProperty _delete; glm::ivec2 _objectSize = glm::ivec2(0); - UniformCache(color, alpha, modelTransform, viewProj, texture) _uniformCache; + UniformCache(color, opacity, mvp, texture) _uniformCache; std::unique_ptr _shader; }; diff --git a/modules/atmosphere/CMakeLists.txt b/modules/atmosphere/CMakeLists.txt index 475810d9fb..72cd611aa6 100644 --- a/modules/atmosphere/CMakeLists.txt +++ b/modules/atmosphere/CMakeLists.txt @@ -40,30 +40,17 @@ set(SHADER_FILES shaders/atmosphere_common.glsl shaders/atmosphere_deferred_vs.glsl shaders/atmosphere_deferred_fs.glsl - shaders/deltaE_calc_vs.glsl + shaders/calculation_gs.glsl + shaders/calculation_vs.glsl shaders/deltaE_calc_fs.glsl - shaders/deltaJ_calc_vs.glsl shaders/deltaJ_calc_fs.glsl - shaders/deltaJ_calc_gs.glsl - shaders/deltaS_calc_vs.glsl - shaders/deltaS_calc_gs.glsl shaders/deltaS_calc_fs.glsl - shaders/deltaS_sup_calc_vs.glsl - shaders/deltaS_sup_calc_gs.glsl shaders/deltaS_sup_calc_fs.glsl - shaders/inScattering_calc_vs.glsl - shaders/inScattering_calc_gs.glsl shaders/inScattering_calc_fs.glsl - shaders/inScattering_sup_calc_vs.glsl - shaders/inScattering_sup_calc_gs.glsl shaders/inScattering_sup_calc_fs.glsl - shaders/irradiance_calc_vs.glsl shaders/irradiance_calc_fs.glsl - shaders/irradiance_final_vs.glsl shaders/irradiance_final_fs.glsl - shaders/irradiance_sup_calc_vs.glsl shaders/irradiance_sup_calc_fs.glsl - shaders/transmittance_calc_vs.glsl shaders/transmittance_calc_fs.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 59a664be99..b2948125fe 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -32,118 +32,182 @@ * Copyright (c) 2008 INRIA * All rights reserved. * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific + * prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include -#include +#include #include -#include -#include #include -#include #include -#include #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WIN32 -#define _USE_MATH_DEFINES -#endif // WIN32 #include - +#include namespace { constexpr const char* _loggerCat = "AtmosphereDeferredcaster"; - constexpr const std::array UniformNames1 = { - "cullAtmosphere", "Rg", "Rt", "groundRadianceEmittion", "HR", "betaRayleigh", + constexpr const std::array UniformNames = { + "cullAtmosphere", "Rg", "Rt", "groundRadianceEmission", "HR", "betaRayleigh", "HM", "betaMieExtinction", "mieG", "sunRadiance", "ozoneLayerEnabled", "HO", - "betaOzoneExtinction", "SAMPLES_R", "SAMPLES_MU", "SAMPLES_MU_S", "SAMPLES_NU" - }; - - constexpr const std::array UniformNames2 = { + "betaOzoneExtinction", "SAMPLES_R", "SAMPLES_MU", "SAMPLES_MU_S", "SAMPLES_NU", "dInverseModelTransformMatrix", "dModelTransformMatrix", "dSgctProjectionToModelTransformMatrix", "dSGCTViewToWorldMatrix", "dCamPosObj", "sunDirectionObj", "hardShadows", "transmittanceTexture", "irradianceTexture", "inscatterTexture" }; - constexpr const char* GlslDeferredcastPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - constexpr const char* GlslDeferredcastFSPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - constexpr const char* GlslDeferredcastVsPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; - constexpr const float ATM_EPS = 2000.f; constexpr const float KM_TO_M = 1000.f; - void createRenderQuad(GLuint* vao, GLuint* vbo, GLfloat size) { glGenVertexArrays(1, vao); glGenBuffers(1, vbo); glBindVertexArray(*vao); glBindBuffer(GL_ARRAY_BUFFER, *vbo); - const GLfloat vertex_data[] = { - // x y z w + const GLfloat VertexData[] = { + // x y z w -size, -size, 0.f, 1.f, - size, size, 0.f, 1.f, + size, size, 0.f, 1.f, -size, size, 0.f, 1.f, -size, -size, 0.f, 1.f, - size, -size, 0.f, 1.f, - size, size, 0.f, 1.f + size, -size, 0.f, 1.f, + size, size, 0.f, 1.f }; - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 4, - nullptr - ); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData, GL_STATIC_DRAW); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); + glBindVertexArray(0); + } + void saveTextureFile(GLenum colorBufferAttachment, + const std::filesystem::path& fileName, const glm::ivec2& size) + { + std::fstream ppmFile; + ppmFile.open(fileName, std::fstream::out); + if (!ppmFile.is_open()) { + return; + } + + std::vector px(size.x * size.y * 3, unsigned char(255)); + + if (colorBufferAttachment != GL_DEPTH_ATTACHMENT) { + glReadBuffer(colorBufferAttachment); + glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, px.data()); + } + else { + glReadPixels( + 0, + 0, + size.x, + size.y, + GL_DEPTH_COMPONENT, + GL_UNSIGNED_BYTE, + px.data() + ); + } + + ppmFile << "P3" << '\n' << size.x << " " << size.y << '\n' << "255" << '\n'; + + int k = 0; + for (int i = 0; i < size.x; i++) { + for (int j = 0; j < size.y; j++) { + ppmFile << static_cast(px[k]) << ' ' + << static_cast(px[k + 1]) << ' ' + << static_cast(px[k + 2]) << ' '; + k += 3; + } + ppmFile << '\n'; + } + } + + bool isAtmosphereInFrustum(const glm::dmat4& MVMatrix, 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]); + + 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]; + + // Normalize Planes + const double invLeftMag = 1.0 / glm::length(leftNormal); + leftNormal *= invLeftMag; + leftDistance *= invLeftMag; + + const double invRightMag = 1.0 / glm::length(rightNormal); + rightNormal *= invRightMag; + rightDistance *= invRightMag; + + const double invBottomMag = 1.0 / glm::length(bottomNormal); + bottomNormal *= invBottomMag; + bottomDistance *= invBottomMag; + + const double invTopMag = 1.0 / glm::length(topNormal); + topNormal *= invTopMag; + topDistance *= invTopMag; + + const double invNearMag = 1.0 / glm::length(nearNormal); + nearNormal *= invNearMag; + nearDistance *= invNearMag; + + const double invFarMag = 1.0 / glm::length(farNormal); + farNormal *= invFarMag; + + if (((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; + } + + void renderQuadForCalc(GLuint vao, GLsizei numberOfVertices) { + glBindVertexArray(vao); + glDrawArrays(GL_TRIANGLES, 0, numberOfVertices); glBindVertexArray(0); } } // namespace @@ -181,7 +245,6 @@ void AtmosphereDeferredcaster::deinitialize() { glDeleteTextures(1, &_deltaSRayleighTableTexture); glDeleteTextures(1, &_deltaSMieTableTexture); glDeleteTextures(1, &_deltaJTableTexture); - glDeleteTextures(1, &_atmosphereTexture); } void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, @@ -202,16 +265,17 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // Radius is in KM const double scaledRadius = glm::length( - glm::dmat3(_modelTransform) * glm::dvec3(1000.0 * _atmosphereRadius, 0.0, 0.0) + glm::dmat3(_modelTransform) * glm::dvec3(KM_TO_M * _atmosphereRadius, 0.0, 0.0) ); + // Number of planet radii to use as distance threshold for culling + const double DISTANCE_CULLING_RADII = 5000; if (distance > scaledRadius * DISTANCE_CULLING_RADII) { program.setUniform(_uniformCache.cullAtmosphere, 1); } else { - glm::dmat4 MV = glm::dmat4( - renderData.camera.sgctInternal.projectionMatrix() - ) * renderData.camera.combinedViewMatrix(); + glm::dmat4 MV = glm::dmat4(renderData.camera.sgctInternal.projectionMatrix()) * + renderData.camera.combinedViewMatrix(); const double totalAtmosphere = (scaledRadius + ATM_EPS); if (!isAtmosphereInFrustum(MV, tPlanetPosWorld, totalAtmosphere)) { @@ -222,8 +286,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); program.setUniform(_uniformCache.Rt, _atmosphereRadius); program.setUniform( - _uniformCache.groundRadianceEmittion, - _planetGroundRadianceEmittion + _uniformCache.groundRadianceEmission, + _planetGroundRadianceEmission ); program.setUniform(_uniformCache.HR, _rayleighHeightScale); program.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); @@ -242,10 +306,10 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // Object Space glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); program.setUniform( - _uniformCache2.dInverseModelTransformMatrix, + _uniformCache.dInverseModelTransformMatrix, inverseModelMatrix ); - program.setUniform(_uniformCache2.dModelTransformMatrix, _modelTransform); + program.setUniform(_uniformCache.dModelTransformMatrix, _modelTransform); // Eye Space in SGCT to Eye Space in OS (SGCT View to OS Camera Rig) // glm::dmat4 dSgctEye2OSEye = glm::inverse( @@ -256,24 +320,27 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); // Eye Space in SGCT to OS World Space - program.setUniform(_uniformCache2.dSGCTViewToWorldMatrix, - dSGCTViewToWorldMatrix); + program.setUniform( + _uniformCache.dSGCTViewToWorldMatrix, + dSGCTViewToWorldMatrix + ); // SGCT Projection to SGCT Eye Space glm::dmat4 dInverseProjection = glm::inverse( - glm::dmat4(renderData.camera.projectionMatrix())); + glm::dmat4(renderData.camera.projectionMatrix()) + ); glm::dmat4 inverseWholeMatrixPipeline = - inverseModelMatrix * - dSGCTViewToWorldMatrix * - dInverseProjection; + inverseModelMatrix * dSGCTViewToWorldMatrix * dInverseProjection; - program.setUniform(_uniformCache2.dSgctProjectionToModelTransformMatrix, - inverseWholeMatrixPipeline); + program.setUniform( + _uniformCache.dSgctProjectionToModelTransformMatrix, + inverseWholeMatrixPipeline + ); - glm::dvec4 camPosObjCoords = inverseModelMatrix * - glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); - program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); + glm::dvec4 camPosObjCoords = + inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); + program.setUniform(_uniformCache.dCamPosObj, camPosObjCoords); double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( @@ -300,7 +367,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // Sun Position in Object Space program.setUniform( - _uniformCache2.sunDirectionObj, + _uniformCache.sunDirectionObj, glm::normalize(glm::dvec3(sunPosObj)) ); @@ -333,18 +400,14 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); casterPos *= KM_TO_M; // converting to meters - const std::string source = shadowConf.source.first; - SceneGraphNode* sourceNode = - global::renderEngine->scene()->sceneGraphNode(source); - const std::string caster = shadowConf.caster.first; - SceneGraphNode* casterNode = - global::renderEngine->scene()->sceneGraphNode(caster); + SceneGraphNode* sourceNode = sceneGraphNode(shadowConf.source.first); + SceneGraphNode* casterNode = sceneGraphNode(shadowConf.caster.first); if ((sourceNode == nullptr) || (casterNode == nullptr)) { LERRORC( "AtmosphereDeferredcaster", "Invalid scenegraph node for the shadow's caster or shadow's " - "receiver." + "receiver" ); return; } @@ -393,8 +456,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, shadowData.rc = shadowConf.caster.second * casterRadiusScale; shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); shadowData.xp = xp_test; - shadowData.xu = shadowData.rc * sc_length / - (shadowData.rs - shadowData.rc); + shadowData.xu = + shadowData.rc * sc_length / (shadowData.rs - shadowData.rc); shadowData.casterPositionVec = casterPos; } _shadowDataArrayCache.push_back(shadowData); @@ -404,10 +467,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, unsigned int counter = 0; for (const ShadowRenderingStruct& sd : _shadowDataArrayCache) { // Add the counter - char* bf = fmt::format_to( - _uniformNameBuffer + 16, - "{}", counter - ); + char* bf = fmt::format_to(_uniformNameBuffer + 16, "{}", counter); std::strcpy(bf, "].isShadowing\0"); program.setUniform(_uniformNameBuffer, sd.isShadowing); @@ -426,28 +486,27 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, } counter++; } - program.setUniform(_uniformCache2.hardShadows, _hardShadowsEnabled); + program.setUniform(_uniformCache.hardShadows, _hardShadowsEnabled); } } } _transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); program.setUniform( - _uniformCache2.transmittanceTexture, + _uniformCache.transmittanceTexture, _transmittanceTableTextureUnit ); _irradianceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); - program.setUniform(_uniformCache2.irradianceTexture, _irradianceTableTextureUnit); + program.setUniform(_uniformCache.irradianceTexture, _irradianceTableTextureUnit); _inScatteringTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); - program.setUniform(_uniformCache2.inscatterTexture, _inScatteringTableTextureUnit); + program.setUniform(_uniformCache.inscatterTexture, _inScatteringTableTextureUnit); } -void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, +void AtmosphereDeferredcaster::postRaycast(const RenderData&, const DeferredcastData&, ghoul::opengl::ProgramObject&) { ZoneScoped @@ -458,33 +517,32 @@ void AtmosphereDeferredcaster::postRaycast(const RenderData&, _inScatteringTableTextureUnit.deactivate(); } -std::string AtmosphereDeferredcaster::deferredcastPath() const { - return GlslDeferredcastPath; +std::filesystem::path AtmosphereDeferredcaster::deferredcastPath() const { + return absPath("${MODULE_ATMOSPHERE}/shaders/atmosphere_deferred_fs.glsl"); } -std::string AtmosphereDeferredcaster::deferredcastFSPath() const { - return GlslDeferredcastFSPath; +std::filesystem::path AtmosphereDeferredcaster::deferredcastFSPath() const { + return absPath("${MODULE_ATMOSPHERE}/shaders/atmosphere_deferred_fs.glsl"); } -std::string AtmosphereDeferredcaster::deferredcastVSPath() const { - return GlslDeferredcastVsPath; +std::filesystem::path AtmosphereDeferredcaster::deferredcastVSPath() const { + return absPath("${MODULE_ATMOSPHERE}/shaders/atmosphere_deferred_vs.glsl"); } -std::string AtmosphereDeferredcaster::helperPath() const { +std::filesystem::path AtmosphereDeferredcaster::helperPath() const { return ""; // no helper file } void AtmosphereDeferredcaster::initializeCachedVariables( ghoul::opengl::ProgramObject& program) { - ghoul::opengl::updateUniformLocations(program, _uniformCache, UniformNames1); - ghoul::opengl::updateUniformLocations(program, _uniformCache2, UniformNames2); + ghoul::opengl::updateUniformLocations(program, _uniformCache, UniformNames); } void AtmosphereDeferredcaster::update(const UpdateData&) {} -void AtmosphereDeferredcaster::setModelTransform(const glm::dmat4& transform) { - _modelTransform = transform; +void AtmosphereDeferredcaster::setModelTransform(glm::dmat4 transform) { + _modelTransform = std::move(transform); } void AtmosphereDeferredcaster::setTime(double time) { @@ -505,10 +563,10 @@ void AtmosphereDeferredcaster::setPlanetAverageGroundReflectance( _planetAverageGroundReflectance = averageGReflectance; } -void AtmosphereDeferredcaster::setPlanetGroundRadianceEmittion( - float groundRadianceEmittion) +void AtmosphereDeferredcaster::setPlanetGroundRadianceEmission( + float groundRadianceEmission) { - _planetGroundRadianceEmittion = groundRadianceEmittion; + _planetGroundRadianceEmission = groundRadianceEmission; } void AtmosphereDeferredcaster::setRayleighHeightScale(float rayleighHeightScale) { @@ -576,17 +634,13 @@ void AtmosphereDeferredcaster::enableSunFollowing(bool enable) { void AtmosphereDeferredcaster::setPrecalculationTextureScale( float preCalculatedTexturesScale) { - _calculationTextureScale = preCalculatedTexturesScale; - _transmittance_table_width *= static_cast(_calculationTextureScale); - _transmittance_table_height *= static_cast(_calculationTextureScale); - _irradiance_table_width *= static_cast(_calculationTextureScale); - _irradiance_table_height *= static_cast(_calculationTextureScale); - _delta_e_table_width *= static_cast(_calculationTextureScale); - _delta_e_table_height *= static_cast(_calculationTextureScale); - _r_samples *= static_cast(_calculationTextureScale); - _mu_samples *= static_cast(_calculationTextureScale); - _mu_s_samples *= static_cast(_calculationTextureScale); - _nu_samples *= static_cast(_calculationTextureScale); + _transmittanceTableSize *= static_cast(preCalculatedTexturesScale); + _irradianceTableSize *= static_cast(preCalculatedTexturesScale); + _deltaETableSize *= static_cast(preCalculatedTexturesScale); + _r_samples *= static_cast(preCalculatedTexturesScale); + _mu_samples *= static_cast(preCalculatedTexturesScale); + _mu_s_samples *= static_cast(preCalculatedTexturesScale); + _nu_samples *= static_cast(preCalculatedTexturesScale); } void AtmosphereDeferredcaster::enablePrecalculationTexturesSaving() { @@ -594,118 +648,114 @@ void AtmosphereDeferredcaster::enablePrecalculationTexturesSaving() { } void AtmosphereDeferredcaster::loadComputationPrograms() { - //============== Transmittance T ================= + // + // Transmittance T if (!_transmittanceProgramObject) { _transmittanceProgramObject = ghoul::opengl::ProgramObject::Build( "transmittanceCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl") ); } using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; - _transmittanceProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); _transmittanceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - //============== Irradiance E ================= + // + // Irradiance E if (!_irradianceProgramObject) { _irradianceProgramObject = ghoul::opengl::ProgramObject::Build( "irradianceCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_fs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_fs.glsl") + ); } - _irradianceProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); _irradianceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); if (!_irradianceSupTermsProgramObject) { _irradianceSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( "irradianceSupTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_fs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_fs.glsl") + ); } - _irradianceSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); _irradianceSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== InScattering S ================= + + // + // InScattering S if (!_inScatteringProgramObject) { _inScatteringProgramObject = ghoul::opengl::ProgramObject::Build( "inScatteringCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_gs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") + ); } - _inScatteringProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); _inScatteringProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); if (!_inScatteringSupTermsProgramObject) { _inScatteringSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( "inScatteringSupTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_gs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") + ); } - _inScatteringSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); _inScatteringSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - //============== Delta E ================= + // + // Delta E if (!_deltaEProgramObject) { _deltaEProgramObject = ghoul::opengl::ProgramObject::Build( "deltaECalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_fs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_fs.glsl") + ); } - _deltaEProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); _deltaEProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - //============== Irradiance finel E ================= + // + // Irradiance finel E if (!_irradianceFinalProgramObject) { _irradianceFinalProgramObject = ghoul::opengl::ProgramObject::Build( "irradianceEFinalProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_fs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_fs.glsl") + ); } - _irradianceFinalProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); _irradianceFinalProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - //============== Delta S ================= + // + // Delta S if (!_deltaSProgramObject) { _deltaSProgramObject = ghoul::opengl::ProgramObject::Build( "deltaSCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_gs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") + ); } - _deltaSProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); _deltaSProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); if (!_deltaSSupTermsProgramObject) { _deltaSSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( "deltaSSUPTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_gs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") + ); } - _deltaSSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); _deltaSSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - //============== Delta J (Radiance Scattered) ================= + // + // Delta J (Radiance Scattered) if (!_deltaJProgramObject) { _deltaJProgramObject = ghoul::opengl::ProgramObject::Build( "deltaJCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_gs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") + ); } - _deltaJProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); _deltaJProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); } @@ -724,7 +774,8 @@ void AtmosphereDeferredcaster::unloadComputationPrograms() { void AtmosphereDeferredcaster::createComputationTextures() { if (!_atmosphereCalculated) { - //============== Transmittance ================= + // + // Transmittance ghoul::opengl::TextureUnit transmittanceTableTextureUnit; transmittanceTableTextureUnit.activate(); glGenTextures(1, &_transmittanceTableTexture); @@ -735,10 +786,20 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _transmittance_table_width, - _transmittance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGB32F, + _transmittanceTableSize.x, + _transmittanceTableSize.y, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); - //============== Irradiance ================= + // + // Irradiance ghoul::opengl::TextureUnit irradianceTableTextureUnit; irradianceTableTextureUnit.activate(); glGenTextures(1, &_irradianceTableTexture); @@ -748,10 +809,20 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _irradiance_table_width, - _irradiance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGB32F, + _irradianceTableSize.x, + _irradianceTableSize.y, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); - //============== InScattering ================= + // + // InScattering ghoul::opengl::TextureUnit inScatteringTableTextureUnit; inScatteringTableTextureUnit.activate(); glGenTextures(1, &_inScatteringTableTexture); @@ -762,11 +833,22 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage3D( + GL_TEXTURE_3D, + 0, + GL_RGBA32F, + _mu_s_samples * _nu_samples, + _mu_samples, + _r_samples, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); } - //============== Delta E ================= + // + // Delta E ghoul::opengl::TextureUnit deltaETableTextureUnit; deltaETableTextureUnit.activate(); glGenTextures(1, &_deltaETableTexture); @@ -776,10 +858,20 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _delta_e_table_width, - _delta_e_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGB32F, + _deltaETableSize.x, + _deltaETableSize.y, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); - //============== Delta S ================= + // + // Delta S ghoul::opengl::TextureUnit deltaSRayleighTableTextureUnit; deltaSRayleighTableTextureUnit.activate(); glGenTextures(1, &_deltaSRayleighTableTexture); @@ -790,8 +882,17 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage3D( + GL_TEXTURE_3D, + 0, + GL_RGB32F, + _mu_s_samples * _nu_samples, + _mu_samples, + _r_samples, + 0, GL_RGB, + GL_FLOAT, + nullptr + ); ghoul::opengl::TextureUnit deltaSMieTableTextureUnit; deltaSMieTableTextureUnit.activate(); @@ -803,10 +904,21 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage3D( + GL_TEXTURE_3D, + 0, + GL_RGB32F, + _mu_s_samples * _nu_samples, + _mu_samples, + _r_samples, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); - //============== Delta J (Radiance Scattered) ================= + // + // Delta J (Radiance Scattered) ghoul::opengl::TextureUnit deltaJTableTextureUnit; deltaJTableTextureUnit.activate(); glGenTextures(1, &_deltaJTableTexture); @@ -817,27 +929,46 @@ void AtmosphereDeferredcaster::createComputationTextures() { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - + glTexImage3D( + GL_TEXTURE_3D, + 0, + GL_RGB32F, + _mu_s_samples * _nu_samples, + _mu_samples, + _r_samples, + 0, + GL_RGB, + GL_FLOAT, + nullptr + ); } void AtmosphereDeferredcaster::deleteComputationTextures() { - // Cleaning up glDeleteTextures(1, &_transmittanceTableTexture); + _transmittanceTableTexture = 0; glDeleteTextures(1, &_irradianceTableTexture); + _irradianceTableTexture = 0; glDeleteTextures(1, &_inScatteringTableTexture); + _inScatteringTableTexture = 0; glDeleteTextures(1, &_deltaETableTexture); + _deltaETableTexture = 0; glDeleteTextures(1, &_deltaSRayleighTableTexture); + _deltaSRayleighTableTexture = 0; glDeleteTextures(1, &_deltaSMieTableTexture); + _deltaSMieTableTexture = 0; glDeleteTextures(1, &_deltaJTableTexture); + _deltaJTableTexture = 0; } void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { glDeleteTextures(1, &_deltaETableTexture); + _deltaETableTexture = 0; glDeleteTextures(1, &_deltaSRayleighTableTexture); + _deltaSRayleighTableTexture = 0; glDeleteTextures(1, &_deltaSMieTableTexture); + _deltaSMieTableTexture = 0; glDeleteTextures(1, &_deltaJTableTexture); + _deltaJTableTexture = 0; } void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, @@ -854,37 +985,32 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, glDisable(GL_BLEND); - // =========================================================== // See Precomputed Atmosphere Scattering from Bruneton et al. paper, algorithm 4.1: - // =========================================================== glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _transmittanceTableTexture, 0 ); - checkFrameBufferState("_transmittanceTableTexture"); - glViewport(0, 0, _transmittance_table_width, _transmittance_table_height); + glViewport(0, 0, _transmittanceTableSize.x, _transmittanceTableSize.y); _transmittanceProgramObject->activate(); - loadAtmosphereDataIntoShaderProgram(_transmittanceProgramObject); - //glClear(GL_COLOR_BUFFER_BIT); - static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glClearBufferfv(GL_COLOR, 0, black); + loadAtmosphereDataIntoShaderProgram(*_transmittanceProgramObject); + + static const float Black[] = { 0.f, 0.f, 0.f, 0.f }; + glClearBufferfv(GL_COLOR, 0, Black); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - saveTextureToPPMFile( + saveTextureFile( GL_COLOR_ATTACHMENT0, - std::string("transmittance_texture.ppm"), - _transmittance_table_width, - _transmittance_table_height + "transmittance_texture.ppm", + _transmittanceTableSize ); } _transmittanceProgramObject->deactivate(); // line 2 in algorithm 4.1 glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _deltaETableTexture, 0); - checkFrameBufferState("_deltaETableTexture"); - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); _irradianceProgramObject->activate(); transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); @@ -892,15 +1018,14 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "transmittanceTexture", transmittanceTableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_irradianceProgramObject); + loadAtmosphereDataIntoShaderProgram(*_irradianceProgramObject); glClear(GL_COLOR_BUFFER_BIT); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - saveTextureToPPMFile( + saveTextureFile( GL_COLOR_ATTACHMENT0, - std::string("deltaE_table_texture.ppm"), - _delta_e_table_width, - _delta_e_table_height + "deltaE_table_texture.ppm", + _deltaETableSize ); } _irradianceProgramObject->deactivate(); @@ -920,7 +1045,6 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, ); GLenum colorBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, colorBuffers); - checkFrameBufferState("_deltaSRay and _deltaSMie TableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); _inScatteringProgramObject->activate(); transmittanceTableTextureUnit.activate(); @@ -929,24 +1053,22 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "transmittanceTexture", transmittanceTableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_inScatteringProgramObject); + loadAtmosphereDataIntoShaderProgram(*_inScatteringProgramObject); glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < _r_samples; ++layer) { - step3DTexture(_inScatteringProgramObject, layer); + step3DTexture(*_inScatteringProgramObject, layer, true); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - saveTextureToPPMFile( + saveTextureFile( GL_COLOR_ATTACHMENT0, - std::string("deltaS_rayleigh_texture.ppm"), - _mu_s_samples * _nu_samples, - _mu_samples + "deltaS_rayleigh_texture.ppm", + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) ); - saveTextureToPPMFile( + saveTextureFile( GL_COLOR_ATTACHMENT1, - std::string("deltaS_mie_texture.ppm"), - _mu_s_samples * _nu_samples, - _mu_samples + "deltaS_mie_texture.ppm", + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) ); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); @@ -961,21 +1083,22 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _irradianceTableTexture, 0 ); - checkFrameBufferState("_irradianceTableTexture"); glDrawBuffer(GL_COLOR_ATTACHMENT0); - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); _deltaEProgramObject->activate(); - //_deltaEProgramObject->setUniform("line", 4); deltaETableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); _deltaEProgramObject->setUniform("deltaETexture", deltaETableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaEProgramObject); + loadAtmosphereDataIntoShaderProgram(*_deltaEProgramObject); glClear(GL_COLOR_BUFFER_BIT); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("irradiance_texture.ppm"), - _delta_e_table_width, _delta_e_table_height); + saveTextureFile( + GL_COLOR_ATTACHMENT0, + "irradiance_texture.ppm", + _deltaETableSize + ); } _deltaEProgramObject->deactivate(); @@ -986,7 +1109,6 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _inScatteringTableTexture, 0 ); - checkFrameBufferState("_inScatteringTableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); _deltaSProgramObject->activate(); deltaSRayleighTableTextureUnit.activate(); @@ -995,15 +1117,18 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); _deltaSProgramObject->setUniform("deltaSRTexture", deltaSRayleighTableTextureUnit); _deltaSProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaSProgramObject); + loadAtmosphereDataIntoShaderProgram(*_deltaSProgramObject); glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < _r_samples; ++layer) { - step3DTexture(_deltaSProgramObject, layer, false); + step3DTexture(*_deltaSProgramObject, layer, false); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("S_texture.ppm"), - _mu_s_samples * _nu_samples, _mu_samples); + saveTextureFile( + GL_COLOR_ATTACHMENT0, + "S_texture.ppm", + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) + ); } _deltaSProgramObject->deactivate(); @@ -1016,7 +1141,6 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _deltaJTableTexture, 0 ); - checkFrameBufferState("_deltaJTableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); _deltaJProgramObject->activate(); if (scatteringOrder == 2) { @@ -1043,15 +1167,17 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, deltaSMieTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); _deltaJProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaJProgramObject); + loadAtmosphereDataIntoShaderProgram(*_deltaJProgramObject); for (int layer = 0; layer < _r_samples; ++layer) { - step3DTexture(_deltaJProgramObject, layer); + step3DTexture(*_deltaJProgramObject, layer, true); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + saveTextureFile( + GL_COLOR_ATTACHMENT0, fmt::format("deltaJ_texture-scattering_order-{}.ppm", scatteringOrder), - _mu_s_samples * _nu_samples, _mu_samples); + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) + ); } _deltaJProgramObject->deactivate(); @@ -1062,8 +1188,7 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _deltaETableTexture, 0 ); - checkFrameBufferState("_deltaETableTexture"); - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); _irradianceSupTermsProgramObject->activate(); if (scatteringOrder == 2) { _irradianceSupTermsProgramObject->setUniform("firstIteraction", 1); @@ -1089,12 +1214,14 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "deltaSMTexture", deltaSMieTableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); + loadAtmosphereDataIntoShaderProgram(*_irradianceSupTermsProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + saveTextureFile( + GL_COLOR_ATTACHMENT0, fmt::format("deltaE_texture-scattering_order-{}.ppm", scatteringOrder), - _delta_e_table_width, _delta_e_table_height); + _deltaETableSize + ); } _irradianceSupTermsProgramObject->deactivate(); @@ -1105,7 +1232,6 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _deltaSRayleighTableTexture, 0 ); - checkFrameBufferState("_deltaSRayleighTableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); _inScatteringSupTermsProgramObject->activate(); transmittanceTableTextureUnit.activate(); @@ -1120,17 +1246,16 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "deltaJTexture", deltaJTableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_inScatteringSupTermsProgramObject); + loadAtmosphereDataIntoShaderProgram(*_inScatteringSupTermsProgramObject); for (int layer = 0; layer < _r_samples; ++layer) { - step3DTexture(_inScatteringSupTermsProgramObject, layer); + step3DTexture(*_inScatteringSupTermsProgramObject, layer, true); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, - fmt::format("deltaS_texture-scattering_order-{}.ppm", - scatteringOrder), - _mu_s_samples * _nu_samples, - _mu_samples + saveTextureFile( + GL_COLOR_ATTACHMENT0, + fmt::format("deltaS_texture-scattering_order-{}.ppm", scatteringOrder), + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) ); } _inScatteringSupTermsProgramObject->deactivate(); @@ -1146,8 +1271,7 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _irradianceTableTexture, 0 ); - checkFrameBufferState("_irradianceTableTexture"); - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); _irradianceFinalProgramObject->activate(); deltaETableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); @@ -1155,13 +1279,14 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "deltaETexture", deltaETableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_irradianceFinalProgramObject); + loadAtmosphereDataIntoShaderProgram(*_irradianceFinalProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, - fmt::format("irradianceTable_order-{}.ppm", - scatteringOrder), - _delta_e_table_width, _delta_e_table_height); + saveTextureFile( + GL_COLOR_ATTACHMENT0, + fmt::format("irradianceTable_order-{}.ppm", scatteringOrder), + _deltaETableSize + ); } _irradianceFinalProgramObject->deactivate(); @@ -1172,7 +1297,6 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, _inScatteringTableTexture, 0 ); - checkFrameBufferState("_inScatteringTableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); _deltaSSupTermsProgramObject->activate(); deltaSRayleighTableTextureUnit.activate(); @@ -1181,16 +1305,16 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, "deltaSTexture", deltaSRayleighTableTextureUnit ); - loadAtmosphereDataIntoShaderProgram(_deltaSSupTermsProgramObject); + loadAtmosphereDataIntoShaderProgram(*_deltaSSupTermsProgramObject); for (int layer = 0; layer < _r_samples; ++layer) { - step3DTexture(_deltaSSupTermsProgramObject, layer, false); + step3DTexture(*_deltaSSupTermsProgramObject, layer, false); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, - fmt::format("inscatteringTable_order-{}.ppm", - scatteringOrder), - _mu_s_samples * _nu_samples, _mu_samples); + saveTextureFile(GL_COLOR_ATTACHMENT0, + fmt::format("inscatteringTable_order-{}.ppm", scatteringOrder), + glm::ivec2(_mu_s_samples * _nu_samples, _mu_samples) + ); } _deltaSSupTermsProgramObject->deactivate(); @@ -1202,22 +1326,18 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, } void AtmosphereDeferredcaster::preCalculateAtmosphereParam() { - //========================================================== - //========= Load Shader Programs for Calculations ========== - //========================================================== + // Load Shader Programs for Calculations loadComputationPrograms(); - //========================================================== - //============ Create Textures for Calculations ============ - //========================================================== + // Create Textures for Calculations createComputationTextures(); // Saves current FBO first GLint defaultFBO; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - GLint m_viewport[4]; - global::renderEngine->openglStateCache().viewport(m_viewport); + GLint viewport[4]; + global::renderEngine->openglStateCache().viewport(viewport); // Creates the FBO for the calculations GLuint calcFBO; @@ -1232,288 +1352,81 @@ void AtmosphereDeferredcaster::preCalculateAtmosphereParam() { createRenderQuad(&quadCalcVAO, &quadCalcVBO, 1.0f); // Starting Calculations... - LDEBUG("Starting precalculations for scattering effects..."); + LDEBUG("Starting precalculations for scattering effects"); - //========================================================== - //=================== Execute Calculations ================= - //========================================================== + // Execute Calculations executeCalculations(quadCalcVAO, drawBuffers, 6); deleteUnusedComputationTextures(); // Restores system state glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - global::renderEngine->openglStateCache().setViewportState(m_viewport); + global::renderEngine->openglStateCache().setViewportState(viewport); glDeleteBuffers(1, &quadCalcVBO); glDeleteVertexArrays(1, &quadCalcVAO); glDeleteFramebuffers(1, &calcFBO); - LDEBUG("Ended precalculations for Atmosphere effects..."); + LDEBUG("Ended precalculations for Atmosphere effects"); } void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( - std::unique_ptr& shaderProg) + ghoul::opengl::ProgramObject& shaderProg) { - shaderProg->setUniform("Rg", _atmospherePlanetRadius); - shaderProg->setUniform("Rt", _atmosphereRadius); - shaderProg->setUniform("AverageGroundReflectance", _planetAverageGroundReflectance); - shaderProg->setUniform("groundRadianceEmittion", _planetGroundRadianceEmittion); - shaderProg->setUniform("HR", _rayleighHeightScale); - shaderProg->setUniform("betaRayleigh", _rayleighScatteringCoeff); - shaderProg->setUniform("HM", _mieHeightScale); - shaderProg->setUniform("betaMieScattering", _mieScatteringCoeff); - shaderProg->setUniform("betaMieExtinction", _mieExtinctionCoeff); - shaderProg->setUniform("mieG", _miePhaseConstant); - shaderProg->setUniform("sunRadiance", _sunRadianceIntensity); - shaderProg->setUniform("TRANSMITTANCE_W", _transmittance_table_width); - shaderProg->setUniform("TRANSMITTANCE_H", _transmittance_table_height); - shaderProg->setUniform("SKY_W", _irradiance_table_width); - shaderProg->setUniform("SKY_H", _irradiance_table_height); - shaderProg->setUniform("OTHER_TEXTURES_W", _delta_e_table_width); - shaderProg->setUniform("OTHER_TEXTURES_H", _delta_e_table_height); - shaderProg->setUniform("SAMPLES_R", _r_samples); - shaderProg->setUniform("SAMPLES_MU", _mu_samples); - shaderProg->setUniform("SAMPLES_MU_S", _mu_s_samples); - shaderProg->setUniform("SAMPLES_NU", _nu_samples); - shaderProg->setUniform("ozoneLayerEnabled", _ozoneEnabled); - shaderProg->setUniform("HO", _ozoneHeightScale); - shaderProg->setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); + shaderProg.setUniform("Rg", _atmospherePlanetRadius); + shaderProg.setUniform("Rt", _atmosphereRadius); + shaderProg.setUniform("AverageGroundReflectance", _planetAverageGroundReflectance); + shaderProg.setUniform("groundRadianceEmission", _planetGroundRadianceEmission); + shaderProg.setUniform("HR", _rayleighHeightScale); + shaderProg.setUniform("betaRayleigh", _rayleighScatteringCoeff); + shaderProg.setUniform("HM", _mieHeightScale); + shaderProg.setUniform("betaMieScattering", _mieScatteringCoeff); + shaderProg.setUniform("betaMieExtinction", _mieExtinctionCoeff); + shaderProg.setUniform("mieG", _miePhaseConstant); + shaderProg.setUniform("sunRadiance", _sunRadianceIntensity); + shaderProg.setUniform("TRANSMITTANCE", _transmittanceTableSize); + shaderProg.setUniform("SKY", _irradianceTableSize); + shaderProg.setUniform("OTHER_TEXTURES", _deltaETableSize); + shaderProg.setUniform("SAMPLES_R", _r_samples); + shaderProg.setUniform("SAMPLES_MU", _mu_samples); + shaderProg.setUniform("SAMPLES_MU_S", _mu_s_samples); + shaderProg.setUniform("SAMPLES_NU", _nu_samples); + shaderProg.setUniform("ozoneLayerEnabled", _ozoneEnabled); + shaderProg.setUniform("HO", _ozoneHeightScale); + shaderProg.setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); } -void AtmosphereDeferredcaster::checkFrameBufferState( - const std::string& codePosition) const -{ - if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - LERROR("Framework not built. " + codePosition); - 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; - } - } -} - -void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVertices) { - glBindVertexArray(vao); - glDrawArrays(GL_TRIANGLES, 0, numberOfVertices); - glBindVertexArray(0); -} - -void AtmosphereDeferredcaster::step3DTexture( - std::unique_ptr& shaderProg, - int layer, - bool doCalculation) +void AtmosphereDeferredcaster::step3DTexture(ghoul::opengl::ProgramObject& shaderProg, + int layer, bool doCalculation) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering if (doCalculation) { - float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; - float atm2 = _atmosphereRadius * _atmosphereRadius; - float diff = atm2 - earth2; - float ri = static_cast(layer) / static_cast(_r_samples - 1); - float ri_2 = ri * ri; - float epsilon = - (layer == 0) ? - 0.01f : - (layer == (_r_samples - 1)) ? -0.001f : 0.0f; - float r = sqrtf(earth2 + ri_2 * diff) + epsilon; - float dminG = r - _atmospherePlanetRadius; - float dminT = _atmosphereRadius - r; - float dh = sqrtf(r * r - earth2); - float dH = dh + sqrtf(diff); - - shaderProg->setUniform("r", r); - shaderProg->setUniform("dhdH", dminT, dH, dminG, dh); - } - - shaderProg->setUniform("layer", layer); -} - -void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, - const std::string& fileName, - int width, int height) const -{ - std::fstream ppmFile; - - ppmFile.open(fileName.c_str(), std::fstream::out); - if (ppmFile.is_open()) { - unsigned char * pixels = new unsigned char[width*height * 3]; - for (int t = 0; t < width*height * 3; ++t) - pixels[t] = 255; - - if (color_buffer_attachment != GL_DEPTH_ATTACHMENT) { - glReadBuffer(color_buffer_attachment); - glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); - - } - else { - glReadPixels( - 0, - 0, - width, - height, - GL_DEPTH_COMPONENT, - GL_UNSIGNED_BYTE, - pixels - ); - } - - ppmFile << "P3" << std::endl; - ppmFile << width << " " << height << std::endl; - ppmFile << "255" << std::endl; - - std::cout << "\n\nFILE\n\n"; - int k = 0; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - ppmFile << static_cast(pixels[k]) << " " - << static_cast(pixels[k + 1]) << " " - << static_cast(pixels[k + 2]) << " "; - k += 3; + const float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; + const float diff = _atmosphereRadius * _atmosphereRadius - earth2; + const float ri = static_cast(layer) / static_cast(_r_samples - 1); + const float eps = [&]() { + if (layer == 0) { + return 0.01f; } - ppmFile << std::endl; - } - delete[] pixels; + else { + if (layer == (_r_samples - 1)) { + return -0.001f; + } + else { + return 0.f; + } + } + }(); + const float r = std::sqrt(earth2 + ri * ri * diff) + eps; + const float dminG = r - _atmospherePlanetRadius; + const float dminT = _atmosphereRadius - r; + const float dh = std::sqrt(r * r - earth2); + const float dH = dh + std::sqrt(diff); - ppmFile.close(); + shaderProg.setUniform("r", r); + shaderProg.setUniform("dhdH", dminT, dH, dminG, dh); } -} -bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const glm::dmat4& MVMatrix, - const glm::dvec3& position, - double radius) const -{ - - // Frustum Planes - //glm::dvec3 col1(MVMatrix[0], MVMatrix[4], MVMatrix[8]); - //glm::dvec3 col2(MVMatrix[1], MVMatrix[5], MVMatrix[9]); - //glm::dvec3 col3(MVMatrix[2], MVMatrix[6], MVMatrix[10]); - //glm::dvec3 col4(MVMatrix[3], MVMatrix[7], MVMatrix[11]); - - 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[15] + MVMatrix[12]; - //double rightDistance = MVMatrix[15] - MVMatrix[12]; - //double bottomDistance = MVMatrix[15] + MVMatrix[13]; - //double topDistance = MVMatrix[15] - MVMatrix[13]; - //double nearDistance = MVMatrix[15] + MVMatrix[14]; - //double farDistance = MVMatrix[15] - MVMatrix[14]; - - 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 - double invMag = 1.0 / glm::length(leftNormal); - leftNormal *= invMag; - leftDistance *= invMag; - - invMag = 1.0 / glm::length(rightNormal); - rightNormal *= invMag; - rightDistance *= invMag; - - invMag = 1.0 / glm::length(bottomNormal); - bottomNormal *= invMag; - bottomDistance *= invMag; - - invMag = 1.0 / glm::length(topNormal); - topNormal *= invMag; - topDistance *= invMag; - - invMag = 1.0 / glm::length(nearNormal); - nearNormal *= invMag; - nearDistance *= invMag; - - invMag = 1.0 / glm::length(farNormal); - farNormal *= invMag; -// farDistance *= invMag; - - 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; - } - // The far plane testing is disabled because the atm has no depth. - /*else if ((glm::dot(farNormal, position) + farDistance) < -radius) { - return false; - }*/ - - return true; + shaderProg.setUniform("layer", layer); } } // namespace openspace diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index f0f142824a..608c5d47b4 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -31,7 +31,6 @@ #include #include #include - #include #include @@ -46,6 +45,16 @@ struct RenderData; struct DeferredcastData; struct ShadowConfiguration; +struct ShadowRenderingStruct { + double xu = 0.0; + double xp = 0.0; + double rs = 0.0; + double rc = 0.0; + glm::dvec3 sourceCasterVec = glm::dvec3(0.0); + glm::dvec3 casterPositionVec = glm::dvec3(0.0); + bool isShadowing = false; +}; + class AtmosphereDeferredcaster : public Deferredcaster { public: virtual ~AtmosphereDeferredcaster() = default; @@ -53,27 +62,27 @@ public: void initialize(); void deinitialize(); void preRaycast(const RenderData& renderData, const DeferredcastData& deferredData, - ghoul::opengl::ProgramObject& program) override; + ghoul::opengl::ProgramObject& program) override; void postRaycast(const RenderData& renderData, const DeferredcastData& deferredData, - ghoul::opengl::ProgramObject& program) override; + ghoul::opengl::ProgramObject& program) override; - std::string deferredcastPath() const override; - std::string deferredcastVSPath() const override; - std::string deferredcastFSPath() const override; - std::string helperPath() const override; + std::filesystem::path deferredcastPath() const override; + std::filesystem::path deferredcastVSPath() const override; + std::filesystem::path deferredcastFSPath() const override; + std::filesystem::path helperPath() const override; - void initializeCachedVariables(ghoul::opengl::ProgramObject&) override; + void initializeCachedVariables(ghoul::opengl::ProgramObject& program) override; void update(const UpdateData&) override; void preCalculateAtmosphereParam(); - void setModelTransform(const glm::dmat4 &transform); + void setModelTransform(glm::dmat4 transform); void setTime(double time); void setAtmosphereRadius(float atmRadius); void setPlanetRadius(float planetRadius); void setPlanetAverageGroundReflectance(float averageGReflectance); - void setPlanetGroundRadianceEmittion(float groundRadianceEmittion); + void setPlanetGroundRadianceEmission(float groundRadianceEmission); void setRayleighHeightScale(float rayleighHeightScale); void enableOzone(bool enable); void setOzoneHeightScale(float ozoneHeightScale); @@ -100,20 +109,9 @@ private: void deleteUnusedComputationTextures(); void executeCalculations(GLuint quadCalcVAO, GLenum drawBuffers[1], GLsizei vertexSize); - void step3DTexture(std::unique_ptr& shaderProg, - int layer, bool doCalculation = true); - void checkFrameBufferState(const std::string& codePosition) const; - void loadAtmosphereDataIntoShaderProgram( - std::unique_ptr & shaderProg - ); - void renderQuadForCalc(GLuint vao, GLsizei numberOfVertices); - void saveTextureToPPMFile(GLenum color_buffer_attachment, const std::string& fileName, - int width, int height) const; - bool isAtmosphereInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position, - double radius) const; - - // Number of planet radii to use as distance threshold for culling - const double DISTANCE_CULLING_RADII = 5000; + void step3DTexture(ghoul::opengl::ProgramObject& shaderProg, int layer, + bool doCalculation); + void loadAtmosphereDataIntoShaderProgram(ghoul::opengl::ProgramObject& shaderProg); std::unique_ptr _transmittanceProgramObject; std::unique_ptr _irradianceProgramObject; @@ -125,19 +123,13 @@ private: std::unique_ptr _deltaSProgramObject; std::unique_ptr _deltaSSupTermsProgramObject; std::unique_ptr _deltaJProgramObject; - std::unique_ptr _atmosphereProgramObject; - std::unique_ptr _deferredAtmosphereProgramObject; - UniformCache(cullAtmosphere, Rg, Rt, - groundRadianceEmittion, HR, betaRayleigh, HM, - betaMieExtinction, mieG, sunRadiance, ozoneLayerEnabled, - HO, betaOzoneExtinction, SAMPLES_R, - SAMPLES_MU, SAMPLES_MU_S, SAMPLES_NU) _uniformCache; - UniformCache(dInverseModelTransformMatrix, dModelTransformMatrix, - dSgctProjectionToModelTransformMatrix, - dSGCTViewToWorldMatrix, dCamPosObj, sunDirectionObj, - hardShadows, transmittanceTexture, irradianceTexture, - inscatterTexture) _uniformCache2; + UniformCache(cullAtmosphere, Rg, Rt, groundRadianceEmission, HR, betaRayleigh, HM, + betaMieExtinction, mieG, sunRadiance, ozoneLayerEnabled, HO, betaOzoneExtinction, + SAMPLES_R, SAMPLES_MU, SAMPLES_MU_S, SAMPLES_NU, dInverseModelTransformMatrix, + dModelTransformMatrix, dSgctProjectionToModelTransformMatrix, + dSGCTViewToWorldMatrix, dCamPosObj, sunDirectionObj, hardShadows, + transmittanceTexture, irradianceTexture, inscatterTexture) _uniformCache; GLuint _transmittanceTableTexture = 0; GLuint _irradianceTableTexture = 0; @@ -146,7 +138,6 @@ private: GLuint _deltaSRayleighTableTexture = 0; GLuint _deltaSMieTableTexture = 0; GLuint _deltaJTableTexture = 0; - GLuint _atmosphereTexture = 0; ghoul::opengl::TextureUnit _transmittanceTableTextureUnit; ghoul::opengl::TextureUnit _irradianceTableTextureUnit; @@ -159,7 +150,7 @@ private: float _atmosphereRadius = 0.f; float _atmospherePlanetRadius = 0.f; float _planetAverageGroundReflectance = 0.f; - float _planetGroundRadianceEmittion = 0.f; + float _planetGroundRadianceEmission = 0.f; float _rayleighHeightScale = 0.f; float _ozoneHeightScale = 0.f; float _mieHeightScale = 0.f; @@ -173,12 +164,9 @@ private: glm::dvec3 _ellipsoidRadii = glm::vec3(0.f); // Atmosphere Textures Dimmensions - int _transmittance_table_width = 256; - int _transmittance_table_height = 64; - int _irradiance_table_width = 64; - int _irradiance_table_height = 16; - int _delta_e_table_width = 64; - int _delta_e_table_height = 16; + glm::ivec2 _transmittanceTableSize = glm::ivec2(256, 64); + glm::ivec2 _irradianceTableSize = glm::ivec2(64, 16); + glm::ivec2 _deltaETableSize = glm::ivec2(64, 16); int _r_samples = 32; int _mu_samples = 128; int _mu_s_samples = 32; @@ -192,7 +180,6 @@ private: bool _hardShadowsEnabled = false; // Atmosphere Debugging - float _calculationTextureScale = 1.f; bool _saveCalculationTextures = false; std::vector _shadowDataArrayCache; diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index ec8550a43d..8356dc06ce 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -25,33 +25,10 @@ #include #include -#include #include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WIN32 -#define _USE_MATH_DEFINES -#endif // WIN32 #include namespace { @@ -69,7 +46,7 @@ namespace { "phase" }; - constexpr openspace::properties::Property::PropertyInfo GroundRadianceEmittioninfo = { + constexpr openspace::properties::Property::PropertyInfo GroundRadianceEmissionInfo = { "GroundRadianceEmission", "Percentage of initial radiance emitted from ground", "Multiplier of the ground radiance color during the rendering phase" @@ -197,7 +174,7 @@ namespace { // [[codegen::verbatim(MieScatteringExtinctionPropCoeffInfo.description)]] std::optional mieScatteringExtinctionPropCoefficient; - // [[codegen::verbatim(GroundRadianceEmittioninfo.description)]] + // [[codegen::verbatim(GroundRadianceEmissionInfo.description)]] float groundRadianceEmission; struct Rayleigh { @@ -252,7 +229,7 @@ RenderableAtmosphere::RenderableAtmosphere(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _atmosphereHeight(AtmosphereHeightInfo, 60.f, 0.1f, 99.0f) , _groundAverageReflectance(AverageGroundReflectanceInfo, 0.f, 0.f, 1.f) - , _groundRadianceEmission(GroundRadianceEmittioninfo, 0.f, 0.f, 1.f) + , _groundRadianceEmission(GroundRadianceEmissionInfo, 0.f, 0.f, 1.f) , _rayleighHeightScale(RayleighHeightScaleInfo, 0.f, 0.1f, 50.f) , _rayleighScatteringCoeff( RayleighScatteringCoeffInfo, @@ -282,9 +259,7 @@ RenderableAtmosphere::RenderableAtmosphere(const ghoul::Dictionary& dictionary) _deferredCasterNeedsUpdate = true; _deferredCasterNeedsCalculation = true; }; - auto updateWithoutCalculation = [this]() { - _deferredCasterNeedsUpdate = true; - }; + auto updateWithoutCalculation = [this]() { _deferredCasterNeedsUpdate = true; }; const Parameters p = codegen::bake(dictionary); @@ -413,8 +388,8 @@ glm::dmat4 RenderableAtmosphere::computeModelTransformMatrix( const TransformData& transformData) { // scale the planet to appropriate size since the planet is a unit sphere - return glm::translate(glm::dmat4(1.0), transformData.translation) * // Translation - glm::dmat4(transformData.rotation) * // Spice rotation + return glm::translate(glm::dmat4(1.0), transformData.translation) * + glm::dmat4(transformData.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(transformData.scale)); } @@ -448,7 +423,7 @@ void RenderableAtmosphere::updateAtmosphereParameters() { _deferredcaster->setAtmosphereRadius(_planetRadius + _atmosphereHeight); _deferredcaster->setPlanetRadius(_planetRadius); _deferredcaster->setPlanetAverageGroundReflectance(_groundAverageReflectance); - _deferredcaster->setPlanetGroundRadianceEmittion(_groundRadianceEmission); + _deferredcaster->setPlanetGroundRadianceEmission(_groundRadianceEmission); _deferredcaster->setRayleighHeightScale(_rayleighHeightScale); _deferredcaster->enableOzone(_ozoneEnabled); _deferredcaster->setOzoneHeightScale(_ozoneHeightScale); diff --git a/modules/atmosphere/rendering/renderableatmosphere.h b/modules/atmosphere/rendering/renderableatmosphere.h index 7fe0cbb477..63ec3afeab 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.h +++ b/modules/atmosphere/rendering/renderableatmosphere.h @@ -33,9 +33,7 @@ #include #include #include - #include - #include #include #include @@ -57,16 +55,6 @@ struct ShadowConfiguration { std::pair caster; }; -struct ShadowRenderingStruct { - double xu = 0.0; - double xp = 0.0; - double rs = 0.0; - double rc = 0.0; - glm::dvec3 sourceCasterVec = glm::dvec3(0.0); - glm::dvec3 casterPositionVec = glm::dvec3(0.0); - bool isShadowing = false; -}; - namespace documentation { struct Documentation; } namespace planetgeometry { class PlanetGeometry; } diff --git a/modules/atmosphere/shaders/atmosphere_common.glsl b/modules/atmosphere/shaders/atmosphere_common.glsl index fd0ca1eb2f..6a0884f861 100644 --- a/modules/atmosphere/shaders/atmosphere_common.glsl +++ b/modules/atmosphere/shaders/atmosphere_common.glsl @@ -27,42 +27,38 @@ * from Eric Bruneton is used in the following code. * ****************************************************************************************/ - /** +/** * Precomputed Atmospheric Scattering * Copyright (c) 2008 INRIA * All rights reserved. * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific + * prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - // Atmosphere Rendering Parameters uniform float Rg; uniform float Rt; uniform float AverageGroundReflectance; -uniform float groundRadianceEmittion; +uniform float groundRadianceEmission; uniform float HR; uniform vec3 betaRayleigh; uniform float HO; @@ -75,12 +71,9 @@ uniform float sunRadiance; uniform bool ozoneLayerEnabled; -uniform int TRANSMITTANCE_W; -uniform int TRANSMITTANCE_H; -uniform int SKY_W; -uniform int SKY_H; -uniform int OTHER_TEXTURES_W; -uniform int OTHER_TEXTURES_H; +uniform ivec2 TRANSMITTANCE; +uniform ivec2 SKY; +uniform ivec2 OTHER_TEXTURES; uniform int SAMPLES_R; uniform int SAMPLES_MU; uniform int SAMPLES_MU_S; @@ -95,46 +88,44 @@ const int IRRADIANCE_INTEGRAL_SAMPLES = 32; const int INSCATTER_SPHERICAL_INTEGRAL_SAMPLES = 16; const float M_PI = 3.141592657; +const float M_2PI = 2.0 * M_PI; uniform sampler2D transmittanceTexture; -float Rg2 = Rg * Rg; -float Rt2 = Rt * Rt; -float H = sqrt(Rt2 - Rg2); -float H2 = Rt2 - Rg2; -float invSamplesMu = 1.0f / float(SAMPLES_MU); -float invSamplesR = 1.0f / float(SAMPLES_R); -float invSamplesMuS = 1.0f / float(SAMPLES_MU_S); -float invSamplesNu = 1.0f / float(SAMPLES_NU); +float Rg2 = Rg * Rg; +float Rt2 = Rt * Rt; +float H = sqrt(Rt2 - Rg2); +float H2 = Rt2 - Rg2; +float invSamplesMu = 1.0 / float(SAMPLES_MU); +float invSamplesR = 1.0 / float(SAMPLES_R); +float invSamplesMuS = 1.0 / float(SAMPLES_MU_S); +float invSamplesNu = 1.0 / float(SAMPLES_NU); float RtMinusRg = float(Rt - Rg); -float invRtMinusRg = 1.0f / RtMinusRg; +float invRtMinusRg = 1.0 / RtMinusRg; float opticalDepth(float localH, float r, float mu, float d) { - float invH = 1.0/localH; - float a = sqrt((0.5 * invH)*r); - vec2 a01 = a*vec2(mu, mu + d / r); - vec2 a01s = sign(a01); - vec2 a01sq = a01*a01; - float x = a01s.y > a01s.x ? exp(a01sq.x) : 0.0; - vec2 y = a01s / (2.3193*abs(a01) + sqrt(1.52*a01sq + 4.0)) * vec2(1.0, exp(-d*invH*(d/(2.0*r)+mu))); - return sqrt((6.2831*H)*r) * exp((Rg-r)*invH) * (x + dot(y, vec2(1.0, -1.0))); + float invH = 1.0 / localH; + float a = sqrt(0.5 * invH * r); + vec2 a01 = a * vec2(mu, mu + d / r); + vec2 a01s = sign(a01); + vec2 a01sq = a01 * a01; + float x = a01s.y > a01s.x ? exp(a01sq.x) : 0.0; + vec2 y = a01s / (2.3193 * abs(a01) + sqrt(1.52 * a01sq + 4.0)) * vec2(1.0, exp(-d * invH * (d / (2.0 * r) + mu))); + return sqrt(M_2PI * H * r) * exp((Rg-r)*invH) * (x + dot(y, vec2(1.0, -1.0))); } vec3 analyticTransmittance(float r, float mu, float d) { + vec3 ozone = vec3(0.0); if (ozoneLayerEnabled) { - return exp(-betaRayleigh * opticalDepth(HR, r, mu, d) - - betaOzoneExtinction * (0.0000006) * opticalDepth(HO, r, mu, d) - - betaMieExtinction * opticalDepth(HM, r, mu, d)); - } - else { - return exp(-betaRayleigh * opticalDepth(HR, r, mu, d) - - betaMieExtinction * opticalDepth(HM, r, mu, d)); + ozone = betaOzoneExtinction * (0.0000006) * opticalDepth(HO, r, mu, d); } + return exp(-betaRayleigh * opticalDepth(HR, r, mu, d) - ozone - + betaMieExtinction * opticalDepth(HM, r, mu, d)); } vec3 irradiance(sampler2D sampler, float r, float muSun) { - float u_r = (r - Rg) * invRtMinusRg; - float u_muSun = (muSun + 0.2) / (1.0 + 0.2); + float u_r = (r - Rg) * invRtMinusRg; + float u_muSun = (muSun + 0.2) / 1.2; return texture(sampler, vec2(u_muSun, u_r)).rgb; } @@ -143,160 +134,104 @@ vec3 irradiance(sampler2D sampler, float r, float muSun) { //=============== General Functions ==============// //================================================// // In the following shaders r (altitude) is the length of vector/position x in the -// atmosphere (or on the top of it when considering an observer in space), -// where the light is comming from the opposite direction of the view direction, -// here the vector v or viewDirection. -// Rg is the planet radius and Rt the atmosphere radius. +// atmosphere (or on the top of it when considering an observer in space), where the light +// is coming from the opposite direction of the view direction, here the vector v or +// viewDirection. Rg is the planet radius and Rt the atmosphere radius. -//--- Calculate the distance of the ray starting at x (height r) -// until the planet's ground or top of atmosphere. --- +// Calculate the distance of the ray starting at x (height r) until the planet's ground +// or top of atmosphere // r := || vec(x) || e [0, Rt] // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r float rayDistance(float r, float mu) { - // The light ray starting at the observer in/on the atmosphere can - // have to possible end points: the top of the atmosphere or the - // planet ground. So the shortest path is the one we are looking for, - // otherwise we may be passing through the ground. + // The light ray starting at the observer in/on the atmosphere can have to possible end + // points: the top of the atmosphere or the planet ground. So the shortest path is the + // one we are looking for, otherwise we may be passing through the ground // cosine law - float atmRadiusEps = Rt + ATM_EPSILON; - float rayDistanceAtmosphere = -r * mu + - sqrt(r * r * (mu * mu - 1.0f) + atmRadiusEps * atmRadiusEps); - float delta = r * r * (mu * mu - 1.0f) + Rg * Rg; + float atmRadiusEps2 = (Rt + ATM_EPSILON) * (Rt + ATM_EPSILON); + float mu2 = mu * mu; + float r2 = r * r; + float rg2 = Rg * Rg; + float rayDistanceAtmosphere = -r * mu + sqrt(r2 * (mu2 - 1.0) + atmRadiusEps2); + float delta = r2 * (mu2 - 1.0) + rg2; // Ray may be hitting ground - if (delta >= 0.0f) { + if (delta >= 0.0) { float rayDistanceGround = -r * mu - sqrt(delta); - if (rayDistanceGround >= 0.0f) { + if (rayDistanceGround >= 0.0) { return min(rayDistanceAtmosphere, rayDistanceGround); } } return rayDistanceAtmosphere; } -//-- Given the window's fragment coordinates, for a defined -// viewport, gives back the interpolated r e [Rg, Rt] and -// mu e [-1, 1] -- -// r := height of starting point vect(x) -// mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r -void unmappingRAndMu(out float r, out float mu) { - float u_mu = gl_FragCoord.x / float(TRANSMITTANCE_W); - float u_r = gl_FragCoord.y / float(TRANSMITTANCE_H); - - // In the paper u_r^2 = (r^2-Rg^2)/(Rt^2-Rg^2) - // So, extracting r from u_r in the above equation: - //r = sqrt( Rg * Rg + (u_r * u_r) * (Rt * Rt - Rg * Rg) ); - r = Rg + (u_r * u_r) * RtMinusRg; - - // In the paper the Bruneton suggest mu = dot(v,x)/||x|| with ||v|| = 1.0 - // Later he proposes u_mu = (1-exp(-3mu-0.6))/(1-exp(-3.6)) - // But the below one is better. See Colliene. - // One must remember that mu is defined from 0 to PI/2 + epsillon. - mu = -0.15f + tan(1.5f * u_mu) / tan(1.5f) * (1.0f + 0.15f); -} - -//-- Given the windows's fragment coordinates, for a defined view port, -// gives back the interpolated r e [Rg, Rt] and muSun e [-1, 1] -- -// r := height of starting point vect(x) -// muSun := cosine of the zeith angle of vec(s). Or muSun = (vec(s) * vec(v)) -void unmappingRAndMuSun(out float r, out float muSun) { - // See Bruneton and Colliene to understand the mapping. - muSun = -0.2f + (gl_FragCoord.x - 0.5f) / (float(OTHER_TEXTURES_W) - 1.0f) * (1.0f + 0.2f); - //r = Rg + (gl_FragCoord.y - 0.5f) / (float(OTHER_TEXTURES_H) - 1.0f) * (Rt - Rg); - r = Rg + (gl_FragCoord.y - 0.5f) / (float(OTHER_TEXTURES_H) ) * RtMinusRg; -} - -//-- Given the windows's fragment coordinates, for a defined view port, -// gives back the interpolated r e [Rg, Rt] and muSun e [-1, 1] for the -// Irradiance deltaE texture table -- -// r := height of starting point vect(x) -// muSun := cosine of the zeith angle of vec(s). Or muSun = (vec(s) * vec(v)) -void unmappingRAndMuSunIrradiance(out float r, out float muSun) { - // See Bruneton and Colliene to understand the mapping. - muSun = -0.2f + (gl_FragCoord.x - 0.5f) / (float(SKY_W) - 1.0f) * (1.0f + 0.2f); - r = Rg + (gl_FragCoord.y - 0.5f) / (float(SKY_H) - 1.0f) * RtMinusRg; -} - -//-- Given the windows's fragment coordinates, for a defined view port, -// gives back the interpolated r e [Rg, Rt] and mu, muSun amd nu e [-1, 1] -- +// Given the windows's fragment coordinates, for a defined view port, gives back the +// interpolated r e [Rg, Rt] and mu, muSun amd nu e [-1, 1] // r := height of starting point vect(x) // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r // muSun := cosine of the zeith angle of vec(s). Or muSun = (vec(s) * vec(v)) // nu := cosone of the angle between vec(s) and vec(v) -// dhdH := it is a vec4. dhdH.x stores the dminT := Rt - r, dhdH.y stores the dH value (see paper), -// dhdH.z stores dminG := r - Rg and dhdH.w stores dh (see paper). +// dhdH := it is a vec4. dhdH.x stores the dminT := Rt - r, dhdH.y stores the dH value +// (see paper), dhdH.z stores dminG := r - Rg and dhdH.w stores dh (see paper) void unmappingMuMuSunNu(float r, vec4 dhdH, out float mu, out float muSun, out float nu) { // Window coordinates of pixel (uncentering also) - float fragmentX = gl_FragCoord.x - 0.5f; - float fragmentY = gl_FragCoord.y - 0.5f; + vec2 fragment = gl_FragCoord.xy - vec2(0.5); // Pre-calculations - //float Rg2 = Rg * Rg; - //float Rt2 = Rt * Rt; float r2 = r * r; - float halfSAMPLE_MU = float(SAMPLES_MU) / 2.0f; - // If the (vec(x) dot vec(v))/r is negative, i.e., - // the light ray has great probability to touch - // the ground, we obtain mu considering the geometry - // of the ground - if (fragmentY < halfSAMPLE_MU) { - float ud = 1.0f - (fragmentY / (halfSAMPLE_MU - 1.0f)); + float halfSAMPLE_MU = float(SAMPLES_MU) / 2.0; + // If the (vec(x) dot vec(v))/r is negative, i.e., the light ray has great probability + // to touch the ground, we obtain mu considering the geometry of the ground + if (fragment.y < halfSAMPLE_MU) { + float ud = 1.0 - (fragment.y / (halfSAMPLE_MU - 1.0)); float d = min(max(dhdH.z, ud * dhdH.w), dhdH.w * 0.999); - // cosine law: Rg^2 = r^2 + d^2 - 2rdcos(pi-theta) - // where cosine(theta) = mu + // cosine law: Rg^2 = r^2 + d^2 - 2rdcos(pi-theta) where cosine(theta) = mu mu = (Rg2 - r2 - d * d) / (2.0 * r * d); - // We can't handle a ray inside the planet, i.e., - // when r ~ Rg, so we check against it. - // If that is the case, we approximate to - // a ray touching the ground. + // We can't handle a ray inside the planet, i.e., when r ~ Rg, so we check against it. + // If that is the case, we approximate to a ray touching the ground. // cosine(pi-theta) = dh/r = sqrt(r^2-Rg^2) // cosine(theta) = - sqrt(1 - Rg^2/r^2) mu = min(mu, -sqrt(1.0 - (Rg2 / r2)) - 0.001); } - // The light ray is touching the atmosphere and - // not the ground + // The light ray is touching the atmosphere and not the ground else { - float d = (fragmentY - halfSAMPLE_MU) / (halfSAMPLE_MU - 1.0f); + float d = (fragment.y - halfSAMPLE_MU) / (halfSAMPLE_MU - 1.0); d = min(max(dhdH.x, d * dhdH.y), dhdH.y * 0.999); - // cosine law: Rt^2 = r^2 + d^2 - 2rdcos(pi-theta) - // whre cosine(theta) = mu - mu = (Rt2 - r2 - d * d) / (2.0f * r * d); + // cosine law: Rt^2 = r^2 + d^2 - 2rdcos(pi-theta) where cosine(theta) = mu + mu = (Rt2 - r2 - d * d) / (2.0 * r * d); } - float modValueMuSun = mod(fragmentX, float(SAMPLES_MU_S)) / (float(SAMPLES_MU_S) - 1.0f); + float modValueMuSun = mod(fragment.x, float(SAMPLES_MU_S)) / (float(SAMPLES_MU_S) - 1.0); // The following mapping is different from the paper. See Colliene for an details. - muSun = tan((2.0f * modValueMuSun - 1.0f + 0.26f) * 1.1f) / tan(1.26f * 1.1f); - nu = -1.0f + floor(fragmentX / float(SAMPLES_MU_S)) / (float(SAMPLES_NU) - 1.0f) * 2.0f; + muSun = tan((2.0 * modValueMuSun - 1.0 + 0.26) * 1.1f) / tan(1.26 * 1.1); + nu = -1.0 + floor(fragment.x / float(SAMPLES_MU_S)) / (float(SAMPLES_NU) - 1.0) * 2.0; } - -//-- Function to access the transmittance texture. Given r -// and mu, returns the transmittance of a ray starting at vec(x), -// height r, and direction vec(v), mu, and length until it hits -// the ground or the top of atmosphere. -- +// Function to access the transmittance texture. Given r and mu, returns the transmittance +// of a ray starting at vec(x), height r, and direction vec(v), mu, and length until it +// hits the ground or the top of atmosphere. // r := height of starting point vect(x) // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r -vec3 transmittanceLUT(float r, float mu) { - // Given the position x (here the altitude r) and the view - // angle v (here the cosine(v)= mu), we map this - float u_r = sqrt((r - Rg) * invRtMinusRg); - //float u_r = sqrt((r*r - Rg*Rg) / (Rt*Rt - Rg*Rg)); - // See Colliene to understand the different mapping. - float u_mu = atan((mu + 0.15f) / (1.0f + 0.15f) * tan(1.5f)) / 1.5f; +vec3 transmittance(float r, float mu) { + // Given the position x (here the altitude r) and the view angle v + // (here the cosine(v)= mu), we map this + float u_r = sqrt((r - Rg) * invRtMinusRg); + // See Colliene to understand the mapping + float u_mu = atan((mu + 0.15) / 1.15 * tan(1.5)) / 1.5; return texture(transmittanceTexture, vec2(u_mu, u_r)).rgb; } -// -- Given a position r and direction mu, calculates de transmittance -// along the ray with length d. This function uses the propriety -// of Transmittance: T(a,b) = TableT(a,v)/TableT(b, v) -- +// Given a position r and direction mu, calculates de transmittance along the ray with +// length d. This function uses the propriety of Transmittance: +// T(a,b) = TableT(a,v)/TableT(b, v) // r := height of starting point vect(x) // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r vec3 transmittance(float r, float mu, float d) { - // Here we use the transmittance property: T(x,v) = T(x,d)*T(d,v) - // to, given a distance d, calculates that transmittance along - // that distance starting in x (hight r): T(x,d) = T(x,v)/T(d,v). + // Here we use the transmittance property: T(x,v) = T(x,d)*T(d,v) to, given a distance + // d, calculates that transmittance along that distance starting in x (height r): + // T(x,d) = T(x,v)/T(d,v). // // From cosine law: c^2 = a^2 + b^2 - 2*a*b*cos(ab) float ri = sqrt(d * d + r * r + 2.0 * r * d * mu); @@ -305,105 +240,75 @@ vec3 transmittance(float r, float mu, float d) { // = (r*mu + d) / r_i float mui = (d + r * mu) / ri; - // It's important to remember that we calculate the Transmittance - // table only for zenith angles between 0 and pi/2+episilon. - // Then, if mu < 0.0, we just need to invert the view direction - // and the start and end points between them, i.e., if + // It's important to remember that we calculate the Transmittance table only for zenith + // angles between 0 and pi/2+episilon. Then, if mu < 0.0, we just need to invert the + // view direction and the start and end points between them, i.e., if // x --> x0, then x0-->x. // Also, let's use the property: T(a,c) = T(a,b)*T(b,c) - // Because T(a,c) and T(b,c) are already in the table T, - // T(a,b) = T(a,c)/T(b,c). - if (mu > 0.0f) { - return min(transmittanceLUT(r, mu) / - transmittanceLUT(ri, mui), 1.0f); + // Because T(a,c) and T(b,c) are already in the table T, T(a,b) = T(a,c)/T(b,c). + if (mu > 0.0) { + return min(transmittance(r, mu) / transmittance(ri, mui), 1.0); } else { - return min(transmittanceLUT(ri, -mui) / - transmittanceLUT(r, -mu), 1.0f); + return min(transmittance(ri, -mui) / transmittance(r, -mu), 1.0); } } -// -- Calculates Rayleigh phase function given the -// scattering cosine angle mu -- +// Calculates Rayleigh phase function given the scattering cosine angle mu // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r float rayleighPhaseFunction(float mu) { //return (3.0f / (16.0f * M_PI)) * (1.0f + mu * mu); - return 0.0596831036 * (1.0f + mu * mu); + return 0.0596831036 * (1.0 + mu * mu); } -// -- Calculates Mie phase function given the -// scattering cosine angle mu -- -// mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r -float miePhaseFunction(float mu) { - //return (3.0f / (8.0f * M_PI)) * - // ( ( (1.0f - (mieG * mieG) ) * (1.0f + mu * mu) ) / - // ( (2.0f + mieG * mieG) * - // pow(1.0f + mieG * mieG - 2.0f * mieG * mu, 3.0f/2.0f) ) ); - // return 1.5f * 1.0f / (4.0f * M_PI) * (1.0f - mieG * mieG) * - // pow(1.0f + (mieG * mieG) - 2.0f * mieG * mu, -3.0f/2.0f) * (1.0f + mu * mu) / (2.0f + mieG*mieG); - +// Calculates Mie phase function given the scattering cosine angle mu +// mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v)) / r +// mieG := mie phase function value +float miePhaseFunction(float mu, float mieG) { float mieG2 = mieG * mieG; - return 0.1193662072 * (1.0f - mieG2) * - pow(1.0f + mieG2 - 2.0f * mieG * mu, -1.5f) * (1.0f + mu * mu) / (2.0f + mieG2); + return 0.1193662072 * (1.0 - mieG2) * + pow(1.0 + mieG2 - 2.0 * mieG * mu, -1.5) * (1.0 + mu * mu) / (2.0 + mieG2); } -// -- Given the height rm view-zenith angle (cosine) mu, -// sun-zenith angle (cosine) muSun and the angle (cosine) -// between the vec(s) and vec(v), nu, we access the 3D textures -// and interpolate between them (r) to find the value for the -// 4D texture. -- +// Given the height rm view-zenith angle (cosine) mu, sun-zenith angle (cosine) muSun and +// the angle (cosine) between the vec(s) and vec(v), nu, we access the 3D textures and +// interpolate between them (r) to find the value for the 4D texture. // r := height of starting point vect(x) // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r // muSun := cosine of the zeith angle of vec(s). Or muSun = (vec(s) * vec(v)) // nu := cosine of the angle between vec(s) and vec(v) vec4 texture4D(sampler3D table, float r, float mu, float muSun, float nu) { - //float Rg2 = Rg * Rg; - //float Rt2 = Rt * Rt; - float r2 = r * r; - //float H = sqrt(Rt2 - Rg2); - float rho = sqrt(r2 - Rg2); - float rmu = r * mu; - float delta = rmu * rmu - r2 + Rg2; - //float invSamplesMu = 1.0f / float(SAMPLES_MU); - //float invSamplesR = 1.0f / float(SAMPLES_R); - //float invSamplesMuS = 1.0f / float(SAMPLES_MU_S); - //float invSamplesNu = 1.0f / float(SAMPLES_NU); - // vec4 cst = rmu < 0.0f && delta > 0.0f ? - // vec4(1.0f, 0.0f, 0.0f, 0.5f - 0.5f / float(SAMPLES_MU)) : - // vec4(-1.0f, H * H, H, 0.5f + 0.5f / float(SAMPLES_MU)); + float r2 = r * r; + float rho = sqrt(r2 - Rg2); + float rmu = r * mu; + float delta = rmu * rmu - r2 + Rg2; - vec4 cst = rmu < 0.0f && delta > 0.0f ? - vec4(1.0f, 0.0f, 0.0f, 0.5f - 0.5f * invSamplesMu) : - vec4(-1.0f, H2, H, 0.5f + 0.5f * invSamplesMu); + vec4 cst = rmu < 0.0 && delta > 0.0 ? + vec4(1.0, 0.0, 0.0, 0.5 - 0.5 * invSamplesMu) : + vec4(-1.0, H2, H, 0.5 + 0.5 * invSamplesMu); - //float u_r = 0.5f / float(SAMPLES_R) + rho / H * (1.0f - 1.0f / float(SAMPLES_R)); - float u_r = 0.5f * invSamplesR + rho / H * (1.0f - invSamplesR); - //float u_mu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5f - 1.0f / float(SAMPLES_MU)); - float u_mu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5f - invSamplesMu); - // float u_mu_s = 0.5f / float(SAMPLES_MU_S) + - // (atan(max(muSun, -0.1975) * tan(1.26f * 1.1f)) / 1.1f + (1.0f - 0.26f)) * 0.5f * (1.0f - 1.0f / float(SAMPLES_MU_S)); - float u_mu_s = 0.5f * invSamplesMuS + - (atan(max(muSun, -0.1975) * tan(1.386f)) * 0.9090909090909090 + (0.74f)) * 0.5f * (1.0f - invSamplesMuS); - float lerp = (nu + 1.0f) / 2.0f * (float(SAMPLES_NU) - 1.0f); + float u_r = 0.5 * invSamplesR + rho / H * (1.0 - invSamplesR); + float u_mu = cst.w + (rmu * cst.x + sqrt(delta + cst.y)) / (rho + cst.z) * (0.5 - invSamplesMu); + float u_mu_s = 0.5 * invSamplesMuS + + (atan(max(muSun, -0.1975) * tan(1.386)) * 0.9090909090909090 + 0.74) * 0.5 * (1.0 - invSamplesMuS); + float lerp = (nu + 1.0) / 2.0 * (float(SAMPLES_NU) - 1.0); float u_nu = floor(lerp); lerp = lerp - u_nu; - // return texture(table, vec3((u_nu + u_mu_s) / float(SAMPLES_NU), u_mu, u_r)) * (1.0f - lerp) + - // texture(table, vec3((u_nu + u_mu_s + 1.0f) / float(SAMPLES_NU), u_mu, u_r)) * lerp; - - return texture(table, vec3((u_nu + u_mu_s) * invSamplesNu, u_mu, u_r)) * (1.0f - lerp) + - texture(table, vec3((u_nu + u_mu_s + 1.0f) * invSamplesNu, u_mu, u_r)) * lerp; + return texture( + table, vec3((u_nu + u_mu_s) * invSamplesNu, u_mu, u_r)) * (1.0 - lerp) + + texture(table, vec3((u_nu + u_mu_s + 1.0) * invSamplesNu, u_mu, u_r)) * lerp; } -// -- Given the irradiance texture table, the cosine of zenith sun vector -// and the height of the observer (ray's stating point x), calculates the -// mapping for u_r and u_muSun and returns the value in the LUT. -- +// Given the irradiance texture table, the cosine of zenith sun vector and the height of +// the observer (ray's stating point x), calculates the mapping for u_r and u_muSun and +// returns the value in the LUT // lut := OpenGL texture2D sampler (the irradiance texture deltaE) // muSun := cosine of the zeith angle of vec(s). Or muSun = (vec(s) * vec(v)) // r := height of starting point vect(x) vec3 irradianceLUT(sampler2D lut, float muSun, float r) { // See Bruneton paper and Coliene to understand the mapping - float u_muSun = (muSun + 0.2f) / (1.0f + 0.2f); - float u_r = (r - Rg) * invRtMinusRg; + float u_muSun = (muSun + 0.2) / 1.2; + float u_r = (r - Rg) * invRtMinusRg; return texture(lut, vec2(u_muSun, u_r)).rgb; } diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 6e7872b129..22e861c107 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -32,40 +32,35 @@ * Copyright (c) 2008 INRIA * All rights reserved. * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific + * prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #version __CONTEXT__ #include "floatoperations.glsl" - #include "atmosphere_common.glsl" -out vec4 renderTarget; -in vec3 interpolatedNDCPos; in vec2 texCoord; +out vec4 renderTarget; uniform int nAaSamples; uniform int cullAtmosphere; @@ -87,611 +82,512 @@ uniform dvec3 sunDirectionObj; /******************************************************************************* ***** ALL CALCULATIONS FOR ECLIPSE ARE IN METERS AND IN WORLD SPACE SYSTEM **** *******************************************************************************/ -// JCC: Remove and use dictionary to -// decides the number of shadows +// JCC: Remove and use dictionary to decide the number of shadows const uint numberOfShadows = 1; struct ShadowRenderingStruct { - double xu, xp; - double rs, rc; - dvec3 sourceCasterVec; - dvec3 casterPositionVec; - bool isShadowing; + double xu, xp; + double rs, rc; + dvec3 sourceCasterVec; + dvec3 casterPositionVec; + bool isShadowing; }; // Eclipse shadow data -// JCC: Remove and use dictionary to -// decides the number of shadows +// JCC: Remove and use dictionary to decide the number of shadows uniform ShadowRenderingStruct shadowDataArray[numberOfShadows]; uniform int shadows; uniform bool hardShadows; -vec4 butterworthFunc(float d, float r, float n) { - return vec4(vec3(sqrt(r/(r + pow(d, 2*n)))), 1.0); -} - -vec4 calcShadow(ShadowRenderingStruct shadowInfoArray[numberOfShadows], dvec3 position, - bool ground) +float calcShadow(ShadowRenderingStruct shadowInfoArray[numberOfShadows], dvec3 position, + bool ground) { - if (shadowInfoArray[0].isShadowing) { - dvec3 pc = shadowInfoArray[0].casterPositionVec - position; - dvec3 sc_norm = shadowInfoArray[0].sourceCasterVec; - dvec3 pc_proj = dot(pc, sc_norm) * sc_norm; - dvec3 d = pc - pc_proj; - - float length_d = float(length(d)); - double length_pc_proj = length(pc_proj); - - float r_p_pi = float(shadowInfoArray[0].rc * (length_pc_proj + shadowInfoArray[0].xp) / shadowInfoArray[0].xp); - float r_u_pi = float(shadowInfoArray[0].rc * (shadowInfoArray[0].xu - length_pc_proj) / shadowInfoArray[0].xu); - - if ( length_d < r_u_pi ) { // umbra - if (ground) { - if (hardShadows) { - return vec4(0.2, 0.2, 0.2, 1.0); - } - else { - return butterworthFunc(length_d, r_u_pi, 2.0); - } - } - else { - if (hardShadows) { - return vec4(0.5, 0.5, 0.5, 1.0); - } - else { - //return vec4(vec3(length_d/r_p_pi), 1.0); - return butterworthFunc(length_d, r_u_pi, 2.0); - } - } - } - else if ( length_d < r_p_pi ) {// penumbra - if (hardShadows) { - return vec4(0.5, 0.5, 0.5, 1.0); - } - else { - return vec4(vec3(length_d/r_p_pi), 1.0); - } - } - } - - return vec4(1.0); -} + if (!shadowInfoArray[0].isShadowing) { + return 1.0; + } -/******************************************************************************* - ******* ALL CALCULATIONS FOR ATMOSPHERE ARE KM AND IN WORLD SPACE SYSTEM ****** - *******************************************************************************/ - -struct dRay { - dvec4 origin; - dvec4 direction; -}; - -/* Function to calculate the initial intersection of the eye (camera) ray - * with the atmosphere. - * In (all parameters in the same coordinate system and same units): - * - planet position - * - ray direction (normalized) - * - eye position - * - atmosphere radius - * Out: true if an intersection happens, false otherwise - * - inside: true if the ray origin is inside atmosphere, false otherwise - * - offset: the initial intersection distance from eye position when - * the eye is outside the atmosphere - * - maxLength : the second intersection distance from eye position when the - * eye is outside the atmosphere or the initial (and only) - * intersection of the ray with atmosphere when the eye position - * is inside atmosphere. - */ -bool dAtmosphereIntersection(dvec3 planetPosition, dRay ray, double atmRadius, - out bool inside, out double offset, out double maxLength ) { - dvec3 l = planetPosition - ray.origin.xyz; - double s = dot(l, ray.direction.xyz); - double l2 = dot(l, l); - double r2 = atmRadius * atmRadius; // avoiding surface acne - - // Ray origin (eye position) is behind sphere - if ((s < 0.0) && (l2 > r2)) { - inside = false; - offset = 0.0; - maxLength = 0.0; - return false; - } - - double m2 = l2 - s*s; - - // Ray misses atmospere - if (m2 > r2) { - inside = false; - offset = 0.0; - maxLength = 0.0; - return false; - } - - // We already now the ray hits the atmosphere - - // If q = 0.0f, there is only one intersection - double q = sqrt(r2 - m2); - - // If l2 < r2, the ray origin is inside the sphere - if (l2 > r2) { - inside = false; - offset = s - q; - maxLength = s + q; + dvec3 pc = shadowInfoArray[0].casterPositionVec - position; + dvec3 sc_norm = shadowInfoArray[0].sourceCasterVec; + dvec3 pc_proj = dot(pc, sc_norm) * sc_norm; + dvec3 d = pc - pc_proj; + + float length_d = float(length(d)); + double length_pc_proj = length(pc_proj); + + float r_p_pi = float(shadowInfoArray[0].rc * (length_pc_proj + shadowInfoArray[0].xp) / shadowInfoArray[0].xp); + float r_u_pi = float(shadowInfoArray[0].rc * (shadowInfoArray[0].xu - length_pc_proj) / shadowInfoArray[0].xu); + + if (length_d < r_u_pi) { + // umbra + if (hardShadows) { + return ground ? 0.2 : 0.5; } else { - inside = true; - offset = 0.0; - maxLength = s + q; + // butterworth function + return sqrt(r_u_pi / (r_u_pi + pow(length_d, 4.0))); } - - return true; + } + else if (length_d < r_p_pi) { + // penumbra + return hardShadows ? 0.5 : length_d / r_p_pi; + } + else { + return 1.0; + } +} + +////////////////////////////////////////////////////////////////////////////////////////// +// ALL CALCULATIONS FOR ATMOSPHERE ARE KM AND IN WORLD SPACE SYSTEM // +////////////////////////////////////////////////////////////////////////////////////////// + +struct Ray { + dvec3 origin; + dvec3 direction; +}; + +/* + * Function to calculate the initial intersection of the eye (camera) ray with the + * atmosphere. + * In (all parameters in the same coordinate system and same units): + * - ray direction (normalized) + * - atmosphere radius + * Out: true if an intersection happens, false otherwise + * - return: true if the ray origin is inside atmosphere, false otherwise + * - offset: the initial intersection distance from eye position when the eye is outside + * the atmosphere + * - maxLength: the second intersection distance from eye position when the eye is + * outside the atmosphere or the initial (and only) intersection of the ray + * with atmosphere when the eye position is inside atmosphere. + */ +bool atmosphereIntersection(Ray ray, double atmRadius, out double offset, + out double maxLength) +{ + dvec3 l = -ray.origin; + double s = dot(l, ray.direction); + double l2 = dot(l, l); + double r2 = atmRadius * atmRadius; // avoiding surface acne + + // Ray origin (eye position) is behind sphere + if ((s < 0.0) && (l2 > r2)) { + offset = 0.0; + maxLength = 0.0; + return false; + } + + double m2 = l2 - s * s; + + // Ray misses atmosphere + if (m2 > r2) { + offset = 0.0; + maxLength = 0.0; + return false; + } + + // We already now the ray hits the atmosphere + + // If q = 0.0, there is only one intersection + double q = sqrt(r2 - m2); + + // If l2 < r2, the ray origin is inside the sphere + if (l2 > r2) { + offset = s - q; + maxLength = s + q; + } + else { + offset = 0.0; + maxLength = s + q; + } + + return true; } /* - * Calculates Intersection Ray by walking through - * all the graphic pipile transformations in the - * opposite direction. - * Instead of passing through all the pipeline, - * it starts at NDC from the interpolated - * positions from the screen quad. - * This method avoids matrices multiplications - * wherever is possible. + * Calculates Intersection Ray by walking through all the graphic pipeline transformations + * in the opposite direction. Instead of passing through all the pipeline, it starts at + * NDC from the interpolated positions from the screen quad. This method avoids matrices + * multiplications wherever is possible. */ -void dCalculateRayRenderableGlobe(out dRay ray, - out dvec4 planetPositionObjectCoords, - out dvec4 cameraPositionInObject) { - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy, 1.0, 1.0); +Ray calculateRayRenderableGlobe() { + vec2 interpolatedNDCPos = (texCoord - 0.5) * 2.0; + dvec4 clipCoords = dvec4(interpolatedNDCPos, 1.0, 1.0); - // Clip to Object Coords - dvec4 objectCoords = dSgctProjectionToModelTransformMatrix * clipCoords; - - objectCoords /= objectCoords.w; - - // Planet Position in Object Space - // JCC: Applying the inverse of the model transformation on the object postion in World - // space results in imprecision. - planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); - - // Camera Position in Object Space (in meters) - cameraPositionInObject = dCamPosObj; - - // ============================ - // ====== Building Ray ======== - // Ray in object space (in KM) - ray.origin = cameraPositionInObject * dvec4(0.001, 0.001, 0.001, 1.0); - //ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); - ray.direction = dvec4(normalize((objectCoords.xyz * dvec3(0.001))- ray.origin.xyz), 0.0); + // Clip to Object Coords + dvec4 objectCoords = dSgctProjectionToModelTransformMatrix * clipCoords; + objectCoords /= objectCoords.w; + + // Building Ray + // Ray in object space (in KM) + Ray ray; + ray.origin = dvec3(dCamPosObj * dvec4(0.001, 0.001, 0.001, 1.0)); + ray.direction = normalize(objectCoords.xyz * dvec3(0.001) - ray.origin); + return ray; } /* - * Calculates the light scattering in the view direction comming from other - * light rays scattered in the atmosphere. + * Calculates the light scattering in the view direction comming from other light rays + * scattered in the atmosphere. * Following the paper: S[L]|x - T(x,xs) * S[L]|xs - * The view direction here is the ray: x + tv, s is the sun direction, - * r and mu the position and zenith cosine angle as in the paper. + * The view direction here is the ray: x + tv, s is the sun direction, r and mu the + * position and zenith cosine angle as in the paper. * Arguments: * x := camera position * t := ray displacement variable after calculating the intersection with the - * atmosphere. It is the distance from the camera to the last intersection with - * the atmosphere. If the ray hits the ground, t is updated to the correct value + * atmosphere. It is the distance from the camera to the last intersection with the + * atmosphere. If the ray hits the ground, t is updated to the correct value * v := view direction (ray's direction) (normalized) * s := Sun direction (normalized) * r := out of ||x|| inside atmosphere (or top of atmosphere) * mu := out of cosine of the zenith view angle - * attenuation := out of transmittance T(x,x0). This will be used later when - * calculating the reflectance R[L]. + * attenuation := out of transmittance T(x,x0). This will be used later when calculating + * the reflectance R[L] */ -vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor, - vec3 v, vec3 s, out float r, out float mu, - out vec3 attenuation, vec3 fragPosObj, out bool groundHit, - double maxLength, double pixelDepth, - vec4 spaceColor, float sunIntensity) { +vec3 inscatterRadiance(vec3 x, inout float t, out float irradianceFactor, vec3 v, vec3 s, + out float r, out float mu, out vec3 attenuation, vec3 fragPosObj, + out bool groundHit, double maxLength, double pixelDepth, + vec4 spaceColor, float sunIntensity) +{ + const float INTERPOLATION_EPS = 0.004; // precision const from Brunetton - const float INTERPOLATION_EPS = 0.004f; // precision const from Brunetton + vec3 radiance; + + r = length(x); + mu = dot(x, v) / r; - vec3 radiance; + float r2 = r * r; + float nu = dot(v, s); + float muSun = dot(x, s) / r; + float rayleighPhase = rayleighPhaseFunction(nu); + float miePhase = miePhaseFunction(nu, mieG); - r = length(x); - mu = dot(x, v) / r; + // S[L](x,s,v) + // I.e. the next line has the scattering light for the "infinite" ray passing through + // the atmosphere. If this ray hits something inside the atmosphere, we will subtract + // the attenuated scattering light from that path in the current path + vec4 inscatterRadiance = max(texture4D(inscatterTexture, r, mu, muSun, nu), 0.0); + + // After removing the initial path from camera pos to top of atmosphere (for an + // observer in the space) we test if the light ray is hitting the atmosphere + float r0 = length(fragPosObj); + float invr0 = 1.0 / r0; + float muSun0 = dot(fragPosObj, s) * invr0; + float mu0 = dot(fragPosObj, v) * invr0; - float mu2 = mu * mu; - float r2 = r * r; - float nu = dot(v, s); - float muSun = dot(x, s) / r; - float rayleighPhase = rayleighPhaseFunction(nu); - float miePhase = miePhaseFunction(nu); - - // S[L](x,s,v) - // I.e. the next line has the scattering light for the "infinite" ray passing - // through the atmosphere. If this ray hits something inside the atmosphere, - // we will subtract the attenuated scattering light from that path in the - // current path. - vec4 inscatterRadiance = max(texture4D(inscatterTexture, r, mu, muSun, nu), 0.0); - - // After removing the initial path from camera pos to top of atmosphere (for an - // observer in the space) we test if the light ray is hitting the atmosphere - vec3 x0 = fragPosObj; - float r0 = length(fragPosObj); - float invr0 = 1.0/r0; - float muSun0 = dot(fragPosObj, s) * invr0; - //vec3 x0 = x + float(pixelDepth) * v; - float mu0 = dot(x0, v) * invr0; + if ((pixelDepth > INTERPOLATION_EPS) && (pixelDepth < maxLength)) { + t = float(pixelDepth); + groundHit = true; + + // Transmittance from point r, direction mu, distance t + // By Analytical calculation + // attenuation = analyticTransmittance(r, mu, t); + // JCC: change from analytical to LUT transmittance to avoid + // acme on planet surface when looking from far away. (11/02/2017) + attenuation = transmittance(r, mu, t); + + // Here we use the idea of S[L](a->b) = S[L](b->a), and get the S[L](x0, v, s) + // Then we calculate S[L] = S[L]|x - T(x, x0)*S[L]|x0 + // The "infinite" ray hist something inside the atmosphere, so we need to remove + // the unsused contribution to the final radiance. + vec4 inscatterFromSurface = texture4D(inscatterTexture, r0, mu0, muSun0, nu); + inscatterRadiance = max(inscatterRadiance - attenuation.rgbr * inscatterFromSurface, 0.0); - if ((pixelDepth > INTERPOLATION_EPS) && (pixelDepth < maxLength)) { - t = float(pixelDepth); - groundHit = true; - - // Transmittance from point r, direction mu, distance t - // By Analytical calculation - //attenuation = analyticTransmittance(r, mu, t); - // JCC: change from analytical to LUT transmittance to avoid - // acme on planet surface when looking from far away. (11/02/2017) - attenuation = transmittance(r, mu, t); - - // Here we use the idea of S[L](a->b) = S[L](b->a), and get the S[L](x0, v, s) - // Then we calculate S[L] = S[L]|x - T(x, x0)*S[L]|x0 - // The "infinite" ray hist something inside the atmosphere, so we need to remove - // the unsused contribution to the final radiance. - vec4 inscatterFromSurface = texture4D(inscatterTexture, r0, mu0, muSun0, nu); - inscatterRadiance = max(inscatterRadiance - attenuation.rgbr * inscatterFromSurface, 0.0); + // We set the irradianceFactor to 1.0 so the reflected irradiance will be considered + // when calculating the reflected light on the ground. + irradianceFactor = 1.0; + } + else { + attenuation = analyticTransmittance(r, mu, t); + groundHit = false; + } - // We set the irradianceFactor to 1.0 so the reflected irradiance will be considered - // when calculating the reflected light on the ground. - irradianceFactor = 1.0; - } - else { - attenuation = analyticTransmittance(r, mu, t); - //attenuation = transmittance(r, mu, t); - groundHit = false; - } + // cos(PI-thetaH) = dist/r + // cos(thetaH) = - dist/r + // muHorizon = -sqrt(r^2-Rg^2)/r = -sqrt(1-(Rg/r)^2) + float muHorizon = -sqrt(1.0 - Rg2 / r2); - // cos(PI-thetaH) = dist/r - // cos(thetaH) = - dist/r - // muHorizon = -sqrt(r^2-Rg^2)/r = -sqrt(1-(Rg/r)^2) - float muHorizon = -sqrt(1.0f - (Rg2 / r2)); + // In order to avoid imprecision problems near horizon, we interpolate between two + // points: above and below horizon + if (abs(mu - muHorizon) < INTERPOLATION_EPS) { + // We want an interpolation value close to 1/2, so the contribution of each radiance + // value is almost the same or it has a heavy weight if from above or + // below horizon + float interpolationValue = (mu - muHorizon + INTERPOLATION_EPS) / (2.0 * INTERPOLATION_EPS); - // In order to avoid imprecision problems near horizon, - // we interpolate between two points: above and below horizon - if (abs(mu - muHorizon) < INTERPOLATION_EPS) { - // We want an interpolation value close to 1/2, so the - // contribution of each radiance value is almost the same - // or it has a heavy weight if from above or below horizon - float interpolationValue = ((mu - muHorizon) + INTERPOLATION_EPS) / (2.0f * INTERPOLATION_EPS); + // Above Horizon + mu = muHorizon - INTERPOLATION_EPS; + // r0 = sqrt(r * r + t * t + 2.0f * r * t * mu); + // From cosine law where t = distance between x and x0 + // r0^2 = r^2 + t^2 - 2 * r * t * cos(PI-theta) + // r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); + float halfCossineLaw1 = r2 + (t * t); + float halfCossineLaw2 = 2.0 * r * t; + r0 = sqrt(halfCossineLaw1 + halfCossineLaw2 * mu); + + // From the dot product: cos(theta0) = (x0 dot v)/(||ro||*||v||) + // mu0 = ((x + t) dot v) / r0 + // mu0 = (x dot v + t dot v) / r0 + // mu0 = (r*mu + t) / r0 + mu0 = (r * mu + t) * (1.0 / r0); + + vec4 inScatterAboveX = texture4D(inscatterTexture, r, mu, muSun, nu); + vec4 inScatterAboveXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); + // Attention for the attenuation.r value applied to the S_Mie + vec4 inScatterAbove = max(inScatterAboveX - attenuation.rgbr * inScatterAboveXs, 0.0); - //float t2 = t * t; - - // Above Horizon - mu = muHorizon - INTERPOLATION_EPS; - //r0 = sqrt(r * r + t * t + 2.0f * r * t * mu); - // From cosine law where t = distance between x and x0 - // r0^2 = r^2 + t^2 - 2 * r * t * cos(PI-theta) - //r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); - float halfCossineLaw1 = r2 + (t * t); - float halfCossineLaw2 = 2.0f * r * t; - r0 = sqrt(halfCossineLaw1 + halfCossineLaw2 * mu); - - float invr0 = 1.0/r0; - // From the dot product: cos(theta0) = (x0 dot v)/(||ro||*||v||) - // mu0 = ((x + t) dot v) / r0 - // mu0 = (x dot v + t dot v) / r0 - // mu0 = (r*mu + t) / r0 - mu0 = (r * mu + t) * invr0; - - vec4 inScatterAboveX = texture4D(inscatterTexture, r, mu, muSun, nu); - vec4 inScatterAboveXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); - // Attention for the attenuation.r value applied to the S_Mie - vec4 inScatterAbove = max(inScatterAboveX - attenuation.rgbr * inScatterAboveXs, 0.0f); + // Below Horizon + mu = muHorizon + INTERPOLATION_EPS; + //r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); + r0 = sqrt(halfCossineLaw1 + halfCossineLaw2 * mu); + + mu0 = (r * mu + t) * (1.0 / r0); + + vec4 inScatterBelowX = texture4D(inscatterTexture, r, mu, muSun, nu); + vec4 inScatterBelowXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); + // Attention for the attenuation.r value applied to the S_Mie + vec4 inScatterBelow = max(inScatterBelowX - attenuation.rgbr * inScatterBelowXs, 0.0); - // Below Horizon - mu = muHorizon + INTERPOLATION_EPS; - //r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); - r0 = sqrt(halfCossineLaw1 + halfCossineLaw2 * mu); - invr0 = 1.0/r0; - - mu0 = (r * mu + t) * invr0; - - vec4 inScatterBelowX = texture4D(inscatterTexture, r, mu, muSun, nu); - vec4 inScatterBelowXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); - // Attention for the attenuation.r value applied to the S_Mie - vec4 inScatterBelow = max(inScatterBelowX - attenuation.rgbr * inScatterBelowXs, 0.0); + // Interpolate between above and below inScattering radiance + inscatterRadiance = mix(inScatterAbove, inScatterBelow, interpolationValue); + } - // Interpolate between above and below inScattering radiance - inscatterRadiance = mix(inScatterAbove, inScatterBelow, interpolationValue); - } - - // The w component of inscatterRadiance has stored the Cm,r value (Cm = Sm[L0]) - // So, we must reintroduce the Mie inscatter by the proximity rule as described in the - // paper by Bruneton and Neyret in "Angular precision" paragraph: - - // Hermite interpolation between two values - // This step is done because imprecision problems happen when the Sun is slightly below - // the horizon. When this happens, we avoid the Mie scattering contribution. - inscatterRadiance.w *= smoothstep(0.0f, 0.02f, muSun); - vec3 inscatterMie = inscatterRadiance.rgb * inscatterRadiance.a / max(inscatterRadiance.r, 1e-4) * + // The w component of inscatterRadiance has stored the Cm,r value (Cm = Sm[L0]) + // So, we must reintroduce the Mie inscatter by the proximity rule as described in the + // paper by Bruneton and Neyret in "Angular precision" paragraph: + + // Hermite interpolation between two values + // This step is done because imprecision problems happen when the Sun is slightly + // below the horizon. When this happens, we avoid the Mie scattering contribution + inscatterRadiance.w *= smoothstep(0.0, 0.02, muSun); + vec3 inscatterMie = + inscatterRadiance.rgb * inscatterRadiance.a / max(inscatterRadiance.r, 1e-4) * (betaRayleigh.r / betaRayleigh); - - radiance = max(inscatterRadiance.rgb * rayleighPhase + inscatterMie * miePhase, 0.0f); - // Finally we add the Lsun (all calculations are done with no Lsun so - // we can change it on the fly with no precomputations) - // return radiance * sunRadiance; - vec3 finalScatteringRadiance = radiance * sunIntensity; - - if (groundHit) { - return finalScatteringRadiance; - } - else { - //return ((r-Rg) * invRtMinusRg)*spaceColor.rgb + finalScatteringRadiance; - return spaceColor.rgb + finalScatteringRadiance; - // return attenuation * spaceColor.rgb + - // (vec3(1.0) - attenuation) * finalScatteringRadiance; - } + radiance = max(inscatterRadiance.rgb * rayleighPhase + inscatterMie * miePhase, 0.0); + + // Finally we add the Lsun (all calculations are done with no Lsun so we can change it + // on the fly with no precomputations) + vec3 finalScatteringRadiance = radiance * sunIntensity; + + if (groundHit) { + return finalScatteringRadiance; + } + else { + return spaceColor.rgb + finalScatteringRadiance; + } } /* - * Calculates the light reflected in the view direction comming from other - * light rays integrated over the hemispehre plus the direct light (L0) from Sun. + * Calculates the light reflected in the view direction comming from other light rays + * integrated over the hemispehre plus the direct light (L0) from Sun. * Following the paper: R[L]= R[L0]+R[L*] - * The the ray is x + tv, v the view direction, s is the sun direction, - * r and mu the position and zenith cosine angle as in the paper. - * As for all calculations in the atmosphere, the center of the coordinate system - * is the planet's center of coordiante system, i.e., the planet's position is (0,0,0). + * The ray is x + tv, v the view direction, s is the sun direction, r and mu the position + * and zenith cosine angle as in the paper. + * As for all calculations in the atmosphere, the center of the coordinate system is the + * planet's center of coordiante system, i.e., the planet's position is (0,0,0). * Arguments: * x := camera position * t := ray displacement variable. Here, differently from the inScatter light calculation, - * the position of the camera is already offset (on top of atmosphere) or inside - * the atmosphere. + * the position of the camera is already offset (on top of atmosphere) or inside + * the atmosphere * v := view direction (ray's direction) (normalized) * s := Sun direction (normalized) - * r := ||x|| inside atmosphere (or top of atmosphere). r <= Rt here. * mu := cosine of the zenith view angle * attenuationXtoX0 := transmittance T(x,x0) */ -vec3 groundColor(vec3 x, float t, vec3 v, vec3 s, float r, - float mu, vec3 attenuationXtoX0, vec4 groundColor, - vec3 normal, float irradianceFactor, - float waterReflectance, float sunIntensity) +vec3 groundColor(vec3 x, float t, vec3 v, vec3 s, vec3 attenuationXtoX0, vec3 groundColor, + vec3 normal, float irradianceFactor, float waterReflectance, + float sunIntensity) { - vec3 reflectedRadiance = vec3(0.0f); + vec3 reflectedRadiance = vec3(0.0); - // First we obtain the ray's end point on the surface - vec3 x0 = x + t * v; - float r0 = length(x0); - // Normal of intersection point. - // Normal must be normalized. - vec3 n = normal; - //vec4 groundReflectance = groundColor * vec4(.37); - vec4 groundReflectance = groundColor * - vec4(groundRadianceEmittion, groundRadianceEmittion, groundRadianceEmittion, 1.0f); + // First we obtain the ray's end point on the surface + float r0 = length(x + t * v); - // L0 is not included in the irradiance texture. - // We first calculate the light attenuation from the top of the atmosphere - // to x0. - float dotNS = dot(n, s); - float muSun = max(dotNS, 0.0f); + vec3 groundReflectance = groundColor * groundRadianceEmission; - // Is direct Sun light arriving at x0? If not, there is no direct light from Sun (shadowed) - vec3 transmittanceL0 = muSun < -sqrt(1.0f - (Rg2 / (r0 * r0))) ? - vec3(0.0f) : transmittanceLUT(r0, muSun); - // E[L*] at x0 - vec3 irradianceReflected = irradiance(irradianceTexture, r0, muSun) * irradianceFactor; + // L0 is not included in the irradiance texture. + // We first calculate the light attenuation from the top of the atmosphere to x0 + float dotNS = dot(normal, s); + float muSun = max(dotNS, 0.0); - // R[L0] + R[L*] - // vec3 groundRadiance = (dotNS < -0.2f ? groundReflectance.rgb * 15 : groundReflectance.rgb) * - // (muSun * transmittanceL0 + irradianceReflected) * sunIntensity / M_PI; + // Is direct Sun light arriving at x0? If not, there is no direct light from Sun (shadowed) + vec3 transmittanceL0 = + muSun < -sqrt(1.0 - (Rg2 / (r0 * r0))) ? vec3(0.0) : transmittance(r0, muSun); - vec3 groundRadiance; - vec3 RLStar = (muSun * transmittanceL0 + irradianceReflected) * sunIntensity / M_PI; - if (dotNS < 0.05f) { - groundRadiance = groundReflectance.rgb * mix(30.0f, 1.0f, smoothstep(-1.0f, 0.05f, dotNS)) * RLStar; - } - else { - groundRadiance = groundReflectance.rgb * RLStar; - } + // E[L*] at x0 + vec3 irradianceReflected = irradiance(irradianceTexture, r0, muSun) * irradianceFactor; - // Specular reflection from sun on oceans and rivers - if ((waterReflectance > 0.1f) && /*(dotNS > -0.2f)*/(muSun > 0.0f)) { - vec3 h = normalize(s - v); - // Fresnell Schlick's approximation - float fresnel = 0.02f + 0.98f * pow(1.0f - dot(-v, h), 5.0f); - // Walter BRDF approximation - float waterBrdf = fresnel * pow(max(dot(h, n), 0.0f), 150.0f); - // Adding Fresnell and Water BRDFs approximation to the final surface color - // (After adding the sunRadiance and the attenuation of the Sun through atmosphere) - groundRadiance += waterReflectance * max(waterBrdf, 0.0f) * transmittanceL0 * sunIntensity; - } - //return groundRadiance; - // Finally, we attenuate the surface Radiance from the the point x0 to the camera location. - reflectedRadiance = attenuationXtoX0 * groundRadiance; - - // Returns reflectedRadiance = 0.0 if the ray doesn't hit the ground. - return reflectedRadiance; + // R[L0] + R[L*] + vec3 RLStar = (muSun * transmittanceL0 + irradianceReflected) * sunIntensity / M_PI; + vec3 groundRadiance = + dotNS < 0.05 ? + groundReflectance * mix(30.0, 1.0, smoothstep(-1.0, 0.05, dotNS)) * RLStar : + groundReflectance * RLStar; + + // Specular reflection from sun on oceans and rivers + if ((waterReflectance > 0.1) && (muSun > 0.0)) { + vec3 h = normalize(s - v); + // Fresnell Schlick's approximation + float fresnel = 0.02 + 0.98 * pow(1.0 - dot(-v, h), 5.0); + // Walter BRDF approximation + float waterBrdf = fresnel * pow(max(dot(h, normal), 0.0), 150.0); + // Adding Fresnell and Water BRDFs approximation to the final surface color + // after adding the sunRadiance and the attenuation of the Sun through atmosphere + groundRadiance += waterReflectance * max(waterBrdf, 0.0) * transmittanceL0 * sunIntensity; + } + + // Finally, we attenuate the surface Radiance from the point x0 to the camera location + reflectedRadiance = attenuationXtoX0 * groundRadiance; + + // Returns reflectedRadiance = 0.0 if the ray doesn't hit the ground. + return reflectedRadiance; } /* - * Calculates the Sun color. - * The the ray is x + tv, v the view direction, s is the sun direction, - * r and mu the position and zenith cosine angle as in the paper. - * As for all calculations in the atmosphere, the center of the coordinate system - * is the planet's center of coordiante system, i.e., the planet's position is (0,0,0). - * Arguments: - * x := camera position - * t := ray displacement variable. Here, differently from the inScatter light calculation, - * the position of the camera is already offset (on top of atmosphere) or inside - * the atmosphere. + * Calculates the Sun color. The ray is x + tv, v the view direction, s is the sun + * direction, r and mu the position and zenith cosine angle as in the paper. As for all + * calculations in the atmosphere, the center of the coordinate system is the planet's + * center of coordiante system, i.e., the planet's position is (0,0,0). Arguments: * v := view direction (ray's direction) (normalized) * s := Sun direction (normalized) * r := ||x|| inside atmosphere (or top of atmosphere). r <= Rt here. * mu := cosine of the zenith view angle * attenuation := transmittance T(x,x0) */ -vec3 sunColor(vec3 x, float t, vec3 v, vec3 s, float r, float mu, float irradianceFactor) -{ - vec3 transmittance = (r <= Rt) ? ( mu < -sqrt(1.0f - Rg2/(r*r)) ? - vec3(0.0f) : transmittanceLUT(r, mu)) : vec3(1.0f); - // JCC: Change this function to a impostor texture with gaussian decay color weighted - // by tge sunRadiance, transmittance and irradianceColor (11/03/2017) - float sunFinalColor = smoothstep(cos(M_PI / 500.0f), cos(M_PI / 900.0f), dot(v, s)) * - sunRadiance * (1.0f - irradianceFactor); +vec3 sunColor(vec3 v, vec3 s, float r, float mu, float irradianceFactor) { + vec3 tm = vec3(1.0); + if (r <= Rt) { + tm = mu < -sqrt(1.0 - Rg2 / (r * r)) ? vec3(0.0) : transmittance(r, mu); + } + // JCC: Change this function to a impostor texture with gaussian decay color weighted + // by the sunRadiance, transmittance and irradianceColor (11/03/2017) + float sunFinalColor = smoothstep(cos(M_PI / 500.0), cos(M_PI / 900.0), dot(v, s)) * + sunRadiance * (1.0 - irradianceFactor); - return transmittance * sunFinalColor; + return tm * sunFinalColor; } void main() { - if (cullAtmosphere == 0) { - vec4 atmosphereFinalColor = vec4(0.0f); - int nSamples = 1; - - // First we determine if the pixel is complex (different fragments on it) - bool complex = false; - vec4 oldColor, currentColor; - vec4 colorTexture; - - colorTexture = texture(mainColorTexture, texCoord); - - // Color from G-Buffer - vec4 color = colorTexture; - // Ray in object space - dRay ray; - dvec4 planetPositionObjectCoords = dvec4(0.0); - dvec4 cameraPositionInObject = dvec4(0.0); - - // Get the ray from camera to atm in object space - dCalculateRayRenderableGlobe(ray, planetPositionObjectCoords, - cameraPositionInObject); - - bool insideATM = false; - double offset = 0.0; // in Km - double maxLength = 0.0; // in Km + if (cullAtmosphere == 1) { + renderTarget = texture(mainColorTexture, texCoord); + return; + } - bool intersectATM = false; + vec4 atmosphereFinalColor = vec4(0.0); + int nSamples = 1; + + // Color from G-Buffer + vec4 color = texture(mainColorTexture, texCoord); + + // Get the ray from camera to atm in object space + Ray ray = calculateRayRenderableGlobe(); + + double offset = 0.0; // in KM + double maxLength = 0.0; // in KM + bool intersect = atmosphereIntersection(ray, Rt - (ATM_EPSILON * 0.001), offset, maxLength); + if (!intersect) { + renderTarget = color; + return; + } - intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, ray, - Rt - (ATM_EPSILON * 0.001), insideATM, offset, maxLength); - - if ( intersectATM ) { - // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel - // in the G-Buffer positions is less than the distance to the atmosphere then the atmosphere - // is occluded - // Fragments positions into G-Buffer are written in SGCT Eye Space (View plus Camera Rig Coords) - // when using their positions later, one must convert them to the planet's coords - - // ======================= - // Get data from G-Buffer - // ======================= + // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel in + // the G-Buffer positions is less than the distance to the atmosphere then the + // atmosphere is occluded. Fragments positions into G-Buffer are written in SGCT Eye + // Space (View plus Camera Rig Coords) when using their positions later, one must + // convert them to the planet's coords - // Normal is stored in SGCT View Space and transformed to the current object space - vec4 normalViewSpaceAndWaterReflectance = texture(mainNormalTexture, texCoord); - dvec4 normalViewSpace = vec4(normalViewSpaceAndWaterReflectance.xyz, 0.0); - dvec4 normalWorldSpace = dSGCTViewToWorldMatrix * normalViewSpace; - vec4 normal = vec4(dInverseModelTransformMatrix * normalWorldSpace); - normal.xyz = normalize(normal.xyz); - normal.w = normalViewSpaceAndWaterReflectance.w; + // + // Get data from G-Buffer - // Data in the mainPositionTexture are written in view space (view plus camera rig) - vec4 position = texture(mainPositionTexture, texCoord); + // Normal is stored in SGCT View Space and transformed to the current object space + vec4 normalViewSpaceAndWaterReflectance = texture(mainNormalTexture, texCoord); + dvec4 normalViewSpace = vec4(normalViewSpaceAndWaterReflectance.xyz, 0.0); + dvec4 normalWorldSpace = dSGCTViewToWorldMatrix * normalViewSpace; + vec4 normal = vec4(dInverseModelTransformMatrix * normalWorldSpace); + normal.xyz = normalize(normal.xyz); + normal.w = normalViewSpaceAndWaterReflectance.w; - // OS Eye to World coords - dvec4 positionWorldCoords = dSGCTViewToWorldMatrix * position; + // Data in the mainPositionTexture are written in view space (view plus camera rig) + vec4 position = texture(mainPositionTexture, texCoord); - // World to Object (Normal and Position in meters) - dvec4 positionObjectsCoords = dInverseModelTransformMatrix * positionWorldCoords; + // OS Eye to World coords + dvec4 positionWorldCoords = dSGCTViewToWorldMatrix * position; - - // Distance of the pixel in the gBuffer to the observer - // JCC (12/12/2017): AMD distance function is buggy. - //double pixelDepth = distance(cameraPositionInObject.xyz, positionObjectsCoords.xyz); - double pixelDepth = length(cameraPositionInObject.xyz - positionObjectsCoords.xyz); - - // JCC (12/13/2017): Trick to remove floating error in texture. - // We see a squared noise on planet's surface when seeing the planet - // from far away. - float dC = float(length(cameraPositionInObject.xyz)); - float x1 = 1e8; - if (dC > x1) { - pixelDepth += 1000.0; - float alpha = 1000.0; - float beta = 1000000.0; - float x2 = 1e9; - float diffGreek = beta - alpha; - float diffDist = x2 - x1; - float varA = diffGreek/diffDist; - float varB = (alpha - varA * x1); - pixelDepth += double(varA * dC + varB); - } + // World to Object (Normal and Position in meters) + dvec4 positionObjectsCoords = dInverseModelTransformMatrix * positionWorldCoords; - // All calculations are done in Km: - pixelDepth *= 0.001; - positionObjectsCoords.xyz *= 0.001; + // Distance of the pixel in the gBuffer to the observer + // JCC (12/12/2017): AMD distance function is buggy. + //double pixelDepth = distance(cameraPositionInObject.xyz, positionObjectsCoords.xyz); + double pixelDepth = length(dCamPosObj.xyz - positionObjectsCoords.xyz); + + // JCC (12/13/2017): Trick to remove floating error in texture. + // We see a squared noise on planet's surface when seeing the planet from far away + float dC = float(length(dCamPosObj.xyz)); + const float x1 = 1e8; + if (dC > x1) { + pixelDepth += 1000.0; + const float alpha = 1000.0; + const float beta = 1000000.0; + const float x2 = 1e9; + const float diffGreek = beta - alpha; + const float diffDist = x2 - x1; + const float varA = diffGreek / diffDist; + const float varB = (alpha - varA * x1); + pixelDepth += double(varA * dC + varB); + } - if (pixelDepth < offset) { - // ATM Occluded - Something in fron of ATM. - atmosphereFinalColor += color; - } - else { - // Following paper nomenclature - double t = offset; - vec3 attenuation; + // All calculations are done in KM: + pixelDepth *= 0.001; + positionObjectsCoords.xyz *= 0.001; - // Moving observer from camera location to top atmosphere - // If the observer is already inside the atm, offset = 0.0 - // and no changes at all. - vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); - float r = 0.0f;//length(x); - vec3 v = vec3(ray.direction.xyz); - float mu = 0.0f;//dot(x, v) / r; - vec3 s = vec3(sunDirectionObj); - float tF = float(maxLength - t); + if (pixelDepth < offset) { + // ATM Occluded - Something in front of ATM + renderTarget = color; + return; + } - // Because we may move the camera origin to the top of atmosphere - // we also need to adjust the pixelDepth for tdCalculateRayRenderableGlobe' offset so the - // next comparison with the planet's ground make sense: - pixelDepth -= offset; - - dvec4 onATMPos = dModelTransformMatrix * dvec4(x * 1000.0, 1.0); - vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); - float sunIntensityInscatter = sunRadiance * eclipseShadowATM.x; + // Following paper nomenclature + double t = offset; + vec3 attenuation; - float irradianceFactor = 0.0; + // Moving observer from camera location to top atmosphere. If the observer is already + // inside the atm, offset = 0.0 and no changes at all + vec3 x = vec3(ray.origin + t * ray.direction); + float r = 0.0; // length(x); + vec3 v = vec3(ray.direction); + float mu = 0.0; // dot(x, v) / r; + vec3 s = vec3(sunDirectionObj); + float tF = float(maxLength - t); - bool groundHit = false; - vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, - s, r, mu, attenuation, - vec3(positionObjectsCoords.xyz), - groundHit, maxLength, pixelDepth, - color, sunIntensityInscatter); - vec3 groundColorV = vec3(0.0); - vec3 sunColorV = vec3(0.0); - if (groundHit) { - vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, positionWorldCoords.xyz, true); - float sunIntensityGround = sunRadiance * eclipseShadowPlanet.x; - groundColorV = groundColor(x, tF, v, s, r, mu, attenuation, - color, normal.xyz, irradianceFactor, - normal.a, sunIntensityGround); - } - else { - // In order to get better performance, we are not tracing - // multiple rays per pixel when the ray doesn't intersect - // the ground. - sunColorV = sunColor(x, tF, v, s, r, mu, irradianceFactor); - } - - // Final Color of ATM plus terrain: - vec4 finalRadiance = vec4(inscatterColor + groundColorV + sunColorV, 1.0); + // Because we may move the camera origin to the top of atmosphere we also need to + // adjust the pixelDepth for tdCalculateRayRenderableGlobe' offset so the next + // comparison with the planet's ground make sense: + pixelDepth -= offset; + + dvec3 onATMPos = (dModelTransformMatrix * dvec4(x * 1000.0, 1.0)).xyz; + float eclipseShadowATM = calcShadow(shadowDataArray, onATMPos, false); + float sunIntensityInscatter = sunRadiance * eclipseShadowATM; - atmosphereFinalColor += finalRadiance; - } - } - else { // no intersection - // Buffer color - atmosphereFinalColor += color; - } - + float irradianceFactor = 0.0; - renderTarget = atmosphereFinalColor; - } - else { // culling - vec4 bColor = texture(mainColorTexture, texCoord); - renderTarget = bColor; - } + bool groundHit = false; + vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, s, r, mu, + attenuation, vec3(positionObjectsCoords.xyz), groundHit, maxLength, pixelDepth, + color, sunIntensityInscatter); + vec3 atmColor = vec3(0.0); + if (groundHit) { + float eclipseShadowPlanet = calcShadow(shadowDataArray, positionWorldCoords.xyz, true); + float sunIntensityGround = sunRadiance * eclipseShadowPlanet; + atmColor = groundColor(x, tF, v, s, attenuation, color.rgb, normal.xyz, + irradianceFactor, normal.w, sunIntensityGround); + } + else { + // In order to get better performance, we are not tracing multiple rays per pixel + // when the ray doesn't intersect the ground + atmColor = sunColor(v, s, r, mu, irradianceFactor); + } + + // Final Color of ATM plus terrain: + vec4 finalRadiance = vec4(inscatterColor + atmColor, 1.0); + renderTarget = finalRadiance; } diff --git a/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl index cbe4d8663f..3e350f6e91 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl @@ -26,11 +26,9 @@ layout(location = 0) in vec4 in_position; -out vec3 interpolatedNDCPos; out vec2 texCoord; void main() { - texCoord = 0.5 + in_position.xy * 0.5; - interpolatedNDCPos = in_position.xyz; - gl_Position = in_position; + texCoord = in_position.xy / 2.0 + 0.5; + gl_Position = in_position; } diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl b/modules/atmosphere/shaders/calculation_gs.glsl similarity index 92% rename from modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl rename to modules/atmosphere/shaders/calculation_gs.glsl index 7cccacb76a..36a7459ee7 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl +++ b/modules/atmosphere/shaders/calculation_gs.glsl @@ -30,10 +30,10 @@ layout (triangles) in; layout (triangle_strip, max_vertices = 3) out; void main() { - for (int n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); + for (int n = 0; n < gl_in.length(); ++n) { + gl_Position = gl_in[n].gl_Position; + gl_Layer = layer; + EmitVertex(); + } + EndPrimitive(); } diff --git a/modules/atmosphere/shaders/irradiance_calc_vs.glsl b/modules/atmosphere/shaders/calculation_vs.glsl similarity index 98% rename from modules/atmosphere/shaders/irradiance_calc_vs.glsl rename to modules/atmosphere/shaders/calculation_vs.glsl index 1ca953fe3c..be225fa6a6 100644 --- a/modules/atmosphere/shaders/irradiance_calc_vs.glsl +++ b/modules/atmosphere/shaders/calculation_vs.glsl @@ -27,5 +27,5 @@ layout(location = 0) in vec3 in_position; void main() { - gl_Position = vec4(in_position, 1.0); + gl_Position = vec4(in_position, 1.0); } diff --git a/modules/atmosphere/shaders/deltaE_calc_vs.glsl b/modules/atmosphere/shaders/deltaE_calc_vs.glsl deleted file mode 100644 index d5a1e43e38..0000000000 --- a/modules/atmosphere/shaders/deltaE_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/atmosphere/shaders/deltaJ_calc_fs.glsl b/modules/atmosphere/shaders/deltaJ_calc_fs.glsl index badfa8934d..37bacbe3b9 100644 --- a/modules/atmosphere/shaders/deltaJ_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaJ_calc_fs.glsl @@ -26,7 +26,7 @@ #include "atmosphere_common.glsl" -out vec4 renderTarget1; +out vec4 renderTarget; uniform float r; uniform vec4 dhdH; @@ -38,14 +38,14 @@ uniform sampler3D deltaSMTexture; uniform int firstIteraction; // -- Spherical Coordinates Steps. phi e [0,2PI] and theta e [0, PI] -const float stepPhi = (2.0f * M_PI) / float(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); +const float stepPhi = (2.0 * M_PI) / float(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); const float stepTheta = M_PI / float(INSCATTER_SPHERICAL_INTEGRAL_SAMPLES); -void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { +vec3 inscatter(float r, float mu, float muSun, float nu) { // Be sure to not get a cosine or height out of bounds - r = clamp(r, Rg, Rt); - mu = clamp(mu, -1.0f, 1.0f); - muSun = clamp(muSun, -1.0f, 1.0f); + r = clamp(r, Rg, Rt); + mu = clamp(mu, -1.0, 1.0); + muSun = clamp(muSun, -1.0, 1.0); // s sigma | theta v // \ | / @@ -55,9 +55,9 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // \ | / cos(theta) = mu // \ | / cos(sigma) = muSun // \|/ cos(ni) = nu - float mu2 = mu * mu; - float muSun2 = muSun * muSun; - float sinThetaSinSigma = sqrt(1.0f - mu2) * sqrt(1.0f - muSun2); + float mu2 = mu * mu; + float muSun2 = muSun * muSun; + float sinThetaSinSigma = sqrt(1.0 - mu2) * sqrt(1.0 - muSun2); // cos(sigma + theta) = cos(theta)cos(sigma)-sin(theta)sin(sigma) // cos(ni) = nu = mu * muSun - sqrt(1.0f - mu*mu)*sqrt(1.0 - muSun*muSun) // sin(theta) = sqrt(1.0 - mu*mu) // Now we make sure the angle between vec(s) and vec(v) is in the right range: @@ -67,8 +67,8 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // theta is the angle between vec(v) and x // cos(PI-theta) = d/r // -cos(theta) = sqrt(r*r-Rg*Rg)/r - float Rg2 = Rg * Rg; - float r2 = r * r; + float Rg2 = Rg * Rg; + float r2 = r * r; float cosHorizon = -sqrt(r2 - Rg2)/r; // Now we get vec(v) and vec(s) from mu, muSun and nu: @@ -80,7 +80,7 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // sin(PI-theta) = x/||v|| => x = sin(theta) =? x = sqrt(1-mu*mu) // cos(PI-theta) = z/||v|| => z = cos(theta) = mu // v.y = 0 because ||v|| = 1 - vec3 v = vec3(sqrt(1.0 - mu2), 0.0, mu); + vec3 v = vec3(sqrt(1.0 - mu2), 0.0, mu); // To obtain vec(s), we use the following properties: // ||vec(s)|| = 1, ||vec(v)|| = 1 @@ -89,7 +89,7 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // So, from vec(s) dot vec(v) = cos(ni) = nu we have, // s.x*v.x +s.y*v.y + s.z*v.z = nu // s.x = (nu - s.z*v.z)/v.x = (nu - mu*muSun)/v.x - float sx = (v.x == 0.0) ? 0.0 : (nu - muSun * mu) / v.x; + float sx = (v.x == 0.0) ? 0.0 : (nu - muSun * mu) / v.x; // Also, ||vec(s)|| = 1, so: // 1 = sqrt(s.x*s.x + s.y*s.y + s.z*s.z) // s.y = sqrt(1 - s.x*s.x - s.z*s.z) = sqrt(1 - s.x*s.x - muSun*muSun) @@ -97,21 +97,21 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // In order to integrate over 4PI, we scan the sphere using the spherical coordinates // previously defined - for (int theta_i = 0; theta_i < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++theta_i) { - float theta = (float(theta_i) + 0.5f) * stepTheta; - float cosineTheta = cos(theta); - float cosineTheta2 = cosineTheta * cosineTheta; - float distanceToGround = 0.0f; - float groundReflectance = 0.0f; - vec3 groundTransmittance = vec3(0.0f); + for (int theta_i = 0; theta_i < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; theta_i++) { + float theta = (float(theta_i) + 0.5) * stepTheta; + float cosineTheta = cos(theta); + float cosineTheta2 = cosineTheta * cosineTheta; + float distanceToGround = 0.0; + float groundReflectance = 0.0; + vec3 groundTransmittance = vec3(0.0); // If the ray w can see the ground we must compute the transmittance // effect from the starting point x to the ground point in direction -vec(v): - if ( cosineTheta < cosHorizon ) { // ray hits ground + if (cosineTheta < cosHorizon) { // ray hits ground // AverageGroundReflectance e [0,1] groundReflectance = AverageGroundReflectance / M_PI; // From cosine law: Rg*Rg = r*r + distanceToGround*distanceToGround - 2*r*distanceToGround*cos(PI-theta) - distanceToGround = -r * cosineTheta - sqrt(r2 * (cosineTheta2 - 1.0f) + Rg2); + distanceToGround = -r * cosineTheta - sqrt(r2 * (cosineTheta2 - 1.0) + Rg2); // | // | theta // | @@ -125,86 +125,84 @@ void inscatter(float r, float mu, float muSun, float nu, inout vec3 radianceJ) { // cos(alpha) = (-r*distG*cos(theta) - distG*distG)/(Rg*distG) // muGround = -(r*cos(theta) + distG)/Rg float muGround = -(r * cosineTheta + distanceToGround) / Rg; - // We can use the same triangle in calculate the distanceToGround to calculate the cosine of the - // angle between the ground touching point at height Rg and the zenith angle - //float muGround = (r2 - distanceToGround*distanceToGround - Rg2)/(2*distanceToGround*Rg); - // Acesss the Transmittance LUT in order to calculate the transmittance from the ground point Rg, - // thorugh the atmosphere, at a distance: distanceToGround + // We can use the same triangle in calculate the distanceToGround to calculate the + // cosine of the angle between the ground touching point at height Rg and the zenith + // angle + // float muGround = (r2 - distanceToGround*distanceToGround - Rg2)/(2*distanceToGround*Rg); + // Access the Transmittance LUT in order to calculate the transmittance from the + // ground point Rg, thorugh the atmosphere, at a distance: distanceToGround groundTransmittance = transmittance(Rg, muGround, distanceToGround); } - //for ( int phi_i = 0; phi_i < 2*INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++phi_i ) { + for (int phi_i = 0; phi_i < INSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++phi_i) { - float phi = (float(phi_i) + 0.5) * stepPhi; + float phi = (float(phi_i) + 0.5) * stepPhi; // spherical coordinates: dw = dtheta*dphi*sin(theta)*rho^2 // rho = 1, we are integrating over a unit sphere - float dw = stepTheta * stepPhi * sin(theta); + float dw = stepTheta * stepPhi * sin(theta); // w = (rho*sin(theta)*cos(phi), rho*sin(theta)*sin(phi), rho*cos(theta)) - float sinPhi = sin(phi); + float sinPhi = sin(phi); float sinTheta = sin(theta); - float cosPhi = cos(phi); - vec3 w = vec3(sinTheta * cosPhi, sinTheta * sinPhi, cosineTheta); + float cosPhi = cos(phi); + vec3 w = vec3(sinTheta * cosPhi, sinTheta * sinPhi, cosineTheta); // We calculate the Rayleigh and Mie phase function for the new scattering angle: // cos(angle between vec(v) and vec(w)), ||v|| = ||w|| = 1 - float nuWV = dot(v, w); + float nuWV = dot(v, w); float phaseRayleighWV = rayleighPhaseFunction(nuWV); - float phaseMieWV = miePhaseFunction(nuWV); + float phaseMieWV = miePhaseFunction(nuWV, mieG); - vec3 groundNormal = (vec3(0.0, 0.0, r) + distanceToGround * w) / Rg; + vec3 groundNormal = (vec3(0.0, 0.0, r) + distanceToGround * w) / Rg; vec3 groundIrradiance = irradianceLUT(deltaETexture, dot(groundNormal, s), Rg); - // We finally calculate the radiance from the reflected ray from ground (0.0 if not reflected) + // We finally calculate the radiance from the reflected ray from ground + // (0.0 if not reflected) vec3 radianceJ1 = groundTransmittance * groundReflectance * groundIrradiance; // We calculate the Rayleigh and Mie phase function for the new scattering angle: // cos(angle between vec(s) and vec(w)), ||s|| = ||w|| = 1 float nuSW = dot(s, w); - // The first iteraction is different from the others, that's because in the first - // iteraction all the light InScattered are coming from the initial pre-computed - // single InScattered light. We stored these values in the deltaS textures (Ray and Mie), - // and in order to avoid problems with the high angle dependency in the phase functions, - // we don't include the phase functions on those tables (that's why we calculate them now). - if ( firstIteraction == 1 ) { + // The first iteraction is different from the others. In the first iteraction all + // the light InScattered is coming from the initial pre-computed single InScattered + // light. We stored these values in the deltaS textures (Ray and Mie), and in order + // to avoid problems with the high angle dependency in the phase functions, we don't + // include the phase functions on those tables (that's why we calculate them now). + if (firstIteraction == 1) { float phaseRaySW = rayleighPhaseFunction(nuSW); - float phaseMieSW = miePhaseFunction(nuSW); + float phaseMieSW = miePhaseFunction(nuSW, mieG); // We can now access the values for the single InScattering in the textures deltaS textures. - vec3 singleRay = texture4D(deltaSRTexture, r, w.z, muSun, nuSW).rgb; - vec3 singleMie = texture4D(deltaSMTexture, r, w.z, muSun, nuSW).rgb; + vec3 singleRay = texture4D(deltaSRTexture, r, w.z, muSun, nuSW).rgb; + vec3 singleMie = texture4D(deltaSMTexture, r, w.z, muSun, nuSW).rgb; // Initial InScattering including the phase functions radianceJ1 += singleRay * phaseRaySW + singleMie * phaseMieSW; } else { - // On line 9 of the algorithm, the texture table deltaSR is updated, so when we are not in the first - // iteraction, we are getting the updated result of deltaSR (not the single inscattered light but the - // accumulated (higher order) inscattered light. + // On line 9 of the algorithm, the texture table deltaSR is updated, so when we + // are not in the first iteraction, we are getting the updated result of deltaSR + // (not the single inscattered light but the accumulated (higher order) + // inscattered light. // w.z is the cosine(theta) = mu for vec(w) radianceJ1 += texture4D(deltaSRTexture, r, w.z, muSun, nuSW).rgb; } - // Finally, we add the atmospheric scale height (See: Radiation Transfer on the Atmosphere and Ocean from - // Thomas and Stamnes, pg 9-10. - radianceJ += radianceJ1 * (betaRayleigh * exp(-(r - Rg) / HR) * phaseRayleighWV + - betaMieScattering * exp(-(r - Rg) / HM) * phaseMieWV) * dw; + // Finally, we add the atmospheric scale height (See: Radiation Transfer on the + // Atmosphere and Ocean from Thomas and Stamnes, pg 9-10. + return radianceJ1 * (betaRayleigh * exp(-(r - Rg) / HR) * phaseRayleighWV + + betaMieScattering * exp(-(r - Rg) / HM) * phaseMieWV) * dw; } } } void main() { - // cosine variables to access deltaS textures + // InScattering Radiance to be calculated at different points in the ray path + // Unmapping the variables from texture texels coordinates to mapped coordinates float mu, muSun, nu; - // InScattering Radiance to be calculated at - // different points in the ray path - vec3 radianceJ = vec3(0.0f); - - // Unmapping the variables from texture texels coordinates - // to mapped coordinates unmappingMuMuSunNu(r, dhdH, mu, muSun, nu); // Calculate the the light inScattered in direction // -vec(v) for the point at height r (vec(y) following Bruneton and Neyret's paper - inscatter(r, mu, muSun, nu, radianceJ); + vec3 radianceJ = inscatter(r, mu, muSun, nu); // Write to texture detaJ - renderTarget1 = vec4(radianceJ, 1.0); + renderTarget = vec4(radianceJ, 1.0); } diff --git a/modules/atmosphere/shaders/deltaJ_calc_gs.glsl b/modules/atmosphere/shaders/deltaJ_calc_gs.glsl deleted file mode 100644 index aea1c7db4d..0000000000 --- a/modules/atmosphere/shaders/deltaJ_calc_gs.glsl +++ /dev/null @@ -1,39 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -uniform int layer; - -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; - -void main() { - for (int n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/modules/atmosphere/shaders/deltaJ_calc_vs.glsl b/modules/atmosphere/shaders/deltaJ_calc_vs.glsl deleted file mode 100644 index d5a1e43e38..0000000000 --- a/modules/atmosphere/shaders/deltaJ_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} \ No newline at end of file diff --git a/modules/atmosphere/shaders/deltaS_calc_fs.glsl b/modules/atmosphere/shaders/deltaS_calc_fs.glsl index d337cb18bf..b5d7de5e79 100644 --- a/modules/atmosphere/shaders/deltaS_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaS_calc_fs.glsl @@ -26,24 +26,21 @@ #include "atmosphere_common.glsl" -out vec4 renderTarget1; +out vec4 renderTarget; uniform int layer; - uniform sampler3D deltaSRTexture; uniform sampler3D deltaSMTexture; void main() { - // First we convert the window's fragment coordinate to - // texel coordinates - vec3 rst = vec3(gl_FragCoord.xy, float(layer) + 0.5f) / + // First we convert the window's fragment coordinate to texel coordinates + vec3 rst = vec3(gl_FragCoord.xy, float(layer) + 0.5) / vec3(ivec3(SAMPLES_MU_S * SAMPLES_NU, SAMPLES_MU, SAMPLES_R)); - vec4 rayleighInscattering0 = texture(deltaSRTexture, rst); - vec4 mieInscattering0 = texture(deltaSMTexture, rst); + vec3 rayleighInscattering = texture(deltaSRTexture, rst).rgb; + float mieInscattering = texture(deltaSMTexture, rst).r; - // We are using only the red component of the Mie scattering - // See the Precomputed Atmosphere Scattering paper for details about - // the angular precision. - renderTarget1 = vec4(rayleighInscattering0.rgb, mieInscattering0.r); + // We are using only the red component of the Mie scattering. See the Precomputed + // Atmosphere Scattering paper for details about the angular precision + renderTarget = vec4(rayleighInscattering, mieInscattering); } diff --git a/modules/atmosphere/shaders/deltaS_calc_gs.glsl b/modules/atmosphere/shaders/deltaS_calc_gs.glsl deleted file mode 100644 index aea1c7db4d..0000000000 --- a/modules/atmosphere/shaders/deltaS_calc_gs.glsl +++ /dev/null @@ -1,39 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -uniform int layer; - -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; - -void main() { - for (int n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/modules/atmosphere/shaders/deltaS_calc_vs.glsl b/modules/atmosphere/shaders/deltaS_calc_vs.glsl deleted file mode 100644 index 1ca953fe3c..0000000000 --- a/modules/atmosphere/shaders/deltaS_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl index 31e6b6670f..ebe63b5071 100644 --- a/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl @@ -26,20 +26,21 @@ #include "atmosphere_common.glsl" -out vec4 renderTarget1; +out vec4 renderTarget; uniform int layer; - uniform sampler3D deltaSTexture; void main() { - float x = gl_FragCoord.x - 0.5f; - float y = gl_FragCoord.y - 0.5f; + vec2 p = gl_FragCoord.xy - vec2(0.5); - float nu = -1.0f + floor(x / float(SAMPLES_MU_S)) / (float(SAMPLES_NU) - 1.0f) * 2.0f; - vec3 uvw = vec3(gl_FragCoord.xy, float(layer) + 0.5f) / vec3(ivec3(SAMPLES_MU_S * SAMPLES_NU, SAMPLES_MU, SAMPLES_R)); + float nu = -1.0 + floor(p.x / float(SAMPLES_MU_S)) / (float(SAMPLES_NU) - 1.0) * 2.0; + vec3 uvw = vec3( + gl_FragCoord.xy, + float(layer) + 0.5) / vec3(ivec3(SAMPLES_MU_S * SAMPLES_NU, SAMPLES_MU, SAMPLES_R) + ); - // See Bruneton and Neyret paper, "Angular Precision" paragraph to understanding why we are - // dividing the S[L*] by the Rayleigh phase function. - renderTarget1 = vec4(texture(deltaSTexture, uvw).rgb / rayleighPhaseFunction(nu), 0.0f); + // See Bruneton and Neyret paper, "Angular Precision" paragraph to understanding why we + // are dividing the S[L*] by the Rayleigh phase function. + renderTarget = vec4(texture(deltaSTexture, uvw).rgb / rayleighPhaseFunction(nu), 0.0); } diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl deleted file mode 100644 index 7cccacb76a..0000000000 --- a/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl +++ /dev/null @@ -1,39 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -uniform int layer; - -layout (triangles) in; -layout (triangle_strip, max_vertices = 3) out; - -void main() { - for (int n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl deleted file mode 100644 index deb9073c8f..0000000000 --- a/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/inScattering_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_calc_fs.glsl index be7281bda3..8443cb1109 100644 --- a/modules/atmosphere/shaders/inScattering_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_calc_fs.glsl @@ -21,6 +21,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #version __CONTEXT__ #include "atmosphere_common.glsl" @@ -31,64 +32,59 @@ layout(location = 1) out vec4 renderTarget2; uniform float r; uniform vec4 dhdH; -//uniform sampler2D transmittanceTexture; - -void integrand(float r, float mu, float muSun, float nu, - float y, out vec3 S_R, out vec3 S_M) { +void integrand(float r, float mu, float muSun, float nu, float y, out vec3 S_R, + out vec3 S_M) +{ // The integral's integrand is the single inscattering radiance: // S[L0] = P_M*S_M[L0] + P_R*S_R[L0] // where S_M[L0] = T*(betaMScattering * exp(-h/H_M))*L0 and // S_R[L0] = T*(betaRScattering * exp(-h/H_R))*L0. // T = transmittance. - // One must remember that because the occlusion on L0, the integrand - // here will be equal to 0 in that cases. - // Also it is important to remember that the phase function for the - // Rayleigh and Mie scattering are added during the rendering time - // to increase the angular precision + // One must remember that because the occlusion on L0, the integrand here will be equal + // to 0 in that cases. Also it is important to remember that the phase function for the + // Rayleigh and Mie scattering are added during the rendering time to increase the + // angular precision S_R = vec3(0.0); S_M = vec3(0.0); // cosine law float ri = max(sqrt(r * r + y * y + 2.0 * r * mu * y), Rg); - // Considering the Sun as a parallel light source, - // thew vector s_i = s. + // Considering the Sun as a parallel light source, thew vector s_i = s. // So muSun_i = (vec(y_i) dot vec(s))/r_i = ((vec(x) + vec(yi-x)) dot vec(s))/r_i // muSun_i = (vec(x) dot vec(s) + vec(yi-x) dot vec(s))/r_i = (r*muSun + yi*nu)/r_i float muSun_i = (nu * y + muSun * r) / ri; - // If the muSun_i is smaller than the angle to horizon (no sun radiance - // hitting the point y), we return S_R = S_M = 0.0f. + // If the muSun_i is smaller than the angle to horizon (no sun radiance hitting the + // point y), we return S_R = S_M = 0.0. if (muSun_i >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { - // It's the transmittance from the point y (ri) to the top of atmosphere - // in direction of the sun (muSun_i) and the transmittance from the observer - // at x (r) to y (ri). - vec3 transmittanceY = transmittance(r, mu, y) * transmittanceLUT(ri, muSun_i); + // It's the transmittance from the point y (ri) to the top of atmosphere in direction + // of the sun (muSun_i) and the transmittance from the observer at x (r) to y (ri). + vec3 transmittanceY = transmittance(r, mu, y) * transmittance(ri, muSun_i); // exp(-h/H)*T(x,v) if (ozoneLayerEnabled) { - S_R = (exp(-(ri - Rg) / HO) + exp( -(ri - Rg) / HR )) * transmittanceY; - S_M = exp( -(ri - Rg) / HM ) * transmittanceY; + S_R = (exp(-(ri - Rg) / HO) + exp(-(ri - Rg) / HR)) * transmittanceY; + S_M = exp(-(ri - Rg) / HM) * transmittanceY; } else { - S_R = exp( -(ri - Rg) / HR ) * transmittanceY; - S_M = exp( -(ri - Rg) / HM ) * transmittanceY; + S_R = exp(-(ri - Rg) / HR) * transmittanceY; + S_M = exp(-(ri - Rg) / HM) * transmittanceY; } // The L0 (sun radiance) is added in real-time. } } void inscatter(float r, float mu, float muSun, float nu, out vec3 S_R, out vec3 S_M) { - // Let's calculate S_M and S_R by integration along the eye ray path inside - // the atmosphere, given a position r, a view angle (cosine) mu, a sun - // position angle (cosine) muSun, and the angle (cosine) between the sun position - // and the view direction, nu. - // Integrating using the Trapezoidal rule: + // Let's calculate S_M and S_R by integration along the eye ray path inside the + // atmosphere, given a position r, a view angle (cosine) mu, a sun position angle + // (cosine) muSun, and the angle (cosine) between the sun position and the view + // direction, nu. Integrating using the Trapezoidal rule: // Integral(f(y)dy)(from a to b) = (b-a)/2n_steps*(Sum(f(y_i+1)+f(y_i))) - S_R = vec3(0.0f); - S_M = vec3(0.0f); + S_R = vec3(0.0); + S_M = vec3(0.0); + float rayDist = rayDistance(r, mu); - float dy = rayDist / float(INSCATTER_INTEGRAL_SAMPLES); - float yi = 0.0f; + float dy = rayDist / float(INSCATTER_INTEGRAL_SAMPLES); vec3 S_Ri; vec3 S_Mi; integrand(r, mu, muSun, nu, 0.0, S_Ri, S_Mi); @@ -99,38 +95,33 @@ void inscatter(float r, float mu, float muSun, float nu, out vec3 S_R, out vec3 integrand(r, mu, muSun, nu, yj, S_Rj, S_Mj); S_R += (S_Ri + S_Rj); S_M += (S_Mi + S_Mj); - yi = yj; S_Ri = S_Rj; S_Mi = S_Mj; } - S_R *= betaRayleigh * (rayDist / (2.0f * float(INSCATTER_INTEGRAL_SAMPLES))); - S_M *= betaMieScattering * (rayDist / (2.0f * float(INSCATTER_INTEGRAL_SAMPLES))); + S_R *= betaRayleigh * (rayDist / (2.0 * float(INSCATTER_INTEGRAL_SAMPLES))); + S_M *= betaMieScattering * (rayDist / (2.0 * float(INSCATTER_INTEGRAL_SAMPLES))); } void main() { vec3 S_R; // First Order Rayleigh InScattering vec3 S_M; // First Order Mie InScattering - float mu, muSun, nu; // parametrization angles - // From the layer interpolation (see C++ code for layer to r) - // and the textures parameters (uv), we unmapping mu, muSun and nu. + // From the layer interpolation (see C++ code for layer to r) and the textures + // parameters (uv), we unmapping mu, muSun and nu. + float mu, muSun, nu; unmappingMuMuSunNu(r, dhdH, mu, muSun, nu); - // Here we calculate the single inScattered light. - // Because this is a single inscattering, the light - // that arrives at a point y in the path from the - // eye to the infinity (top of atmosphere or planet's - // ground), comes only from the light source, i.e., the - // sun. So, the there is no need to integrate over the - // whole solid angle (4pi), we need only to consider - // the Sun position (cosine of sun pos = muSun). - // Then, following the paper notation: + // Here we calculate the single inScattered light. Because this is a single + // inscattering, the light that arrives at a point y in the path from the eye to the + // infinity (top of atmosphere or planet's ground), comes only from the light source, + // i.e., the sun. So, the there is no need to integrate over the whole solid angle + // (4pi), we need only to consider the Sun position (cosine of sun pos = muSun). Then, + // following the paper notation: // S[L] = P_R*S_R[L0] + P_M*S_M[L0] + S[L*] // For single inscattering only: // S[L0] = P_R*S_R[L0] + P_M*S_M[L0] - // In order to save memory, we just store the red component - // of S_M[L0], and later we use the proportionality rule - // to calcule the other components. + // In order to save memory, we just store the red component of S_M[L0], and later we use + // the proportionality rule to calcule the other components. inscatter(r, mu, muSun, nu, S_R, S_M); renderTarget1 = vec4(S_R, 1.0); renderTarget2 = vec4(S_M, 1.0); diff --git a/modules/atmosphere/shaders/inScattering_calc_gs.glsl b/modules/atmosphere/shaders/inScattering_calc_gs.glsl deleted file mode 100644 index 823cd6a71e..0000000000 --- a/modules/atmosphere/shaders/inScattering_calc_gs.glsl +++ /dev/null @@ -1,39 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -uniform int layer; - -layout (triangles) in; -layout (triangle_strip, max_vertices=3) out; - -void main() { - for (int n = 0; n < gl_in.length(); ++n) { - gl_Position = gl_in[n].gl_Position; - gl_Layer = layer; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/modules/atmosphere/shaders/inScattering_calc_vs.glsl b/modules/atmosphere/shaders/inScattering_calc_vs.glsl deleted file mode 100644 index 1ca953fe3c..0000000000 --- a/modules/atmosphere/shaders/inScattering_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl index 81377100bc..fd128b3b16 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl @@ -26,23 +26,21 @@ #include "atmosphere_common.glsl" -out vec4 renderTarget1; +out vec4 renderTarget; uniform float r; uniform vec4 dhdH; - -//uniform sampler2D transmittanceTexture; uniform sampler3D deltaJTexture; // The integrand here is the f(y) of the trapezoidal rule: vec3 integrand(float r, float mu, float muSun, float nu, float dist) { // We can calculate r_i by the cosine law: r_i^2=dist^2 + r^2 - 2*r*dist*cos(PI-theta) - float r_i = sqrt(r * r + dist * dist + 2.0f * r * dist * mu); + float r_i = sqrt(r * r + dist * dist + 2.0f * r * dist * mu); // r_i can be found using the dot product: // vec(y_i) dot vec(dist) = cos(theta_i) * ||vec(y_i)|| * ||vec(dist)|| // But vec(y_i) = vec(x) + vec(dist), also: vec(x) dot vec(dist) = cos(theta) = mu // So, cos(theta_i) = mu_i = (r*dist**mu + dist*2)/(r_i*dist) - float mu_i = (r * mu + dist) / r_i; + float mu_i = (r * mu + dist) / r_i; // muSun_i can also be found by the dot product: // cos(sigma_i) = muSun_i = (vec(s) dot vec(y_i))/(||vec(y_i)|| * ||vec(s)||) // But vec(y_i) = vec(x) + vec(dist), and vec(x) dot vec(s) = muSun, cos(sigma_i + theta_i) = nu @@ -52,28 +50,29 @@ vec3 integrand(float r, float mu, float muSun, float nu, float dist) { } vec3 inscatter(float r, float mu, float muSun, float nu) { - vec3 inScatteringRadiance = vec3(0.0f); - float dy = rayDistance(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); - vec3 inScatteringRadiance_i = integrand(r, mu, muSun, nu, 0.0); + vec3 inScatteringRadiance = vec3(0.0); + float dy = rayDistance(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); + vec3 inScatteringRadiance_i = integrand(r, mu, muSun, nu, 0.0); - // 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))) + // 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) { float y_j = float(i) * dy; vec3 inScatteringRadiance_j = integrand(r, mu, muSun, nu, y_j); - inScatteringRadiance += (inScatteringRadiance_i + inScatteringRadiance_j) / 2.0 * dy; + inScatteringRadiance += (inScatteringRadiance_i + inScatteringRadiance_j) / 2.0 * dy; inScatteringRadiance_i = inScatteringRadiance_j; } return inScatteringRadiance; } void main() { - float mu = 0.0f, muSunun = 0.0f, nu = 0.0f; - // Unmapping the variables from texture texels coordinates - // to mapped coordinates - unmappingMuMuSunNu(r, dhdH, mu, muSunun, nu); + float mu = 0.0; + float muSun = 0.0; + float nu = 0.0; + // Unmapping the variables from texture texels coordinates to mapped coordinates + unmappingMuMuSunNu(r, dhdH, mu, muSun, nu); // Write to texture deltaSR - renderTarget1 = vec4(inscatter(r, mu, muSunun, nu), 1.0); + renderTarget = vec4(inscatter(r, mu, muSun, nu), 1.0); } diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl deleted file mode 100644 index deb9073c8f..0000000000 --- a/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/irradiance_calc_fs.glsl b/modules/atmosphere/shaders/irradiance_calc_fs.glsl index 94ea44c834..93fca5128e 100644 --- a/modules/atmosphere/shaders/irradiance_calc_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_calc_fs.glsl @@ -21,23 +21,23 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #version __CONTEXT__ #include "atmosphere_common.glsl" out vec4 renderTableColor; -//uniform sampler2D transmittanceTexture; - void main() { - float muSun, r; - unmappingRAndMuSun(r, muSun); - // We are calculating the Irradiance for L0, i.e., - // only the radiance comming from sun direction is accounted: + // See Bruneton and Colliene to understand the mapping + float muSun = -0.2 + (gl_FragCoord.x - 0.5) / (float(OTHER_TEXTURES.x) - 1.0) * 1.2; + float r = Rg + (gl_FragCoord.y - 0.5) / (float(OTHER_TEXTURES.y) ) * RtMinusRg; + + // We are calculating the Irradiance for L0, i.e., only the radiance coming from Sun + // direction is accounted: // E[L0](x,s) = L0*dot(w,n) or 0 (if v!=s or the sun is occluded). - // Because we consider the Planet as a perfect sphere and we are - // considering only single scattering here, the - // dot product dot(w,n) is equal to dot(s,n) that is equal to + // Because we consider the Planet as a perfect sphere and we are considering only single + // scattering here, the dot product dot(w,n) is equal to dot(s,n) that is equal to // dot(s, r/||r||) = muSun. - renderTableColor = vec4(transmittanceLUT(r, muSun) * max(muSun, 0.0), 0.0); + renderTableColor = vec4(transmittance(r, muSun) * max(muSun, 0.0), 0.0); } diff --git a/modules/atmosphere/shaders/irradiance_final_fs.glsl b/modules/atmosphere/shaders/irradiance_final_fs.glsl index f21d74bdba..5f9834ab2c 100644 --- a/modules/atmosphere/shaders/irradiance_final_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_final_fs.glsl @@ -31,7 +31,7 @@ out vec4 renderTableColor; uniform sampler2D deltaETexture; void main() { - vec2 uv = gl_FragCoord.xy / vec2(OTHER_TEXTURES_W, OTHER_TEXTURES_H); + vec2 uv = gl_FragCoord.xy / vec2(OTHER_TEXTURES); // Update texture E with E plus deltaE textures. renderTableColor = texture(deltaETexture, uv); diff --git a/modules/atmosphere/shaders/irradiance_final_vs.glsl b/modules/atmosphere/shaders/irradiance_final_vs.glsl deleted file mode 100644 index 1ca953fe3c..0000000000 --- a/modules/atmosphere/shaders/irradiance_final_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl index 5ac81a7406..06b31090b8 100644 --- a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl @@ -29,60 +29,56 @@ out vec4 renderTableColor; uniform int firstIteraction; -//uniform float firstIteraction; - -// -- Spherical Coordinates Steps. phi e [0,2PI] and theta e [0, PI/2] -const float stepPhi = (2.0f * M_PI) / float(IRRADIANCE_INTEGRAL_SAMPLES); -const float stepTheta = M_PI / (2.0f * float(IRRADIANCE_INTEGRAL_SAMPLES)); - -//uniform sampler2D transmittanceTexture; uniform sampler3D deltaSRTexture; uniform sampler3D deltaSMTexture; +// Spherical Coordinates Steps. phi e [0,2PI] and theta e [0, PI/2] +const float stepPhi = (2.0 * M_PI) / float(IRRADIANCE_INTEGRAL_SAMPLES); +const float stepTheta = M_PI / (2.0 * float(IRRADIANCE_INTEGRAL_SAMPLES)); + void main() { - float r = 0.0f; - float muSun = 0.0f; - // Unmapping the variables from texture texels coordinates - // to mapped coordinates - unmappingRAndMuSunIrradiance(r, muSun); + // See Bruneton and Colliene to understand the mapping. + float muSun = -0.2 + (gl_FragCoord.x - 0.5) / (float(SKY.x) - 1.0) * 1.2; + float r = Rg + (gl_FragCoord.y - 0.5) / (float(SKY.y) - 1.0) * RtMinusRg; // We know that muSun = cos(sigma) = s.z/||s|| // But, ||s|| = 1, so s.z = muSun. Also, // ||s|| = 1, so s.x = sin(sigma) = sqrt(1-muSun^2) and s.y = 0.0f - vec3 s = vec3(max(sqrt(1.0f - muSun * muSun), 0.0f), 0.0f, muSun); + vec3 s = vec3(max(sqrt(1.0 - muSun * muSun), 0.0), 0.0, muSun); - // 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.0f); + // 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) { - float phi = (float(iphi) + 0.5f) * stepPhi; + float phi = (float(iphi) + 0.5) * stepPhi; for (int itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES; ++itheta) { - float theta = (float(itheta) + 0.5f) * stepTheta; + 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 - float dw = stepTheta * stepPhi * sin(theta); + float dw = stepTheta * stepPhi * sin(theta); // w = (cos(phi) * sin(theta) * rho, sin(phi) * sin(theta) * rho, cos(theta) * rho) - vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - float nu = dot(s, w); + vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + float nu = dot(s, w); // The first iteraction is different from the others, that's because in the first // iteraction all the light arriving are coming from the initial pre-computed - // single scattered light. We stored these values in the deltaS textures (Ray and Mie), - // and in order to avoid problems with the high angle dependency in the phase functions, - // we don't include the phase functions on those tables (that's why we calculate them now). + // single scattered light. We stored these values in the deltaS textures (Ray and + // Mie), and in order to avoid problems with the high angle dependency in the phase + // functions, we don't include the phase functions on those tables (that's why we + // calculate them now) if (firstIteraction == 1) { float phaseRay = rayleighPhaseFunction(nu); - float phaseMie = miePhaseFunction(nu); + float phaseMie = miePhaseFunction(nu, mieG); vec3 singleRay = texture4D(deltaSRTexture, r, w.z, muSun, nu).rgb; vec3 singleMie = texture4D(deltaSMTexture, r, w.z, muSun, nu).rgb; // w.z is the cosine(theta) = mu for vec(w) and also vec(w) dot vec(n(xo)) irradianceE += (singleRay * phaseRay + singleMie * phaseMie) * w.z * dw; } else { - // On line 10 of the algorithm, the texture table deltaE is updated, so when we are not in the first - // iteraction, we are getting the updated result of deltaE (not the single irradiance light but the - // accumulated (higher order) irradiance light. - // w.z is the cosine(theta) = mu for vec(w) and also vec(w) dot vec(n(xo)) + // On line 10 of the algorithm, the texture table deltaE is updated, so when we + // are not in the first iteraction, we are getting the updated result of deltaE + // (not the single irradiance light but the accumulated (higher order) irradiance + // light. w.z is the cosine(theta) = mu for vec(w) and also vec(w) dot vec(n(xo)) irradianceE += texture4D(deltaSRTexture, r, w.z, muSun, nu).rgb * w.z * dw; } } diff --git a/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl b/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl deleted file mode 100644 index 1ca953fe3c..0000000000 --- a/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/modules/atmosphere/shaders/transmittance_calc_fs.glsl b/modules/atmosphere/shaders/transmittance_calc_fs.glsl index 0c1dddd0ff..cf78347f29 100644 --- a/modules/atmosphere/shaders/transmittance_calc_fs.glsl +++ b/modules/atmosphere/shaders/transmittance_calc_fs.glsl @@ -21,33 +21,31 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #version __CONTEXT__ #include "atmosphere_common.glsl" -//layout(location = 1) out vec4 renderTableColor; out vec4 renderTableColor; -//-- Optical depth by integration, from ray starting at point vec(x), i.e, -// height r and angle mu (cosine of vec(v)) until top of atmosphere -// or planet's ground. -- +// Optical depth by integration, from ray starting at point vec(x), i.e, height r and +// angle mu (cosine of vec(v)) until top of atmosphere or planet's ground. // r := height of starting point vect(x) // mu := cosine of the zeith angle of vec(v). Or mu = (vec(x) * vec(v))/r -// H := Thickness of atmosphere if its density were uniform (can be used -// for Rayleigh and Mie. +// H := Thickness of atmosphere if its density were uniform (used for Rayleigh and Mie) float opticalDepth(float r, float mu, float H) { - float r2 = r*r; - // Is ray below horizon? The transmittance table will have only - // the values for transmittance starting at r (x) until the - // light ray touches the atmosphere or the ground and only for - // view angles v between 0 and pi/2 + eps. That's because we - // can calculate the transmittance for angles bigger than pi/2 - // just inverting the ray direction and starting and ending points. + float r2 = r * r; + // Is ray below horizon? The transmittance table will have only the values for + // transmittance starting at r (x) until the light ray touches the atmosphere or the + // ground and only for view angles v between 0 and pi/2 + eps. That's because we can + // calculate the transmittance for angles bigger than pi/2 just inverting the ray + // direction and starting and ending points. // cosine law for triangles: y_i^2 = a^2 + b^2 - 2abcos(alpha) - float cosZenithHorizon = -sqrt( 1.0f - ( ( Rg * Rg ) / r2 ) ); - if (mu < cosZenithHorizon) + float cosZenithHorizon = -sqrt(1.0 - (Rg * Rg / r2)); + if (mu < cosZenithHorizon) { return 1e9; + } // Integrating using the Trapezoidal rule: // Integral(f(y)dy)(from a to b) = ((b-a)/2n_steps)*(Sum(f(y_i+1)+f(y_i))) @@ -56,36 +54,39 @@ float opticalDepth(float r, float mu, float H) { // cosine law float y_i = exp(-(r - Rg) / H); - float x_step = 0.0f; - float accumulation = 0.0f; + float accumulation = 0.0; 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 - float y_ii = exp(-(sqrt(r2 + x_i * x_i + 2.0 * x_i * r * mu) - Rg) / H); + float y_ii = exp(-(sqrt(r2 + x_i * x_i + 2.0 * x_i * r * mu) - Rg) / H); accumulation += (y_ii + y_i); - //x_step = x_i; y_i = y_ii; } - return accumulation * ( b_a / ( 2 * TRANSMITTANCE_STEPS ) ); + return accumulation * (b_a / (2.0 * TRANSMITTANCE_STEPS)); } - void main() { - float r, muSun; - unmappingRAndMu(r, muSun); + float u_mu = gl_FragCoord.x / float(TRANSMITTANCE.x); + float u_r = gl_FragCoord.y / float(TRANSMITTANCE.y); - vec3 opDepth = vec3(0.0); + // In the paper u_r^2 = (r^2-Rg^2)/(Rt^2-Rg^2) + // So, extracting r from u_r in the above equation: + float r = Rg + (u_r * u_r) * RtMinusRg; + // In the paper the Bruneton suggest mu = dot(v,x)/||x|| with ||v|| = 1.0 + // Later he proposes u_mu = (1-exp(-3mu-0.6))/(1-exp(-3.6)) + // But the below one is better. See Colliene. + // One must remember that mu is defined from 0 to PI/2 + epsilon + float muSun = -0.15 + tan(1.5 * u_mu) / tan(1.5) * 1.15; + + vec3 ozoneContribution = vec3(0.0); if (ozoneLayerEnabled) { - opDepth = betaOzoneExtinction * (0.0000006) * opticalDepth(r, muSun, HO) + + ozoneContribution = betaOzoneExtinction * 0.0000006 * opticalDepth(r, muSun, HO); + } + vec3 opDepth = ozoneContribution + betaMieExtinction * opticalDepth(r, muSun, HM) + betaRayleigh * opticalDepth(r, muSun, HR); - } - else { - opDepth = betaMieExtinction * opticalDepth(r, muSun, HM) + - betaRayleigh * opticalDepth(r, muSun, HR); - } - renderTableColor = vec4(exp(-opDepth), 0.0f); + renderTableColor = vec4(exp(-opDepth), 0.0); } diff --git a/modules/atmosphere/shaders/transmittance_calc_vs.glsl b/modules/atmosphere/shaders/transmittance_calc_vs.glsl deleted file mode 100644 index aead855d65..0000000000 --- a/modules/atmosphere/shaders/transmittance_calc_vs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec4 in_position; - -void main() { - gl_Position = in_position; -} diff --git a/modules/base/shaders/axes_fs.glsl b/modules/base/shaders/axes_fs.glsl index 6bbcd9b84b..912657481c 100644 --- a/modules/base/shaders/axes_fs.glsl +++ b/modules/base/shaders/axes_fs.glsl @@ -35,7 +35,7 @@ uniform vec3 zColor; Fragment getFragment() { Fragment frag; - vec3 colorComponents = step(0.01f, vs_positionModelSpace); + vec3 colorComponents = step(0.01, vs_positionModelSpace); frag.color.rgb = colorComponents.x * xColor + colorComponents.y * yColor + diff --git a/modules/base/shaders/axes_vs.glsl b/modules/base/shaders/axes_vs.glsl index b7d5caae03..539b4ddd18 100644 --- a/modules/base/shaders/axes_vs.glsl +++ b/modules/base/shaders/axes_vs.glsl @@ -37,7 +37,7 @@ void main() { vec4 positionViewSpace = modelViewTransform * vec4(in_position, 1.0); vec4 positionClipSpace = projectionTransform * positionViewSpace; vec4 positionScreenSpace = positionClipSpace; - positionScreenSpace.z = 0.f; + positionScreenSpace.z = 0.0; vs_positionModelSpace = in_position; vs_screenSpaceDepth = positionScreenSpace.w; vs_positionViewSpace = positionViewSpace; diff --git a/modules/base/shaders/grid_fs.glsl b/modules/base/shaders/grid_fs.glsl index 06d83fa764..0046d605d1 100644 --- a/modules/base/shaders/grid_fs.glsl +++ b/modules/base/shaders/grid_fs.glsl @@ -33,13 +33,12 @@ uniform float opacity; Fragment getFragment() { Fragment frag; frag.color.rgb = gridColor; - frag.color.a = opacity; - frag.depth = vs_depthClipSpace; + frag.color.a = opacity; + frag.depth = vs_depthClipSpace; frag.gPosition = vs_positionViewSpace; // There is no normal here frag.gNormal = vec4(0.0, 0.0, -1.0, 1.0); return frag; - } diff --git a/modules/base/shaders/grid_vs.glsl b/modules/base/shaders/grid_vs.glsl index 30351ea566..755eb91e0a 100644 --- a/modules/base/shaders/grid_vs.glsl +++ b/modules/base/shaders/grid_vs.glsl @@ -33,13 +33,13 @@ uniform dmat4 modelViewTransform; uniform dmat4 MVPTransform; void main() { - dvec4 objPosDouble = dvec4(in_position, 1.0); + dvec4 objPosDouble = dvec4(in_position, 1.0); dvec4 positionViewSpace = modelViewTransform * objPosDouble; dvec4 positionClipSpace = MVPTransform * objPosDouble; positionClipSpace.z = 0.0; - vs_depthClipSpace = float(positionClipSpace.w); + vs_depthClipSpace = float(positionClipSpace.w); vs_positionViewSpace = vec4(positionViewSpace); gl_Position = vec4(positionClipSpace); diff --git a/modules/base/shaders/line_fs.glsl b/modules/base/shaders/line_fs.glsl index 0045d65d15..7d60291b6d 100644 --- a/modules/base/shaders/line_fs.glsl +++ b/modules/base/shaders/line_fs.glsl @@ -23,7 +23,6 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "floatoperations.glsl" in float vs_depth; in vec4 vs_positionViewSpace; diff --git a/modules/base/shaders/plane_fs.glsl b/modules/base/shaders/plane_fs.glsl index b11a3da7bc..b70c9a0ebd 100644 --- a/modules/base/shaders/plane_fs.glsl +++ b/modules/base/shaders/plane_fs.glsl @@ -24,10 +24,10 @@ #include "fragment.glsl" -in float vs_screenSpaceDepth; -in vec2 vs_st; in vec4 vs_gPosition; in vec3 vs_gNormal; +in float vs_screenSpaceDepth; +in vec2 vs_st; uniform sampler2D texture1; uniform bool additiveBlending; @@ -57,8 +57,8 @@ Fragment getFragment() { } // G-Buffer - frag.gPosition = vs_gPosition; - frag.gNormal = vec4(vs_gNormal, 1.0); + frag.gPosition = vs_gPosition; + frag.gNormal = vec4(vs_gNormal, 1.0); return frag; } diff --git a/modules/base/shaders/plane_vs.glsl b/modules/base/shaders/plane_vs.glsl index e93dd95a92..a3af07c14e 100644 --- a/modules/base/shaders/plane_vs.glsl +++ b/modules/base/shaders/plane_vs.glsl @@ -29,12 +29,10 @@ layout(location = 0) in vec4 in_position; layout(location = 1) in vec2 in_st; -out vec2 vs_st; -out float vs_screenSpaceDepth; -out vec4 vs_positionScreenSpace; -// G-Buffer out vec4 vs_gPosition; out vec3 vs_gNormal; +out float vs_screenSpaceDepth; +out vec2 vs_st; uniform mat4 modelViewProjectionTransform; uniform mat4 modelViewTransform; diff --git a/modules/base/shaders/screenspace_fs.glsl b/modules/base/shaders/screenspace_fs.glsl index fabb553c14..0d36c6ef4f 100644 --- a/modules/base/shaders/screenspace_fs.glsl +++ b/modules/base/shaders/screenspace_fs.glsl @@ -26,21 +26,20 @@ #include "PowerScaling/powerScaling_fs.hglsl" in vec2 vs_st; -in vec4 vs_position; +in float vs_depth; -uniform sampler2D texture1; -uniform vec3 MultiplyColor = vec3(1.0, 1.0, 1.0); -uniform float Alpha = 1.0; +uniform sampler2D tex; +uniform vec3 color = vec3(1.0, 1.0, 1.0); +uniform float opacity = 1.0; Fragment getFragment() { - Fragment frag; + Fragment frag; - frag.color = texture(texture1, vs_st) * vec4(MultiplyColor, Alpha); - if (frag.color.a == 0.0) { - discard; - } + frag.color = texture(tex, vs_st) * vec4(color, opacity); + if (frag.color.a == 0.0) { + discard; + } - frag.depth = vs_position.z; - - return frag; + frag.depth = vs_depth; + return frag; } diff --git a/modules/base/shaders/screenspace_vs.glsl b/modules/base/shaders/screenspace_vs.glsl index 2f057ce33d..4932574f04 100644 --- a/modules/base/shaders/screenspace_vs.glsl +++ b/modules/base/shaders/screenspace_vs.glsl @@ -28,14 +28,13 @@ layout(location = 0) in vec3 in_position; layout(location = 1) in vec2 in_st; out vec2 vs_st; -out vec4 vs_position; - -uniform mat4 ModelTransform; -uniform mat4 ViewProjectionMatrix; +out float vs_depth; +uniform mat4 mvpMatrix; void main() { - vs_st = in_st; - vs_position = ViewProjectionMatrix * ModelTransform * vec4(in_position, 1.0); - gl_Position = vec4(vs_position); + vs_st = in_st; + vec4 p = mvpMatrix * vec4(in_position, 1.0); + vs_depth = p.z; + gl_Position = vec4(p); } diff --git a/modules/base/shaders/sphere_fs.glsl b/modules/base/shaders/sphere_fs.glsl index 0a3a97acec..33b5374993 100644 --- a/modules/base/shaders/sphere_fs.glsl +++ b/modules/base/shaders/sphere_fs.glsl @@ -23,13 +23,11 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "PowerScaling/powerScaling_fs.hglsl" in vec4 vs_position; in vec2 vs_textureCoords; in vec3 vs_normal; -uniform float time; uniform sampler2D colorTexture; uniform float opacity; uniform bool mirrorTexture; diff --git a/modules/base/shaders/sphere_vs.glsl b/modules/base/shaders/sphere_vs.glsl index 873646d23a..99e4a11973 100644 --- a/modules/base/shaders/sphere_vs.glsl +++ b/modules/base/shaders/sphere_vs.glsl @@ -42,5 +42,5 @@ void main() { vs_position = position; // Set z to 0 to disable near/far-plane clipping - gl_Position = vec4(position.xy, 0.0, position.w); + gl_Position = vec4(position.xy, 0.0, position.w); } diff --git a/modules/cefwebgui/shaders/gui_fs.glsl b/modules/cefwebgui/shaders/gui_fs.glsl index 08a149d55a..1a08596b5e 100644 --- a/modules/cefwebgui/shaders/gui_fs.glsl +++ b/modules/cefwebgui/shaders/gui_fs.glsl @@ -24,12 +24,11 @@ #version __CONTEXT__ -in vec2 Texcoord; - +in vec2 vs_st; out vec4 outputColor; uniform sampler2D tex; void main() { - outputColor = texture(tex, Texcoord); + outputColor = texture(tex, vs_st); } diff --git a/modules/cefwebgui/shaders/gui_vs.glsl b/modules/cefwebgui/shaders/gui_vs.glsl index 6044288f45..88ee25ef02 100644 --- a/modules/cefwebgui/shaders/gui_vs.glsl +++ b/modules/cefwebgui/shaders/gui_vs.glsl @@ -25,13 +25,12 @@ #version __CONTEXT__ layout(location = 0) in vec2 position; +out vec2 vs_st; uniform mat4 ortho; -out vec2 Texcoord; - void main() { - Texcoord = vec2(position.x + 1.0f, position.y + 1.0f) * 0.5; + vs_st = vec2(position.x + 1.0, position.y + 1.0) * 0.5; gl_Position = vec4(position, 0.0, 1.0); } diff --git a/modules/digitaluniverse/CMakeLists.txt b/modules/digitaluniverse/CMakeLists.txt index 8eb459ec5e..b8abefa7da 100644 --- a/modules/digitaluniverse/CMakeLists.txt +++ b/modules/digitaluniverse/CMakeLists.txt @@ -41,12 +41,6 @@ set(SOURCE_FILES source_group("Source Files" FILES ${SOURCE_FILES}) set(SHADER_FILES - shaders/pointssprite_fs.glsl - shaders/pointssprite_vs.glsl - shaders/points_sprite_fs.glsl - shaders/points_fs.glsl - shaders/points_gs.glsl - shaders/points_vs.glsl shaders/billboard_fs.glsl shaders/billboard_gs.glsl shaders/billboard_vs.glsl @@ -57,6 +51,8 @@ set(SHADER_FILES shaders/dumesh_fs.glsl shaders/plane_vs.glsl shaders/plane_fs.glsl + shaders/points_sprite_fs.glsl + shaders/points_vs.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 678b20592a..203310715a 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -29,47 +29,44 @@ flat in float vs_screenSpaceDepth; in vec2 texCoord; in float ta; -uniform float alphaValue; // opacity +uniform float alphaValue; uniform vec3 color; uniform sampler2D spriteTexture; uniform bool hasColorMap; uniform float fadeInValue; Fragment getFragment() { - vec4 textureColor = texture(spriteTexture, texCoord); + if (gs_colorMap.a == 0.0 || ta == 0.0 || fadeInValue == 0.0 || alphaValue == 0.0) { + discard; + } + + vec4 textureColor = texture(spriteTexture, texCoord); + if (textureColor.a == 0.0) { + discard; + } + + vec4 fullColor = textureColor; - if (textureColor.a == 0.f || gs_colorMap.a == 0.f || ta == 0.f || fadeInValue == 0.f) - { - discard; - } + if (hasColorMap) { + fullColor *= gs_colorMap; + } + else { + fullColor.rgb *= color; + } - vec4 fullColor = vec4(1.0); - - if (hasColorMap) { - fullColor = vec4( - gs_colorMap.rgb * textureColor.rgb, - gs_colorMap.a * textureColor.a * alphaValue - ); - } - else { - fullColor = vec4(color.rgb * textureColor.rgb, textureColor.a * alphaValue); - } + float textureOpacity = dot(fullColor.rgb, vec3(1.0)); + if (textureOpacity == 0.0) { + discard; + } - fullColor.a *= fadeInValue * ta; - - float textureOpacity = dot(fullColor.rgb, vec3(1.0)); - if (fullColor.a == 0.f || textureOpacity == 0.0) { - discard; - } + fullColor.a *= alphaValue * fadeInValue * ta; - Fragment frag; - frag.color = fullColor; - frag.depth = vs_screenSpaceDepth; - // Setting the position of the billboards to not interact - // with the ATM. - frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - //frag.disableLDR2HDR = true; + Fragment frag; + frag.color = fullColor; + frag.depth = vs_screenSpaceDepth; + // Setting the position of the billboards to not interact with the ATM + frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - return frag; + return frag; } diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index e2f7fb4fc7..0fa9023e8e 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -29,117 +29,110 @@ layout(points) in; layout(triangle_strip, max_vertices = 4) out; -uniform float scaleFactor; -uniform vec3 up; -uniform vec3 right; -uniform dvec3 cameraPosition; // in world space (no SGCT View was considered) -uniform vec3 cameraLookUp; // in world space (no SGCT View was considered) -uniform int renderOption; -uniform vec2 screenSize; -uniform float maxBillboardSize; -uniform float minBillboardSize; - -uniform mat4 cameraViewProjectionMatrix; -uniform dmat4 modelMatrix; - -uniform float correctionSizeFactor; -uniform float correctionSizeEndDistance; - -uniform bool enabledRectSizeControl; - -uniform bool hasDvarScaling; - flat in vec4 colorMap[]; flat in float dvarScaling[]; flat out vec4 gs_colorMap; - out vec2 texCoord; flat out float vs_screenSpaceDepth; out float ta; +// General settings +uniform float scaleFactor; +uniform int renderOption; +uniform mat4 cameraViewProjectionMatrix; +uniform dmat4 modelMatrix; +uniform bool enabledRectSizeControl; +uniform bool hasDvarScaling; + +// RenderOption: CameraViewDirection +uniform vec3 up; +uniform vec3 right; + +// RenderOption: CameraPositionNormal +uniform dvec3 cameraPosition; +uniform vec3 cameraLookUp; +uniform float correctionSizeFactor; +uniform float correctionSizeEndDistance; + +// Pixel size control: true +uniform vec2 screenSize; +uniform float maxBillboardSize; +uniform float minBillboardSize; + const double PARSEC = 0.308567756e17LF; const vec2 corners[4] = vec2[4]( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(1.0, 1.0), - vec2(0.0, 1.0) + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(1.0, 1.0), + vec2(0.0, 1.0) ); +const int RenderOptionCameraViewDirection = 0; +const int RenderOptionCameraPositionNormal = 1; void main() { - ta = 1.0f; - vec4 pos = gl_in[0].gl_Position; // in object space - gs_colorMap = colorMap[0]; + ta = 1.0; + vec4 pos = gl_in[0].gl_Position; + gs_colorMap = colorMap[0]; - double unit = PARSEC; + double unit = PARSEC; // Must be the same as the enum in RenderableBillboardsCloud.h - if (pos.w == 1.f) { - unit = 1E3; - } - else if (pos.w == 2.f) { - unit = PARSEC; - } - else if (pos.w == 3.f) { - unit = 1E3 * PARSEC; - } - else if (pos.w == 4.f) { - unit = 1E6 * PARSEC; - } - else if (pos.w == 5.f) { - unit = 1E9 * PARSEC; - } - else if (pos.w == 6.f) { - // Convertion factor from Parsecs to GigalightYears + if (pos.w == 1.0) { unit = 1E3; } + else if (pos.w == 2.0) { unit = PARSEC; } + else if (pos.w == 3.0) { unit = 1E3 * PARSEC; } + else if (pos.w == 4.0) { unit = 1E6 * PARSEC; } + else if (pos.w == 5.0) { unit = 1E9 * PARSEC; } + else if (pos.w == 6.0) { + // Conversion factor from Parsecs to GigalightYears unit = 306391534.73091 * PARSEC; } - dvec4 dpos = dvec4(dvec3(pos.xyz) * unit, 1.0); - dpos = modelMatrix * dpos; + dvec4 dpos = modelMatrix * dvec4(dvec3(pos.xyz) * unit, 1.0); - float scaleMultiply = exp(scaleFactor * 0.10f); - scaleMultiply = hasDvarScaling ? dvarScaling[0] * scaleMultiply : scaleMultiply; - - vec3 scaledRight = vec3(0.f); - vec3 scaledUp = vec3(0.f); - - vec4 initialPosition, secondPosition, thirdPosition, crossCorner; - - if (renderOption == 0) { // Camera View Direction - scaledRight = scaleMultiply * right * 0.5f; - scaledUp = scaleMultiply * up * 0.5f; + float scaleMultiply = exp(scaleFactor * 0.10); + if (hasDvarScaling) { + scaleMultiply *= dvarScaling[0]; } - else if (renderOption == 1) { // Camera Position Normal - vec3 normal = vec3(normalize(cameraPosition - dpos.xyz)); + + vec3 scaledRight = vec3(0.0); + vec3 scaledUp = vec3(0.0); + + if (renderOption == RenderOptionCameraViewDirection) { + scaledRight = scaleMultiply * right * 0.5; + scaledUp = scaleMultiply * up * 0.5; + } + else if (renderOption == RenderOptionCameraPositionNormal) { + vec3 normal = vec3(normalize(cameraPosition - dpos.xyz)); vec3 newRight = normalize(cross(cameraLookUp, normal)); - vec3 newUp = cross(normal, newRight); + vec3 newUp = cross(normal, newRight); if (!enabledRectSizeControl) { double distCamera = length(cameraPosition - dpos.xyz); - float expVar = float(-distCamera) / pow(10.f, correctionSizeEndDistance); - float factorVar = pow(10.f, correctionSizeFactor); - scaleMultiply *= 1.f / (1.f + factorVar * exp(expVar)); + float expVar = float(-distCamera) / pow(10.0, correctionSizeEndDistance); + float factorVar = pow(10.0, correctionSizeFactor); + scaleMultiply *= 1.0 / (1.0 + factorVar * exp(expVar)); } - scaledRight = scaleMultiply * newRight * 0.5f; - scaledUp = scaleMultiply * newUp * 0.5f; + scaledRight = scaleMultiply * newRight * 0.5; + scaledUp = scaleMultiply * newUp * 0.5; } if (enabledRectSizeControl) { - initialPosition = z_normalization(cameraViewProjectionMatrix * + vec4 initialPosition = z_normalization(cameraViewProjectionMatrix * vec4(vec3(dpos.xyz) - scaledRight - scaledUp, dpos.w)); vs_screenSpaceDepth = initialPosition.w; - crossCorner = z_normalization(cameraViewProjectionMatrix * + vec4 crossCorner = z_normalization(cameraViewProjectionMatrix * vec4(vec3(dpos.xyz) + scaledUp + scaledRight, dpos.w)); // Testing size for rectangular viewport: - vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; - vec2 topRight = crossCorner.xy/crossCorner.w; - vec2 bottomLeft = initialPosition.xy/initialPosition.w; + vec2 halfViewSize = screenSize * 0.5; + vec2 topRight = crossCorner.xy / crossCorner.w; + vec2 bottomLeft = initialPosition.xy / initialPosition.w; // width and height vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); @@ -148,18 +141,18 @@ void main() { float correctionScale = maxBillboardSize / length(sizes); scaledRight *= correctionScale; - scaledUp *= correctionScale; - + scaledUp *= correctionScale; } else { // linear alpha decay - if (sizes.x < 2.0f * minBillboardSize) { - float maxVar = 2.0f * minBillboardSize; + if (sizes.x < 2.0 * minBillboardSize) { + float maxVar = 2.0 * minBillboardSize; float minVar = minBillboardSize; - float var = (sizes.y + sizes.x); - ta = ( (var - minVar)/(maxVar - minVar) ); - if (ta == 0.0f) + float var = sizes.y + sizes.x; + ta = (var - minVar) / (maxVar - minVar); + if (ta == 0.0) { return; + } } } } @@ -169,27 +162,26 @@ void main() { vec4 scaledRightClip = cameraViewProjectionMatrix * vec4(scaledRight, 0.0); vec4 scaledUpClip = cameraViewProjectionMatrix * vec4(scaledUp, 0.0); - initialPosition = z_normalization(dposClip - scaledRightClip - scaledUpClip); + vec4 initialPosition = z_normalization(dposClip - scaledRightClip - scaledUpClip); vs_screenSpaceDepth = initialPosition.w; - secondPosition = z_normalization(dposClip + scaledRightClip - scaledUpClip); - crossCorner = z_normalization(dposClip + scaledUpClip + scaledRightClip); - thirdPosition = z_normalization(dposClip + scaledUpClip - scaledRightClip); + vec4 secondPosition = z_normalization(dposClip + scaledRightClip - scaledUpClip); + vec4 crossCorner = z_normalization(dposClip + scaledUpClip + scaledRightClip); + vec4 thirdPosition = z_normalization(dposClip + scaledUpClip - scaledRightClip); // Build primitive - - texCoord = corners[0]; + texCoord = corners[0]; gl_Position = initialPosition; EmitVertex(); - texCoord = corners[1]; + texCoord = corners[1]; gl_Position = secondPosition; EmitVertex(); - texCoord = corners[3]; + texCoord = corners[3]; gl_Position = thirdPosition; EmitVertex(); - texCoord = corners[2]; + texCoord = corners[2]; gl_Position = crossCorner; EmitVertex(); diff --git a/modules/digitaluniverse/shaders/billboard_vs.glsl b/modules/digitaluniverse/shaders/billboard_vs.glsl index 98517afeb5..53bd0bd9d8 100644 --- a/modules/digitaluniverse/shaders/billboard_vs.glsl +++ b/modules/digitaluniverse/shaders/billboard_vs.glsl @@ -34,7 +34,7 @@ flat out vec4 colorMap; flat out float dvarScaling; void main() { - colorMap = in_colormap; - dvarScaling = in_dvarScaling; - gl_Position = in_position; + colorMap = in_colormap; + dvarScaling = in_dvarScaling; + gl_Position = in_position; } diff --git a/modules/digitaluniverse/shaders/billboardpolygon_gs.glsl b/modules/digitaluniverse/shaders/billboardpolygon_gs.glsl index 2bd88f5b90..6b6936eca4 100644 --- a/modules/digitaluniverse/shaders/billboardpolygon_gs.glsl +++ b/modules/digitaluniverse/shaders/billboardpolygon_gs.glsl @@ -25,7 +25,6 @@ #version __CONTEXT__ layout(points) in; -//layout(line_strip, max_vertices = 19) out; layout(triangle_strip, max_vertices = 63) out; uniform int sides; @@ -33,41 +32,24 @@ uniform int sides; const float PI = 3.1415926; void main() { - // for (int i = 0; i <= sides; i++) { - // // Angle between each side in radians - // float ang = PI * 2.0 / float(sides) * i; - - // // Offset from center of point (0.3 to accomodate for aspect ratio) - // //vec4 offset = vec4(cos(ang) * 0.003, -sin(ang) * 0.004, 0.0, 0.0); - // vec4 offset = vec4(cos(ang) * 0.8, -sin(ang) * 0.8, 0.0, 0.0); - // gl_Position = gl_in[0].gl_Position + offset; - - // // vec4 offset = vec4(cos(ang) * gl_in[0].gl_Position[0], -sin(ang) * gl_in[0].gl_Position[1], - // // gl_in[0].gl_Position[2] , gl_in[0].gl_Position[3]); - // // gl_Position = offset; - - // EmitVertex(); - // } - // EndPrimitive(); + vec4 v0 = gl_in[0].gl_Position; - vec4 v0 = gl_in[0].gl_Position; - - for (int i = sides; i > 0; --i) { - // Angle between each side in radians - float ang = PI * 2.0 / float(sides) * i; + for (int i = sides; i > 0; --i) { + // Angle between each side in radians + float ang = 2.0 * PI / float(sides) * i; - gl_Position = v0; - EmitVertex(); + gl_Position = v0; + EmitVertex(); - vec4 vi = v0 + vec4(cos(ang) * 0.8, -sin(ang) * 0.8, 0.0, 0.0); - gl_Position = vi; - EmitVertex(); + vec4 vi = v0 + vec4(cos(ang) * 0.8, -sin(ang) * 0.8, 0.0, 0.0); + gl_Position = vi; + EmitVertex(); - ang = PI * 2.0 / float(sides) * (i-1); - vec4 vii = v0 + vec4(cos(ang) * 0.8, -sin(ang) * 0.8, 0.0, 0.0); - gl_Position = vii; - EmitVertex(); + ang = 2.0 * PI / float(sides) * (i - 1); + vec4 vii = v0 + vec4(cos(ang) * 0.8, -sin(ang) * 0.8, 0.0, 0.0); + gl_Position = vii; + EmitVertex(); - EndPrimitive(); - } + EndPrimitive(); + } } diff --git a/modules/digitaluniverse/shaders/billboardpolygon_vs.glsl b/modules/digitaluniverse/shaders/billboardpolygon_vs.glsl index aead855d65..8e814f1955 100644 --- a/modules/digitaluniverse/shaders/billboardpolygon_vs.glsl +++ b/modules/digitaluniverse/shaders/billboardpolygon_vs.glsl @@ -27,5 +27,5 @@ layout(location = 0) in vec4 in_position; void main() { - gl_Position = in_position; + gl_Position = in_position; } diff --git a/modules/digitaluniverse/shaders/dumesh_fs.glsl b/modules/digitaluniverse/shaders/dumesh_fs.glsl index 1e28d7ce69..a9a0507272 100644 --- a/modules/digitaluniverse/shaders/dumesh_fs.glsl +++ b/modules/digitaluniverse/shaders/dumesh_fs.glsl @@ -31,18 +31,18 @@ uniform vec3 color; uniform float alphaValue; Fragment getFragment() { - Fragment frag; + Fragment frag; - if (alphaValue == 0.0) { - discard; - } + if (alphaValue == 0.0) { + discard; + } - frag.color = vec4(color, alphaValue); - frag.depth = vs_screenSpaceDepth; + frag.color = vec4(color, alphaValue); + frag.depth = vs_screenSpaceDepth; - // JCC: Need to change the position to camera space - frag.gPosition = vs_positionViewSpace; - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + // JCC: Need to change the position to camera space + frag.gPosition = vs_positionViewSpace; + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - return frag; + return frag; } diff --git a/modules/digitaluniverse/shaders/dumesh_vs.glsl b/modules/digitaluniverse/shaders/dumesh_vs.glsl index 281d1d0a64..58f891144d 100644 --- a/modules/digitaluniverse/shaders/dumesh_vs.glsl +++ b/modules/digitaluniverse/shaders/dumesh_vs.glsl @@ -28,19 +28,19 @@ in vec3 in_position; -uniform dmat4 modelViewTransform; -uniform dmat4 projectionTransform; - out float vs_screenSpaceDepth; out vec4 vs_positionViewSpace; +uniform dmat4 modelViewTransform; +uniform dmat4 projectionTransform; + void main() { - dvec4 positionViewSpace = modelViewTransform * dvec4(in_position, 1.0); - vec4 positionClipSpace = vec4(projectionTransform * positionViewSpace); - vec4 positionScreenSpace = vec4(z_normalization(positionClipSpace)); + dvec4 positionViewSpace = modelViewTransform * dvec4(in_position, 1.0); + vec4 positionClipSpace = vec4(projectionTransform * positionViewSpace); + vec4 positionScreenSpace = vec4(z_normalization(positionClipSpace)); - vs_screenSpaceDepth = positionScreenSpace.w; - vs_positionViewSpace = vec4(positionViewSpace); + vs_screenSpaceDepth = positionScreenSpace.w; + vs_positionViewSpace = vec4(positionViewSpace); - gl_Position = positionScreenSpace; + gl_Position = positionScreenSpace; } diff --git a/modules/digitaluniverse/shaders/plane_fs.glsl b/modules/digitaluniverse/shaders/plane_fs.glsl index 5282ce582e..c3a0a39965 100644 --- a/modules/digitaluniverse/shaders/plane_fs.glsl +++ b/modules/digitaluniverse/shaders/plane_fs.glsl @@ -28,37 +28,24 @@ in float vs_screenSpaceDepth; in vec2 vs_st; uniform sampler2D galaxyTexture; -//uniform bool additiveBlending; uniform float alphaValue; uniform float fadeInValue; - Fragment getFragment() { - Fragment frag; - // if (gl_FrontFacing) { - // frag.color = texture(galaxyTexture, vs_st); - // } - // else { - // frag.color = texture(galaxyTexture, vec2(1 - vs_st.s, vs_st.t)); - // } + Fragment frag; - frag.color = texture(galaxyTexture, vs_st); - frag.color *= alphaValue; + frag.color = texture(galaxyTexture, vs_st); + frag.color *= alphaValue; - frag.color *= fadeInValue; + frag.color *= fadeInValue; - if (frag.color.a == 0.0) { - discard; - } + if (frag.color.a == 0.0) { + discard; + } - // if (additiveBlending) { - // frag.blend = BLEND_MODE_ADDITIVE; - // } + frag.depth = vs_screenSpaceDepth; + frag.gPosition = vec4(vs_screenSpaceDepth, vs_screenSpaceDepth, vs_screenSpaceDepth, 1.0); + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - //frag.color = texture(galaxyTexture, vs_st); - frag.depth = vs_screenSpaceDepth; - frag.gPosition = vec4(vs_screenSpaceDepth, vs_screenSpaceDepth, vs_screenSpaceDepth, 1.0); - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - - return frag; + return frag; } diff --git a/modules/digitaluniverse/shaders/plane_vs.glsl b/modules/digitaluniverse/shaders/plane_vs.glsl index cb84739b05..d373add7ec 100644 --- a/modules/digitaluniverse/shaders/plane_vs.glsl +++ b/modules/digitaluniverse/shaders/plane_vs.glsl @@ -34,12 +34,11 @@ out float vs_screenSpaceDepth; uniform dmat4 modelViewProjectionTransform; - void main() { - vs_st = in_st; - vec4 positionClipSpace = vec4(modelViewProjectionTransform * dvec4(in_position)); - vec4 positionScreenSpace = z_normalization(positionClipSpace); + vs_st = in_st; + vec4 positionClipSpace = vec4(modelViewProjectionTransform * dvec4(in_position)); + vec4 positionScreenSpace = z_normalization(positionClipSpace); - vs_screenSpaceDepth = positionScreenSpace.w; - gl_Position = positionScreenSpace; + vs_screenSpaceDepth = positionScreenSpace.w; + gl_Position = positionScreenSpace; } diff --git a/modules/digitaluniverse/shaders/points_fs.glsl b/modules/digitaluniverse/shaders/points_fs.glsl deleted file mode 100644 index a38eb2d5fb..0000000000 --- a/modules/digitaluniverse/shaders/points_fs.glsl +++ /dev/null @@ -1,55 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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 "fragment.glsl" - -//in float gs_screenSpaceDepth; -in float vs_screenSpaceDepth; -in vec4 colorMap; - -uniform vec3 color; -uniform float alphaValue; -uniform bool hasColorMap; - -Fragment getFragment() { - Fragment frag; - - if (alphaValue == 0.0) { - discard; - } - - if (hasColorMap) { - frag.color = vec4(colorMap.xyz, alphaValue); - } - else { - frag.color = vec4(color, alphaValue); - } - - //frag.depth = gs_screenSpaceDepth; - frag.depth = vs_screenSpaceDepth; - frag.gPosition = vec4(1e27, 1e27, 1e27, 1.0); - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - - return frag; -} diff --git a/modules/digitaluniverse/shaders/points_gs.glsl b/modules/digitaluniverse/shaders/points_gs.glsl deleted file mode 100644 index dc074d0484..0000000000 --- a/modules/digitaluniverse/shaders/points_gs.glsl +++ /dev/null @@ -1,63 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(points) in; -//layout(points, max_vertices = 13) out; -layout(line_strip, max_vertices = 13) out; - -in float vs_screenSpaceDepth[]; -in float vs_scaleFactor[]; -in vec4 colorMap[] - -uniform int sides; - -out float gs_screenSpaceDepth; - -const float PI = 3.1415926; - -void main() { - gs_screenSpaceDepth = vs_screenSpaceDepth[0]; - - for (int i = 0; i <= sides; i++) { - // Angle between each side in radians - float ang = PI * 2.0 / float(sides) * i; - - // Offset from center of point (0.3 to accomodate for aspect ratio) - //vec4 offset = vec4(cos(ang) * 0.003, -sin(ang) * 0.004, 0.0, 0.0); - //gl_Position = gl_in[0].gl_Position + offset; - - vec4 offset = vec4(cos(ang) * gl_in[0].gl_Position[0], -sin(ang) * gl_in[0].gl_Position[1], - gl_in[0].gl_Position[2] , gl_in[0].gl_Position[3]); - gl_Position = offset; - - EmitVertex(); - } - - //gl_Position = gl_in[0].gl_Position;// + offset; - //EmitVertex(); - - EndPrimitive(); -} diff --git a/modules/digitaluniverse/shaders/points_sprite_fs.glsl b/modules/digitaluniverse/shaders/points_sprite_fs.glsl index 03fdcfd916..1614127071 100644 --- a/modules/digitaluniverse/shaders/points_sprite_fs.glsl +++ b/modules/digitaluniverse/shaders/points_sprite_fs.glsl @@ -24,25 +24,23 @@ #include "fragment.glsl" -//in float gs_screenSpaceDepth; in float vs_screenSpaceDepth; uniform vec3 color; uniform float alphaValue; - uniform sampler2D spriteTexture; Fragment getFragment() { - Fragment frag; + Fragment frag; - if (alphaValue == 0.0) { - discard; - } + if (alphaValue == 0.0) { + discard; + } - frag.color = texture(spriteTexture, gl_PointCoord) * vec4(color, alphaValue); - //frag.depth = gs_screenSpaceDepth; - frag.depth = vs_screenSpaceDepth; - frag.blend = BLEND_MODE_ADDITIVE; + frag.color = texture(spriteTexture, gl_PointCoord) * vec4(color, alphaValue); + //frag.depth = gs_screenSpaceDepth; + frag.depth = vs_screenSpaceDepth; + frag.blend = BLEND_MODE_ADDITIVE; - return frag; + return frag; } diff --git a/modules/digitaluniverse/shaders/points_vs.glsl b/modules/digitaluniverse/shaders/points_vs.glsl index a741bea69e..bf8aea92e4 100644 --- a/modules/digitaluniverse/shaders/points_vs.glsl +++ b/modules/digitaluniverse/shaders/points_vs.glsl @@ -29,23 +29,21 @@ in dvec4 in_position; in dvec4 in_colormap; -uniform dmat4 modelViewProjectionTransform; -uniform float scaleFactor; - out float vs_screenSpaceDepth; out float vs_scaleFactor; out vec4 colorMap; +uniform dmat4 modelViewProjectionTransform; +uniform float scaleFactor; + void main() { - vec4 positionClipSpace = vec4(modelViewProjectionTransform * in_position); - // positionClipSpace = vec4( modelViewProjectionTransform * - // vec4(0,0,0,1)); - vec4 positionScreenSpace = vec4(z_normalization(positionClipSpace)); + vec4 positionClipSpace = vec4(modelViewProjectionTransform * in_position); + vec4 positionScreenSpace = vec4(z_normalization(positionClipSpace)); - vs_screenSpaceDepth = positionScreenSpace.w; - vs_scaleFactor = scaleFactor; - colorMap = vec4(in_colormap); + vs_screenSpaceDepth = positionScreenSpace.w; + vs_scaleFactor = scaleFactor; + colorMap = vec4(in_colormap); - gl_PointSize = scaleFactor; - gl_Position = positionScreenSpace; + gl_PointSize = scaleFactor; + gl_Position = positionScreenSpace; } diff --git a/modules/digitaluniverse/shaders/pointssprite_fs.glsl b/modules/digitaluniverse/shaders/pointssprite_fs.glsl deleted file mode 100644 index 6a6cfdb647..0000000000 --- a/modules/digitaluniverse/shaders/pointssprite_fs.glsl +++ /dev/null @@ -1,53 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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 "fragment.glsl" - -in float vs_screenSpaceDepth; -in vec2 vs_st; - -uniform sampler2D texture1; -uniform bool additiveBlending; - - -Fragment getFragment() { - Fragment frag; - if (gl_FrontFacing) { - frag.color = texture(texture1, vs_st); - } - else { - frag.color = texture(texture1, vec2(1 - vs_st.s, vs_st.t)); - } - - if (frag.color.a == 0.0) { - discard; - } - - frag.depth = vs_screenSpaceDepth; - - if (additiveBlending) { - frag.blend = BLEND_MODE_ADDITIVE; - } - return frag; -} diff --git a/modules/digitaluniverse/shaders/pointssprite_vs.glsl b/modules/digitaluniverse/shaders/pointssprite_vs.glsl deleted file mode 100644 index 7f06ce0d6a..0000000000 --- a/modules/digitaluniverse/shaders/pointssprite_vs.glsl +++ /dev/null @@ -1,48 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -#include "PowerScaling/powerScaling_vs.hglsl" - -layout(location = 0) in vec4 in_position; -layout(location = 1) in vec2 in_st; - -out vec2 vs_st; -out float vs_screenSpaceDepth; -out vec4 vs_positionScreenSpace; - -uniform mat4 modelViewProjectionTransform; - - -void main() { - vec4 position = vec4(in_position.xyz * pow(10, in_position.w), 1); - vec4 positionClipSpace = modelViewProjectionTransform * position; - vec4 positionScreenSpace = z_normalization(positionClipSpace); - - gl_Position = positionScreenSpace; - - vs_st = in_st; - vs_screenSpaceDepth = positionScreenSpace.w; -} diff --git a/modules/exoplanets/shaders/orbitdisc_fs.glsl b/modules/exoplanets/shaders/orbitdisc_fs.glsl index 0f56ee08a1..bab75b0556 100644 --- a/modules/exoplanets/shaders/orbitdisc_fs.glsl +++ b/modules/exoplanets/shaders/orbitdisc_fs.glsl @@ -22,11 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "PowerScaling/powerScaling_fs.hglsl" #include "fragment.glsl" in vec2 vs_st; -in vec4 vs_position; +in float vs_depth; uniform sampler1D discTexture; uniform vec2 offset; // relative to semi major axis @@ -38,7 +37,7 @@ const float Epsilon = 0.0000001; // Compute semi minor axis from major axis, a, and eccentricity, e float semiMinorAxis(float a, float e) { - return a * sqrt(1.0 - e * e); + return a * sqrt(1.0 - e * e); } // If returned value <= 1, the point is insdie or on the ellipse specified by the input: @@ -46,84 +45,84 @@ float semiMinorAxis(float a, float e) { // cx is the displacement of the center of the ellipse along the x-axis (for an orbit, // the y-displacement is always zero) float ellipseTest(vec2 point, float a, float b, float cx) { - float x = point.x; - float y = point.y; - return (pow(x - cx, 2.0) / (a*a)) + ((y*y) / (b*b)); + float x = point.x; + float y = point.y; + return (pow(x - cx, 2.0) / (a*a)) + ((y*y) / (b*b)); } Fragment getFragment() { - // Moving the origin to the center - vec2 st = (vs_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vec2 st = (vs_st - vec2(0.5)) * 2.0; - float offsetLower = offset.x * semiMajorAxis; - float offsetUpper = offset.y * semiMajorAxis; + float offsetLower = offset.x * semiMajorAxis; + float offsetUpper = offset.y * semiMajorAxis; - float AUpper = semiMajorAxis + offsetUpper; - float BUpper = semiMinorAxis(AUpper, eccentricity); - float CUpper = sqrt(AUpper*AUpper - BUpper*BUpper); - float outerApoapsisDistance = AUpper * (1 + eccentricity); + float AUpper = semiMajorAxis + offsetUpper; + float BUpper = semiMinorAxis(AUpper, eccentricity); + float CUpper = sqrt(AUpper*AUpper - BUpper*BUpper); + float outerApoapsisDistance = AUpper * (1.0 + eccentricity); - float ALower = semiMajorAxis - offsetLower; - float BLower = semiMinorAxis(ALower, eccentricity); - float CLower = sqrt(ALower*ALower - BLower*BLower); - float innerApoapsisDistance = ALower * (1 + eccentricity); + float ALower = semiMajorAxis - offsetLower; + float BLower = semiMinorAxis(ALower, eccentricity); + float CLower = sqrt(ALower*ALower - BLower*BLower); + float innerApoapsisDistance = ALower * (1.0 + eccentricity); - // Normalize based on outer apoapsis distance (size of plane) - float AU_n = AUpper / outerApoapsisDistance; - float BU_n = BUpper / outerApoapsisDistance; - float CU_n = CUpper / outerApoapsisDistance; - float AL_n = ALower / outerApoapsisDistance; - float BL_n = BLower / outerApoapsisDistance; - float CL_n = CLower / outerApoapsisDistance; + // Normalize based on outer apoapsis distance (size of plane) + float AU_n = AUpper / outerApoapsisDistance; + float BU_n = BUpper / outerApoapsisDistance; + float CU_n = CUpper / outerApoapsisDistance; + float AL_n = ALower / outerApoapsisDistance; + float BL_n = BLower / outerApoapsisDistance; + float CL_n = CLower / outerApoapsisDistance; - if (eccentricity <= Epsilon) { - CU_n = 0.0; - CL_n = 0.0; - } + if (eccentricity <= Epsilon) { + CU_n = 0.0; + CL_n = 0.0; + } - float outer = ellipseTest(st, AU_n, BU_n, -CU_n); - float inner = ellipseTest(st, AL_n, BL_n, -CL_n); - if (outer > 1.0 || inner < 1.0) { - // point is outside outer ellipse or inside inner eliipse - discard; - } + float outer = ellipseTest(st, AU_n, BU_n, -CU_n); + float inner = ellipseTest(st, AL_n, BL_n, -CL_n); + if (outer > 1.0 || inner < 1.0) { + // Point is outside outer ellipse or inside inner ellipse + discard; + } - // Remapping the texture coordinates - vec2 dir = normalize(st); + // Remapping the texture coordinates + vec2 dir = normalize(st); - // Find outer ellipse: where along the direction does the equation == 1? - float denominator = pow(BU_n * dir.x, 2.0) + pow(AU_n * dir.y, 2.0); - float first = -(BU_n * BU_n * dir.x * CU_n) / denominator; - float second = pow((BU_n * BU_n * dir.x * CU_n) / denominator, 2.0); - float third = (pow(BU_n * CU_n, 2.0) - pow(AU_n * BU_n, 2.0)) / denominator; + // Find outer ellipse: where along the direction does the equation == 1? + float denominator = pow(BU_n * dir.x, 2.0) + pow(AU_n * dir.y, 2.0); + float first = -(BU_n * BU_n * dir.x * CU_n) / denominator; + float second = pow((BU_n * BU_n * dir.x * CU_n) / denominator, 2.0); + float third = (pow(BU_n * CU_n, 2.0) - pow(AU_n * BU_n, 2.0)) / denominator; - float scale = first + sqrt(second - third); + float scale = first + sqrt(second - third); - vec2 outerPoint = dir * scale; - vec2 innerPoint = outerPoint * (innerApoapsisDistance / outerApoapsisDistance); + vec2 outerPoint = dir * scale; + vec2 innerPoint = outerPoint * (innerApoapsisDistance / outerApoapsisDistance); - float discWidth = distance(outerPoint, innerPoint); - float distanceFromOuterEdge = distance(outerPoint, st); - float relativeDistance = distanceFromOuterEdge / discWidth; + float discWidth = distance(outerPoint, innerPoint); + float distanceFromOuterEdge = distance(outerPoint, st); + float relativeDistance = distanceFromOuterEdge / discWidth; - // Compute texture coordinate based on the distance to outer edge - float textureCoord = 0.0; + // Compute texture coordinate based on the distance to outer edge + float textureCoord = 0.0; - // The midpoint (textureCoord = 0.5) depends on the ratio between the offsets - // (Note that the texture goes from outer to inner edge of disc) - float midPoint = offsetUpper / (offsetUpper + offsetLower); - if(relativeDistance > midPoint) { - textureCoord = 0.5 + 0.5 * (relativeDistance - midPoint) / (1.0 - midPoint); - } - else { - textureCoord = 0.5 * (relativeDistance / midPoint); - } + // The midpoint (textureCoord = 0.5) depends on the ratio between the offsets + // (Note that the texture goes from outer to inner edge of disc) + float midPoint = offsetUpper / (offsetUpper + offsetLower); + if (relativeDistance > midPoint) { + textureCoord = 0.5 + 0.5 * (relativeDistance - midPoint) / (1.0 - midPoint); + } + else { + textureCoord = 0.5 * (relativeDistance / midPoint); + } - vec4 diffuse = texture(discTexture, textureCoord); - diffuse.a *= opacity; + vec4 diffuse = texture(discTexture, textureCoord); + diffuse.a *= opacity; - Fragment frag; - frag.color = diffuse; - frag.depth = vs_position.w; - return frag; + Fragment frag; + frag.color = diffuse; + frag.depth = vs_depth; + return frag; } diff --git a/modules/exoplanets/shaders/orbitdisc_vs.glsl b/modules/exoplanets/shaders/orbitdisc_vs.glsl index 80a55c613d..37fda99a3f 100644 --- a/modules/exoplanets/shaders/orbitdisc_vs.glsl +++ b/modules/exoplanets/shaders/orbitdisc_vs.glsl @@ -30,15 +30,16 @@ layout(location = 0) in vec2 in_position; layout(location = 1) in vec2 in_st; out vec2 vs_st; -out vec4 vs_position; +out float vs_depth; uniform mat4 modelViewProjectionTransform; void main() { - vs_st = in_st; - vs_position = z_normalization( - modelViewProjectionTransform * vec4(in_position, 0.0, 1.0) - ); + vs_st = in_st; + vec4 pos = z_normalization( + modelViewProjectionTransform * vec4(in_position, 0.0, 1.0) + ); - gl_Position = vs_position; + vs_depth = pos.w; + gl_Position = pos; } diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 0b3ee6bcd9..52d9c010c7 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -58,12 +58,12 @@ namespace { constexpr const char* _loggerCat = "Renderable Galaxy"; constexpr const std::array UniformNamesPoints = { - "modelMatrix", "cameraViewProjectionMatrix", "eyePosition", + "modelMatrix", "viewProjectionMatrix", "eyePosition", "opacityCoefficient" }; constexpr const std::array UniformNamesBillboards = { - "modelMatrix", "cameraViewProjectionMatrix", + "modelMatrix", "viewProjectionMatrix", "cameraUp", "eyePosition", "psfTexture" }; diff --git a/modules/galaxy/shaders/billboard_fs.glsl b/modules/galaxy/shaders/billboard_fs.glsl index 69931514a8..30930c7495 100644 --- a/modules/galaxy/shaders/billboard_fs.glsl +++ b/modules/galaxy/shaders/billboard_fs.glsl @@ -23,28 +23,25 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "floatoperations.glsl" - -uniform sampler2D psfTexture; in vec4 vs_position; in vec2 psfCoords; flat in vec3 ge_color; flat in float ge_screenSpaceDepth; +uniform sampler2D psfTexture; + Fragment getFragment() { - Fragment frag; + vec4 textureColor = texture(psfTexture, 0.5 * psfCoords + 0.5); + vec4 fullColor = vec4(ge_color * textureColor.a, textureColor.a); + if (fullColor.a == 0) { + discard; + } - vec4 textureColor = texture(psfTexture, 0.5*psfCoords + 0.5); - vec4 fullColor = vec4(ge_color*textureColor.a, textureColor.a); - if (fullColor.a == 0) { - discard; - } - frag.color = fullColor; - - frag.depth = ge_screenSpaceDepth; - frag.gPosition = vs_position; - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - - return frag; + Fragment frag; + frag.color = fullColor; + frag.depth = ge_screenSpaceDepth; + frag.gPosition = vs_position; + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + return frag; } diff --git a/modules/galaxy/shaders/billboard_ge.glsl b/modules/galaxy/shaders/billboard_ge.glsl index 0cd652d36f..49a23edbca 100644 --- a/modules/galaxy/shaders/billboard_ge.glsl +++ b/modules/galaxy/shaders/billboard_ge.glsl @@ -27,11 +27,6 @@ #include "floatoperations.glsl" #include "PowerScaling/powerScalingMath.hglsl" -uniform dvec3 eyePosition; -uniform dvec3 cameraUp; -uniform dmat4 cameraViewProjectionMatrix; -uniform dmat4 modelMatrix; - layout(points) in; layout(triangle_strip, max_vertices = 4) out; @@ -43,59 +38,63 @@ out vec2 psfCoords; flat out vec3 ge_color; flat out float ge_screenSpaceDepth; +uniform dvec3 eyePosition; +uniform dvec3 cameraUp; +uniform dmat4 viewProjectionMatrix; +uniform dmat4 modelMatrix; + const double PARSEC = 3.08567756E16; void main() { - vs_position = gl_in[0].gl_Position; // in object space - ge_color = vs_color[0]; + vs_position = gl_in[0].gl_Position; + ge_color = vs_color[0]; - double scaleMultiply = 8.0; + double scaleMultiply = 8.0; - dvec4 dpos = dvec4(vs_position); - dpos.xyz *= scaleMultiply; - dpos = modelMatrix * dpos; - dpos /= PARSEC; - //It lies about 8 kpc from the center on what is known as the Orion Arm of the Milky Way - dpos.x += 8000; + dvec4 dpos = dvec4(vs_position); + dpos.xyz *= scaleMultiply; + dpos = modelMatrix * dpos; + dpos /= PARSEC; + // It lies about 8 kpc from the center on the Orion Arm of the Milky Way + dpos.x += 8000; - scaleMultiply *= 4.0; - dvec3 scaledRight = dvec3(0.0); - dvec3 scaledUp = dvec3(0.0); - vec4 bottomLeftVertex, bottomRightVertex, topLeftVertex, topRightVertex; + scaleMultiply *= 4.0; - dvec3 normal = normalize(eyePosition - dpos.xyz); - dvec3 newRight = normalize(cross(cameraUp, normal)); - dvec3 newUp = cross(normal, newRight); - scaledRight = scaleMultiply * newRight; - scaledUp = scaleMultiply * newUp; + dvec3 normal = normalize(eyePosition - dpos.xyz); + dvec3 newRight = normalize(cross(cameraUp, normal)); + dvec3 newUp = cross(normal, newRight); + dvec3 scaledRight = scaleMultiply * newRight; + dvec3 scaledUp = scaleMultiply * newUp; - bottomLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + vec4 bottomLeftVertex = z_normalization( + vec4(viewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w)) + ); - //dvec4 dposCamera = cameraViewProjectionMatrix * dpos; - //ge_screenSpaceDepth = float(length(eyePosition - dposCamera.xyz)/PARSEC); - ge_screenSpaceDepth = bottomLeftVertex.w; + ge_screenSpaceDepth = bottomLeftVertex.w; - topRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + vec4 topRightVertex = z_normalization( + vec4(viewProjectionMatrix * dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w)) + ); - bottomRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - topLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); + vec4 bottomRightVertex = z_normalization( + vec4(viewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w)) + ); + vec4 topLeftVertex = z_normalization( + vec4(viewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w)) + ); - // Build primitive - gl_Position = topLeftVertex; - psfCoords = vec2(-1.0, 1.0); - EmitVertex(); - gl_Position = bottomLeftVertex; - psfCoords = vec2(-1.0, -1.0); - EmitVertex(); - gl_Position = topRightVertex; - psfCoords = vec2(1.0, 1.0); - EmitVertex(); - gl_Position = bottomRightVertex; - psfCoords = vec2(1.0, -1.0); - EmitVertex(); - EndPrimitive(); + // Build primitive + gl_Position = topLeftVertex; + psfCoords = vec2(-1.0, 1.0); + EmitVertex(); + gl_Position = bottomLeftVertex; + psfCoords = vec2(-1.0, -1.0); + EmitVertex(); + gl_Position = topRightVertex; + psfCoords = vec2(1.0, 1.0); + EmitVertex(); + gl_Position = bottomRightVertex; + psfCoords = vec2(1.0, -1.0); + EmitVertex(); + EndPrimitive(); } diff --git a/modules/galaxy/shaders/billboard_vs.glsl b/modules/galaxy/shaders/billboard_vs.glsl index 36e1cb8f56..f466ef2103 100644 --- a/modules/galaxy/shaders/billboard_vs.glsl +++ b/modules/galaxy/shaders/billboard_vs.glsl @@ -30,6 +30,6 @@ layout(location = 1) in vec3 in_color; out vec3 vs_color; void main() { - vs_color = in_color; - gl_Position = vec4(in_position, 1.0); + vs_color = in_color; + gl_Position = vec4(in_position, 1.0); } diff --git a/modules/galaxy/shaders/galaxyraycast.glsl b/modules/galaxy/shaders/galaxyraycast.glsl index c8d4c870fe..a73e31501e 100644 --- a/modules/galaxy/shaders/galaxyraycast.glsl +++ b/modules/galaxy/shaders/galaxyraycast.glsl @@ -32,42 +32,42 @@ uniform sampler3D galaxyTexture#{id}; void sample#{id}(vec3 samplePos, vec3 dir, inout vec3 accumulatedColor, inout vec3 accumulatedAlpha, inout float stepSize) { - vec3 aspect = aspect#{id}; - stepSize = maxStepSize#{id} / length(dir / aspect); + vec3 aspect = aspect#{id}; + stepSize = maxStepSize#{id} / length(dir / aspect); - // Early ray termination on black parts of the data - vec3 normalizedPos = samplePos * 2.f - 1.f; - if (normalizedPos.x * normalizedPos.x + normalizedPos.y * normalizedPos.y > 0.7) { - return; - } - - vec4 sampledColor = texture(galaxyTexture#{id}, samplePos.xyz); - - // Source textures currently are square-rooted to avoid dithering in the shadows. - // So square them back - sampledColor = sampledColor*sampledColor; - - // Fudge for the dust "spreading" - sampledColor.a = clamp(sampledColor.a, 0.f, 1.f); - sampledColor.a = pow(sampledColor.a, 0.7f); - - // Absorption probability - float scaledDensity = sampledColor.a * stepSize * absorptionMultiply#{id}; - vec3 alphaTint = vec3(0.3f, 0.54f, 0.85f); - vec3 absorption = alphaTint * scaledDensity; - - // Extinction - vec3 extinction = exp(-absorption); - accumulatedColor.rgb *= extinction; - - // Emission - accumulatedColor.rgb += - sampledColor.rgb * stepSize * emissionMultiply#{id} * opacityCoefficient#{id}; - - vec3 oneMinusFrontAlpha = vec3(1.f) - accumulatedAlpha; - accumulatedAlpha += oneMinusFrontAlpha * sampledColor.rgb * opacityCoefficient#{id}; + // Early ray termination on black parts of the data + vec3 normalizedPos = samplePos * 2.0 - 1.0; + if (normalizedPos.x * normalizedPos.x + normalizedPos.y * normalizedPos.y > 0.7) { + return; } - float stepSize#{id}(vec3 samplePos, vec3 dir) { - return maxStepSize#{id} * length(dir * 1.f / aspect#{id}); - } + vec4 sampledColor = texture(galaxyTexture#{id}, samplePos.xyz); + + // Source textures currently are square-rooted to avoid dithering in the shadows. + // So square them back + sampledColor = sampledColor*sampledColor; + + // Fudge for the dust "spreading" + sampledColor.a = clamp(sampledColor.a, 0.0, 1.0); + sampledColor.a = pow(sampledColor.a, 0.7); + + // Absorption probability + float scaledDensity = sampledColor.a * stepSize * absorptionMultiply#{id}; + vec3 alphaTint = vec3(0.3, 0.54, 0.85); + vec3 absorption = alphaTint * scaledDensity; + + // Extinction + vec3 extinction = exp(-absorption); + accumulatedColor.rgb *= extinction; + + // Emission + accumulatedColor.rgb += + sampledColor.rgb * stepSize * emissionMultiply#{id} * opacityCoefficient#{id}; + + vec3 oneMinusFrontAlpha = vec3(1.0) - accumulatedAlpha; + accumulatedAlpha += oneMinusFrontAlpha * sampledColor.rgb * opacityCoefficient#{id}; +} + +float stepSize#{id}(vec3 samplePos, vec3 dir) { + return maxStepSize#{id} * length(dir * 1.0 / aspect#{id}); +} diff --git a/modules/galaxy/shaders/points_fs.glsl b/modules/galaxy/shaders/points_fs.glsl index faa4974546..d3c2220566 100644 --- a/modules/galaxy/shaders/points_fs.glsl +++ b/modules/galaxy/shaders/points_fs.glsl @@ -33,20 +33,23 @@ in float vs_starBrightness; uniform float opacityCoefficient; Fragment getFragment() { - Fragment frag; + Fragment frag; - float multipliedOpacityCoefficient = opacityCoefficient*opacityCoefficient; - vec3 extinction = exp(vec3(0.6, 0.2, 0.3) - vs_color); + float multipliedOpacityCoefficient = opacityCoefficient * opacityCoefficient; + vec3 extinction = exp(vec3(0.6, 0.2, 0.3) - vs_color); - // We use the star brightness as the alpha value here to dim the stars as the camera - // moves further away. Otherwise they would occlude the main milkway image even though - // they themselves nolonger have any color contribution left - vec4 fullColor = vec4(vs_color*extinction*vs_starBrightness*multipliedOpacityCoefficient, vs_starBrightness); - frag.color = fullColor; + // We use the star brightness as the alpha value here to dim the stars as the camera + // moves further away. Otherwise they would occlude the main milkway image even though + // they themselves nolonger have any color contribution left + vec4 fullColor = vec4( + vs_color * extinction * vs_starBrightness * multipliedOpacityCoefficient, + vs_starBrightness + ); + frag.color = fullColor; - frag.depth = vs_screenSpaceDepth; - frag.gPosition = vs_position; - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + frag.depth = vs_screenSpaceDepth; + frag.gPosition = vs_position; + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - return frag; + return frag; } diff --git a/modules/galaxy/shaders/points_vs.glsl b/modules/galaxy/shaders/points_vs.glsl index 9b7612e4c5..ae1a199dc8 100644 --- a/modules/galaxy/shaders/points_vs.glsl +++ b/modules/galaxy/shaders/points_vs.glsl @@ -34,7 +34,7 @@ out vec3 vs_color; out float vs_screenSpaceDepth; out float vs_starBrightness; -uniform dmat4 cameraViewProjectionMatrix; +uniform dmat4 viewProjectionMatrix; uniform dmat4 modelMatrix; uniform dvec3 eyePosition; @@ -44,14 +44,14 @@ void main() { vs_position = vec4(in_position, 1.0); dvec4 dpos = dvec4(vs_position); - double distanceToStar = length((dpos.xyz - eyePosition)); - vs_starBrightness = clamp(float(8000*PARSEC/distanceToStar), 0.0, 1.0); + double distanceToStar = length(dpos.xyz - eyePosition); + vs_starBrightness = clamp(float(8000.0 * PARSEC / distanceToStar), 0.0, 1.0); dpos.xyz *= 8.0; dpos = modelMatrix * dpos; dpos /= PARSEC; - vec4 positionScreenSpace = z_normalization(vec4(cameraViewProjectionMatrix * dpos)); + vec4 positionScreenSpace = z_normalization(vec4(viewProjectionMatrix * dpos)); vs_color = in_color; vs_screenSpaceDepth = positionScreenSpace.w; gl_Position = positionScreenSpace; diff --git a/modules/galaxy/shaders/raycasterbounds_fs.glsl b/modules/galaxy/shaders/raycasterbounds_fs.glsl index 50013a0642..7cd49070e7 100644 --- a/modules/galaxy/shaders/raycasterbounds_fs.glsl +++ b/modules/galaxy/shaders/raycasterbounds_fs.glsl @@ -29,18 +29,10 @@ in vec3 modelPosition; in vec4 viewPosition; Fragment getFragment() { - Fragment frag; - //Early ray termination on black parts of the data - /*vec3 normalizedPos = (modelPosition*2.0)-1.0; - if (abs(modelPosition.x) > 0.9 || abs(modelPosition.y) > 0.9) { - frag.color = vec4(0.0, 0.0, 0.0, 1.0); - } - else {*/ - vec3 pos = modelPosition + 0.5; - //vec3 posClamp = clamp(pos, vec3(0.0), vec3(1.0)); - frag.color = vec4(pos, 1.0); - //} + Fragment frag; + vec3 pos = modelPosition + 0.5; + frag.color = vec4(pos, 1.0); - frag.depth = safeLength(viewPosition); - return frag; + frag.depth = safeLength(viewPosition); + return frag; } diff --git a/modules/galaxy/shaders/raycasterbounds_vs.glsl b/modules/galaxy/shaders/raycasterbounds_vs.glsl index acd3fb47b2..f5ecb07e09 100644 --- a/modules/galaxy/shaders/raycasterbounds_vs.glsl +++ b/modules/galaxy/shaders/raycasterbounds_vs.glsl @@ -32,12 +32,11 @@ out vec4 viewPosition; uniform mat4 projectionTransform; uniform mat4 modelViewTransform; - void main() { - modelPosition = vertPosition.xyz; - viewPosition = modelViewTransform*vertPosition; + modelPosition = vertPosition.xyz; + viewPosition = modelViewTransform*vertPosition; - // project the position to view space - gl_Position = projectionTransform * viewPosition; - gl_Position.z = 0.0; + // project the position to view space + gl_Position = projectionTransform * viewPosition; + gl_Position.z = 0.0; } diff --git a/modules/globebrowsing/CMakeLists.txt b/modules/globebrowsing/CMakeLists.txt index 4e2434894b..2b0496967b 100644 --- a/modules/globebrowsing/CMakeLists.txt +++ b/modules/globebrowsing/CMakeLists.txt @@ -94,7 +94,7 @@ source_group("Source Files" FILES ${SOURCE_FILES}) set(SHADER_FILES shaders/advanced_rings_vs.glsl shaders/advanced_rings_fs.glsl - shaders/blending.hglsl + shaders/blending.glsl shaders/globalrenderer_vs.glsl shaders/localrenderer_vs.glsl shaders/renderer_fs.glsl @@ -102,10 +102,10 @@ set(SHADER_FILES shaders/rings_fs.glsl shaders/rings_geom_vs.glsl shaders/rings_geom_fs.glsl - shaders/texturetilemapping.hglsl - shaders/tile.hglsl - shaders/tileheight.hglsl - shaders/tilevertexskirt.hglsl + shaders/texturetilemapping.glsl + shaders/tile.glsl + shaders/tileheight.glsl + shaders/tilevertexskirt.glsl ) source_group("Shader Files" FILES ${SHADER_FILES}) diff --git a/modules/globebrowsing/shaders/advanced_rings_fs.glsl b/modules/globebrowsing/shaders/advanced_rings_fs.glsl index e6ddd8bd7b..1406127d30 100644 --- a/modules/globebrowsing/shaders/advanced_rings_fs.glsl +++ b/modules/globebrowsing/shaders/advanced_rings_fs.glsl @@ -45,99 +45,88 @@ uniform float colorFilterValue; uniform vec3 sunPosition; uniform vec3 sunPositionObj; uniform vec3 camPositionObj; -uniform float _nightFactor; +uniform float nightFactor; uniform float zFightingPercentage; -// temp -in vec4 fragPosInLightSpace; - - Fragment getFragment() { - // Moving the origin to the center - vec2 st = (vs_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vec2 st = (vs_st - vec2(0.5)) * 2.0; - // The length of the texture coordinates vector is our distance from the center - float radius = length(st); + // The length of the texture coordinates vector is our distance from the center + float radius = length(st); - // We only want to consider ring-like objects so we need to discard everything else - if (radius > 1.0) { - discard; - } + // We only want to consider ring-like objects so we need to discard everything else + if (radius > 1.0) { + discard; + } - // Remapping the texture coordinates - // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] - // textureOffset.x -> 0 - // textureOffset.y -> 1 - float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); - if (texCoord < 0.f || texCoord > 1.f) { - discard; - } + // Remapping the texture coordinates + // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] + // textureOffset.x -> 0 + // textureOffset.y -> 1 + float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); + if (texCoord < 0.0 || texCoord > 1.0) { + discard; + } - vec4 colorBckwrd = texture(ringTextureBckwrd, texCoord); - vec4 colorFwrd = texture(ringTextureFwrd, texCoord); - vec4 colorMult = texture(ringTextureColor, texCoord); - vec4 transparency = texture(ringTextureTransparency, texCoord); + vec4 colorBckwrd = texture(ringTextureBckwrd, texCoord); + vec4 colorFwrd = texture(ringTextureFwrd, texCoord); + vec4 colorMult = texture(ringTextureColor, texCoord); + vec4 transparency = texture(ringTextureTransparency, texCoord); - float lerpFactor = dot(camPositionObj, sunPositionObj); + float lerpFactor = dot(camPositionObj, sunPositionObj); - // Jon Colors: - //vec4 diffuse = mix(colorFwrd * vec4(1, 0.88, 0.82, 1.0), colorBckwrd * vec4(1, 0.88, 0.82, 1.0), lerpFactor); - vec4 diffuse = mix(colorFwrd * colorMult, colorBckwrd * colorMult, lerpFactor); - diffuse.a = colorFilterValue * transparency.a; - float colorValue = length(diffuse.rgb) / 0.57735026919; - if (colorValue < 0.1) { - discard; - } + // Jon Colors: + //vec4 diffuse = mix(colorFwrd * vec4(1, 0.88, 0.82, 1.0), colorBckwrd * vec4(1, 0.88, 0.82, 1.0), lerpFactor); + vec4 diffuse = mix(colorFwrd * colorMult, colorBckwrd * colorMult, lerpFactor); + diffuse.a = colorFilterValue * transparency.a; + float colorValue = length(diffuse.rgb) / 0.57735026919; + if (colorValue < 0.1) { + discard; + } - // shadow == 1.0 means it is not in shadow - float shadow = 1.0; - if (shadowCoords.z >= 0) { - vec4 normalizedShadowCoords = shadowCoords; - normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); - normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; - normalizedShadowCoords.w = 1.0; - - float sum = 0; - #for i in 0..#{nShadowSamples} - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); - #endfor - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); - shadow = clamp(sum / (8.0 * NSSamples + 1.f), 0.35, 1.0); - } + // shadow == 1.0 means it is not in shadow + float shadow = 1.0; + if (shadowCoords.z >= 0) { + vec4 normalizedShadowCoords = shadowCoords; + normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); + normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; + normalizedShadowCoords.w = 1.0; + + float sum = 0; + #for i in 0..#{nShadowSamples} + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); + #endfor + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); + shadow = clamp(sum / (8.0 * NSSamples + 1.f), 0.35, 1.0); + } - // The normal for the one plane depends on whether we are dealing - // with a front facing or back facing fragment - vec3 normal; - // The plane is oriented on the xz plane - // WARNING: This might not be the case for Uranus - if (gl_FrontFacing) { - normal = vec3(-1.0, 0.0, 0.0); - } - else { - normal = vec3(1.0, 0.0, 0.0); - } + // The normal for the one plane depends on whether we are dealing + // with a front facing or back facing fragment + // The plane is oriented on the xz plane + // WARNING: This might not be the case for Uranus + vec3 normal = gl_FrontFacing ? vec3(-1.0, 0.0, 0.0) : vec3(1.0, 0.0, 0.0); - // Reduce the color of the fragment by the user factor - // if we are facing away from the Sun - if (dot(sunPosition, normal) < 0) { - diffuse.xyz = vec3(1.0, 0.97075, 0.952) * - texture(ringTextureUnlit, texCoord).xyz * - _nightFactor; - } + // Reduce the color of the fragment by the user factor + // if we are facing away from the Sun + if (dot(sunPosition, normal) < 0.0) { + diffuse.xyz = + vec3(1.0, 0.97075, 0.952) * texture(ringTextureUnlit, texCoord).xyz * nightFactor; + } - Fragment frag; + Fragment frag; - frag.color = diffuse * shadow; - frag.depth = vs_screenSpaceDepth; - frag.gPosition = vec4(1e30, 1e30, 1e30, 1.0); - frag.gNormal = vec4(normal, 1.0); + frag.color = diffuse * shadow; + frag.depth = vs_screenSpaceDepth; + frag.gPosition = vec4(1e30, 1e30, 1e30, 1.0); + frag.gNormal = vec4(normal, 1.0); - return frag; + return frag; } diff --git a/modules/globebrowsing/shaders/advanced_rings_vs.glsl b/modules/globebrowsing/shaders/advanced_rings_vs.glsl index 8b43a60571..5d58c668c9 100644 --- a/modules/globebrowsing/shaders/advanced_rings_vs.glsl +++ b/modules/globebrowsing/shaders/advanced_rings_vs.glsl @@ -31,7 +31,6 @@ layout(location = 1) in vec2 in_st; out vec2 vs_st; out float vs_screenSpaceDepth; -out vec4 vs_positionViewSpace; out vec4 shadowCoords; uniform dmat4 modelViewProjectionMatrix; @@ -42,12 +41,12 @@ uniform dmat4 modelViewProjectionMatrix; uniform dmat4 shadowMatrix; void main() { - vs_st = in_st; + vs_st = in_st; - dvec4 positionClipSpace = modelViewProjectionMatrix * dvec4(in_position, 0.0, 1.0); - vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); - - shadowCoords = vec4(shadowMatrix * dvec4(in_position, 0.0, 1.0)); - vs_screenSpaceDepth = positionClipSpaceZNorm.w; - gl_Position = positionClipSpaceZNorm; + dvec4 positionClipSpace = modelViewProjectionMatrix * dvec4(in_position, 0.0, 1.0); + vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); + + shadowCoords = vec4(shadowMatrix * dvec4(in_position, 0.0, 1.0)); + vs_screenSpaceDepth = positionClipSpaceZNorm.w; + gl_Position = positionClipSpaceZNorm; } diff --git a/modules/globebrowsing/shaders/blending.hglsl b/modules/globebrowsing/shaders/blending.glsl similarity index 56% rename from modules/globebrowsing/shaders/blending.hglsl rename to modules/globebrowsing/shaders/blending.glsl index aff6b667d9..2456503c7a 100644 --- a/modules/globebrowsing/shaders/blending.hglsl +++ b/modules/globebrowsing/shaders/blending.glsl @@ -26,92 +26,91 @@ #define BLENDING_HGLSL vec4 blendNormal(vec4 oldColor, vec4 newColor) { - vec4 toReturn; - toReturn.a = mix(oldColor.a, 1.0, newColor.a); - toReturn.rgb = - (newColor.rgb * newColor.a + oldColor.rgb * oldColor.a * (1 - newColor.a)) / - toReturn.a; - return toReturn; + vec4 toReturn; + toReturn.a = mix(oldColor.a, 1.0, newColor.a); + toReturn.rgb = + (newColor.rgb * newColor.a + oldColor.rgb * oldColor.a * (1 - newColor.a)) / toReturn.a; + return toReturn; } vec4 blendMultiply(vec4 oldColor, vec4 newColor) { - return oldColor * newColor; + return oldColor * newColor; } vec4 blendAdd(vec4 oldColor, vec4 newColor) { - return oldColor + newColor; + return oldColor + newColor; } vec4 blendSubtract(vec4 oldColor, vec4 newColor) { - return oldColor - newColor; + return oldColor - newColor; } vec3 hsl2rgb(in vec3 c) { - vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0); + vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0); - return c.z + c.y * (rgb - 0.5) * (1.0 - abs(2.0 * c.z - 1.0)); + return c.z + c.y * (rgb - 0.5) * (1.0 - abs(2.0 * c.z - 1.0)); } vec3 HueShift(in vec3 color, in float shift) { - vec3 P = vec3(0.55735) * dot(vec3(0.55735), color); - vec3 U = color - P; - vec3 V = cross(vec3(0.55735), U); - vec3 c = U * cos(shift*6.2832) + V * sin(shift*6.2832) + P; - return c; + vec3 P = vec3(0.55735) * dot(vec3(0.55735), color); + vec3 U = color - P; + vec3 V = cross(vec3(0.55735), U); + vec3 c = U * cos(shift*6.2832) + V * sin(shift*6.2832) + P; + return c; } vec3 rgb2hsl(in vec3 c) { - float r = c.r; - float g = c.g; - float b = c.b; - float cMin = min(r, min(g, b)); - float cMax = max(r, max(g, b)); + float r = c.r; + float g = c.g; + float b = c.b; + float cMin = min(r, min(g, b)); + float cMax = max(r, max(g, b)); - if (cMax > cMin) { - float l = (cMax + cMin) / 2.0; + if (cMax > cMin) { + float l = (cMax + cMin) / 2.0; - float cDelta = cMax - cMin; + float cDelta = cMax - cMin; - //s = l < .05 ? cDelta / ( cMax + cMin ) : cDelta / ( 2.0 - ( cMax + cMin ) ); Original - float s = (l < 0.0) ? cDelta / (cMax + cMin) : cDelta / (2.0 - (cMax + cMin)); + //s = l < .05 ? cDelta / ( cMax + cMin ) : cDelta / ( 2.0 - ( cMax + cMin ) ); Original + float s = (l < 0.0) ? cDelta / (cMax + cMin) : cDelta / (2.0 - (cMax + cMin)); - float h = 0.0; - if (r == cMax) { - h = (g - b) / cDelta; - } - else if (g == cMax) { - h = 2.0 + (b - r) / cDelta; - } - else { - h = 4.0 + (r - g) / cDelta; - } - - if (h < 0.0) { - h += 6.0; - } - h = h / 6.0; - - return vec3(h, s, l); + float h = 0.0; + if (r == cMax) { + h = (g - b) / cDelta; + } + else if (g == cMax) { + h = 2.0 + (b - r) / cDelta; } else { - return vec3(0.0); + h = 4.0 + (r - g) / cDelta; } + + if (h < 0.0) { + h += 6.0; + } + h = h / 6.0; + + return vec3(h, s, l); + } + else { + return vec3(0.0); + } } vec3 rgb2hsv(vec3 c) { - vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = (c.g < c.b) ? vec4(c.bg, K.wz) : vec4(c.gb, K.xy); - vec4 q = (c.r < p.x) ? vec4(p.xyw, c.r) : vec4(c.r, p.yzx); + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = (c.g < c.b) ? vec4(c.bg, K.wz) : vec4(c.gb, K.xy); + vec4 q = (c.r < p.x) ? vec4(p.xyw, c.r) : vec4(c.r, p.yzx); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); } vec3 hsv2rgb(vec3 c) { - vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); - return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); } -#endif +#endif // BLENDING_HGLSL diff --git a/modules/globebrowsing/shaders/globalrenderer_vs.glsl b/modules/globebrowsing/shaders/globalrenderer_vs.glsl index 7f1755f19d..3d59c08d04 100644 --- a/modules/globebrowsing/shaders/globalrenderer_vs.glsl +++ b/modules/globebrowsing/shaders/globalrenderer_vs.glsl @@ -25,10 +25,10 @@ #version __CONTEXT__ #include "PowerScaling/powerScaling_vs.hglsl" -#include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/tilevertexskirt.hglsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tile.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tilevertexskirt.glsl> layout(location = 1) in vec2 in_uv; @@ -39,22 +39,22 @@ out vec3 levelWeights; out vec3 positionCameraSpace; #if USE_ACCURATE_NORMALS - out vec3 ellipsoidTangentThetaCameraSpace; - out vec3 ellipsoidTangentPhiCameraSpace; + out vec3 ellipsoidTangentThetaCameraSpace; + out vec3 ellipsoidTangentPhiCameraSpace; #endif // USE_ACCURATE_NORMALS #if USE_ECLIPSE_SHADOWS - out vec3 positionWorldSpace; - uniform dmat4 modelTransform; -#endif + out vec3 positionWorldSpace; + uniform dmat4 modelTransform; +#endif // USE_ECLIPSE_SHADOWS #if SHADOW_MAPPING_ENABLED - // ShadowMatrix is the matrix defined by: - // textureCoordsMatrix * projectionMatrix * combinedViewMatrix * modelMatrix - // where textureCoordsMatrix is just a scale and bias computation: [-1,1] to [0,1] - uniform dmat4 shadowMatrix; - out vec4 shadowCoords; -#endif + // ShadowMatrix is the matrix defined by: + // textureCoordsMatrix * projectionMatrix * combinedViewMatrix * modelMatrix + // where textureCoordsMatrix is just a scale and bias computation: [-1,1] to [0,1] + uniform dmat4 shadowMatrix; + out vec4 shadowCoords; +#endif // SHADOW_MAPPING_ENABLED uniform mat4 modelViewProjectionTransform; uniform mat4 modelViewTransform; @@ -68,78 +68,77 @@ uniform float chunkMinHeight; uniform float distanceScaleFactor; uniform int chunkLevel; - struct PositionNormalPair { - vec3 position; - vec3 normal; + vec3 position; + vec3 normal; }; PositionNormalPair globalInterpolation(vec2 uv) { - vec2 lonlat = lonLatScalingFactor * uv + minLatLon; + vec2 lonlat = lonLatScalingFactor * uv + minLatLon; - // geodetic surface normal - float cosLat = cos(lonlat.y); - vec3 normal = vec3(cosLat * cos(lonlat.x), cosLat * sin(lonlat.x), sin(lonlat.y)); - vec3 k = radiiSquared * normal; - float gamma = sqrt(dot(k, normal)); + // geodetic surface normal + float cosLat = cos(lonlat.y); + vec3 normal = vec3(cosLat * cos(lonlat.x), cosLat * sin(lonlat.x), sin(lonlat.y)); + vec3 k = radiiSquared * normal; + float gamma = sqrt(dot(k, normal)); - PositionNormalPair result; - result.position = k / gamma; - result.normal = normal; - return result; + PositionNormalPair result; + result.position = k / gamma; + result.normal = normal; + return result; } vec3 getLevelWeights(float distToVertexOnEllipsoid) { - float projectedScaleFactor = distanceScaleFactor / distToVertexOnEllipsoid; - float desiredLevel = log2(projectedScaleFactor); - float levelInterp = chunkLevel - desiredLevel; + float projectedScaleFactor = distanceScaleFactor / distToVertexOnEllipsoid; + float desiredLevel = log2(projectedScaleFactor); + float levelInterp = chunkLevel - desiredLevel; - return vec3( - clamp(1.0 - levelInterp, 0.0, 1.0), - clamp(levelInterp, 0.0, 1.0) - clamp(levelInterp - 1.0, 0.0, 1.0), - clamp(levelInterp - 1.0, 0.0, 1.0) - ); + return vec3( + clamp(1.0 - levelInterp, 0.0, 1.0), + clamp(levelInterp, 0.0, 1.0) - clamp(levelInterp - 1.0, 0.0, 1.0), + clamp(levelInterp - 1.0, 0.0, 1.0) + ); } void main() { - PositionNormalPair pair = globalInterpolation(in_uv); - float distToVertexOnEllipsoid = length((pair.normal * chunkMinHeight + pair.position) - cameraPosition); + PositionNormalPair pair = globalInterpolation(in_uv); + float distToVertexOnEllipsoid = length((pair.normal * chunkMinHeight + pair.position) - cameraPosition); - // use level weight for height sampling, and output to fragment shader - levelWeights = getLevelWeights(distToVertexOnEllipsoid); + // use level weight for height sampling, and output to fragment shader + levelWeights = getLevelWeights(distToVertexOnEllipsoid); - // Get the height value and apply skirts - float height = getTileHeight(in_uv, levelWeights) - getTileVertexSkirtLength(); + // Get the height value and apply skirts + float height = getTileHeight(in_uv, levelWeights) - getTileVertexSkirtLength(); #if USE_ACCURATE_NORMALS - // Calculate tangents - // tileDelta is a step length (epsilon). Should be small enough for accuracy but not - // Too small for precision. 1 / 512 is good. - const float tileDelta = 1.0 / 512.0; - PositionNormalPair pair10 = globalInterpolation(vec2(1.0, 0.0) * tileDelta + in_uv); - PositionNormalPair pair01 = globalInterpolation(vec2(0.0, 1.0) * tileDelta + in_uv); - vec3 ellipsoidTangentTheta = normalize(pair10.position - pair.position); - vec3 ellipsoidTangentPhi = normalize(pair01.position - pair.position); - ellipsoidTangentThetaCameraSpace = mat3(modelViewTransform) * ellipsoidTangentTheta; - ellipsoidTangentPhiCameraSpace = mat3(modelViewTransform) * ellipsoidTangentPhi; + // Calculate tangents + // tileDelta is a step length (epsilon). Should be small enough for accuracy but not + // Too small for precision. 1 / 512 is good. + const float tileDelta = 1.0 / 512.0; + PositionNormalPair pair10 = globalInterpolation(vec2(1.0, 0.0) * tileDelta + in_uv); + PositionNormalPair pair01 = globalInterpolation(vec2(0.0, 1.0) * tileDelta + in_uv); + vec3 ellipsoidTangentTheta = normalize(pair10.position - pair.position); + vec3 ellipsoidTangentPhi = normalize(pair01.position - pair.position); + ellipsoidTangentThetaCameraSpace = mat3(modelViewTransform) * ellipsoidTangentTheta; + ellipsoidTangentPhiCameraSpace = mat3(modelViewTransform) * ellipsoidTangentPhi; #endif // USE_ACCURATE_NORMALS - // Add the height in the direction of the normal - pair.position = pair.normal * height + pair.position; - vec4 positionClippingSpace = modelViewProjectionTransform * vec4(pair.position, 1.0); + // Add the height in the direction of the normal + pair.position = pair.normal * height + pair.position; + vec4 positionClippingSpace = modelViewProjectionTransform * vec4(pair.position, 1.0); - // Write output - fs_uv = in_uv; - fs_position = z_normalization(positionClippingSpace); - gl_Position = fs_position; - ellipsoidNormalCameraSpace = mat3(modelViewTransform) * pair.normal; - positionCameraSpace = vec3(modelViewTransform * vec4(pair.position, 1.0)); + // Write output + fs_uv = in_uv; + fs_position = z_normalization(positionClippingSpace); + gl_Position = fs_position; + ellipsoidNormalCameraSpace = mat3(modelViewTransform) * pair.normal; + positionCameraSpace = vec3(modelViewTransform * vec4(pair.position, 1.0)); #if USE_ECLIPSE_SHADOWS - positionWorldSpace = vec3(modelTransform * dvec4(pair.position, 1.0)); -#endif + positionWorldSpace = vec3(modelTransform * dvec4(pair.position, 1.0)); +#endif // USE_ECLIPSE_SHADOWS #if SHADOW_MAPPING_ENABLED - shadowCoords = vec4(shadowMatrix * dvec4(pair.position, 1.0)); -#endif + shadowCoords = vec4(shadowMatrix * dvec4(pair.position, 1.0)); +#endif // SHADOW_MAPPING_ENABLED } diff --git a/modules/globebrowsing/shaders/localrenderer_vs.glsl b/modules/globebrowsing/shaders/localrenderer_vs.glsl index 5c1439139d..642a2a2ae4 100644 --- a/modules/globebrowsing/shaders/localrenderer_vs.glsl +++ b/modules/globebrowsing/shaders/localrenderer_vs.glsl @@ -25,10 +25,10 @@ #version __CONTEXT__ #include "PowerScaling/powerScaling_vs.hglsl" -#include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/tilevertexskirt.hglsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tile.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tilevertexskirt.glsl> layout(location = 1) in vec2 in_uv; @@ -39,22 +39,22 @@ out vec3 levelWeights; out vec3 positionCameraSpace; #if USE_ACCURATE_NORMALS - out vec3 ellipsoidTangentThetaCameraSpace; - out vec3 ellipsoidTangentPhiCameraSpace; + out vec3 ellipsoidTangentThetaCameraSpace; + out vec3 ellipsoidTangentPhiCameraSpace; #endif // USE_ACCURATE_NORMALS #if USE_ECLIPSE_SHADOWS out vec3 positionWorldSpace; uniform dmat4 inverseViewTransform; -#endif +#endif // USE_ECLIPSE_SHADOWS #if SHADOW_MAPPING_ENABLED - // ShadowMatrix is the matrix defined by: - // textureCoordsMatrix * projectionMatrix * combinedViewMatrix * modelMatrix - // where textureCoordsMatrix is just a scale and bias computation: [-1,1] to [0,1] - uniform dmat4 shadowMatrix; - out vec4 shadowCoords; -#endif + // ShadowMatrix is the matrix defined by: + // textureCoordsMatrix * projectionMatrix * combinedViewMatrix * modelMatrix + // where textureCoordsMatrix is just a scale and bias computation: [-1,1] to [0,1] + uniform dmat4 shadowMatrix; + out vec4 shadowCoords; +#endif // SHADOW_MAPPING_ENABLED uniform mat4 projectionTransform; // Input points in camera space @@ -69,60 +69,60 @@ uniform float distanceScaleFactor; uniform int chunkLevel; vec3 bilinearInterpolation(vec2 uv) { - vec3 p0 = mix(p00, p10, uv.x); - vec3 p1 = mix(p01, p11, uv.x); - return mix(p0, p1, uv.y); + vec3 p0 = mix(p00, p10, uv.x); + vec3 p1 = mix(p01, p11, uv.x); + return mix(p0, p1, uv.y); } vec3 getLevelWeights(float distToVertexOnEllipsoid) { - float projectedScaleFactor = distanceScaleFactor / distToVertexOnEllipsoid; - float desiredLevel = log2(projectedScaleFactor); - float levelInterp = chunkLevel - desiredLevel; + float projectedScaleFactor = distanceScaleFactor / distToVertexOnEllipsoid; + float desiredLevel = log2(projectedScaleFactor); + float levelInterp = chunkLevel - desiredLevel; - return vec3( - clamp(1.0 - levelInterp, 0.0, 1.0), - clamp(levelInterp, 0.0, 1.0) - clamp(levelInterp - 1.0, 0.0, 1.0), - clamp(levelInterp - 1.0, 0.0, 1.0) - ); + return vec3( + clamp(1.0 - levelInterp, 0.0, 1.0), + clamp(levelInterp, 0.0, 1.0) - clamp(levelInterp - 1.0, 0.0, 1.0), + clamp(levelInterp - 1.0, 0.0, 1.0) + ); } void main() { - // Position in cameraspace - vec3 p = bilinearInterpolation(in_uv); - - // Calculate desired level based on distance to the vertex on the ellipsoid - // Before any heightmapping is done - float distToVertexOnEllipsoid = length(p + patchNormalCameraSpace * chunkMinHeight); + // Position in cameraspace + vec3 p = bilinearInterpolation(in_uv); + + // Calculate desired level based on distance to the vertex on the ellipsoid + // Before any heightmapping is done + float distToVertexOnEllipsoid = length(p + patchNormalCameraSpace * chunkMinHeight); - // use level weight for height sampling, and output to fragment shader - levelWeights = getLevelWeights(distToVertexOnEllipsoid); + // use level weight for height sampling, and output to fragment shader + levelWeights = getLevelWeights(distToVertexOnEllipsoid); - // Get the height value and apply skirts - float height = getTileHeightScaled(in_uv, levelWeights) - getTileVertexSkirtLength(); - - // Translate the point along normal - p += patchNormalCameraSpace * height; + // Get the height value and apply skirts + float height = getTileHeightScaled(in_uv, levelWeights) - getTileVertexSkirtLength(); + + // Translate the point along normal + p += patchNormalCameraSpace * height; - vec4 positionClippingSpace = projectionTransform * vec4(p, 1); + vec4 positionClippingSpace = projectionTransform * vec4(p, 1); #if USE_ACCURATE_NORMALS - // Calculate tangents - ellipsoidTangentThetaCameraSpace = normalize(p10 - p00); - ellipsoidTangentPhiCameraSpace = normalize(p01 - p00); + // Calculate tangents + ellipsoidTangentThetaCameraSpace = normalize(p10 - p00); + ellipsoidTangentPhiCameraSpace = normalize(p01 - p00); #endif // USE_ACCURATE_NORMALS - // Write output - fs_uv = in_uv; - fs_position = z_normalization(positionClippingSpace); - gl_Position = fs_position; - ellipsoidNormalCameraSpace = patchNormalCameraSpace; - positionCameraSpace = p; + // Write output + fs_uv = in_uv; + fs_position = z_normalization(positionClippingSpace); + gl_Position = fs_position; + ellipsoidNormalCameraSpace = patchNormalCameraSpace; + positionCameraSpace = p; #if USE_ECLIPSE_SHADOWS - positionWorldSpace = vec3(inverseViewTransform * dvec4(p, 1.0)); -#endif + positionWorldSpace = vec3(inverseViewTransform * dvec4(p, 1.0)); +#endif // USE_ECLIPSE_SHADOWS #if SHADOW_MAPPING_ENABLED - shadowCoords = vec4(shadowMatrix * dvec4(p, 1.0)); -#endif + shadowCoords = vec4(shadowMatrix * dvec4(p, 1.0)); +#endif // SHADOW_MAPPING_ENABLED } diff --git a/modules/globebrowsing/shaders/renderer_fs.glsl b/modules/globebrowsing/shaders/renderer_fs.glsl index 07ba765e6c..c02fe78d19 100644 --- a/modules/globebrowsing/shaders/renderer_fs.glsl +++ b/modules/globebrowsing/shaders/renderer_fs.glsl @@ -24,9 +24,9 @@ #include "fragment.glsl" -#include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.hglsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tile.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/texturetilemapping.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tileheight.glsl> #include "PowerScaling/powerScaling_fs.hglsl" // Below are all the tiles that are used for contributing the actual fragment color @@ -49,15 +49,13 @@ uniform Layer WaterMasks[NUMLAYERS_WATERMASK]; #if SHOW_HEIGHT_RESOLUTION uniform vec2 vertexResolution; -#endif +#endif // SHOW_HEIGHT_RESOLUTION -//#if USE_NIGHTTEXTURE || USE_WATERMASK || PERFORM_SHADING uniform vec3 lightDirectionCameraSpace; -//#endif #if PERFORM_SHADING uniform float orenNayarRoughness; -#endif +#endif // PERFORM_SHADING #if SHADOW_MAPPING_ENABLED @@ -67,23 +65,22 @@ uniform float orenNayarRoughness; in vec4 shadowCoords; uniform sampler2DShadow shadowMapTexture; uniform float zFightingPercentage; -#endif +#endif // SHADOW_MAPPING_ENABLED #if USE_ECLIPSE_SHADOWS - #define NSEclipseShadowsMinusOne #{nEclipseShadows} #define NSEclipseShadows (NSEclipseShadowsMinusOne + 1) /******************************************************************************* - ***** ALL CALCULATIONS FOR ECLIPSE ARE IN METERS AND IN WORLD SPACE SYSTEM **** - *******************************************************************************/ + ***** ALL CALCULATIONS FOR ECLIPSE ARE IN METERS AND IN WORLD SPACE SYSTEM **** + *******************************************************************************/ struct ShadowRenderingStruct { - double xu, xp; - double rs, rc; - dvec3 sourceCasterVec; - dvec3 casterPositionVec; - bool isShadowing; + double xu, xp; + double rs, rc; + dvec3 sourceCasterVec; + dvec3 casterPositionVec; + bool isShadowing; }; // Eclipse shadow data @@ -96,48 +93,46 @@ uniform bool hardShadows; vec4 calcShadow(const ShadowRenderingStruct shadowInfoArray[NSEclipseShadows], const dvec3 position, const bool ground) { - #for i in 0..#{nEclipseShadows} - if (shadowInfoArray[#{i}].isShadowing) { - dvec3 pc = shadowInfoArray[#{i}].casterPositionVec - position; - dvec3 sc_norm = shadowInfoArray[#{i}].sourceCasterVec; - dvec3 pc_proj = dot(pc, sc_norm) * sc_norm; - dvec3 d = pc - pc_proj; + #for i in 0..#{nEclipseShadows} + if (shadowInfoArray[#{i}].isShadowing) { + dvec3 pc = shadowInfoArray[#{i}].casterPositionVec - position; + dvec3 sc_norm = shadowInfoArray[#{i}].sourceCasterVec; + dvec3 pc_proj = dot(pc, sc_norm) * sc_norm; + dvec3 d = pc - pc_proj; + float length_d = float(length(d)); + double length_pc_proj = length(pc_proj); - float length_d = float(length(d)); - double length_pc_proj = length(pc_proj); + float r_p_pi = float(shadowInfoArray[#{i}].rc * (length_pc_proj + shadowInfoArray[#{i}].xp) / shadowInfoArray[#{i}].xp); + float r_u_pi = float(shadowInfoArray[#{i}].rc * (shadowInfoArray[#{i}].xu - length_pc_proj) / shadowInfoArray[#{i}].xu); - float r_p_pi = float(shadowInfoArray[#{i}].rc * (length_pc_proj + shadowInfoArray[#{i}].xp) / shadowInfoArray[#{i}].xp); - float r_u_pi = float(shadowInfoArray[#{i}].rc * (shadowInfoArray[#{i}].xu - length_pc_proj) / shadowInfoArray[#{i}].xu); - - if (length_d < r_u_pi) { // umbra - if (ground) { - #if USE_ECLIPSE_HARD_SHADOWS - return vec4(0.2, 0.2, 0.2, 1.0); - #else - // butterworthFunc - return vec4(vec3(sqrt(r_u_pi / (r_u_pi + pow(length_d, 2.0)))), 1.0); - #endif - } - else { - #if USE_ECLIPSE_HARD_SHADOWS - return vec4(0.5, 0.5, 0.5, 1.0); - #else - return vec4(vec3(length_d / r_p_pi), 1.0); - #endif - } - } - else if (length_d < r_p_pi) {// penumbra - #if USE_ECLIPSE_HARD_SHADOWS - return vec4(0.5, 0.5, 0.5, 1.0); - #else - return vec4(vec3(length_d / r_p_pi), 1.0); - #endif - } + if (length_d < r_u_pi) { // umbra + if (ground) { +#if USE_ECLIPSE_HARD_SHADOWS + return vec4(0.2, 0.2, 0.2, 1.0); +#else + // butterworthFunc + return vec4(vec3(sqrt(r_u_pi / (r_u_pi + pow(length_d, 2.0)))), 1.0); +#endif } - - #endfor - return vec4(1.0); + else { +#if USE_ECLIPSE_HARD_SHADOWS + return vec4(0.5, 0.5, 0.5, 1.0); +#else + return vec4(vec3(length_d / r_p_pi), 1.0); +#endif + } + } + else if (length_d < r_p_pi) {// penumbra +#if USE_ECLIPSE_HARD_SHADOWS + return vec4(0.5, 0.5, 0.5, 1.0); +#else + return vec4(vec3(length_d / r_p_pi), 1.0); +#endif + } + } + #endfor + return vec4(1.0); } #endif @@ -148,8 +143,8 @@ in vec3 levelWeights; in vec3 positionCameraSpace; #if USE_ACCURATE_NORMALS - in vec3 ellipsoidTangentThetaCameraSpace; - in vec3 ellipsoidTangentPhiCameraSpace; + in vec3 ellipsoidTangentThetaCameraSpace; + in vec3 ellipsoidTangentPhiCameraSpace; #endif // USE_ACCURATE_NORMALS #if USE_ECLIPSE_SHADOWS @@ -158,146 +153,142 @@ in vec3 positionWorldSpace; uniform float opacity; - Fragment getFragment() { - Fragment frag; - frag.color = vec4(0.3, 0.3, 0.3, 1.0); + Fragment frag; + frag.color = vec4(0.3, 0.3, 0.3, 1.0); - vec3 normal = normalize(ellipsoidNormalCameraSpace); + vec3 normal = normalize(ellipsoidNormalCameraSpace); #if USE_ACCURATE_NORMALS - normal = getTileNormal( - fs_uv, - levelWeights, - normalize(ellipsoidNormalCameraSpace), - normalize(ellipsoidTangentThetaCameraSpace), - normalize(ellipsoidTangentPhiCameraSpace) - ); + normal = getTileNormal( + fs_uv, + levelWeights, + normalize(ellipsoidNormalCameraSpace), + normalize(ellipsoidTangentThetaCameraSpace), + normalize(ellipsoidTangentPhiCameraSpace) + ); #endif /// USE_ACCURATE_NORMALS #if USE_COLORTEXTURE - frag.color = calculateColor(frag.color, fs_uv, levelWeights, ColorLayers); + frag.color = calculateColor(frag.color, fs_uv, levelWeights, ColorLayers); #endif // USE_COLORTEXTURE #if USE_WATERMASK - float waterReflectance = 0.0; - frag.color = calculateWater( - frag.color, - fs_uv, - levelWeights, - WaterMasks, - normal, - lightDirectionCameraSpace, // Should already be normalized - positionCameraSpace, - waterReflectance - ); - + float waterReflectance = 0.0; + frag.color = calculateWater( + frag.color, + fs_uv, + levelWeights, + WaterMasks, + normal, + lightDirectionCameraSpace, // Should already be normalized + positionCameraSpace, + waterReflectance + ); #endif // USE_WATERMASK #if USE_NIGHTTEXTURE - frag.color = calculateNight( - frag.color, - fs_uv, - levelWeights, - NightLayers, - normalize(ellipsoidNormalCameraSpace), - lightDirectionCameraSpace // Should already be normalized - ); - + frag.color = calculateNight( + frag.color, + fs_uv, + levelWeights, + NightLayers, + normalize(ellipsoidNormalCameraSpace), + lightDirectionCameraSpace // Should already be normalized + ); #endif // USE_NIGHTTEXTURE #if PERFORM_SHADING - frag.color = calculateShadedColor( - frag.color, - normal, - lightDirectionCameraSpace, - normalize(positionCameraSpace), - orenNayarRoughness - ); + frag.color = calculateShadedColor( + frag.color, + normal, + lightDirectionCameraSpace, + normalize(positionCameraSpace), + orenNayarRoughness + ); #endif // PERFORM_SHADING #if USE_ECLIPSE_SHADOWS - frag.color *= calcShadow(shadowDataArray, dvec3(positionWorldSpace), true); -#endif + frag.color *= calcShadow(shadowDataArray, dvec3(positionWorldSpace), true); +#endif // USE_ECLIPSE_SHADOWS #if USE_OVERLAY - frag.color = calculateOverlay(frag.color, fs_uv, levelWeights, Overlays); + frag.color = calculateOverlay(frag.color, fs_uv, levelWeights, Overlays); #endif // USE_OVERLAY #if SHOW_HEIGHT_INTENSITIES - frag.color.rgb *= vec3(0.1); + frag.color.rgb *= vec3(0.1); - float untransformedHeight = getUntransformedTileVertexHeight(fs_uv, levelWeights); - float contourLine = fract(10.0 * untransformedHeight) > 0.98 ? 1.0 : 0.0; - frag.color.r += untransformedHeight; - frag.color.b = contourLine; -#endif + float untransformedHeight = getUntransformedTileVertexHeight(fs_uv, levelWeights); + float contourLine = fract(10.0 * untransformedHeight) > 0.98 ? 1.0 : 0.0; + frag.color.r += untransformedHeight; + frag.color.b = contourLine; +#endif // SHOW_HEIGHT_INTENSITIES #if SHOW_HEIGHT_RESOLUTION - frag.color += 0.0001 * calculateDebugColor(fs_uv, fs_position, vertexResolution); - #if USE_HEIGHTMAP - frag.color.r = min(frag.color.r, 0.8); - frag.color.r += tileResolution(fs_uv, HeightLayers[0].pile.chunkTile0) > 0.9 ? 1 : 0; - #endif -#endif + frag.color += 0.0001 * calculateDebugColor(fs_uv, fs_position, vertexResolution); + #if USE_HEIGHTMAP + frag.color.r = min(frag.color.r, 0.8); + frag.color.r += tileResolution(fs_uv, HeightLayers[0].pile.chunkTile0) > 0.9 ? 1 : 0; + #endif // USE_HEIGHTMAP +#endif // SHOW_HEIGHT_RESOLUTION - // Other data + // Other data #if USE_WATERMASK - // Water reflectance is added to the G-Buffer. - frag.gNormal.w = waterReflectance; + // Water reflectance is added to the G-Buffer. + frag.gNormal.w = waterReflectance; #else - frag.gNormal.w = 0.0; + frag.gNormal.w = 0.0; #endif - // Normal is written View Space (Including SGCT View Matrix). - frag.gNormal.xyz = normal; + // Normal is written View Space (Including SGCT View Matrix). + frag.gNormal.xyz = normal; - if (dot(positionCameraSpace, vec3(1.0)) != 0.0) { - frag.gPosition = vec4(positionCameraSpace, 1.0); // in Camera Rig Space - } - else { - frag.gPosition = vec4(1.0); // in Camera Rig Space - } + if (dot(positionCameraSpace, vec3(1.0)) != 0.0) { + frag.gPosition = vec4(positionCameraSpace, 1.0); // in Camera Rig Space + } + else { + frag.gPosition = vec4(1.0); // in Camera Rig Space + } - frag.depth = fs_position.w; + frag.depth = fs_position.w; #if SHOW_CHUNK_EDGES - const float BorderSize = 0.005; - const vec3 BorderColor = vec3(1.0, 0.0, 0.0); + const float BorderSize = 0.005; + const vec3 BorderColor = vec3(1.0, 0.0, 0.0); - vec2 uvOffset = fs_uv - vec2(0.5); - float thres = 0.5 - BorderSize * 0.5; - bool isBorder = abs(uvOffset.x) > thres || abs(uvOffset.y) > thres; - if (isBorder) { - frag.color.rgb += BorderColor; - } + vec2 uvOffset = fs_uv - vec2(0.5); + float thres = 0.5 - BorderSize * 0.5; + bool isBorder = abs(uvOffset.x) > thres || abs(uvOffset.y) > thres; + if (isBorder) { + frag.color.rgb += BorderColor; + } #endif // SHOW_CHUNK_EDGES #if SHADOW_MAPPING_ENABLED - float shadow = 1.0; - if (shadowCoords.w > 1) { - vec4 normalizedShadowCoords = shadowCoords; - normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); - normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; - normalizedShadowCoords.w = 1.0; + float shadow = 1.0; + if (shadowCoords.w > 1) { + vec4 normalizedShadowCoords = shadowCoords; + normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); + normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; + normalizedShadowCoords.w = 1.0; - float sum = 0; - #for i in 0..#{nShadowSamples} - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); - #endfor - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); - shadow = sum / (8.0 * NSSamples + 1.f); - } - frag.color.xyz *= shadow < 0.99 ? clamp(shadow + 0.3, 0.0, 1.0) : shadow; + float sum = 0; + #for i in 0..#{nShadowSamples} + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); + #endfor + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); + shadow = sum / (8.0 * NSSamples + 1.f); + } + frag.color.xyz *= shadow < 0.99 ? clamp(shadow + 0.3, 0.0, 1.0) : shadow; #endif - frag.color.a *= opacity; - - return frag; + frag.color.a *= opacity; + return frag; } diff --git a/modules/globebrowsing/shaders/rings_fs.glsl b/modules/globebrowsing/shaders/rings_fs.glsl index d3fb2bc9e4..128ac8b687 100644 --- a/modules/globebrowsing/shaders/rings_fs.glsl +++ b/modules/globebrowsing/shaders/rings_fs.glsl @@ -38,91 +38,82 @@ uniform vec2 textureOffset; uniform float colorFilterValue; uniform vec3 sunPosition; -uniform float _nightFactor; +uniform float nightFactor; uniform float zFightingPercentage; -// temp -in vec4 fragPosInLightSpace; - - Fragment getFragment() { - // Moving the origin to the center - vec2 st = (vs_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vec2 st = (vs_st - vec2(0.5)) * 2.0; - // The length of the texture coordinates vector is our distance from the center - float radius = length(st); + // The length of the texture coordinates vector is our distance from the center + float radius = length(st); - // We only want to consider ring-like objects so we need to discard everything else - if (radius > 1.0) { - discard; + // We only want to consider ring-like objects so we need to discard everything else + if (radius > 1.0) { + discard; + } + + // Remapping the texture coordinates + // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] + // textureOffset.x -> 0 + // textureOffset.y -> 1 + float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); + if (texCoord < 0.0 || texCoord > 1.0) { + discard; + } + + vec4 diffuse = texture(ringTexture, texCoord); + // divided by 3 as length of vec3(1.0, 1.0, 1.0) will return 3 and we want + // to normalize the alpha value to [0,1] + float colorValue = length(diffuse.rgb) / 3.0; + if (colorValue < colorFilterValue) { + diffuse.a = colorValue * colorFilterValue; + if (diffuse.a < 0.65) { + discard; } - - // Remapping the texture coordinates - // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] - // textureOffset.x -> 0 - // textureOffset.y -> 1 - float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); - if (texCoord < 0.f || texCoord > 1.f) { - discard; - } - - vec4 diffuse = texture(ringTexture, texCoord); - // divided by 3 as length of vec3(1.0, 1.0, 1.0) will return 3 and we want - // to normalize the alpha value to [0,1] - float colorValue = length(diffuse.rgb) / 3.0; - if (colorValue < colorFilterValue) { - diffuse.a = colorValue * colorFilterValue; - if (diffuse.a < 0.65) - discard; - } - - // shadow == 1.0 means it is not in shadow - float shadow = 1.0; - if (shadowCoords.z >= 0) { - vec4 normalizedShadowCoords = shadowCoords; - normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); - normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; - normalizedShadowCoords.w = 1.0; - - float sum = 0; - #for i in 0..#{nShadowSamples} - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); - #endfor - sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); - shadow = clamp(sum / (8.0 * NSSamples + 1.f), 0.35, 1.0); - } - - // The normal for the one plane depends on whether we are dealing - // with a front facing or back facing fragment - vec3 normal; - // The plane is oriented on the xz plane - // WARNING: This might not be the case for Uranus - if (gl_FrontFacing) { - normal = vec3(-1.0, 0.0, 0.0); - } - else { - normal = vec3(1.0, 0.0, 0.0); - } - - // Reduce the color of the fragment by the user factor - // if we are facing away from the Sun - if (dot(sunPosition, normal) < 0) { - diffuse.xyz *= _nightFactor; - } - - Fragment frag; - - frag.color = diffuse * shadow; - frag.depth = vs_screenSpaceDepth; - frag.gPosition = vec4(1e30, 1e30, 1e30, 1.0); - frag.gNormal = vec4(normal, 1.0); - - return frag; +} + + // shadow == 1.0 means it is not in shadow + float shadow = 1.0; + if (shadowCoords.z >= 0) { + vec4 normalizedShadowCoords = shadowCoords; + normalizedShadowCoords.z = normalizeFloat(zFightingPercentage * normalizedShadowCoords.w); + normalizedShadowCoords.xy = normalizedShadowCoords.xy / normalizedShadowCoords.w; + normalizedShadowCoords.w = 1.0; + + float sum = 0; + #for i in 0..#{nShadowSamples} + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(-NSSamples + #{i}, NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( 0 , NSSamples - #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, -NSSamples + #{i})); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, 0)); + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2( NSSamples - #{i}, NSSamples - #{i})); + #endfor + sum += textureProjOffset(shadowMapTexture, normalizedShadowCoords, ivec2(0, 0)); + shadow = clamp(sum / (8.0 * NSSamples + 1.0), 0.35, 1.0); + } + + // The normal for the one plane depends on whether we are dealing + // with a front facing or back facing fragment + // The plane is oriented on the xz plane + // WARNING: This might not be the case for Uranus + vec3 normal = gl_FrontFacing ? vec3(-1.0, 0.0, 0.0) : vec3(1.0, 0.0, 0.0); + + // Reduce the color of the fragment by the user factor + // if we are facing away from the Sun + if (dot(sunPosition, normal) < 0.0) { + diffuse.xyz *= _nightFactor; + } + + Fragment frag; + + frag.color = diffuse * shadow; + frag.depth = vs_screenSpaceDepth; + frag.gPosition = vec4(1e30, 1e30, 1e30, 1.0); + frag.gNormal = vec4(normal, 1.0); + + return frag; } diff --git a/modules/globebrowsing/shaders/rings_geom_fs.glsl b/modules/globebrowsing/shaders/rings_geom_fs.glsl index 6d2126b842..0eaa13a96f 100644 --- a/modules/globebrowsing/shaders/rings_geom_fs.glsl +++ b/modules/globebrowsing/shaders/rings_geom_fs.glsl @@ -32,43 +32,43 @@ uniform sampler1D ringTexture; uniform vec2 textureOffset; Fragment getFragment() { - // Moving the origin to the center - vec2 st = (vs_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vec2 st = (vs_st - vec2(0.5)) * 2.0; - // The length of the texture coordinates vector is our distance from the center - float radius = length(st); + // The length of the texture coordinates vector is our distance from the center + float radius = length(st); - // We only want to consider ring-like objects so we need to discard everything else - if (radius > 1.0) { - discard; - } + // We only want to consider ring-like objects so we need to discard everything else + if (radius > 1.0) { + discard; + } - // Remapping the texture coordinates - // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] - // textureOffset.x -> 0 - // textureOffset.y -> 1 - float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); - if (texCoord < 0.f || texCoord > 1.f) { - discard; - } + // Remapping the texture coordinates + // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] + // textureOffset.x -> 0 + // textureOffset.y -> 1 + float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); + if (texCoord < 0.0 || texCoord > 1.0) { + discard; + } - float diffuse = length(texture(ringTexture, texCoord).rgb); - - // The normal for the one plane depends on whether we are dealing - // with a front facing or back facing fragment - //vec3 normal; - // The plane is oriented on the xz plane - // WARNING: This might not be the case for Uranus - // if (gl_FrontFacing) { - // normal = vec3(-1.0, 0.0, 0.0); - // } - // else { - // normal = vec3(1.0, 0.0, 0.0); - // } + float diffuse = length(texture(ringTexture, texCoord).rgb); + + // The normal for the one plane depends on whether we are dealing + // with a front facing or back facing fragment + //vec3 normal; + // The plane is oriented on the xz plane + // WARNING: This might not be the case for Uranus + // if (gl_FrontFacing) { + // normal = vec3(-1.0, 0.0, 0.0); + // } + // else { + // normal = vec3(1.0, 0.0, 0.0); + // } - Fragment frag; - frag.color = vec4(vec3(vs_screenSpaceDepth), 1.0); - frag.depth = (diffuse < 0.5) ? 1E30 : vs_screenSpaceDepth; - - return frag; + Fragment frag; + frag.color = vec4(vec3(vs_screenSpaceDepth), 1.0); + frag.depth = (diffuse < 0.5) ? 1E30 : vs_screenSpaceDepth; + + return frag; } diff --git a/modules/globebrowsing/shaders/rings_geom_vs.glsl b/modules/globebrowsing/shaders/rings_geom_vs.glsl index 7698109c5b..2c18bd7fe2 100644 --- a/modules/globebrowsing/shaders/rings_geom_vs.glsl +++ b/modules/globebrowsing/shaders/rings_geom_vs.glsl @@ -35,13 +35,10 @@ out float vs_screenSpaceDepth; uniform dmat4 modelViewProjectionMatrix; void main() { - vs_st = in_st; + vs_st = in_st; - dvec4 positionClipSpace = modelViewProjectionMatrix * - dvec4(in_position, 0.0, 1.0); - vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); - - vs_screenSpaceDepth = positionClipSpaceZNorm.w; - - gl_Position = positionClipSpaceZNorm; + dvec4 positionClipSpace = modelViewProjectionMatrix * dvec4(in_position, 0.0, 1.0); + vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); + vs_screenSpaceDepth = positionClipSpaceZNorm.w; + gl_Position = positionClipSpaceZNorm; } diff --git a/modules/globebrowsing/shaders/rings_vs.glsl b/modules/globebrowsing/shaders/rings_vs.glsl index 8b43a60571..5d58c668c9 100644 --- a/modules/globebrowsing/shaders/rings_vs.glsl +++ b/modules/globebrowsing/shaders/rings_vs.glsl @@ -31,7 +31,6 @@ layout(location = 1) in vec2 in_st; out vec2 vs_st; out float vs_screenSpaceDepth; -out vec4 vs_positionViewSpace; out vec4 shadowCoords; uniform dmat4 modelViewProjectionMatrix; @@ -42,12 +41,12 @@ uniform dmat4 modelViewProjectionMatrix; uniform dmat4 shadowMatrix; void main() { - vs_st = in_st; + vs_st = in_st; - dvec4 positionClipSpace = modelViewProjectionMatrix * dvec4(in_position, 0.0, 1.0); - vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); - - shadowCoords = vec4(shadowMatrix * dvec4(in_position, 0.0, 1.0)); - vs_screenSpaceDepth = positionClipSpaceZNorm.w; - gl_Position = positionClipSpaceZNorm; + dvec4 positionClipSpace = modelViewProjectionMatrix * dvec4(in_position, 0.0, 1.0); + vec4 positionClipSpaceZNorm = z_normalization(vec4(positionClipSpace)); + + shadowCoords = vec4(shadowMatrix * dvec4(in_position, 0.0, 1.0)); + vs_screenSpaceDepth = positionClipSpaceZNorm.w; + gl_Position = positionClipSpaceZNorm; } diff --git a/modules/globebrowsing/shaders/smviewer_fs.glsl b/modules/globebrowsing/shaders/smviewer_fs.glsl deleted file mode 100644 index 56d518a85e..0000000000 --- a/modules/globebrowsing/shaders/smviewer_fs.glsl +++ /dev/null @@ -1,40 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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 "PowerScaling/powerScaling_fs.hglsl" -#include "fragment.glsl" - -precision highp float; - -in vec2 texCoord; - -uniform highp sampler2D shadowMapTexture; - -Fragment getFragment() { - Fragment frag; - frag.color = vec4(vec3(1.f) - texture(shadowMapTexture, texCoord).rrr, 1.f); - frag.depth = 0.f; - - return frag; -} diff --git a/modules/globebrowsing/shaders/smviewer_vs.glsl b/modules/globebrowsing/shaders/smviewer_vs.glsl deleted file mode 100644 index 208ce361c4..0000000000 --- a/modules/globebrowsing/shaders/smviewer_vs.glsl +++ /dev/null @@ -1,51 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -out vec2 texCoord; - -const vec3 posData[6] = vec3[] ( - vec3(1.0, -0.5, 0.0), - vec3(0.5, -0.5, 0.0), - vec3(0.5, -1.0, 0.0), - vec3(1.0, -1.0, 0.0), - vec3(1.0, -0.5, 0.0), - vec3(0.5, -1.0, 0.0) -); - -const vec2 texData[6] = vec2[] ( - vec2(1.0, 1.0), - vec2(0.0, 1.0), - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(1.0, 1.0), - vec2(0.0, 0.0) - -); - -void main() { - texCoord = texData[gl_VertexID]; - gl_Position = vec4(posData[gl_VertexID], 1.0); -} diff --git a/modules/globebrowsing/shaders/texturetilemapping.glsl b/modules/globebrowsing/shaders/texturetilemapping.glsl new file mode 100644 index 0000000000..5b39d02c42 --- /dev/null +++ b/modules/globebrowsing/shaders/texturetilemapping.glsl @@ -0,0 +1,457 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2021 * + * * + * 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 TEXTURETILEMAPPING_HGLSL +#define TEXTURETILEMAPPING_HGLSL + +#include <${MODULE_GLOBEBROWSING}/shaders/tile.glsl> +#include <${MODULE_GLOBEBROWSING}/shaders/blending.glsl> + +// First layer type from LayerShaderManager is height map +#define NUMLAYERS_HEIGHTMAP #{lastLayerIndexHeightLayers} + 1 +#define USE_HEIGHTMAP #{useHeightLayers} +#define HEIGHTMAP_BLENDING_ENABLED #{blendHeightLayers} + +// Second layer type from LayerShaderManager is color texture +#define NUMLAYERS_COLORTEXTURE #{lastLayerIndexColorLayers} + 1 +#define USE_COLORTEXTURE #{useColorLayers} +#define COLORTEXTURE_BLENDING_ENABLED #{blendColorLayers} + + // Third layer type from LayerShaderManager is water mask +#define NUMLAYERS_WATERMASK #{lastLayerIndexWaterMasks} + 1 +#define USE_WATERMASK #{useWaterMasks} +#define WATERMASK_BLENDING_ENABLED #{blendWaterMasks} + +// Fourth layer type from LayerShaderManager is night texture +#define NUMLAYERS_NIGHTTEXTURE #{lastLayerIndexNightLayers} + 1 +#define USE_NIGHTTEXTURE #{useNightLayers} +#define NIGHTTEXTURE_BLENDING_ENABLED #{blendNightLayers} + +// Fifth layer type from LayerShaderManager is overlay +#define NUMLAYERS_OVERLAY #{lastLayerIndexOverlays} + 1 +#define USE_OVERLAY #{useOverlays} +#define OVERLAY_BLENDING_ENABLED #{blendOverlays} + +// Global constants +#define CHUNK_DEFAULT_HEIGHT #{defaultHeight} + +// Other key value pairs used for settings +#define USE_ACCURATE_NORMALS #{useAccurateNormals} +#define PERFORM_SHADING #{performShading} +#define USE_ECLIPSE_SHADOWS #{useEclipseShadows} +#define USE_ECLIPSE_HARD_SHADOWS #{useEclipseHardShadows} +#define SHOW_CHUNK_EDGES #{showChunkEdges} +#define SHOW_HEIGHT_RESOLUTION #{showHeightResolution} +#define SHOW_HEIGHT_INTENSITIES #{showHeightIntensities} +#define SHADOW_MAPPING_ENABLED #{enableShadowMapping} + +const vec3 DefaultLevelWeights = vec3(1.0, 0.0, 0.0); + +float orenNayarDiffuse(vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, + float roughness) +{ + // calculate intermediary values + float NdotL = dot(surfaceNormal, lightDirection); + float NdotV = dot(surfaceNormal, viewDirection); + + float angleVN = acos(NdotV); + float angleLN = acos(NdotL); + + float alpha = max(angleVN, angleLN); + float beta = min(angleVN, angleLN); + float gamma = dot( + viewDirection - surfaceNormal * dot(viewDirection, surfaceNormal), + lightDirection - surfaceNormal * dot(lightDirection, surfaceNormal) + ); + + float roughnessSquared = roughness * roughness; + + // calculate A and B + float A = 1.0 - 0.5 * (roughnessSquared / (roughnessSquared + 0.57)); + float B = 0.45 * (roughnessSquared / (roughnessSquared + 0.09)); + float C = sin(alpha) * tan(beta); + + // put it all together + return max(0.0, NdotL) * (A + B * max(0.0, gamma) * C); +} + +float performLayerSettings(float value, LayerSettings settings) { + float v = pow(abs(value), settings.gamma) * settings.multiplier + settings.offset; + return sign(value) * v * settings.opacity; +} + +vec4 performLayerSettings(vec4 currentValue, LayerSettings settings) { + vec3 newValue = sign(currentValue.rgb) * pow(abs(currentValue.rgb), vec3(settings.gamma)) * + settings.multiplier + settings.offset; + return vec4(newValue, currentValue.a * settings.opacity); +} + +vec2 tileUVToTextureSamplePosition(ChunkTile chunkTile, vec2 tileUV, PixelPadding padding) +{ + vec2 uv = chunkTile.uvTransform.uvOffset + chunkTile.uvTransform.uvScale * tileUV; + + // compensateSourceTextureSampling + ivec2 resolution = textureSize(chunkTile.textureSampler, 0); + vec2 sourceSize = vec2(resolution) + padding.sizeDifference; + vec2 currentSize = vec2(resolution); + vec2 sourceToCurrentSize = currentSize / sourceSize; + return sourceToCurrentSize * (uv - padding.startOffset / sourceSize); +} + +vec4 getTexVal(ChunkTilePile chunkTilePile, vec3 w, vec2 uv, PixelPadding padding) { + vec4 v1 = texture( + chunkTilePile.chunkTile0.textureSampler, + tileUVToTextureSamplePosition(chunkTilePile.chunkTile0, uv, padding) + ); + vec4 v2 = texture( + chunkTilePile.chunkTile1.textureSampler, + tileUVToTextureSamplePosition(chunkTilePile.chunkTile1, uv, padding) + ); + vec4 v3 = texture( + chunkTilePile.chunkTile2.textureSampler, + tileUVToTextureSamplePosition(chunkTilePile.chunkTile2, uv, padding) + ); + + return w.x * v1 + w.y * v2 + w.z * v3; +} + +#for id, layerGroup in layerGroups +#for i in 0..#{lastLayerIndex#{layerGroup}} + +vec4 getSample#{layerGroup}#{i}(vec2 uv, vec3 levelWeights, + Layer #{layerGroup}[#{lastLayerIndex#{layerGroup}} + 1]) +{ + vec4 c = vec4(0.0, 0.0, 0.0, 1.0); + + // All tile layers are the same. Sample from texture +#if (#{#{layerGroup}#{i}LayerType} == 0) // DefaultTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 1) // SingleImageTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 2) // SizeReferenceTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 3) // TemporalTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 4) // TileIndexTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 5) // ByIndexTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 6) // ByLevelTileLayer + c = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); +#elif (#{#{layerGroup}#{i}LayerType} == 7) // SolidColor + c.rgb = #{layerGroup}[#{i}].color; +#endif + + return c; +} + +#endfor +#endfor + +#define BlendModeDefault 0 +#define BlendModeMultiply 1 +#define BlendModeAdd 2 +#define BlendModeSubtract 3 +#define BlendModeColor 4 + +#for id, layerGroup in layerGroups +#for i in 0..#{lastLayerIndex#{layerGroup}} + +vec4 blend#{layerGroup}#{i}(vec4 currentColor, vec4 newColor, float blendFactor) { +#if (#{#{layerGroup}#{i}BlendMode} == BlendModeDefault) + return blendNormal(currentColor, vec4(newColor.rgb, newColor.a * blendFactor)); +#elif (#{#{layerGroup}#{i}BlendMode} == BlendModeMultiply) + return blendMultiply(currentColor, newColor * blendFactor); +#elif (#{#{layerGroup}#{i}BlendMode} == BlendModeAdd) + return blendAdd(currentColor, newColor * blendFactor); +#elif (#{#{layerGroup}#{i}BlendMode} == BlendModeSubtract) + return blendSubtract(currentColor, newColor * blendFactor); +#elif (#{#{layerGroup}#{i}BlendMode} == BlendModeColor) + // Convert color to grayscale + float gray = (newColor.r + newColor.g + newColor.b) / 3.0; + + vec3 hsvCurrent = rgb2hsv(currentColor.rgb); + // Use gray from new color as value in hsv + vec3 hsvNew = vec3(hsvCurrent.x, hsvCurrent.y, gray); + vec3 rgbNew = hsv2rgb(hsvNew); + + vec4 color = blendNormal(currentColor, vec4(rgbNew, newColor.a * blendFactor)); + return color; +#endif +} + +#endfor +#endfor + +#define LayerAdjustmentTypeDefault 0 +#define LayerAdjustmentTypeChroma 1 +#define LayerAdjustmentTypeTransferFunction 1 + +#for id, layerGroup in layerGroups +#for i in 0..#{lastLayerIndex#{layerGroup}} + +vec4 performAdjustment#{layerGroup}#{i}(vec4 currentColor, LayerAdjustment adjustment) { +#if (#{#{layerGroup}#{i}LayerAdjustmentType} == LayerAdjustmentTypeDefault) + return currentColor; +#elif (#{#{layerGroup}#{i}LayerAdjustmentType} == LayerAdjustmentTypeChroma) + if (distance(currentColor.rgb, adjustment.chromaKeyColor) <= + adjustment.chromaKeyTolerance) + { + return vec4(0.0); + } + else { + return currentColor; + } +#elif (#{#{layerGroup}#{i}LayerAdjustmentType} == LayerAdjustmentTypeTransferFunction) + return currentColor; +#else + return currentColor; +#endif +} + +#endfor +#endfor + +float calculateUntransformedHeight(vec2 uv, vec3 levelWeights, + Layer HeightLayers[NUMLAYERS_HEIGHTMAP]) +{ + + float height = 0; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !HEIGHTMAP_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // HEIGHTMAP_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexHeightLayers} + { + vec4 colorSample = getSampleHeightLayers#{i}(uv, levelWeights, HeightLayers); + colorSample = performAdjustmentHeightLayers#{i}(colorSample, HeightLayers[#{i}].adjustment); + height = colorSample.r; + + height = performLayerSettings(height, HeightLayers[#{i}].settings); + } + #endfor + return height; +} + +float calculateHeight(vec2 uv, vec3 levelWeights, Layer HeightLayers[NUMLAYERS_HEIGHTMAP]) +{ + float height = 0; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !HEIGHTMAP_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // HEIGHTMAP_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexHeightLayers} + { + vec4 colorSample = getSampleHeightLayers#{i}(uv, levelWeights, HeightLayers); + colorSample = performAdjustmentHeightLayers#{i}(colorSample, HeightLayers[#{i}].adjustment); + float untransformedHeight = colorSample.r; + + TileDepthTransform transform = HeightLayers[#{i}].depthTransform; + float heightSample = transform.depthScale * untransformedHeight + transform.depthOffset; + if (heightSample > -100000) { + heightSample = performLayerSettings(heightSample, HeightLayers[#{i}].settings); + height = heightSample; + } + } + #endfor + return height; +} + +vec4 calculateColor(vec4 currentColor, vec2 uv, vec3 levelWeights, + Layer ColorLayers[NUMLAYERS_COLORTEXTURE]) +{ + vec4 color = currentColor; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !COLORTEXTURE_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // COLORTEXTURE_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexColorLayers} + { + vec4 colorSample = getSampleColorLayers#{i}(uv, levelWeights, ColorLayers); + colorSample = performAdjustmentColorLayers#{i}(colorSample, ColorLayers[#{i}].adjustment); + colorSample = performLayerSettings(colorSample, ColorLayers[#{i}].settings); + + color = blendColorLayers#{i}(color, colorSample, 1.0); + } + #endfor + + return color; +} + +float gridDots(vec2 uv, vec2 gridResolution) { + vec2 uvVertexSpace = fract((gridResolution) * uv) + 0.5; + + vec2 uvDotSpace = abs(2.0 * (uvVertexSpace - 0.5)); + return 1.0 - length(1.0 - uvDotSpace); +} + +vec4 calculateDebugColor(vec2 uv, vec4 fragPos, vec2 vertexResolution) { + vec2 uvVertexSpace = fract(vertexResolution * uv); + vec3 colorUv = vec3(0.3 * uv.x, 0.3 * uv.y, 0); + vec3 colorDistance = vec3(0.0, 0.0, min(0.4 * log(fragPos.w) - 3.9, 1)); + vec3 colorVertex = (1.0 - length(uvVertexSpace)) * vec3(0.5); + vec3 colorSum = colorUv + colorDistance + colorVertex; + return vec4(0.5 * colorSum, 1); +} + +float tileResolution(vec2 tileUV, ChunkTile chunkTile) { + PixelPadding padding; + padding.startOffset = ivec2(0); + padding.sizeDifference = ivec2(0); + + vec2 heightResolution = textureSize(chunkTile.textureSampler, 0); + vec2 uv = tileUVToTextureSamplePosition(chunkTile, tileUV, padding); + return gridDots(uv, heightResolution); +} + +vec4 calculateNight(vec4 currentColor, vec2 uv, vec3 levelWeights, + Layer NightLayers[NUMLAYERS_NIGHTTEXTURE], + vec3 ellipsoidNormalCameraSpace, vec3 lightDirectionCameraSpace) +{ + vec4 nightColor = vec4(0.0); + vec4 color = currentColor; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !NIGHTTEXTURE_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // NIGHTTEXTURE_BLENDING_ENABLED + + vec3 n = normalize(ellipsoidNormalCameraSpace); + vec3 l = lightDirectionCameraSpace; + float cosineFactor = clamp(dot(l, normalize(n + 0.20 * l)) * 3 , 0, 1); + + #for i in 0..#{lastLayerIndexNightLayers} + { + vec4 colorSample = getSampleNightLayers#{i}(uv, levelWeights, NightLayers); + colorSample = performAdjustmentNightLayers#{i}(colorSample, NightLayers[#{i}].adjustment); + colorSample = performLayerSettings(colorSample, NightLayers[#{i}].settings); + + float adjustedAlpha = cosineFactor * colorSample.a; + // Filter to night side + vec4 newColor = vec4(cosineFactor * colorSample.xyz, adjustedAlpha); + + color = blendNightLayers#{i}(color, newColor, adjustedAlpha); + } + #endfor + + return color; +} + +vec4 calculateShadedColor(vec4 currentColor, vec3 ellipsoidNormalCameraSpace, + vec3 lightDirectionCameraSpace, vec3 viewDirectionCameraSpace, + float roughness) +{ + vec3 shadedColor = currentColor.rgb * 0.05; + + vec3 n = normalize(ellipsoidNormalCameraSpace); + + float power = orenNayarDiffuse( + -lightDirectionCameraSpace, + viewDirectionCameraSpace, + ellipsoidNormalCameraSpace, + roughness + ); + + vec3 l = lightDirectionCameraSpace; + power = max(smoothstep(0.0, 0.1, max(dot(-l, n), 0.0)) * power, 0.0); + + vec4 color = vec4(shadedColor + currentColor.rgb * power, currentColor.a); + return color; +} + +vec4 calculateOverlay(vec4 currentColor, vec2 uv, vec3 levelWeights, + Layer Overlays[NUMLAYERS_OVERLAY]) +{ + vec4 color = currentColor; + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !OVERLAY_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // OVERLAY_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexOverlays} + { + vec4 colorSample = getSampleOverlays#{i}(uv, levelWeights, Overlays); + colorSample = performAdjustmentOverlays#{i}(colorSample, Overlays[#{i}].adjustment); + + colorSample = performLayerSettings(colorSample, Overlays[#{i}].settings); + + color = blendNormal(color, colorSample); + color = blendOverlays#{i}(color, colorSample, 1.0); + } + #endfor + + return color; +} + +vec4 calculateWater(vec4 currentColor, vec2 uv, vec3 levelWeights, + Layer WaterMasks[NUMLAYERS_WATERMASK], + vec3 ellipsoidNormalCameraSpace, vec3 lightDirectionCameraSpace, + vec3 positionCameraSpace, out float reflectance) +{ + vec4 waterColor = vec4(0.0); + + // The shader compiler will remove unused code when variables are multiplied by + // a constant 0 +#if !WATERMASK_BLENDING_ENABLED + levelWeights = DefaultLevelWeights; +#endif // WATERMASK_BLENDING_ENABLED + + #for i in 0..#{lastLayerIndexWaterMasks} + { + vec4 colorSample = getSampleWaterMasks#{i}(uv, levelWeights, WaterMasks); + colorSample = performAdjustmentWaterMasks#{i}(colorSample, WaterMasks[#{i}].adjustment); + + colorSample.a = performLayerSettings(colorSample.a, WaterMasks[#{i}].settings); + + waterColor = blendWaterMasks#{i}(waterColor, colorSample, 1.0); + } + #endfor + + vec3 directionToFragmentCameraSpace = normalize(positionCameraSpace - vec3(0, 0, 0)); + vec3 reflectionDirectionCameraSpace = reflect(lightDirectionCameraSpace, ellipsoidNormalCameraSpace); + // float cosineFactor = clamp(dot(-reflectionDirectionCameraSpace, directionToFragmentCameraSpace), 0, 1); + // cosineFactor = pow(cosineFactor, 100); + + // const float specularIntensity = 0.4; + // vec3 specularTotal = cosineFactor * specularIntensity * waterColor.a; + + reflectance = waterColor.a; + //return blendNormal(currentColor, waterColor); + //return currentColor + vec4(specularTotal, 1); + return currentColor; +} + +#endif // TEXTURETILEMAPPING_HGLSL diff --git a/modules/globebrowsing/shaders/texturetilemapping.hglsl b/modules/globebrowsing/shaders/texturetilemapping.hglsl deleted file mode 100644 index 5cf2214291..0000000000 --- a/modules/globebrowsing/shaders/texturetilemapping.hglsl +++ /dev/null @@ -1,461 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2021 * - * * - * 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 TEXTURETILEMAPPING_HGLSL -#define TEXTURETILEMAPPING_HGLSL - -#include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> -#include <${MODULE_GLOBEBROWSING}/shaders/blending.hglsl> - -// First layer type from LayerShaderManager is height map -#define NUMLAYERS_HEIGHTMAP #{lastLayerIndexHeightLayers} + 1 -#define USE_HEIGHTMAP #{useHeightLayers} -#define HEIGHTMAP_BLENDING_ENABLED #{blendHeightLayers} - -// Second layer type from LayerShaderManager is color texture -#define NUMLAYERS_COLORTEXTURE #{lastLayerIndexColorLayers} + 1 -#define USE_COLORTEXTURE #{useColorLayers} -#define COLORTEXTURE_BLENDING_ENABLED #{blendColorLayers} - - // Third layer type from LayerShaderManager is water mask -#define NUMLAYERS_WATERMASK #{lastLayerIndexWaterMasks} + 1 -#define USE_WATERMASK #{useWaterMasks} -#define WATERMASK_BLENDING_ENABLED #{blendWaterMasks} - -// Fourth layer type from LayerShaderManager is night texture -#define NUMLAYERS_NIGHTTEXTURE #{lastLayerIndexNightLayers} + 1 -#define USE_NIGHTTEXTURE #{useNightLayers} -#define NIGHTTEXTURE_BLENDING_ENABLED #{blendNightLayers} - -// Fifth layer type from LayerShaderManager is overlay -#define NUMLAYERS_OVERLAY #{lastLayerIndexOverlays} + 1 -#define USE_OVERLAY #{useOverlays} -#define OVERLAY_BLENDING_ENABLED #{blendOverlays} - -// Global constants -#define CHUNK_DEFAULT_HEIGHT #{defaultHeight} - -// Other key value pairs used for settings -#define USE_ACCURATE_NORMALS #{useAccurateNormals} -#define PERFORM_SHADING #{performShading} -#define USE_ECLIPSE_SHADOWS #{useEclipseShadows} -#define USE_ECLIPSE_HARD_SHADOWS #{useEclipseHardShadows} -#define SHOW_CHUNK_EDGES #{showChunkEdges} -#define SHOW_HEIGHT_RESOLUTION #{showHeightResolution} -#define SHOW_HEIGHT_INTENSITIES #{showHeightIntensities} -#define SHADOW_MAPPING_ENABLED #{enableShadowMapping} - -const vec3 DefaultLevelWeights = vec3(1.0, 0.0, 0.0); - -float orenNayarDiffuse(vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, - float roughness) -{ - // calculate intermediary values - float NdotL = dot(surfaceNormal, lightDirection); - float NdotV = dot(surfaceNormal, viewDirection); - - float angleVN = acos(NdotV); - float angleLN = acos(NdotL); - - float alpha = max(angleVN, angleLN); - float beta = min(angleVN, angleLN); - float gamma = dot( - viewDirection - surfaceNormal * dot(viewDirection, surfaceNormal), - lightDirection - surfaceNormal * dot(lightDirection, surfaceNormal) - ); - - float roughnessSquared = roughness * roughness; - - // calculate A and B - float A = 1.0 - 0.5 * (roughnessSquared / (roughnessSquared + 0.57)); - float B = 0.45 * (roughnessSquared / (roughnessSquared + 0.09)); - float C = sin(alpha) * tan(beta); - - // put it all together - return max(0.0, NdotL) * (A + B * max(0.0, gamma) * C); -} - -float performLayerSettings(float currentValue, LayerSettings settings) { - float v = sign(currentValue) * pow(abs(currentValue), settings.gamma) * - settings.multiplier + settings.offset; - return v * settings.opacity; -} - -vec4 performLayerSettings(vec4 currentValue, LayerSettings settings) { - vec3 newValue = sign(currentValue.rgb) * pow(abs(currentValue.rgb), vec3(settings.gamma)) * - settings.multiplier + settings.offset; - return vec4(newValue, currentValue.a * settings.opacity); -} - -vec2 tileUVToTextureSamplePosition(ChunkTile chunkTile, vec2 tileUV, - PixelPadding padding) -{ - vec2 uv = chunkTile.uvTransform.uvOffset + chunkTile.uvTransform.uvScale * tileUV; - - // compensateSourceTextureSampling - ivec2 resolution = textureSize(chunkTile.textureSampler, 0); - vec2 sourceSize = vec2(resolution) + padding.sizeDifference; - vec2 currentSize = vec2(resolution); - vec2 sourceToCurrentSize = currentSize / sourceSize; - return sourceToCurrentSize * (uv - padding.startOffset / sourceSize); -} - -vec4 getTexVal(ChunkTilePile chunkTilePile, vec3 w, vec2 uv, - PixelPadding padding) -{ - vec4 v1 = texture( - chunkTilePile.chunkTile0.textureSampler, - tileUVToTextureSamplePosition(chunkTilePile.chunkTile0, uv, padding) - ); - vec4 v2 = texture( - chunkTilePile.chunkTile1.textureSampler, - tileUVToTextureSamplePosition(chunkTilePile.chunkTile1, uv, padding) - ); - vec4 v3 = texture( - chunkTilePile.chunkTile2.textureSampler, - tileUVToTextureSamplePosition(chunkTilePile.chunkTile2, uv, padding) - ); - - return w.x * v1 + w.y * v2 + w.z * v3; -} - -#for id, layerGroup in layerGroups -#for i in 0..#{lastLayerIndex#{layerGroup}} - -vec4 getSample#{layerGroup}#{i}(vec2 uv, vec3 levelWeights, - Layer #{layerGroup}[#{lastLayerIndex#{layerGroup}} + 1]) -{ - vec4 color = vec4(0.0, 0.0, 0.0, 1.0); - - // All tile layers are the same. Sample from texture -#if (#{#{layerGroup}#{i}LayerType} == 0) // DefaultTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 1) // SingleImageTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 2) // SizeReferenceTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 3) // TemporalTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 4) // TileIndexTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 5) // ByIndexTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 6) // ByLevelTileLayer - color = getTexVal(#{layerGroup}[#{i}].pile, levelWeights, uv, #{layerGroup}[#{i}].padding); -#elif (#{#{layerGroup}#{i}LayerType} == 7) // SolidColor - color.rgb = #{layerGroup}[#{i}].color; -#endif - - return color; -} - -#endfor -#endfor - -#for id, layerGroup in layerGroups -#for i in 0..#{lastLayerIndex#{layerGroup}} - -vec4 blend#{layerGroup}#{i}(vec4 currentColor, vec4 newColor, float blendFactor) { -#if (#{#{layerGroup}#{i}BlendMode} == 0) // Default, Normal - return blendNormal(currentColor, vec4(newColor.rgb, newColor.a * blendFactor)); -#elif (#{#{layerGroup}#{i}BlendMode} == 1) // Multiply - return blendMultiply(currentColor, newColor * blendFactor); -#elif (#{#{layerGroup}#{i}BlendMode} == 2) // Add - return blendAdd(currentColor, newColor * blendFactor); -#elif (#{#{layerGroup}#{i}BlendMode} == 3) // Subtract - return blendSubtract(currentColor, newColor * blendFactor); -#elif (#{#{layerGroup}#{i}BlendMode} == 4) // Color - // Convert color to grayscale - float gray = (newColor.r + newColor.g + newColor.b) / 3.0; - - vec3 hsvCurrent = rgb2hsv(currentColor.rgb); - // Use gray from new color as value in hsv - vec3 hsvNew = vec3(hsvCurrent.x, hsvCurrent.y, gray); - vec3 rgbNew = hsv2rgb(hsvNew); - - vec4 color = blendNormal(currentColor, vec4(rgbNew, newColor.a * blendFactor)); - return color; -#endif -} - -#endfor -#endfor - - -#for id, layerGroup in layerGroups -#for i in 0..#{lastLayerIndex#{layerGroup}} - -vec4 performAdjustment#{layerGroup}#{i}(vec4 currentColor, - LayerAdjustment adjustment) -{ -#if (#{#{layerGroup}#{i}LayerAdjustmentType} == 0) // Default, None - return currentColor; -#elif (#{#{layerGroup}#{i}LayerAdjustmentType} == 1) // ChromaKey - if (distance( - currentColor.rgb, - adjustment.chromaKeyColor - ) <= adjustment.chromaKeyTolerance) - { - return vec4(0.0); - } - else { - return currentColor; - } -#elif (#{#{layerGroup}#{i}LayerAdjustmentType} == 2) // TransferFunction - return currentColor; -#else - return currentColor; -#endif -} - -#endfor -#endfor - -float calculateUntransformedHeight(vec2 uv, vec3 levelWeights, - Layer HeightLayers[NUMLAYERS_HEIGHTMAP]) -{ - - float height = 0; - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !HEIGHTMAP_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // HEIGHTMAP_BLENDING_ENABLED - - #for i in 0..#{lastLayerIndexHeightLayers} - { - vec4 colorSample = getSampleHeightLayers#{i}(uv, levelWeights, HeightLayers); - colorSample = performAdjustmentHeightLayers#{i}(colorSample, HeightLayers[#{i}].adjustment); - height = colorSample.r; - - height = performLayerSettings(height, HeightLayers[#{i}].settings); - } - #endfor - return height; -} - -float calculateHeight(vec2 uv, vec3 levelWeights, Layer HeightLayers[NUMLAYERS_HEIGHTMAP]) -{ - float height = 0; - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !HEIGHTMAP_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // HEIGHTMAP_BLENDING_ENABLED - - - #for i in 0..#{lastLayerIndexHeightLayers} - { - vec4 colorSample = getSampleHeightLayers#{i}(uv, levelWeights, HeightLayers); - colorSample = performAdjustmentHeightLayers#{i}(colorSample, HeightLayers[#{i}].adjustment); - float untransformedHeight = colorSample.r; - - TileDepthTransform transform = HeightLayers[#{i}].depthTransform; - float heightSample = - transform.depthScale * untransformedHeight + transform.depthOffset; - if (heightSample > -100000) { - heightSample = performLayerSettings(heightSample, HeightLayers[#{i}].settings); - height = heightSample; - } - } - #endfor - return height; -} - -vec4 calculateColor(vec4 currentColor, vec2 uv, vec3 levelWeights, - Layer ColorLayers[NUMLAYERS_COLORTEXTURE]) -{ - vec4 color = currentColor; - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !COLORTEXTURE_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // COLORTEXTURE_BLENDING_ENABLED - - #for i in 0..#{lastLayerIndexColorLayers} - { - vec4 colorSample = getSampleColorLayers#{i}(uv, levelWeights, ColorLayers); - colorSample = performAdjustmentColorLayers#{i}(colorSample, ColorLayers[#{i}].adjustment); - colorSample = performLayerSettings(colorSample, ColorLayers[#{i}].settings); - - color = blendColorLayers#{i}(color, colorSample, 1.0); - } - #endfor - - return color; -} - -float gridDots(vec2 uv, vec2 gridResolution) { - vec2 uvVertexSpace = fract((gridResolution) * uv) + 0.5; - - vec2 uvDotSpace = abs(2.0 * (uvVertexSpace - 0.5)); - return 1.0 - length(1.0 - uvDotSpace); -} - -vec4 calculateDebugColor(vec2 uv, vec4 fragPos, vec2 vertexResolution) { - vec2 uvVertexSpace = fract(vertexResolution * uv); - vec3 colorUv = vec3(0.3 * uv.x, 0.3 * uv.y, 0); - vec3 colorDistance = vec3(0.0, 0.0, min(0.4 * log(fragPos.w) - 3.9, 1)); - vec3 colorVertex = (1.0 - length(uvVertexSpace)) * vec3(0.5); - vec3 colorSum = colorUv + colorDistance + colorVertex; - return vec4(0.5 * colorSum, 1); -} - -float tileResolution(vec2 tileUV, ChunkTile chunkTile) { - PixelPadding padding; - padding.startOffset = ivec2(0); - padding.sizeDifference = ivec2(0); - - vec2 heightResolution = textureSize(chunkTile.textureSampler, 0); - vec2 uv = tileUVToTextureSamplePosition(chunkTile, tileUV, padding); - return gridDots(uv, heightResolution); -} - -vec4 calculateNight(vec4 currentColor, vec2 uv, vec3 levelWeights, - Layer NightLayers[NUMLAYERS_NIGHTTEXTURE], - vec3 ellipsoidNormalCameraSpace, - vec3 lightDirectionCameraSpace) -{ - vec4 nightColor = vec4(0.0); - vec4 color = currentColor; - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !NIGHTTEXTURE_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // NIGHTTEXTURE_BLENDING_ENABLED - - vec3 n = normalize(ellipsoidNormalCameraSpace); - vec3 l = lightDirectionCameraSpace; - float cosineFactor = clamp(dot(l, normalize(n + 0.20 * l)) * 3 , 0, 1); - - #for i in 0..#{lastLayerIndexNightLayers} - { - vec4 colorSample = getSampleNightLayers#{i}(uv, levelWeights, NightLayers); - colorSample = performAdjustmentNightLayers#{i}(colorSample, NightLayers[#{i}].adjustment); - colorSample = performLayerSettings(colorSample, NightLayers[#{i}].settings); - - float adjustedAlpha = cosineFactor * colorSample.a; - // Filter to night side - vec4 newColor = vec4(cosineFactor * colorSample.xyz, adjustedAlpha); - - color = blendNightLayers#{i}(color, newColor, adjustedAlpha); - } - #endfor - - return color; -} - -vec4 calculateShadedColor(vec4 currentColor, vec3 ellipsoidNormalCameraSpace, - vec3 lightDirectionCameraSpace, vec3 viewDirectionCameraSpace, - float roughness) -{ - vec3 shadedColor = currentColor.rgb * 0.05; - - vec3 n = normalize(ellipsoidNormalCameraSpace); - - float power = orenNayarDiffuse( - -lightDirectionCameraSpace, - viewDirectionCameraSpace, - ellipsoidNormalCameraSpace, - roughness); - - vec3 l = lightDirectionCameraSpace; - power = max(smoothstep(0.0f, 0.1f, max(dot(-l, n), 0.0f)) * power, 0.0f); - - vec4 color = vec4(shadedColor + currentColor.rgb * power, currentColor.a); - return color; -} - -vec4 calculateOverlay(vec4 currentColor, vec2 uv, vec3 levelWeights, - Layer Overlays[NUMLAYERS_OVERLAY]) -{ - vec4 color = currentColor; - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !OVERLAY_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // OVERLAY_BLENDING_ENABLED - - #for i in 0..#{lastLayerIndexOverlays} - { - vec4 colorSample = getSampleOverlays#{i}(uv, levelWeights, Overlays); - colorSample = performAdjustmentOverlays#{i}(colorSample, Overlays[#{i}].adjustment); - - colorSample = performLayerSettings(colorSample, Overlays[#{i}].settings); - - color = blendNormal(color, colorSample); - color = blendOverlays#{i}(color, colorSample, 1.0); - } - #endfor - - return color; -} - -vec4 calculateWater(vec4 currentColor, vec2 uv, vec3 levelWeights, - Layer WaterMasks[NUMLAYERS_WATERMASK], - vec3 ellipsoidNormalCameraSpace, - vec3 lightDirectionCameraSpace, vec3 positionCameraSpace, - out float reflectance) -{ - vec4 waterColor = vec4(0.0); - - // The shader compiler will remove unused code when variables are multiplied by - // a constant 0 -#if !WATERMASK_BLENDING_ENABLED - levelWeights = DefaultLevelWeights; -#endif // WATERMASK_BLENDING_ENABLED - - #for i in 0..#{lastLayerIndexWaterMasks} - { - vec4 colorSample = getSampleWaterMasks#{i}(uv, levelWeights, WaterMasks); - colorSample = performAdjustmentWaterMasks#{i}(colorSample, WaterMasks[#{i}].adjustment); - - colorSample.a = performLayerSettings(colorSample.a, WaterMasks[#{i}].settings); - - waterColor = blendWaterMasks#{i}(waterColor, colorSample, 1.0); - } - #endfor - - vec3 directionToFragmentCameraSpace = normalize(positionCameraSpace - vec3(0, 0, 0)); - vec3 reflectionDirectionCameraSpace = reflect(lightDirectionCameraSpace, ellipsoidNormalCameraSpace); - float cosineFactor = clamp(dot(-reflectionDirectionCameraSpace, directionToFragmentCameraSpace), 0, 1); - cosineFactor = pow(cosineFactor, 100); - - const vec3 specularColor = vec3(1.0); - const float specularIntensity = 0.4; - - vec3 specularTotal = specularColor * cosineFactor * specularIntensity * waterColor.a; - - reflectance = waterColor.a; - //return blendNormal(currentColor, waterColor); - //return currentColor + vec4(specularTotal, 1); - return currentColor; -} - -#endif // TEXTURETILEMAPPING_HGLSL diff --git a/modules/globebrowsing/shaders/tile.hglsl b/modules/globebrowsing/shaders/tile.glsl similarity index 78% rename from modules/globebrowsing/shaders/tile.hglsl rename to modules/globebrowsing/shaders/tile.glsl index d074581c8c..7b2ce24ea4 100644 --- a/modules/globebrowsing/shaders/tile.hglsl +++ b/modules/globebrowsing/shaders/tile.glsl @@ -26,53 +26,53 @@ #define TEXTURETILE_HGLSL struct TileDepthTransform { - float depthScale; - float depthOffset; + float depthScale; + float depthOffset; }; struct TileUvTransform { - vec2 uvOffset; - vec2 uvScale; + vec2 uvOffset; + vec2 uvScale; }; struct ChunkTile { - sampler2D textureSampler; - TileUvTransform uvTransform; + sampler2D textureSampler; + TileUvTransform uvTransform; }; struct PixelPadding { - ivec2 startOffset; - ivec2 sizeDifference; + ivec2 startOffset; + ivec2 sizeDifference; }; struct ChunkTilePile { - ChunkTile chunkTile0; - ChunkTile chunkTile1; - ChunkTile chunkTile2; + ChunkTile chunkTile0; + ChunkTile chunkTile1; + ChunkTile chunkTile2; }; struct LayerSettings { - float opacity; - float gamma; - float multiplier; - float offset; - float valueBlending; + float opacity; + float gamma; + float multiplier; + float offset; + float valueBlending; }; struct LayerAdjustment { - vec3 chromaKeyColor; - float chromaKeyTolerance; + vec3 chromaKeyColor; + float chromaKeyTolerance; }; struct Layer { - ChunkTilePile pile; - TileDepthTransform depthTransform; - LayerSettings settings; - LayerAdjustment adjustment; - PixelPadding padding; - - // Other layer type properties stuff - vec3 color; + ChunkTilePile pile; + TileDepthTransform depthTransform; + LayerSettings settings; + LayerAdjustment adjustment; + PixelPadding padding; + + // Other layer type properties stuff + vec3 color; }; #endif // TEXTURETILE_HGLSL diff --git a/modules/globebrowsing/shaders/tileheight.hglsl b/modules/globebrowsing/shaders/tileheight.glsl similarity index 66% rename from modules/globebrowsing/shaders/tileheight.hglsl rename to modules/globebrowsing/shaders/tileheight.glsl index 47865f9bb5..64f026c328 100644 --- a/modules/globebrowsing/shaders/tileheight.hglsl +++ b/modules/globebrowsing/shaders/tileheight.glsl @@ -26,16 +26,15 @@ #define TILE_HEIGHT_HGLSL #include "PowerScaling/powerScaling_vs.hglsl" - -#include <${MODULE_GLOBEBROWSING}/shaders/tile.hglsl> +#include <${MODULE_GLOBEBROWSING}/shaders/tile.glsl> #ifndef USE_HEIGHTMAP #define USE_HEIGHTMAP #{useAccurateNormals} -#endif //USE_HEIGHTMAP +#endif // USE_HEIGHTMAP #ifndef USE_ACCURATE_NORMALS #define USE_ACCURATE_NORMALS #{useAccurateNormals} -#endif //USE_ACCURATE_NORMALS +#endif // USE_ACCURATE_NORMALS #if USE_HEIGHTMAP uniform Layer HeightLayers[NUMLAYERS_HEIGHTMAP]; @@ -48,42 +47,38 @@ uniform float deltaTheta1; uniform float deltaPhi0; uniform float deltaPhi1; uniform float tileDelta; -#endif //USE_ACCURATE_NORMALS && USE_HEIGHTMAP +#endif // USE_ACCURATE_NORMALS && USE_HEIGHTMAP +// levelWeights := Variable to determine which texture to sample from +// HeightLayers := Three textures to sample from float getUntransformedTileHeight(vec2 uv, vec3 levelWeights) { - float height = CHUNK_DEFAULT_HEIGHT; + float height = CHUNK_DEFAULT_HEIGHT; #if USE_HEIGHTMAP - // Calculate desired level based on distance to the vertex on the ellipsoid - // Before any heightmapping is done - height = calculateUntransformedHeight( - uv, - levelWeights, // Variable to determine which texture to sample from - HeightLayers // Three textures to sample from - ); + // Calculate desired level based on distance to the vertex on the ellipsoid before any + // heightmapping is done. + height = calculateUntransformedHeight(uv, levelWeights, HeightLayers); #endif // USE_HEIGHTMAP return height; } +// levelWeights := Variable to determine which texture to sample from +// HeightLayers := Three textures to sample from float getTileHeight(vec2 uv, vec3 levelWeights) { - float height = CHUNK_DEFAULT_HEIGHT; + float height = CHUNK_DEFAULT_HEIGHT; #if USE_HEIGHTMAP - // Calculate desired level based on distance to the vertex on the ellipsoid - // Before any heightmapping is done - height = calculateHeight( - uv, - levelWeights, // Variable to determine which texture to sample from - HeightLayers // Three textures to sample from - ); + // Calculate desired level based on distance to the vertex on the ellipsoid before any + // heightmapping is done + height = calculateHeight(uv, levelWeights, HeightLayers); #endif // USE_HEIGHTMAP return height; } float getTileHeightScaled(vec2 uv, vec3 levelWeights) { - float height = getTileHeight(uv, levelWeights); + float height = getTileHeight(uv, levelWeights); #if USE_HEIGHTMAP height *= heightScale; @@ -96,25 +91,25 @@ vec3 getTileNormal(vec2 uv, vec3 levelWeights, vec3 ellipsoidNormalCameraSpace, vec3 ellipsoidTangentThetaCameraSpace, vec3 ellipsoidTangentPhiCameraSpace) { - vec3 normal = ellipsoidNormalCameraSpace; + vec3 normal = ellipsoidNormalCameraSpace; #if USE_ACCURATE_NORMALS - float deltaPhi = mix(deltaPhi0, deltaPhi1, uv.x); - float deltaTheta = mix(deltaTheta0, deltaTheta1, uv.y); + float deltaPhi = mix(deltaPhi0, deltaPhi1, uv.x); + float deltaTheta = mix(deltaTheta0, deltaTheta1, uv.y); - vec3 deltaPhiVec = ellipsoidTangentPhiCameraSpace * deltaPhi; - vec3 deltaThetaVec = ellipsoidTangentThetaCameraSpace * deltaTheta; + vec3 deltaPhiVec = ellipsoidTangentPhiCameraSpace * deltaPhi; + vec3 deltaThetaVec = ellipsoidTangentThetaCameraSpace * deltaTheta; - float height00 = getTileHeightScaled(uv, levelWeights); - float height10 = getTileHeightScaled(uv + vec2(tileDelta, 0.0f), levelWeights); - float height01 = getTileHeightScaled(uv + vec2(0.0f, tileDelta), levelWeights); + float height00 = getTileHeightScaled(uv, levelWeights); + float height10 = getTileHeightScaled(uv + vec2(tileDelta, 0.0), levelWeights); + float height01 = getTileHeightScaled(uv + vec2(0.0, tileDelta), levelWeights); - vec3 diffTheta = deltaThetaVec + ellipsoidNormalCameraSpace * (height10 - height00); - vec3 diffPhi = deltaPhiVec + ellipsoidNormalCameraSpace * (height01 - height00); + vec3 diffTheta = deltaThetaVec + ellipsoidNormalCameraSpace * (height10 - height00); + vec3 diffPhi = deltaPhiVec + ellipsoidNormalCameraSpace * (height01 - height00); - normal = normalize(cross(diffTheta, diffPhi)); + normal = normalize(cross(diffTheta, diffPhi)); #endif // USE_ACCURATE_NORMALS - return normal; + return normal; } #endif // TILE_HEIGHT_HGLSL diff --git a/modules/globebrowsing/shaders/tilevertexskirt.hglsl b/modules/globebrowsing/shaders/tilevertexskirt.glsl similarity index 89% rename from modules/globebrowsing/shaders/tilevertexskirt.hglsl rename to modules/globebrowsing/shaders/tilevertexskirt.glsl index 37bcce883c..ac1bcccccc 100644 --- a/modules/globebrowsing/shaders/tilevertexskirt.hglsl +++ b/modules/globebrowsing/shaders/tilevertexskirt.glsl @@ -31,14 +31,14 @@ uniform int xSegments; uniform float skirtLength; bool tileVertexIsSkirtVertex() { - int vertexIDx = gl_VertexID % (xSegments + 3); - int vertexIDy = gl_VertexID / (xSegments + 3); - return vertexIDx == 0 || vertexIDy == 0 || - vertexIDx == (xSegments + 2) || vertexIDy == (xSegments + 2); + int vertexIDx = gl_VertexID % (xSegments + 3); + int vertexIDy = gl_VertexID / (xSegments + 3); + return vertexIDx == 0 || vertexIDy == 0 || + vertexIDx == (xSegments + 2) || vertexIDy == (xSegments + 2); } float getTileVertexSkirtLength() { - return tileVertexIsSkirtVertex() ? skirtLength : 0.0; + return tileVertexIsSkirtVertex() ? skirtLength : 0.0; } #endif // TILE_VERTEX_SKIRT_HGLSL diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index eaf7a178e4..adc0ca2516 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -732,8 +732,6 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask glEnable(GL_BLEND); - _shadowComponent.setViewDepthMap(false); - _shadowComponent.end(); // Render again from original point of view diff --git a/modules/globebrowsing/src/ringscomponent.cpp b/modules/globebrowsing/src/ringscomponent.cpp index 07883a709d..9a57781935 100644 --- a/modules/globebrowsing/src/ringscomponent.cpp +++ b/modules/globebrowsing/src/ringscomponent.cpp @@ -55,13 +55,13 @@ namespace { constexpr const char* _loggerCat = "RingsComponent"; constexpr const std::array UniformNames = { - "modelViewProjectionMatrix", "textureOffset", "colorFilterValue", "_nightFactor", + "modelViewProjectionMatrix", "textureOffset", "colorFilterValue", "nightFactor", "sunPosition", "ringTexture", "shadowMatrix", "shadowMapTexture", "zFightingPercentage" }; constexpr const std::array UniformNamesAdvancedRings = { - "modelViewProjectionMatrix", "textureOffset", "colorFilterValue", "_nightFactor", + "modelViewProjectionMatrix", "textureOffset", "colorFilterValue", "nightFactor", "sunPosition", "sunPositionObj", "camPositionObj", "ringTextureFwrd", "ringTextureBckwrd", "ringTextureUnlit", "ringTextureColor", "ringTextureTransparency", "shadowMatrix", "shadowMapTexture", "zFightingPercentage" diff --git a/modules/globebrowsing/src/shadowcomponent.cpp b/modules/globebrowsing/src/shadowcomponent.cpp index 55a5285480..4d45705b5f 100644 --- a/modules/globebrowsing/src/shadowcomponent.cpp +++ b/modules/globebrowsing/src/shadowcomponent.cpp @@ -356,33 +356,6 @@ void ShadowComponent::end() { if (_blendIsEnabled) { glEnable(GL_BLEND); } - - if (_viewDepthMap) { - if (!_renderDMProgram) { - _renderDMProgram = global::renderEngine->buildRenderProgram( - "ShadowMappingDebuggingProgram", - absPath("${MODULE_GLOBEBROWSING}/shaders/smviewer_vs.glsl"), - absPath("${MODULE_GLOBEBROWSING}/shaders/smviewer_fs.glsl") - ); - } - - if (!_quadVAO) { - glGenVertexArrays(1, &_quadVAO); - } - - _renderDMProgram->activate(); - - ghoul::opengl::TextureUnit shadowMapUnit; - shadowMapUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _shadowDepthTexture); - - _renderDMProgram->setUniform("shadowMapTexture", shadowMapUnit); - - glBindVertexArray(_quadVAO); - glDrawArrays(GL_TRIANGLES, 0, 6); - - _renderDMProgram->deactivate(); - } } void ShadowComponent::update(const UpdateData&) { @@ -619,10 +592,6 @@ ShadowComponent::ShadowMapData ShadowComponent::shadowMapData() const { return _shadowData; } -void ShadowComponent::setViewDepthMap(bool enable) { - _viewDepthMap = enable; -} - GLuint ShadowComponent::dDepthTexture() const { return _dDepthTexture; } diff --git a/modules/globebrowsing/src/shadowcomponent.h b/modules/globebrowsing/src/shadowcomponent.h index dddea2fb66..b39c832b2a 100644 --- a/modules/globebrowsing/src/shadowcomponent.h +++ b/modules/globebrowsing/src/shadowcomponent.h @@ -77,8 +77,6 @@ public: ShadowComponent::ShadowMapData shadowMapData() const; - void setViewDepthMap(bool enable); - GLuint dDepthTexture() const; private: @@ -137,9 +135,6 @@ private: // DEBUG bool _executeDepthTextureSave = false; - bool _viewDepthMap = false; - std::unique_ptr _renderDMProgram; - GLuint _quadVAO = 0u; }; } // namespace openspace diff --git a/modules/imgui/shaders/gui_fs.glsl b/modules/imgui/shaders/gui_fs.glsl index 55266b7681..159603cd92 100644 --- a/modules/imgui/shaders/gui_fs.glsl +++ b/modules/imgui/shaders/gui_fs.glsl @@ -32,5 +32,5 @@ in vec4 out_color; out vec4 FragColor; void main() { - FragColor = out_color * texture(tex, out_uv); + FragColor = out_color * texture(tex, out_uv); } diff --git a/modules/imgui/shaders/gui_vs.glsl b/modules/imgui/shaders/gui_vs.glsl index aed40bd172..ae30863e23 100644 --- a/modules/imgui/shaders/gui_vs.glsl +++ b/modules/imgui/shaders/gui_vs.glsl @@ -34,7 +34,7 @@ out vec4 out_color; uniform mat4 ortho; void main() { - out_uv = in_uv; - out_color = in_color; - gl_Position = ortho * vec4(in_position.xy, 0.0, 1.0); + out_uv = in_uv; + out_color = in_color; + gl_Position = ortho * vec4(in_position.xy, 0.0, 1.0); } diff --git a/modules/imgui/src/guifilepathcomponent.cpp b/modules/imgui/src/guifilepathcomponent.cpp index bfee3703ad..d6f0d97f7e 100644 --- a/modules/imgui/src/guifilepathcomponent.cpp +++ b/modules/imgui/src/guifilepathcomponent.cpp @@ -51,7 +51,7 @@ void GuiFilePathComponent::render() { for (const std::string& t : tokens) { ImGui::Text("%s", t.c_str()); ImGui::NextColumn(); - ImGui::Text("%s", absPath(t).c_str()); + ImGui::Text("%s", absPath(t).string().c_str()); ImGui::NextColumn(); ImGui::Separator(); } diff --git a/modules/space/shaders/constellationbounds_fs.glsl b/modules/space/shaders/constellationbounds_fs.glsl index 32ea62a82e..5e0f05b820 100644 --- a/modules/space/shaders/constellationbounds_fs.glsl +++ b/modules/space/shaders/constellationbounds_fs.glsl @@ -27,16 +27,14 @@ in vec4 vs_position; -uniform vec4 campos; -uniform vec4 objpos; uniform vec3 color; Fragment getFragment() { - vec4 position = vs_position; + vec4 position = vs_position; - Fragment frag; - frag.color = vec4(color, 1.0); - frag.depth = pscDepth(position); + Fragment frag; + frag.color = vec4(color, 1.0); + frag.depth = pscDepth(position); - return frag; + return frag; } diff --git a/modules/space/shaders/constellationbounds_vs.glsl b/modules/space/shaders/constellationbounds_vs.glsl index 1f3bc5245e..12c74b2476 100644 --- a/modules/space/shaders/constellationbounds_vs.glsl +++ b/modules/space/shaders/constellationbounds_vs.glsl @@ -33,11 +33,11 @@ uniform mat4 ModelTransform; #include "PowerScaling/powerScaling_vs.hglsl" void main() { - vec4 tmp = vec4(in_position, 0.0); - vs_position = tmp; + vec4 tmp = vec4(in_position, 0.0); + vs_position = tmp; - vec4 position = pscTransform(tmp, ModelTransform); - vs_position = tmp; - position = ViewProjection * position; - gl_Position = z_normalization(position); + vec4 position = pscTransform(tmp, ModelTransform); + vs_position = tmp; + position = ViewProjection * position; + gl_Position = z_normalization(position); } diff --git a/modules/space/shaders/convolution_fs.glsl b/modules/space/shaders/convolution_fs.glsl index c884ce1846..cea22697c0 100644 --- a/modules/space/shaders/convolution_fs.glsl +++ b/modules/space/shaders/convolution_fs.glsl @@ -26,8 +26,7 @@ out vec4 renderTableColor; -in vec2 psfCoords; -in vec2 texturesCoords; +in vec2 vs_uv; uniform int psfTextureSize; uniform int convolvedfTextureSize; @@ -35,42 +34,19 @@ uniform sampler2D psfTexture; uniform sampler2D shapeTexture; void main() { - float fullColor = 0.0; - - // Kernel Center - //vec2 psfTextureCoords = vec2((float(psfTextureSize)/2.0 + 1.0) / float(psfTextureSize)); - // fullColor += texture2D(shapeTexture, texturesCoords) * - // texture2D(psfTexture, psfTextureCoords); - - float maxConvSize = float(psfTextureSize); - float convStep = 1.0 / maxConvSize; - float textureStep = 1.0 / float(convolvedfTextureSize); - for (float i = 0.0, ii = 0.0; i < maxConvSize; i += convStep, ii += textureStep) { - for (float j = 0.0, jj = 0.0; j < maxConvSize; j += convStep, jj += textureStep) { - vec2 newTexCoords = texturesCoords; - newTexCoords.x = i < 0.5 ? texturesCoords.x - ii : texturesCoords.x + ii; - newTexCoords.y = j < 0.5 ? texturesCoords.y - jj : texturesCoords.y + jj; - newTexCoords.x = newTexCoords.x > 1.0 ? 1.0 : newTexCoords.x < 0.0 ? 0.0 : newTexCoords.x; - newTexCoords.y = newTexCoords.y > 1.0 ? 1.0 : newTexCoords.y < 0.0 ? 0.0 : newTexCoords.y; - fullColor += texture2D(shapeTexture, newTexCoords).x * - texture2D(psfTexture, vec2(i, j)).x; - } + float fullColor = 0.0; + + float maxConvSize = float(psfTextureSize); + float convStep = 1.0 / maxConvSize; + float textureStep = 1.0 / float(convolvedfTextureSize); + for (float i = 0.0, ii = 0.0; i < maxConvSize; i += convStep, ii += textureStep) { + for (float j = 0.0, jj = 0.0; j < maxConvSize; j += convStep, jj += textureStep) { + vec2 uv = vs_uv; + uv.x = clamp(i < 0.5 ? vs_uv.x - ii : vs_uv.x + ii, 0.0, 1.0); + uv.y = clamp(j < 0.5 ? vs_uv.y - jj : vs_uv.y + jj, 0.0, 1.0); + fullColor += texture(shapeTexture, uv).x * texture(psfTexture, vec2(i, j)).x; } + } - /* - vec2 onePixel = vec2(1.0, 1.0) / float(psfTextureSize); - vec4 fullColor = - texture2D(shapeTexture, texturesCoords + onePixel * vec2(-1, -1)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 0, -1)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 1, -1)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2(-1, 0)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 0, 0)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 1, 0)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2(-1, 1)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 0, 1)) * texture2D(psfTexture, vec2(i, j)) + - texture2D(shapeTexture, texturesCoords + onePixel * vec2( 1, 1)) * texture2D(psfTexture, vec2(i, j)); - */ - - - renderTableColor = vec4(fullColor/40.0); + renderTableColor = vec4(fullColor / 40.0); } diff --git a/modules/space/shaders/convolution_vs.glsl b/modules/space/shaders/convolution_vs.glsl index a92bf82d5d..d3cb844fbe 100644 --- a/modules/space/shaders/convolution_vs.glsl +++ b/modules/space/shaders/convolution_vs.glsl @@ -26,11 +26,9 @@ layout(location = 0) in vec4 in_position; -out vec2 psfCoords; -out vec2 texturesCoords; +out vec2 vs_uv; void main() { - gl_Position = vec4(in_position.xy, 0.f, 1.f); - psfCoords = vec2(in_position); - texturesCoords = vec2(in_position.zw); + gl_Position = vec4(in_position.xy, 0.0, 1.0); + vs_uv = vec2(in_position.zw); } diff --git a/modules/space/shaders/debrisViz_fs.glsl b/modules/space/shaders/debrisViz_fs.glsl index b7a8476e81..239894d9ea 100644 --- a/modules/space/shaders/debrisViz_fs.glsl +++ b/modules/space/shaders/debrisViz_fs.glsl @@ -23,77 +23,52 @@ ****************************************************************************************/ #include "fragment.glsl" -//#include "floatoperations.glsl" + +in vec4 viewSpacePosition; +in float viewSpaceDepth; +in float periodFraction; +in float offsetPeriods; uniform vec3 color; uniform float opacity = 1.0; - uniform float lineFade; -// uniform int numberOfSegments; - -in vec4 viewSpacePosition; -in float vs_position_w; - -in float periodFraction_f; -in float offsetPeriods; -in float vertexID_f; - -// debuggers : -// in float offset; -// in float epoch; -// in float period; -// in flat double tajm; Fragment getFragment() { - // float offsetPeriods = offset / period; - // This is now done in the fragment shader instead - // to make smooth movement between vertecies. - // We want vertexDistance to be double up to this point, I think. - // (hence the unnessesary float to float conversion) - float vertexDistance = periodFraction_f - offsetPeriods; - float vertexDistance_f = float(vertexDistance); - - // This is the alternative way of calculating - // the offsetPeriods: (vertexID_perOrbit/nrOfSegments_f) - // float vertexID_perOrbit = mod(vertexID_f, numberOfSegments); - // float nrOfSegments_f = float(numberOfSegments); - // float vertexDistance = periodFraction_f - (vertexID_perOrbit/nrOfSegments_f); + // float offsetPeriods = offset / period; + // This is now done in the fragment shader instead to make smooth movement between + // vertices. We want vertexDistance to be double up to this point, I think, (hence the + // unnessesary float to float conversion) + float vertexDistance = periodFraction - offsetPeriods; + + // This is the alternative way of calculating + // the offsetPeriods: (vertexID_perOrbit/nrOfSegments_f) + // float vertexID_perOrbit = mod(vertexID_f, numberOfSegments); + // float nrOfSegments_f = float(numberOfSegments); + // float vertexDistance = periodFraction - (vertexID_perOrbit/nrOfSegments_f); - if (vertexDistance_f < 0.0) { - vertexDistance_f += 1.0; - } + if (vertexDistance < 0.0) { + vertexDistance += 1.0; + } - float invert = pow((1.0 - vertexDistance_f), lineFade); - float fade = clamp(invert, 0.0, 1.0); + float invert = pow((1.0 - vertexDistance), lineFade); + float fade = clamp(invert, 0.0, 1.0); - // Currently even fully transparent lines can occlude other lines, thus we discard - // these fragments since debris and satellites are rendered so close to each other - if (fade < 0.05) { - discard; - } - Fragment frag; + // Currently even fully transparent lines can occlude other lines, thus we discard these + // fragments since debris and satellites are rendered so close to each other + if (fade < 0.05) { + discard; + } + Fragment frag; + if (fade < 0.15) { // Use additive blending for some values to make the discarding less abrupt - if (fade < 0.15) { - frag.blend = BLEND_MODE_ADDITIVE; - } + frag.blend = BLEND_MODE_ADDITIVE; + } - frag.color = vec4(color, fade * opacity); - frag.depth = vs_position_w; - frag.gPosition = viewSpacePosition; - frag.gNormal = vec4(1, 1, 1, 0); + frag.color = vec4(color, fade * opacity); + frag.depth = viewSpaceDepth; + frag.gPosition = viewSpacePosition; + frag.gNormal = vec4(1.0, 1.0, 1.0, 0.0); - - // to debug using colors use this if-statment. - // float ep = 0.01; - // if (fract(vertexID_f) < ep) { - // periodFraction < ep - // frag.color = vec4(1, 0, 0, 1); - // } - - return frag; + return frag; } - - - - diff --git a/modules/space/shaders/debrisViz_vs.glsl b/modules/space/shaders/debrisViz_vs.glsl index 7ec4e86faf..460e8f6e87 100644 --- a/modules/space/shaders/debrisViz_vs.glsl +++ b/modules/space/shaders/debrisViz_vs.glsl @@ -26,68 +26,47 @@ #include "PowerScaling/powerScalingMath.hglsl" -layout (location = 0) in vec4 vertex_data; // 1: x, 2: y, 3: z, 4: timeOffset, -layout (location = 1) in vec2 orbit_data; // 1: epoch, 2: period +layout (location = 0) in vec4 vertexData; // 1: x, 2: y, 3: z, 4: timeOffset, +layout (location = 1) in vec2 orbitData; // 1: epoch, 2: period + +out vec4 viewSpacePosition; +out float viewSpaceDepth; +out float periodFraction; +out float offsetPeriods; uniform dmat4 modelViewTransform; uniform mat4 projectionTransform; - -//uniform float lineFade; uniform double inGameTime; -out vec4 viewSpacePosition; -out float vs_position_w; - -out float periodFraction_f; -out float offsetPeriods; -out float vertexID_f; - -// debugers : -// out float offset; -// out float epoch; -// out float period; -// out double tajm; - void main() { - // tajm = inGameTime; - /** The way the position and line fade is calculated is: - * By using inGameTime, epoch and period of this orbit, - * we get how many revolutions it has done since epoch. - * The fract of that, is how far into a revolution it has traveld since epoch. - * Similarly we do the same but for this vertex, but calculating offsetPeriods. - * In the fragment shader the difference between - * periodFraction_f and offsetPeriods is calculated to know how much to fade - * that specific fragment. - */ + /* + * The way the position and line fade is calculated is: + * By using inGameTime, epoch and period of this orbit, we get how many revolutions it + * has done since epoch. The fract of that, is how far into a revolution it has traveled + * since epoch. Similarly we do the same but for this vertex, but calculating + * offsetPeriods. In the fragment shader the difference between periodFraction_f and + * offsetPeriods is calculated to know how much to fade that specific fragment. + */ - // If orbit_data is doubles, cast to float first - float offset = vertex_data.w; - double epoch = orbit_data.x; - double period = orbit_data.y; - - // calculate nr of periods, get fractional part to know where - // the vertex closest to the debris part is right now - double nrOfRevolutions = (inGameTime - epoch) / period; - //double periodFraction = fract(nrOfRevolutions); //mod(nrOfRevolutions, 1.0); - int intfrac = int(nrOfRevolutions); - double doublefrac = double(intfrac); - double periodFraction = nrOfRevolutions - doublefrac; - if (periodFraction < 0.0) { - periodFraction += 1.0; - } - periodFraction_f = float(periodFraction); + // If orbit_data is doubles, cast to float first + float epoch = orbitData.x; + float period = orbitData.y; - // same procedure for the current vertex - float period_f = float(period); - offsetPeriods = offset / period_f; + // calculate nr of periods, get fractional part to know where the vertex closest to the + // debris part is right now + double nrOfRevolutions = (inGameTime - epoch) / period; + double frac = double(int(nrOfRevolutions)); + double periodFractiond = nrOfRevolutions - frac; + if (periodFractiond < 0.0) { + periodFractiond += 1.0; + } + periodFraction = float(periodFractiond); - // offsetPeriods can also be calculated by passing the vertexID as a float - // to the fragment shader and deviding it by nrOfSegments. - vertexID_f = float(gl_VertexID); - dvec3 positions = dvec3(vertex_data.x, vertex_data.y, vertex_data.z); - dvec4 vertexPosition = dvec4(positions, 1); - viewSpacePosition = vec4(modelViewTransform * vertexPosition); - vec4 vs_position = z_normalization( projectionTransform * viewSpacePosition); - gl_Position = vs_position; - vs_position_w = vs_position.w; + // same procedure for the current vertex + offsetPeriods = vertexData.w / float(period); + + viewSpacePosition = vec4(modelViewTransform * dvec4(vertexData.xyz, 1)); + vec4 vs_position = z_normalization(projectionTransform * viewSpacePosition); + gl_Position = vs_position; + viewSpaceDepth = vs_position.w; } diff --git a/modules/space/shaders/habitablezone_fs.glsl b/modules/space/shaders/habitablezone_fs.glsl index 11bcca4f3b..565a0f8379 100644 --- a/modules/space/shaders/habitablezone_fs.glsl +++ b/modules/space/shaders/habitablezone_fs.glsl @@ -40,48 +40,48 @@ uniform bool showOptimistic; float computeTextureCoord(float radius, float innerRadius, float conservativeInner, float conservativeOuter) { - const float t1 = 1.0 / 3.0; - const float t2 = 2.0 / 3.0; + const float t1 = 1.0 / 3.0; + const float t2 = 2.0 / 3.0; - if (radius < conservativeInner) { - float t = (radius - innerRadius) / (conservativeInner - innerRadius); - return mix(0.0, t1, t); - } - else if (radius > conservativeOuter) { - float t = (radius - conservativeOuter) / (1.0 - conservativeOuter); - return mix(t2, 1.0, t); - } - else { - float t = (radius - conservativeInner) / (conservativeOuter - conservativeInner); - return mix(t1, t2, t); - } + if (radius < conservativeInner) { + float t = (radius - innerRadius) / (conservativeInner - innerRadius); + return mix(0.0, t1, t); + } + else if (radius > conservativeOuter) { + float t = (radius - conservativeOuter) / (1.0 - conservativeOuter); + return mix(t2, 1.0, t); + } + else { + float t = (radius - conservativeInner) / (conservativeOuter - conservativeInner); + return mix(t1, t2, t); + } } Fragment getFragment() { - // The length of the texture coordinates vector is our distance from the center - float radius = length(vs_st); - float innerRadius = 1.0 - width; + // The length of the texture coordinates vector is our distance from the center + float radius = length(vs_st); + float innerRadius = 1.0 - width; - // We only want to consider ring-like objects so we need to discard everything else - if (radius > 1.0 || radius < innerRadius) { - discard; - } + // We only want to consider ring-like objects so we need to discard everything else + if (radius > 1.0 || radius < innerRadius) { + discard; + } - float consInner = conservativeBounds.x; - float consOuter = conservativeBounds.y; - bool outsideConservative = (radius < consInner) || (radius > consOuter); + float consInner = conservativeBounds.x; + float consOuter = conservativeBounds.y; + bool outsideConservative = (radius < consInner) || (radius > consOuter); - if (!showOptimistic && outsideConservative) { - discard; - } + if (!showOptimistic && outsideConservative) { + discard; + } - float texCoord = computeTextureCoord(radius, innerRadius, consInner, consOuter); + float texCoord = computeTextureCoord(radius, innerRadius, consInner, consOuter); - vec4 diffuse = texture(transferFunctionTexture, texCoord); - diffuse.a *= opacity; + vec4 diffuse = texture(transferFunctionTexture, texCoord); + diffuse.a *= opacity; - Fragment frag; - frag.color = diffuse; - frag.depth = vs_screenSpaceDepth; - return frag; + Fragment frag; + frag.color = diffuse; + frag.depth = vs_screenSpaceDepth; + return frag; } diff --git a/modules/space/shaders/habitablezone_vs.glsl b/modules/space/shaders/habitablezone_vs.glsl index d5796d62d9..599b4a2a8a 100644 --- a/modules/space/shaders/habitablezone_vs.glsl +++ b/modules/space/shaders/habitablezone_vs.glsl @@ -35,13 +35,13 @@ out float vs_screenSpaceDepth; uniform mat4 modelViewProjectionTransform; void main() { - vec4 position = vec4(in_position.xy, 0.0, 1.0); - vec4 positionScreenSpace = z_normalization(modelViewProjectionTransform * position); + vec4 position = vec4(in_position.xy, 0.0, 1.0); + vec4 positionScreenSpace = z_normalization(modelViewProjectionTransform * position); - // Moving the origin to the center - vs_st = (in_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vs_st = (in_st - vec2(0.5)) * 2.0; - vs_screenSpaceDepth = positionScreenSpace.w; + vs_screenSpaceDepth = positionScreenSpace.w; - gl_Position = positionScreenSpace; + gl_Position = positionScreenSpace; } diff --git a/modules/space/shaders/psfToTexture_fs.glsl b/modules/space/shaders/psfToTexture_fs.glsl index 288149d9b2..b4cba15cb2 100644 --- a/modules/space/shaders/psfToTexture_fs.glsl +++ b/modules/space/shaders/psfToTexture_fs.glsl @@ -24,7 +24,6 @@ #version __CONTEXT__ -//layout(location = 1) out vec4 renderTableColor; out vec4 renderTableColor; uniform int psfMethod; @@ -39,30 +38,32 @@ uniform float betaConstant; in vec2 psfCoords; +const int PsfMethodSpencer = 0; +const int PsfMethodMoffat = 1; + void main() { - vec4 fullColor = vec4(0.0, 0.0, 0.0, 1.0); - if (psfMethod == 0) { - // PSF Functions from paper: Physically-Based Galre Effects for Digital - // Images - Spencer, Shirley, Zimmerman and Greenberg. - float theta = sqrt((psfCoords.y*psfCoords.y + psfCoords.x*psfCoords.x)) * 90.0; - float f0 = 2.61E6 * exp(-pow(theta/alphaConst, 2.0)); - float f1 = 20.91/pow(theta + alphaConst, 3.0); - float f2 = 72.37/pow(theta + alphaConst, 2.0); - float psf_p = p0Param * f0 + p1Param * f1 + p2Param * f2; - fullColor = vec4(psf_p); - } - else if (psfMethod == 1) { - // Moffat - float r = sqrt((psfCoords.y*psfCoords.y + psfCoords.x*psfCoords.x)) * 90.0; - float alpha = FWHM / (2.f * sqrt(pow(2.f, 1.f/betaConstant) - 1)); - float moffat_psf = pow(1.f + (r/alpha)*(r/alpha), -betaConstant); - - fullColor = vec4(moffat_psf); - } - - if (fullColor.a == 0) { - discard; - } - - renderTableColor = fullColor; + vec4 fullColor = vec4(0.0, 0.0, 0.0, 1.0); + if (psfMethod == PsfMethodSpencer) { + // PSF Functions from paper: Physically-Based Galre Effects for Digital + // Images - Spencer, Shirley, Zimmerman and Greenberg. + float theta = sqrt((psfCoords.y * psfCoords.y + psfCoords.x * psfCoords.x)) * 90.0; + float f0 = 2.61E6 * exp(-pow(theta / alphaConst, 2.0)); + float f1 = 20.91 / pow(theta + alphaConst, 3.0); + float f2 = 72.37 / pow(theta + alphaConst, 2.0); + float spencer = p0Param * f0 + p1Param * f1 + p2Param * f2; + fullColor = vec4(spencer); +} + else if (psfMethod == PsfMethodMoffat) { + // Moffat + float r = sqrt((psfCoords.y * psfCoords.y + psfCoords.x * psfCoords.x)) * 90.0; + float alpha = FWHM / (2.0 * sqrt(pow(2.0, 1.0 / betaConstant) - 1.0)); + float moffat = pow(1.0 + (r/alpha) * (r/alpha), -betaConstant); + fullColor = vec4(moffat); + } + + if (fullColor.a == 0) { + discard; + } + + renderTableColor = fullColor; } diff --git a/modules/space/shaders/psfToTexture_vs.glsl b/modules/space/shaders/psfToTexture_vs.glsl index 03ae1f2ef5..e460cf80b8 100644 --- a/modules/space/shaders/psfToTexture_vs.glsl +++ b/modules/space/shaders/psfToTexture_vs.glsl @@ -29,6 +29,6 @@ layout(location = 0) in vec4 in_position; out vec2 psfCoords; void main() { - gl_Position = vec4(in_position.xy, 0.f, 1.f); - psfCoords = vec2(in_position); + gl_Position = vec4(in_position.xy, 0.0, 1.0); + psfCoords = vec2(in_position); } diff --git a/modules/space/shaders/rings_fs.glsl b/modules/space/shaders/rings_fs.glsl index 76c92cb733..b5fa7f35a2 100644 --- a/modules/space/shaders/rings_fs.glsl +++ b/modules/space/shaders/rings_fs.glsl @@ -38,61 +38,62 @@ uniform bool hasSunPosition; uniform vec3 sunPosition; uniform float _nightFactor; - Fragment getFragment() { - // Moving the origin to the center - vec2 st = (vs_st - vec2(0.5)) * 2.0; + // Moving the origin to the center + vec2 st = (vs_st - vec2(0.5)) * 2.0; - // The length of the texture coordinates vector is our distance from the center - float radius = length(st); + // The length of the texture coordinates vector is our distance from the center + float radius = length(st); - // We only want to consider ring-like objects so we need to discard everything else - if (radius > 1.0) - discard; + // We only want to consider ring-like objects so we need to discard everything else + if (radius > 1.0) { + discard; + } - // Remapping the texture coordinates - // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] - // textureOffset.x -> 0 - // textureOffset.y -> 1 - float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); - if (texCoord < 0.f || texCoord > 1.f) { - discard; - } - - vec4 diffuse = texture(texture1, texCoord); - // divided by 3 as length of vec3(1.0, 1.0, 1.0) will return 3 and we want - // to normalize the alpha value to [0,1] - float colorValue = length(diffuse.rgb) / 3.0; - if (colorValue < colorFilterValue) { - diffuse.a = colorValue * colorFilterValue; - if (diffuse.a < 0.65) - discard; + // Remapping the texture coordinates + // Radius \in [0,1], texCoord \in [textureOffset.x, textureOffset.y] + // textureOffset.x -> 0 + // textureOffset.y -> 1 + float texCoord = (radius - textureOffset.x) / (textureOffset.y - textureOffset.x); + if (texCoord < 0.0 || texCoord > 1.0) { + discard; + } + + vec4 diffuse = texture(texture1, texCoord); + // divided by 3 as length of vec3(1.0, 1.0, 1.0) will return 3 and we want + // to normalize the alpha value to [0,1] + float colorValue = length(diffuse.rgb) / 3.0; + if (colorValue < colorFilterValue) { + diffuse.a = colorValue * colorFilterValue; + if (diffuse.a < 0.65) { + discard; } + } - // The normal for the one plane depends on whether we are dealing - // with a front facing or back facing fragment - vec3 normal; - // The plane is oriented on the xz plane - // WARNING: This might not be the case for Uranus - if (gl_FrontFacing) { - normal = vec3(-1.0, 0.0, 0.0); - } - else { - normal = vec3(1.0, 0.0, 0.0); - } + // The normal for the one plane depends on whether we are dealing + // with a front facing or back facing fragment + vec3 normal; + // The plane is oriented on the xz plane + // WARNING: This might not be the case for Uranus + if (gl_FrontFacing) { + normal = vec3(-1.0, 0.0, 0.0); + } + else { + normal = vec3(1.0, 0.0, 0.0); + } - // Reduce the color of the fragment by the user factor - // if we are facing away from the Sun - if (dot(sunPosition, normal) < 0) { - diffuse.xyz *= _nightFactor; - } + // Reduce the color of the fragment by the user factor + // if we are facing away from the Sun + if (dot(sunPosition, normal) < 0) { + diffuse.xyz *= _nightFactor; + } - Fragment frag; - frag.color = diffuse; - frag.depth = vs_position.w; + Fragment frag; + frag.color = diffuse; + frag.depth = vs_position.w; - //frag.gPosition = vs_gPosition; - //frag.gNormal = vs_gNormal; + //frag.gPosition = vs_gPosition; + //frag.gNormal = vs_gNormal; - return frag; + return frag; } diff --git a/modules/space/shaders/rings_vs.glsl b/modules/space/shaders/rings_vs.glsl index c81afe6f9d..788298015f 100644 --- a/modules/space/shaders/rings_vs.glsl +++ b/modules/space/shaders/rings_vs.glsl @@ -31,16 +31,14 @@ layout(location = 1) in vec2 in_st; out vec2 vs_st; out vec4 vs_position; -//out vec4 vs_gPosition; -//out vec3 vs_gNormal; uniform mat4 modelViewProjectionTransform; void main() { - vs_st = in_st; + vs_st = in_st; - vs_position = z_normalization( - modelViewProjectionTransform * vec4(in_position.xy, 0.0, 1.0) - ); - gl_Position = vs_position; + vs_position = z_normalization( + modelViewProjectionTransform * vec4(in_position.xy, 0.0, 1.0) + ); + gl_Position = vs_position; } diff --git a/modules/space/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl index 24ac77cf6f..166c2515aa 100644 --- a/modules/space/shaders/star_fs.glsl +++ b/modules/space/shaders/star_fs.glsl @@ -51,60 +51,60 @@ flat in float ge_speed; flat in float gs_screenSpaceDepth; vec4 bv2rgb(float bv) { - // BV is [-0.4,2.0] - float t = (bv + 0.4) / (2.0 + 0.4); - return texture(colorTexture, t); + // BV is [-0.4,2.0] + float t = (bv + 0.4) / (2.0 + 0.4); + return texture(colorTexture, t); } bool isOtherDataValueInRange() { - float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); - return t >= 0.0 && t <= 1.0; + float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); + return t >= 0.0 && t <= 1.0; } vec4 otherDataValue() { - float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); - t = clamp(t, 0.0, 1.0); - return texture(otherDataTexture, t); + float t = (ge_bv - otherDataRange.x) / (otherDataRange.y - otherDataRange.x); + t = clamp(t, 0.0, 1.0); + return texture(otherDataTexture, t); } Fragment getFragment() { - vec4 color = vec4(0.0); - switch (colorOption) { - case ColorOptionColor: - color = bv2rgb(ge_bv); - break; - case ColorOptionVelocity: - color = vec4(abs(ge_velocity), 0.5); - break; - case ColorOptionSpeed: - // @TODO Include a transfer function here ---abock - color = vec4(vec3(ge_speed), 0.5); - break; - case ColorOptionOtherData: - if (filterOutOfRange && !isOtherDataValueInRange()) { - discard; - } - else { - color = otherDataValue(); - } - break; - case ColorOptionFixedColor: - color = vec4(fixedColor, 1.0); - break; - } - - vec4 textureColor = texture(psfTexture, texCoords); - vec4 fullColor = vec4(color.rgb, textureColor.a * alphaValue); - - if (fullColor.a < 0.001) { + vec4 color = vec4(0.0); + switch (colorOption) { + case ColorOptionColor: + color = bv2rgb(ge_bv); + break; + case ColorOptionVelocity: + color = vec4(abs(ge_velocity), 0.5); + break; + case ColorOptionSpeed: + // @TODO Include a transfer function here ---abock + color = vec4(vec3(ge_speed), 0.5); + break; + case ColorOptionOtherData: + if (filterOutOfRange && !isOtherDataValueInRange()) { discard; - } + } + else { + color = otherDataValue(); + } + break; + case ColorOptionFixedColor: + color = vec4(fixedColor, 1.0); + break; + } - Fragment frag; - frag.color = fullColor; - frag.depth = gs_screenSpaceDepth; - frag.gPosition = vec4(vs_position, 1.0); - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); - frag.disableLDR2HDR = true; - - return frag; + vec4 textureColor = texture(psfTexture, texCoords); + vec4 fullColor = vec4(color.rgb, textureColor.a * alphaValue); + + if (fullColor.a < 0.001) { + discard; + } + + Fragment frag; + frag.color = fullColor; + frag.depth = gs_screenSpaceDepth; + frag.gPosition = vec4(vs_position, 1.0); + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + frag.disableLDR2HDR = true; + + return frag; } diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index 0c832f69f6..36c8ad316b 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -70,155 +70,155 @@ const float SunAbsMagnitude = 4.83; const float SunRadius = 6.957E8; // meters float bvToKelvin(float bv) { - float tmp = 0.92 * bv; - return 4600 * (1.f / (tmp + 1.7) + 1.f / (tmp + 0.62)); + float tmp = 0.92 * bv; + return 4600 * (1.0 / (tmp + 1.7) + 1.0 / (tmp + 0.62)); } double scaleForApparentBrightness(dvec3 dpos, float luminance) { - // Working like Partiview - double pSize = pow(10, 29.0 + magnitudeExponent); - float luminosity = luminance * 10.0; - double distanceToStar = length(dpos - eyePosition); - return (pSize * luminosity) / distanceToStar; + // Working like Partiview + double pSize = pow(10, 29.0 + magnitudeExponent); + float luminosity = luminance * 10.0; + double distanceToStar = length(dpos - eyePosition); + return (pSize * luminosity) / distanceToStar; } double scaleForLuminositySize(float bv, float luminance, float absMagnitude) { - double adjustedLuminance = luminance + 5E9; - float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); - float temperature = bvToKelvin(bv); - float relativeTemperature = SunTemperature / temperature; - double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); - return (lumCent * adjustedLuminance + (radiusCent * starRadius)) * pow(10.0, magnitudeExponent); + double adjustedLuminance = luminance + 5E9; + float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); + float temperature = bvToKelvin(bv); + float relativeTemperature = SunTemperature / temperature; + double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); + return (lumCent * adjustedLuminance + (radiusCent * starRadius)) * pow(10.0, magnitudeExponent); } double scaleForLuminositySizeAppBrightness(dvec3 dpos, float bv, float luminance, float absMagnitude) { - double luminosity = double(1.0 - luminance); - double distanceToStarInParsecs = trunc(length(dpos - eyePosition) / PARSEC); - double apparentBrightness = luminosity / distanceToStarInParsecs; - float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); - float temperature = bvToKelvin(bv); - float relativeTemperature = SunTemperature / temperature; - double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); + double luminosity = double(1.0 - luminance); + double distanceToStarInParsecs = trunc(length(dpos - eyePosition) / PARSEC); + double apparentBrightness = luminosity / distanceToStarInParsecs; + float L_over_Lsun = pow(2.51, SunAbsMagnitude - absMagnitude); + float temperature = bvToKelvin(bv); + float relativeTemperature = SunTemperature / temperature; + double starRadius = SunRadius * pow(relativeTemperature, 2.0) * sqrt(L_over_Lsun); - double scaledLuminance = lumCent * (luminance + 5E9); - double scaledStarRadius = radiusCent * starRadius; - double scaledBrightness = brightnessCent * apparentBrightness * 5E15; - return (scaledLuminance + scaledStarRadius + scaledBrightness) * pow(10.0, magnitudeExponent); + double scaledLuminance = lumCent * (luminance + 5E9); + double scaledStarRadius = radiusCent * starRadius; + double scaledBrightness = brightnessCent * apparentBrightness * 5E15; + return (scaledLuminance + scaledStarRadius + scaledBrightness) * pow(10.0, magnitudeExponent); } double scaleForAbsoluteMagnitude(float absMagnitude) { - return (-absMagnitude + 35) * pow(10.0, magnitudeExponent + 8.5); + return (-absMagnitude + 35) * pow(10.0, magnitudeExponent + 8.5); } double scaleForApparentMagnitude(dvec3 dpos, float absMag) { - double distanceToStarInMeters = length(dpos - eyePosition); - double distanceToCenterInMeters = length(eyePosition); - float distanceToStarInParsecs = float(distanceToStarInMeters/PARSEC); - //float appMag = absMag + 5*log(distanceToStarInParsecs) - 5.0; - float appMag = absMag + 5.0 * (log(distanceToStarInParsecs/10.0)/log(2.0)); - //appMag = vs_bvLumAbsMagAppMag[0].w; + double distanceToStarInMeters = length(dpos - eyePosition); + double distanceToCenterInMeters = length(eyePosition); + float distanceToStarInParsecs = float(distanceToStarInMeters/PARSEC); + //float appMag = absMag + 5*log(distanceToStarInParsecs) - 5.0; + float appMag = absMag + 5.0 * (log(distanceToStarInParsecs/10.0)/log(2.0)); + //appMag = vs_bvLumAbsMagAppMag[0].w; - //scaleMultiply = (30.623 - appMag) * pow(10.0, magnitudeExponent + 7.0);// * - //float(distanceToStarInMeters/distanceToCenterInMeters); + //scaleMultiply = (30.623 - appMag) * pow(10.0, magnitudeExponent + 7.0);// * + //float(distanceToStarInMeters/distanceToCenterInMeters); - return (-appMag + 50.f) * pow(10.0, magnitudeExponent + 7.5f); - // return log(35.f + appMag) * pow(10.0, magnitudeExponent + 6.5f); - // return exp((35.f - appMag) * 0.2) * pow(10.0, magnitudeExponent + 2.5f); - // return appMag * pow(10.0, magnitudeExponent + 8.5f); - // return exp((-30.0 - appMag) * 0.45) * pow(10.0, magnitudeExponent + 8.f); - // return pow(10.0, (appMag - absMag)*(1.0/5.0) + 1.0) * pow(10.0, magnitudeExponent + 3.f); + return (-appMag + 50.0) * pow(10.0, magnitudeExponent + 7.5); + // return log(35.f + appMag) * pow(10.0, magnitudeExponent + 6.5f); + // return exp((35.f - appMag) * 0.2) * pow(10.0, magnitudeExponent + 2.5f); + // return appMag * pow(10.0, magnitudeExponent + 8.5f); + // return exp((-30.0 - appMag) * 0.45) * pow(10.0, magnitudeExponent + 8.f); + // return pow(10.0, (appMag - absMag)*(1.0/5.0) + 1.0) * pow(10.0, magnitudeExponent + 3.f); } double scaleForDistanceModulus(float absMag) { - return exp((-30.623 - absMag) * 0.462) * pow(10.0, magnitudeExponent + 12.5) * 2000; + return exp((-30.623 - absMag) * 0.462) * pow(10.0, magnitudeExponent + 12.5) * 2000; } void main() { - vec3 pos = gl_in[0].gl_Position.xyz; - vs_position = pos; // in object space - dvec4 dpos = modelMatrix * dvec4(pos, 1.0); + vec3 pos = gl_in[0].gl_Position.xyz; + vs_position = pos; // in object space + dvec4 dpos = modelMatrix * dvec4(pos, 1.0); - ge_bv = vs_bvLumAbsMagAppMag[0].x; - ge_velocity = vs_velocity[0]; - ge_speed = vs_speed[0]; + ge_bv = vs_bvLumAbsMagAppMag[0].x; + ge_velocity = vs_velocity[0]; + ge_speed = vs_speed[0]; - double scaleMultiply = 1.0; + double scaleMultiply = 1.0; - if (psfParamConf == SizeCompositionOptionAppBrightness) { - float luminance = vs_bvLumAbsMagAppMag[0].y; + if (psfParamConf == SizeCompositionOptionAppBrightness) { + float luminance = vs_bvLumAbsMagAppMag[0].y; - scaleMultiply = scaleForApparentBrightness(dpos.xyz, luminance); - } - else if (psfParamConf == SizeCompositionOptionLumSize) { - float bv = vs_bvLumAbsMagAppMag[0].x; - float luminance = vs_bvLumAbsMagAppMag[0].y; - float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + scaleMultiply = scaleForApparentBrightness(dpos.xyz, luminance); + } + else if (psfParamConf == SizeCompositionOptionLumSize) { + float bv = vs_bvLumAbsMagAppMag[0].x; + float luminance = vs_bvLumAbsMagAppMag[0].y; + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - scaleMultiply = scaleForLuminositySize(bv, luminance, absMagnitude); - } - else if (psfParamConf == SizeCompositionOptionLumSizeAppBrightness) { - float bv = vs_bvLumAbsMagAppMag[0].x; - float luminance = vs_bvLumAbsMagAppMag[0].y; - float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + scaleMultiply = scaleForLuminositySize(bv, luminance, absMagnitude); + } + else if (psfParamConf == SizeCompositionOptionLumSizeAppBrightness) { + float bv = vs_bvLumAbsMagAppMag[0].x; + float luminance = vs_bvLumAbsMagAppMag[0].y; + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - scaleMultiply = scaleForLuminositySizeAppBrightness(dpos.xyz, bv, luminance, absMagnitude); - } - else if (psfParamConf == SizeCompositionOptionLumSizeAbsMagnitude) { - float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + scaleMultiply = scaleForLuminositySizeAppBrightness(dpos.xyz, bv, luminance, absMagnitude); + } + else if (psfParamConf == SizeCompositionOptionLumSizeAbsMagnitude) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - scaleMultiply = scaleForAbsoluteMagnitude(absMagnitude); - } - else if (psfParamConf == SizeCompositionOptionLumSizeAppMagnitude) { - float absMagnitude = vs_bvLumAbsMagAppMag[0].z; + scaleMultiply = scaleForAbsoluteMagnitude(absMagnitude); + } + else if (psfParamConf == SizeCompositionOptionLumSizeAppMagnitude) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - scaleMultiply = scaleForApparentMagnitude(dpos.xyz, absMagnitude); - } - else if (psfParamConf == SizeCompositionOptionLumSizeDistanceModulus) { - float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - - scaleMultiply = scaleForDistanceModulus(absMagnitude); - } - - dvec3 normal = eyePosition - dpos.xyz; - dvec3 newRight = normalize(cross(cameraUp, normal)); - dvec3 newUp = normalize(cross(normal, newRight)); - dvec3 scaledRight = scaleMultiply * newRight; - dvec3 scaledUp = scaleMultiply * newUp; + scaleMultiply = scaleForApparentMagnitude(dpos.xyz, absMagnitude); + } + else if (psfParamConf == SizeCompositionOptionLumSizeDistanceModulus) { + float absMagnitude = vs_bvLumAbsMagAppMag[0].z; - vec4 lowerLeft = z_normalization( - vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w)) - ); - - vec4 upperRight = z_normalization( - vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w)) - ); + scaleMultiply = scaleForDistanceModulus(absMagnitude); + } - vec4 lowerRight = z_normalization( - vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w)) - ); - - vec4 upperLeft = z_normalization( - vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w)) - ); + dvec3 normal = eyePosition - dpos.xyz; + dvec3 newRight = normalize(cross(cameraUp, normal)); + dvec3 newUp = normalize(cross(normal, newRight)); + dvec3 scaledRight = scaleMultiply * newRight; + dvec3 scaledUp = scaleMultiply * newUp; + + vec4 lowerLeft = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w)) + ); + + vec4 upperRight = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w)) + ); - gs_screenSpaceDepth = lowerLeft.w; + vec4 lowerRight = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w)) + ); + + vec4 upperLeft = z_normalization( + vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w)) + ); - // Build primitive - gl_Position = lowerLeft; - texCoords = vec2(0.0, 0.0); - EmitVertex(); - - gl_Position = lowerRight; - texCoords = vec2(1.0,0.0); - EmitVertex(); + gs_screenSpaceDepth = lowerLeft.w; - gl_Position = upperLeft; - texCoords = vec2(0.0, 1.0); - EmitVertex(); - - gl_Position = upperRight; - texCoords = vec2(1.0, 1.0); - EmitVertex(); - - EndPrimitive(); + // Build primitive + gl_Position = lowerLeft; + texCoords = vec2(0.0, 0.0); + EmitVertex(); + + gl_Position = lowerRight; + texCoords = vec2(1.0,0.0); + EmitVertex(); + + gl_Position = upperLeft; + texCoords = vec2(0.0, 1.0); + EmitVertex(); + + gl_Position = upperRight; + texCoords = vec2(1.0, 1.0); + EmitVertex(); + + EndPrimitive(); } diff --git a/modules/space/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl index 3213cbc96a..d03a9be2ad 100644 --- a/modules/space/shaders/star_vs.glsl +++ b/modules/space/shaders/star_vs.glsl @@ -34,9 +34,9 @@ out vec3 vs_velocity; out float vs_speed; void main() { - vs_bvLumAbsMagAppMag = in_bvLumAbsMagAppMag; - vs_velocity = in_velocity; - vs_speed = in_speed; + vs_bvLumAbsMagAppMag = in_bvLumAbsMagAppMag; + vs_velocity = in_velocity; + vs_speed = in_speed; - gl_Position = vec4(in_position, 1.0); + gl_Position = vec4(in_position, 1.0); } diff --git a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp index 84debee14f..1e1eceba13 100644 --- a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp +++ b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp @@ -39,22 +39,6 @@ #include namespace { - constexpr const char* KeyFontMono = "Mono"; - constexpr const float DefaultFontSize = 10.f; - - constexpr openspace::properties::Property::PropertyInfo FontNameInfo = { - "FontName", - "Font Name", - "This value is the name of the font that is used. It can either refer to an " - "internal name registered previously, or it can refer to a path that is used." - }; - - constexpr openspace::properties::Property::PropertyInfo FontSizeInfo = { - "FontSize", - "Font Size", - "This value determines the size of the font that is used to render the date." - }; - constexpr openspace::properties::Property::PropertyInfo ActiveColorInfo = { "ActiveColor", "Active Color", @@ -89,12 +73,6 @@ namespace { } struct [[codegen::Dictionary(DashboardItemInstruments)]] Parameters { - // [[codegen::verbatim(FontNameInfo.description)]] - std::optional fontName; - - // [[codegen::verbatim(FontSizeInfo.description)]] - std::optional fontSize; - // [[codegen::verbatim(ActiveColorInfo.description)]] std::optional activeColor [[codegen::color()]]; @@ -113,9 +91,7 @@ documentation::Documentation DashboardItemInstruments::Documentation() { } DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dictionary) - : DashboardItem(dictionary) - , _fontName(FontNameInfo, KeyFontMono) - , _fontSize(FontSizeInfo, DefaultFontSize, 6.f, 144.f, 1.f) + : DashboardTextItem(dictionary) , _activeColor( ActiveColorInfo, glm::vec3(0.6f, 1.f, 0.f), @@ -127,28 +103,13 @@ DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dict glm::vec3(0.f), glm::vec3(1.f) ) - , _font(global::fontManager->font(KeyFontMono, 10)) { const Parameters p = codegen::bake(dictionary); - _fontName = p.fontName.value_or(_fontName); - _fontName.onChange([this]() { - _font = global::fontManager->font(_fontName, _fontSize); - }); - addProperty(_fontName); - - _fontSize = p.fontSize.value_or(_fontSize); - _fontSize.onChange([this]() { - _font = global::fontManager->font(_fontName, _fontSize); - }); - addProperty(_fontSize); - _activeColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_activeColor); _activeFlash.setViewOption(properties::Property::ViewOptions::Color); addProperty(_activeFlash); - - _font = global::fontManager->font(_fontName, _fontSize); } void DashboardItemInstruments::render(glm::vec2& penPosition) { @@ -163,14 +124,14 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { penPosition.y -= 25.f; - glm::vec4 targetColor(0.f, 0.75f, 1.f, 1.f); + constexpr const glm::vec4 targetColor(0.f, 0.75f, 1.f, 1.f); + double previous = sequencer.prevCaptureTime(currentTime); + double next = sequencer.nextCaptureTime(currentTime); double remaining = sequencer.nextCaptureTime(currentTime) - currentTime; - const float t = static_cast( - 1.0 - remaining / sequencer.intervalLength(currentTime) - ); + const float t = static_cast(1.0 - remaining / (next - previous)); - if (remaining > 0) { + if (remaining > 0.0) { RenderFont( *_font, penPosition, @@ -235,8 +196,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { *_font, penPosition, fmt::format( - "Next image: [{:02d}:{:02d}:{:02d}]", - tlh.count(), tlm.count(), tls.count() + "Next image: [{:02d}:{:02d}:{:02d}]", tlh.count(), tlm.count(), tls.count() ), targetColor, ghoul::fontrendering::CrDirection::Down @@ -247,7 +207,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { const std::vector>& activeMap = sequencer.activeInstruments(currentTime); - glm::vec4 firing(0.58f - t, 1.f - t, 1.f - t, 1.f); + glm::vec4 firing = glm::vec4(0.58f - t, 1.f - t, 1.f - t, 1.f); RenderFont( *_font, @@ -286,7 +246,6 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { glm::vec2 DashboardItemInstruments::size() const { glm::vec2 size = glm::vec2(0.f); - //return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( double currentTime = global::timeManager->time().j2000Seconds(); if (!ImageSequencer::ref().isReady()) { @@ -294,24 +253,20 @@ glm::vec2 DashboardItemInstruments::size() const { } ImageSequencer& sequencer = ImageSequencer::ref(); - const double remaining = sequencer.nextCaptureTime(currentTime) - currentTime; - const float t = static_cast( - 1.0 - remaining / sequencer.intervalLength(currentTime) - ); + double previous = sequencer.prevCaptureTime(currentTime); + double next = sequencer.nextCaptureTime(currentTime); + double remaining = sequencer.nextCaptureTime(currentTime) - currentTime; + const float t = static_cast(1.0 - remaining / (next - previous)); const std::string& str = SpiceManager::ref().dateFromEphemerisTime( sequencer.nextCaptureTime(currentTime), "YYYY MON DD HR:MN:SC" ); - - if (remaining > 0) { + if (remaining > 0.0) { std::string progress = progressToStr(25, t); - size = addToBoundingbox( - size, - _font->boundingBox("Next instrument activity:") - ); + size = addToBoundingbox(size, _font->boundingBox("Next instrument activity:")); size = addToBoundingbox( size, @@ -322,9 +277,7 @@ glm::vec2 DashboardItemInstruments::size() const { size = addToBoundingbox( size, - _font->boundingBox( - fmt::format("Data acquisition time: {}", str) - ) + _font->boundingBox(fmt::format("Data acquisition time: {}", str)) ); } std::pair nextTarget = sequencer.nextTarget(currentTime); @@ -368,10 +321,7 @@ glm::vec2 DashboardItemInstruments::size() const { size.y += _font->height(); - size = addToBoundingbox( - size, - _font->boundingBox("Active Instruments:") - ); + size = addToBoundingbox(size, _font->boundingBox("Active Instruments:")); return size; } diff --git a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.h b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.h index 06be3f5dd9..a08c2b96dc 100644 --- a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.h +++ b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.h @@ -25,19 +25,15 @@ #ifndef __OPENSPACE_MODULE_SPACECRAFTINSTRUMENTS___DASHBOARDITEMINSTRUMENTS___H__ #define __OPENSPACE_MODULE_SPACECRAFTINSTRUMENTS___DASHBOARDITEMINSTRUMENTS___H__ -#include +#include #include #include #include -namespace ghoul::fontrendering { class Font; } - namespace openspace { -namespace documentation { struct Documentation; } - -class DashboardItemInstruments : public DashboardItem { +class DashboardItemInstruments : public DashboardTextItem { public: DashboardItemInstruments(const ghoul::Dictionary& dictionary); ~DashboardItemInstruments() = default; @@ -49,13 +45,8 @@ public: static documentation::Documentation Documentation(); private: - properties::StringProperty _fontName; - properties::FloatProperty _fontSize; - properties::Vec3Property _activeColor; properties::Vec3Property _activeFlash; - - std::shared_ptr _font; }; } // namespace openspace diff --git a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp index 1ed8bfcddd..1d3071ef0d 100644 --- a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp +++ b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp @@ -31,10 +31,8 @@ #include #include #include -#include #include #include -#include namespace { struct VBOData { @@ -120,7 +118,7 @@ void RenderableCrawlingLine::initializeGL() { GL_FLOAT, GL_FALSE, sizeof(VBOData), - reinterpret_cast(offsetof(VBOData, color)) // NOLINT + reinterpret_cast(offsetof(VBOData, color)) ); glBindVertexArray(0); @@ -147,8 +145,8 @@ void RenderableCrawlingLine::render(const RenderData& data, RendererTasks&) { _frameCounter++; glm::dmat4 modelTransform = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation - glm::dmat4(data.modelTransform.rotation) * // Spice rotation + 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)); glm::dmat4 modelViewProjectionTransform = data.camera.projectionMatrix() * @@ -162,10 +160,9 @@ void RenderableCrawlingLine::render(const RenderData& data, RendererTasks&) { glLineWidth(2.f); - _program->setUniform("_alpha", alpha); + _program->setUniform("alpha", alpha); glBindVertexArray(_vao); - glDrawArrays(GL_LINES, 0, 2); glBindVertexArray(0); @@ -204,20 +201,15 @@ 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); if (ImageSequencer::ref().isReady()) { - _imageSequenceTime = ImageSequencer::ref().instrumentActiveTime( + float imageSequenceTime = ImageSequencer::ref().instrumentActiveTime( data.time.j2000Seconds(), _instrumentName ); - _drawLine = _imageSequenceTime != -1.f; + _drawLine = (imageSequenceTime != -1.f); } } diff --git a/modules/spacecraftinstruments/rendering/renderablecrawlingline.h b/modules/spacecraftinstruments/rendering/renderablecrawlingline.h index 4f9c0a41cb..02c493f896 100644 --- a/modules/spacecraftinstruments/rendering/renderablecrawlingline.h +++ b/modules/spacecraftinstruments/rendering/renderablecrawlingline.h @@ -54,7 +54,6 @@ private: std::string _instrumentName; std::string _source; std::string _target; - std::string _referenceFrame; glm::vec4 _lineColorBegin = glm::vec4(0.f); glm::vec4 _lineColorEnd = glm::vec4(0.f); @@ -62,7 +61,6 @@ private: int _frameCounter = 0; bool _drawLine = false; - float _imageSequenceTime = -1.f; GLuint _vao = 0; GLuint _vbo = 0; diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index 30e0753aa5..3894fbeb42 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -41,13 +41,12 @@ namespace { constexpr const char* ProgramName = "FovProgram"; constexpr const std::array UniformNames = { - "modelViewProjectionTransform", "defaultColorStart", "defaultColorEnd", + "modelViewProjectionTransform", "colorStart", "colorEnd", "activeColor", "targetInFieldOfViewColor", "intersectionStartColor", "intersectionEndColor", "squareColor", "interpolation" }; constexpr const int InterpolationSteps = 5; - constexpr const double Epsilon = 1e-4; constexpr openspace::properties::Property::PropertyInfo LineWidthInfo = { @@ -145,6 +144,7 @@ namespace { return 0.5 * bisect(p1, half, testFunction, half); } } + // Needs support for std::map first for the frameConversions struct [[codegen::Dictionary(RenderableFov)]] Parameters { // The SPICE name of the source body for which the field of view should be @@ -197,37 +197,15 @@ documentation::Documentation RenderableFov::Documentation() { return doc; } - RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _lineWidth(LineWidthInfo, 1.f, 1.f, 20.f) - , _drawSolid(DrawSolidInfo, false) , _standOffDistance(StandoffDistanceInfo, 0.9999, 0.99, 1.0, 0.000001) , _colors({ - { - DefaultStartColorInfo, - glm::vec3(0.4f), - glm::vec3(0.f), - glm::vec3(1.f) - }, - { - DefaultEndColorInfo, - glm::vec3(0.85f), - glm::vec3(0.f), - glm::vec3(1.f) - }, - { - ActiveColorInfo, - glm::vec3(0.f, 1.f, 0.f), - glm::vec3(0.f), - glm::vec3(1.f) - }, - { - TargetInFovInfo, - glm::vec3(0.f, 0.5f, 0.7f), - glm::vec3(0.f), - glm::vec3(1.f) - }, + { DefaultStartColorInfo, glm::vec3(0.4f), glm::vec3(0.f), glm::vec3(1.f) }, + { DefaultEndColorInfo, glm::vec3(0.85f), glm::vec3(0.f), glm::vec3(1.f) }, + { ActiveColorInfo, glm::vec3(0.f, 1.f, 0.f), glm::vec3(0.f), glm::vec3(1.f) }, + { TargetInFovInfo, glm::vec3(0.f, 0.5f, 0.7f), glm::vec3(0.f), glm::vec3(1.f) }, { IntersectionStartInfo, glm::vec3(1.f, 0.89f, 0.f), @@ -240,12 +218,7 @@ RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) glm::vec3(0.f), glm::vec3(1.f) }, - { - SquareColorInfo, - glm::vec3(0.85f), - glm::vec3(0.f), - glm::vec3(1.f) - } + { SquareColorInfo, glm::vec3(0.85f), glm::vec3(0.f), glm::vec3(1.f) } }) { const Parameters p = codegen::bake(dictionary); @@ -278,8 +251,6 @@ RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) _simplifyBounds = p.simplifyBounds.value_or(_simplifyBounds); - addProperty(_drawSolid); - addProperty(_colors.defaultStart); addProperty(_colors.defaultEnd); addProperty(_colors.active); @@ -290,17 +261,16 @@ RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) } void RenderableFov::initializeGL() { - _program = - SpacecraftInstrumentsModule::ProgramObjectManager.request( - ProgramName, - []() -> std::unique_ptr { - return global::renderEngine->buildRenderProgram( - ProgramName, - absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_vs.glsl"), - absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_fs.glsl") - ); - } - ); + _program = SpacecraftInstrumentsModule::ProgramObjectManager.request( + ProgramName, + []() -> std::unique_ptr { + return global::renderEngine->buildRenderProgram( + ProgramName, + absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_vs.glsl"), + absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_fs.glsl") + ); + } + ); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); @@ -402,7 +372,7 @@ void RenderableFov::initializeGL() { 1, GL_INT, sizeof(RenderInformation::VBOData), - reinterpret_cast(offsetof(RenderInformation::VBOData, color)) // NOLINT + reinterpret_cast(offsetof(RenderInformation::VBOData, color)) ); // Orthogonal Plane @@ -432,7 +402,7 @@ void RenderableFov::initializeGL() { 1, GL_INT, sizeof(RenderInformation::VBOData), - reinterpret_cast(offsetof(RenderInformation::VBOData, color)) // NOLINT + reinterpret_cast(offsetof(RenderInformation::VBOData, color)) ); glBindVertexArray(0); @@ -478,7 +448,7 @@ glm::dvec3 RenderableFov::orthogonalProjection(const glm::dvec3& vecFov, double return p * 1000.0; // km -> m } -void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& target, +void RenderableFov::computeIntercepts(double time, const std::string& target, bool isInFov) { auto makeBodyFixedReferenceFrame = @@ -488,22 +458,16 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& if (convert) { SpacecraftInstrumentsModule* m = global::moduleEngine->module(); - return { - m->frameFromBody(target), - true - }; + return { m->frameFromBody(target), true }; } else { return { ref, false }; } }; - //std::vector intersects(_instrument.bounds.size()); - // 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 and not - // continue + // distance) as the field of view rendering should stop at the surface for (size_t i = 0; i < _instrument.bounds.size(); ++i) { const glm::dvec3& bound = _instrument.bounds[i]; @@ -517,11 +481,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& if (!isInFov) { // If the target is not in the field of view, we don't need to perform any // surface intercepts - const glm::vec3 o = orthogonalProjection( - bound, - data.time.j2000Seconds(), - target - ); + const glm::vec3 o = orthogonalProjection(bound, time, target); second = { { o.x, o.y, o.z }, @@ -542,12 +502,10 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& _instrument.name, ref.first, _instrument.aberrationCorrection, - data.time.j2000Seconds(), + time, bound ); - //intersects[i] = r.interceptFound; - if (r.interceptFound) { // This point intersected the target first.color = RenderInformation::VertexColorTypeIntersectionStart; @@ -558,7 +516,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& r.surfaceVector = SpiceManager::ref().frameTransformationMatrix( ref.first, _instrument.referenceFrame, - data.time.j2000Seconds() + time ) * r.surfaceVector; } @@ -575,11 +533,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& } else { // This point did not intersect the target though others did - const glm::vec3 o = orthogonalProjection( - bound, - data.time.j2000Seconds(), - target - ); + const glm::vec3 o = orthogonalProjection(bound, time, target); second = { { o.x, o.y, o.z }, RenderInformation::VertexColorTypeInFieldOfView @@ -593,9 +547,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& // earlier // Each boundary in _instrument.bounds has 'InterpolationSteps' steps between - auto indexForBounds = [](size_t idx) -> size_t { - return idx * InterpolationSteps; - }; + auto indexForBounds = [](size_t idx) -> size_t { return idx * InterpolationSteps; }; auto copyFieldOfViewValues = [&](size_t iBound, size_t begin, size_t end) -> void { std::fill( @@ -630,7 +582,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& _instrument.name, makeBodyFixedReferenceFrame(_instrument.referenceFrame).first, _instrument.aberrationCorrection, - data.time.j2000Seconds(), + time, probe ).interceptFound; }; @@ -646,7 +598,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& _instrument.name, ref.first, _instrument.aberrationCorrection, - data.time.j2000Seconds(), + time, probe ); @@ -654,7 +606,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& r.surfaceVector = SpiceManager::ref().frameTransformationMatrix( ref.first, _instrument.referenceFrame, - data.time.j2000Seconds() + time ) * r.surfaceVector; } @@ -675,12 +627,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& }; } else { - const glm::vec3 o = orthogonalProjection( - tBound, - data.time.j2000Seconds(), - target - ); - + const glm::vec3 o = orthogonalProjection(tBound, time, target); _orthogonalPlane.data[indexForBounds(i) + m] = { { o.x, o.y, o.z }, RenderInformation::VertexColorTypeSquare @@ -707,7 +654,7 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& _instrument.name, makeBodyFixedReferenceFrame(_instrument.referenceFrame).first, _instrument.aberrationCorrection, - data.time, + time, probe ).interceptFound; }; @@ -787,61 +734,52 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& } void RenderableFov::render(const RenderData& data, RendererTasks&) { - if (_drawFOV) { - _program->activate(); - - // Model transform and view transform needs to be in double precision - 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)); - - glm::mat4 modelViewProjectionTransform = - data.camera.projectionMatrix() * - glm::mat4(data.camera.combinedViewMatrix() * modelTransform); - - _program->setUniform( - _uniformCache.modelViewProjection, - modelViewProjectionTransform - ); - - _program->setUniform(_uniformCache.defaultColorStart, _colors.defaultStart); - _program->setUniform(_uniformCache.defaultColorEnd, _colors.defaultEnd); - _program->setUniform(_uniformCache.activeColor, _colors.active); - _program->setUniform( - _uniformCache.targetInFieldOfViewColor, - _colors.targetInFieldOfView - ); - _program->setUniform( - _uniformCache.intersectionStartColor, - _colors.intersectionStart - ); - _program->setUniform( - _uniformCache.intersectionEndColor, - _colors.intersectionEnd - ); - _program->setUniform(_uniformCache.squareColor, _colors.square); - _program->setUniform(_uniformCache.interpolation, _interpolationTime); - - GLenum mode = _drawSolid ? GL_TRIANGLE_STRIP : GL_LINES; - - glLineWidth(_lineWidth); - glBindVertexArray(_fieldOfViewBounds.vao); - glDrawArrays(mode, 0, static_cast(_fieldOfViewBounds.data.size())); - - glLineWidth(2.f); - glBindVertexArray(_orthogonalPlane.vao); - glDrawArrays(GL_LINE_LOOP, 0, static_cast(_orthogonalPlane.data.size())); - glBindVertexArray(0); - glLineWidth(1.f); - - _program->deactivate(); + if (!_drawFOV) { + return; } + + _program->activate(); + + // Model transform and view transform needs to be in double precision + 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)); + + glm::mat4 modelViewProjectionTransform = + data.camera.projectionMatrix() * + glm::mat4(data.camera.combinedViewMatrix() * modelTransform); + + _program->setUniform(_uniformCache.modelViewProjection, modelViewProjectionTransform); + + _program->setUniform(_uniformCache.defaultColorStart, _colors.defaultStart); + _program->setUniform(_uniformCache.defaultColorEnd, _colors.defaultEnd); + _program->setUniform(_uniformCache.activeColor, _colors.active); + _program->setUniform( + _uniformCache.targetInFieldOfViewColor, + _colors.targetInFieldOfView + ); + _program->setUniform(_uniformCache.intersectionStartColor, _colors.intersectionStart); + _program->setUniform(_uniformCache.intersectionEndColor, _colors.intersectionEnd); + _program->setUniform(_uniformCache.squareColor, _colors.square); + _program->setUniform(_uniformCache.interpolation, _interpolationTime); + + glLineWidth(_lineWidth); + glBindVertexArray(_fieldOfViewBounds.vao); + glDrawArrays(GL_LINES, 0, static_cast(_fieldOfViewBounds.data.size())); + + glLineWidth(2.f); + glBindVertexArray(_orthogonalPlane.vao); + glDrawArrays(GL_LINE_LOOP, 0, static_cast(_orthogonalPlane.data.size())); + glBindVertexArray(0); + glLineWidth(1.f); + + _program->deactivate(); } void RenderableFov::update(const UpdateData& data) { _drawFOV = false; - if (openspace::ImageSequencer::ref().isReady()) { + if (ImageSequencer::ref().isReady()) { _drawFOV = ImageSequencer::ref().isInstrumentActive( data.time.j2000Seconds(), _instrument.name @@ -852,7 +790,7 @@ void RenderableFov::update(const UpdateData& data) { if (_drawFOV /* && time changed */) { const std::pair& t = determineTarget(data.time.j2000Seconds()); - computeIntercepts(data, t.first, t.second); + computeIntercepts(data.time.j2000Seconds(), t.first, t.second); updateGPU(); const double t2 = ImageSequencer::ref().nextCaptureTime(data.time.j2000Seconds()); diff --git a/modules/spacecraftinstruments/rendering/renderablefov.h b/modules/spacecraftinstruments/rendering/renderablefov.h index 25bda493d7..6ae7fe6513 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.h +++ b/modules/spacecraftinstruments/rendering/renderablefov.h @@ -64,48 +64,26 @@ private: // the potential targets are returns the first name of the target that is in field of // view, the previous target, or the closest target to the space craft. The second // return value is whether the target is currently in the field of view - std::pair determineTarget(double time); + std::pair determineTarget(double time); void updateGPU(); - void insertPoint(std::vector& arr, glm::vec4 p, glm::vec4 c); - glm::vec3 squareColor(float t) const { - return _colors.active.value() * t + _colors.square.value() * (1 - t); - } - - glm::vec3 endColor(float t) const { - return _colors.active.value() * t + _colors.intersectionEnd.value() * (1 - t); - } - - glm::vec3 fovColor(float t) const { - return _colors.active.value() * t + _colors.targetInFieldOfView.value() * (1 - t); - } - - void computeIntercepts(const UpdateData& data, const std::string& target, + void computeIntercepts(double time, const std::string& target, bool isInFov); glm::dvec3 orthogonalProjection(const glm::dvec3& vecFov, double time, const std::string& target) const; - glm::dvec3 checkForIntercept(const glm::dvec3& ray, double time, - const std::string& target) const; // properties properties::FloatProperty _lineWidth; - properties::BoolProperty _drawSolid; properties::DoubleProperty _standOffDistance; ghoul::opengl::ProgramObject* _program = nullptr; UniformCache(modelViewProjection, defaultColorStart, defaultColorEnd, activeColor, targetInFieldOfViewColor, intersectionStartColor, intersectionEndColor, squareColor, interpolation) _uniformCache; - // instance variables - bool _rebuild = false; - bool _simplifyBounds = false; - //std::vector _fovBounds; - //std::vector _fovPlane; - std::string _previousTarget; bool _drawFOV = false; diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 117f88c7fb..1eb9c230ab 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -24,44 +24,32 @@ #include +#include #include #include #include #include -#include #include -#include -#include #include #include #include #include -#include #include -#include -#include #include -#include -#include -#include namespace { constexpr const char* _loggerCat = "RenderableModelProjection"; - constexpr const char* KeyGeomModelFile = "GeometryFile"; - constexpr const char* keyProjection = "Projection"; - constexpr const char* keyBoundingSphereRadius = "BoundingSphereRadius"; - constexpr const char* DestinationFrame = "GALACTIC"; constexpr const std::array MainUniformNames = { - "_performShading", "directionToSunViewSpace", "modelViewTransform", - "projectionTransform", "_projectionFading", "baseTexture", "projectionTexture" + "performShading", "directionToSunViewSpace", "modelViewTransform", + "projectionTransform", "projectionFading", "baseTexture", "projectionTexture" }; - constexpr const std::array FboUniformNames = { - "projectionTexture", "needShadowMap", "ProjectorMatrix", "ModelTransform", - "boresight" + constexpr const std::array FboUniformNames = { + "projectionTexture", "depthTexture", "needShadowMap", "ProjectorMatrix", + "ModelTransform", "boresight" }; constexpr const std::array DepthFboUniformNames = { @@ -84,7 +72,8 @@ namespace { std::filesystem::path geometryFile; // Contains information about projecting onto this planet. - ghoul::Dictionary projection [[codegen::reference("newhorizons_projectioncomponent")]]; + ghoul::Dictionary projection + [[codegen::reference("newhorizons_projectioncomponent")]]; // [[codegen::verbatim(PerformShadingInfo.description)]] std::optional performShading; @@ -120,17 +109,12 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di ); addPropertySubOwner(_projectionComponent); - - _projectionComponent.initialize( - identifier(), - p.projection - ); + _projectionComponent.initialize(identifier(), p.projection); double boundingSphereRadius = p.boundingSphereRadius.value_or(1.0e9); setBoundingSphere(boundingSphereRadius); _performShading = p.performShading.value_or(_performShading); - addProperty(_performShading); } @@ -210,33 +194,46 @@ void RenderableModelProjection::render(const RenderData& data, RendererTasks&) { _projectionComponent.clearAllProjections(); } - _up = data.camera.lookUpVectorCameraSpace(); + glm::vec3 up = data.camera.lookUpVectorCameraSpace(); if (_shouldCapture && _projectionComponent.doesPerformProjection()) { - project(); + for (const Image& i : _imageTimes) { + try { + glm::mat4 projectorMatrix = attitudeParameters(i.timeRange.start, up); + std::shared_ptr t = + _projectionComponent.loadProjectionTexture(i.path, i.isPlaceholder); + imageProjectGPU(*t, projectorMatrix); + } + catch (const SpiceManager::SpiceException& e) { + LERRORC(e.component, e.what()); + } + } + _shouldCapture = false; } _programObject->activate(); - attitudeParameters(_time); + try { + attitudeParameters(data.time.j2000Seconds(), up); + } + catch (const SpiceManager::SpiceException& e) { + LERRORC(e.component, e.what()); + } _imageTimes.clear(); // Calculate variables to be used as uniform variables in shader - const glm::dvec3 bodyPosition = data.modelTransform.translation; + const glm::vec3 bodyPos = data.modelTransform.translation; // Model transform and view transform needs to be in double precision - const glm::dmat4 modelTransform = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation - glm::dmat4(data.modelTransform.rotation) * // Rotation - glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); // Scale - const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * - modelTransform; - const glm::vec3 directionToSun = glm::normalize( - _sunPosition - glm::vec3(bodyPosition) + const glm::dmat4 transform = + 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)); + const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * transform; + const glm::vec3 directionToSun = glm::normalize(_sunPosition - bodyPos); + const glm::vec3 directionToSunViewSpace = glm::normalize( + glm::mat3(data.camera.combinedViewMatrix()) * directionToSun ); - const glm::vec3 directionToSunViewSpace = glm::normalize(glm::mat3( - data.camera.combinedViewMatrix() - ) * directionToSun); _programObject->setUniform(_mainUniformCache.performShading, _performShading); _programObject->setUniform( @@ -307,18 +304,16 @@ void RenderableModelProjection::update(const UpdateData& data) { const double integrateFromTime = data.previousFrameTime.j2000Seconds(); // Only project new images if time changed since last update. - if (time > integrateFromTime) { - if (ImageSequencer::ref().isReady()) { - if (_projectionComponent.doesPerformProjection()) { - _shouldCapture = ImageSequencer::ref().imagePaths( - _imageTimes, - _projectionComponent.projecteeId(), - _projectionComponent.instrumentId(), - time, - integrateFromTime - ); - } - } + if (time > integrateFromTime && ImageSequencer::ref().isReady() && + _projectionComponent.doesPerformProjection()) + { + _imageTimes = ImageSequencer::ref().imagePaths( + _projectionComponent.projecteeId(), + _projectionComponent.instrumentId(), + time, + integrateFromTime + ); + _shouldCapture = !_imageTimes.empty(); } glm::dmat3 stateMatrix = data.modelTransform.rotation; @@ -336,14 +331,15 @@ void RenderableModelProjection::update(const UpdateData& data) { } void RenderableModelProjection::imageProjectGPU( - const ghoul::opengl::Texture& projectionTexture) + const ghoul::opengl::Texture& projectionTexture, + const glm::mat4& projectorMatrix) { if (_projectionComponent.needsShadowMap()) { _projectionComponent.depthMapRenderBegin(); _depthFboProgramObject->activate(); _depthFboProgramObject->setUniform( _depthFboUniformCache.ProjectorMatrix, - _projectorMatrix + projectorMatrix ); _depthFboProgramObject->setUniform( _depthFboUniformCache.ModelTransform, @@ -373,36 +369,31 @@ void RenderableModelProjection::imageProjectGPU( if (_projectionComponent.needsShadowMap()) { unitDepthFbo.activate(); _projectionComponent.depthTexture().bind(); - _fboProgramObject->setUniform("depthTexture", unitDepthFbo); + _fboProgramObject->setUniform(_fboUniformCache.depthTexture, unitDepthFbo); } - _fboProgramObject->setUniform(_fboUniformCache.ProjectorMatrix, _projectorMatrix); + _fboProgramObject->setUniform(_fboUniformCache.ProjectorMatrix, projectorMatrix); _fboProgramObject->setUniform(_fboUniformCache.ModelTransform, _transform); _fboProgramObject->setUniform(_fboUniformCache.boresight, _boresight); _geometry->render(*_fboProgramObject, false); _fboProgramObject->deactivate(); - _projectionComponent.imageProjectEnd(); } -void RenderableModelProjection::attitudeParameters(double time) { - try { - _instrumentMatrix = SpiceManager::ref().positionTransformMatrix( - _projectionComponent.instrumentId(), - DestinationFrame, - time - ); +glm::mat4 RenderableModelProjection::attitudeParameters(double time, const glm::vec3& up) +{ + _instrumentMatrix = SpiceManager::ref().positionTransformMatrix( + _projectionComponent.instrumentId(), + DestinationFrame, + time + ); - SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( - _projectionComponent.instrumentId() - ); - _boresight = std::move(res.boresightVector); - } - catch (const SpiceManager::SpiceException&) { - return; - } + SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( + _projectionComponent.instrumentId() + ); + _boresight = std::move(res.boresightVector); double lightTime; const glm::dvec3 p = SpiceManager::ref().targetPosition( @@ -418,11 +409,10 @@ void RenderableModelProjection::attitudeParameters(double time) { const float distance = glm::length(cpos); const double radius = boundingSphere(); - - _projectorMatrix = _projectionComponent.computeProjectorMatrix( + return _projectionComponent.computeProjectorMatrix( cpos, _boresight, - _up, + up, _instrumentMatrix, _projectionComponent.fieldOfViewY(), _projectionComponent.aspectRatio(), @@ -432,14 +422,4 @@ void RenderableModelProjection::attitudeParameters(double time) { ); } -void RenderableModelProjection::project() { - for (const Image& img : _imageTimes) { - attitudeParameters(img.timeRange.start); - std::shared_ptr projTexture = - _projectionComponent.loadProjectionTexture(img.path, img.isPlaceholder); - imageProjectGPU(*projTexture); - } - _shouldCapture = false; -} - } // namespace openspace diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.h b/modules/spacecraftinstruments/rendering/renderablemodelprojection.h index 85027bd997..85a66483c6 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.h +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.h @@ -66,10 +66,9 @@ public: static documentation::Documentation Documentation(); private: - void attitudeParameters(double time); - void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture); - - void project(); + glm::mat4 attitudeParameters(double time, const glm::vec3& up); + void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture, + const glm::mat4& projectorMatrix); ProjectionComponent _projectionComponent; @@ -79,8 +78,8 @@ private: projectionTexture) _mainUniformCache; std::unique_ptr _fboProgramObject; - UniformCache(projectionTexture, needShadowMap, ProjectorMatrix, ModelTransform, - boresight) _fboUniformCache; + UniformCache(projectionTexture, depthTexture, needShadowMap, ProjectorMatrix, + ModelTransform, boresight) _fboUniformCache; std::unique_ptr _depthFboProgramObject; UniformCache(ProjectorMatrix, ModelTransform) _depthFboUniformCache; @@ -89,13 +88,10 @@ private: glm::dmat3 _instrumentMatrix = glm::dmat3(1.0); // uniforms - glm::vec3 _up = glm::vec3(0.f); glm::mat4 _transform = glm::mat4(1.f); - glm::mat4 _projectorMatrix = glm::mat4(1.f); glm::vec3 _boresight = glm::vec3(0.f); std::vector _imageTimes; - double _time = -std::numeric_limits::max(); bool _shouldCapture = false; diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 48ed1e43ab..3a442112c9 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -41,7 +40,6 @@ #include #include #include -#include namespace { constexpr const char* _loggerCat = "RenderablePlaneProjection"; @@ -124,10 +122,10 @@ void RenderablePlaneProjection::render(const RenderData& data, RendererTasks&) { glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(_stateMatrix); - glm::mat4 modelViewProjectionTransform = data.camera.projectionMatrix() * - glm::mat4(data.camera.combinedViewMatrix() * modelTransform); + glm::mat4 mvp = data.camera.projectionMatrix() * + glm::mat4(data.camera.combinedViewMatrix() * modelTransform); - _shader->setUniform("modelViewProjectionTransform", modelViewProjectionTransform); + _shader->setUniform("modelViewProjectionTransform", mvp); ghoul::opengl::TextureUnit unit; unit.activate(); @@ -142,9 +140,7 @@ void RenderablePlaneProjection::render(const RenderData& data, RendererTasks&) { void RenderablePlaneProjection::update(const UpdateData& data) { const double time = data.time.j2000Seconds(); - const Image& img = openspace::ImageSequencer::ref().latestImageForInstrument( - _instrument - ); + const Image& img = ImageSequencer::ref().latestImageForInstrument(_instrument); if (img.path.empty()) { return; @@ -163,8 +159,7 @@ void RenderablePlaneProjection::update(const UpdateData& data) { if (_moving || _planeIsDirty) { updatePlane(img, time); } - - else if (timePast > DBL_EPSILON) { + else if (timePast > std::numeric_limits::epsilon()) { _previousTime = img.timeRange.start; updatePlane(img, img.timeRange.start); } @@ -180,25 +175,27 @@ void RenderablePlaneProjection::update(const UpdateData& data) { } void RenderablePlaneProjection::loadTexture() { - if (!_texturePath.empty()) { - using TR = ghoul::io::TextureReader; - std::unique_ptr texture = TR::ref().loadTexture( - absPath(_texturePath).string() - ); - if (texture) { - if (texture->format() == ghoul::opengl::Texture::Format::Red) { - texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE }); - } - texture->uploadTexture(); - // TODO: AnisotropicMipMap crashes on ATI cards ---abock - //texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); - _texture = std::move(texture); - - _textureFile = std::make_unique(_texturePath); - _textureFile->setCallback([this]() { _textureIsDirty = true; }); - } + if (_texturePath.empty()) { + return; } + + std::unique_ptr texture = + ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath).string()); + if (!texture) { + return; + } + + if (texture->format() == ghoul::opengl::Texture::Format::Red) { + texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE }); + } + texture->uploadTexture(); + // TODO: AnisotropicMipMap crashes on ATI cards ---abock + //texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); + texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); + _texture = std::move(texture); + + _textureFile = std::make_unique(_texturePath); + _textureFile->setCallback([this]() { _textureIsDirty = true; }); } void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime) { @@ -233,8 +230,8 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime ); // The apparent position, CN+S, makes image align best with target - glm::dvec3 projection[4]; - std::fill(std::begin(projection), std::end(projection), glm::dvec3(0.0)); + glm::vec3 projection[4]; + std::fill(std::begin(projection), std::end(projection), glm::vec3(0.f)); for (size_t j = 0; j < bounds.size(); ++j) { bounds[j] = SpiceManager::ref().frameTransformationMatrix( frame, @@ -253,40 +250,33 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime ) * cornerPosition; // km -> m - projection[j] = cornerPosition * 1000.0; + projection[j] = glm::vec3(cornerPosition * 1000.0); } if (!_moving) { - SceneGraphNode* thisNode = global::renderEngine->scene()->sceneGraphNode(_name); - SceneGraphNode* newParent = global::renderEngine->scene()->sceneGraphNode( - _target.node - ); + Scene* scene = global::renderEngine->scene(); + SceneGraphNode* thisNode = scene->sceneGraphNode(_name); + SceneGraphNode* newParent = scene->sceneGraphNode(_target.node); if (thisNode && newParent) { thisNode->setParent(*newParent); } } - glm::vec3 p[4] = { - glm::vec3(projection[0]), - glm::vec3(projection[1]), - glm::vec3(projection[2]), - glm::vec3(projection[3]) - }; const GLfloat vertex_data[] = { // square of two triangles drawn within fov in target coordinates // x y z w s t // Lower left 1 - p[1].x, p[1].y, p[1].z, 0.f, 0.f, 0.f, + projection[1].x, projection[1].y, projection[1].z, 0.f, 0.f, 0.f, // Upper right 2 - p[3].x, p[3].y, p[3].z, 0.f, 1.f, 1.f, + projection[3].x, projection[3].y, projection[3].z, 0.f, 1.f, 1.f, // Upper left 3 - p[2].x, p[2].y, p[2].z, 0.f, 0.f, 1.f, + projection[2].x, projection[2].y, projection[2].z, 0.f, 0.f, 1.f, // Lower left 4 = 1 - p[1].x, p[1].y, p[1].z, 0.f, 0.f, 0.f, + projection[1].x, projection[1].y, projection[1].z, 0.f, 0.f, 0.f, // Lower right 5 - p[0].x, p[0].y, p[0].z, 0.f, 1.f, 0.f, + projection[0].x, projection[0].y, projection[0].z, 0.f, 1.f, 0.f, // Upper left 6 = 2 - p[3].x, p[3].y, p[3].z, 0.f, 1.f, 1.f, + projection[3].x, projection[3].y, projection[3].z, 0.f, 1.f, 1.f, }; glBindVertexArray(_quad); @@ -300,7 +290,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime 2, GL_FLOAT, GL_FALSE, - sizeof(GLfloat) * 6, + 6 * sizeof(GLfloat), reinterpret_cast(sizeof(GLfloat) * 4) ); diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.h b/modules/spacecraftinstruments/rendering/renderableplaneprojection.h index d4d72f0ab8..4b84eaebda 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.h +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.h @@ -71,7 +71,6 @@ private: std::unique_ptr _shader; bool _textureIsDirty = false; std::unique_ptr _texture; -// ghoul::opengl::Texture* _texture; std::unique_ptr _textureFile; GLuint _quad = 0; GLuint _vertexPositionBuffer = 0; diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index 2b78d315ea..ff1b7fbe51 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -26,20 +26,17 @@ #include #include +#include #include #include -#include #include #include #include #include #include -#include -#include #include #include #include -#include namespace { constexpr const char* _loggerCat = "RenderablePlanetProjection"; @@ -47,19 +44,18 @@ namespace { constexpr const char* FBOPassProgramName = "FBOPassProgram"; constexpr const std::array MainUniformNames = { - "sun_pos", "modelTransform", "modelViewProjectionTransform", "_hasBaseMap", - "_hasHeightMap", "_heightExaggeration", "_meridianShift", "_ambientBrightness", - "_projectionFading", "baseTexture", "projectionTexture", "heightTexture" + "sun_pos", "modelTransform", "modelViewProjectionTransform", "hasBaseMap", + "hasHeightMap", "heightExaggeration", "meridianShift", "ambientBrightness", + "projectionFading", "baseTexture", "projectionTexture", "heightTexture" }; - constexpr const std::array FboUniformNames = { - "projectionTexture", "ProjectorMatrix", "ModelTransform", "_scaling", - "boresight", "_radius", "_segments" + constexpr const std::array FboUniformNames = { + "projectionTexture", "ProjectorMatrix", "ModelTransform", + "boresight", "radius", "segments" }; constexpr const char* KeyRadius = "Geometry.Radius"; - constexpr const char* _mainFrame = "GALACTIC"; - + constexpr const char* MainFrame = "GALACTIC"; constexpr const char* NoImageText = "No Image"; constexpr openspace::properties::Property::PropertyInfo ColorTexturePathsInfo = { @@ -180,7 +176,7 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& , _heightExaggeration(HeightExaggerationInfo, 1.f, 0.f, 1e6f, 1.f) , _meridianShift(MeridianShiftInfo, false) , _ambientBrightness(AmbientBrightnessInfo, 0.075f, 0.f, 1.f) - , _maxProjectionsPerFrame(MaxProjectionsPerFrameInfo, 1, 1, 64) + , _maxProjectionsPerFrame(MaxProjectionsPerFrameInfo, 3, 1, 64) , _projectionsInBuffer(ProjectionsInBufferInfo, 0, 1, 32) , _clearProjectionBuffer(ClearProjectionBufferInfo) { @@ -199,24 +195,20 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& t ); } - _colorTexturePaths = static_cast( - _colorTexturePaths.options().size() - 1 - ); + _colorTexturePaths = static_cast(_colorTexturePaths.options().size() - 1); _addColorTexturePath.onChange([this]() { - if (!_addColorTexturePath.value().empty()) { - _colorTexturePaths.addOption( - // as we started with 0, this works - static_cast(_colorTexturePaths.options().size()), - _addColorTexturePath.value() - ); - - _colorTexturePaths = static_cast( - _colorTexturePaths.options().size() - 1 - ); - - _addColorTexturePath = ""; + if (_addColorTexturePath.value().empty()) { + return; } + _colorTexturePaths.addOption( + // as we started with 0, this works + static_cast(_colorTexturePaths.options().size()), + _addColorTexturePath.value() + ); + + _colorTexturePaths = static_cast(_colorTexturePaths.options().size() - 1); + _addColorTexturePath = ""; }); addProperty(_addColorTexturePath); @@ -274,7 +266,6 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& addProperty(_ambientBrightness); addProperty(_projectionsInBuffer); - _clearProjectionBuffer.onChange([this]() { _imageTimes.clear(); _projectionsInBuffer = static_cast(_imageTimes.size()); @@ -286,21 +277,20 @@ RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& RenderablePlanetProjection::~RenderablePlanetProjection() {} // NOLINT void RenderablePlanetProjection::initializeGL() { - _programObject = - SpacecraftInstrumentsModule::ProgramObjectManager.request( - ProjectiveProgramName, - []() -> std::unique_ptr { - return global::renderEngine->buildRenderProgram( - ProjectiveProgramName, - absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" - "renderablePlanet_vs.glsl" - ), - absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" - "renderablePlanet_fs.glsl" - ) - ); - } - ); + _programObject = SpacecraftInstrumentsModule::ProgramObjectManager.request( + ProjectiveProgramName, + []() -> std::unique_ptr { + return global::renderEngine->buildRenderProgram( + ProjectiveProgramName, + absPath( + "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/renderablePlanet_vs.glsl" + ), + absPath( + "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/renderablePlanet_fs.glsl" + ) + ); + } + ); ghoul::opengl::updateUniformLocations( *_programObject, @@ -308,23 +298,22 @@ void RenderablePlanetProjection::initializeGL() { MainUniformNames ); - _fboProgramObject = - SpacecraftInstrumentsModule::ProgramObjectManager.request( - FBOPassProgramName, - []() -> std::unique_ptr { - return ghoul::opengl::ProgramObject::Build( - FBOPassProgramName, - absPath( - "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" - "renderablePlanetProjection_vs.glsl" - ), - absPath( - "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" - "renderablePlanetProjection_fs.glsl" - ) - ); - } - ); + _fboProgramObject = SpacecraftInstrumentsModule::ProgramObjectManager.request( + FBOPassProgramName, + []() -> std::unique_ptr { + return ghoul::opengl::ProgramObject::Build( + FBOPassProgramName, + absPath( + "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" + "renderablePlanetProjection_vs.glsl" + ), + absPath( + "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" + "renderablePlanetProjection_fs.glsl" + ) + ); + } + ); ghoul::opengl::updateUniformLocations( *_fboProgramObject, @@ -338,7 +327,6 @@ void RenderablePlanetProjection::initializeGL() { _geometry->initialize(); setBoundingSphere(_geometry->boundingSphere()); - //completeSuccess &= auxiliaryRendertarget(); // SCREEN-QUAD const GLfloat vertexData[] = { -1.f, -1.f, @@ -355,17 +343,7 @@ void RenderablePlanetProjection::initializeGL() { glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 2, nullptr); - // glEnableVertexAttribArray(1); - // glVertexAttribPointer( - // 1, - // 2, - // GL_FLOAT, - // GL_FALSE, - // sizeof(GLfloat) * 2, - // reinterpret_cast(sizeof(GLfloat) * 4) - // ); - + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); } @@ -385,9 +363,7 @@ void RenderablePlanetProjection::deinitializeGL() { ); _programObject = nullptr; - SpacecraftInstrumentsModule::ProgramObjectManager.release( - FBOPassProgramName - ); + SpacecraftInstrumentsModule::ProgramObjectManager.release(FBOPassProgramName); _fboProgramObject = nullptr; } @@ -396,7 +372,8 @@ bool RenderablePlanetProjection::isReady() const { } void RenderablePlanetProjection::imageProjectGPU( - const ghoul::opengl::Texture& projectionTexture) + const ghoul::opengl::Texture& projectionTexture, + const glm::mat4& projectorMatrix) { _projectionComponent.imageProjectBegin(); @@ -407,9 +384,8 @@ void RenderablePlanetProjection::imageProjectGPU( projectionTexture.bind(); _fboProgramObject->setUniform(_fboUniformCache.projectionTexture, unitFbo); - _fboProgramObject->setUniform(_fboUniformCache.projectorMatrix, _projectorMatrix); + _fboProgramObject->setUniform(_fboUniformCache.projectorMatrix, projectorMatrix); _fboProgramObject->setUniform(_fboUniformCache.modelTransform, _transform); - _fboProgramObject->setUniform(_fboUniformCache.scaling, _camScaling); _fboProgramObject->setUniform(_fboUniformCache.boresight, _boresight); if (_geometry->hasProperty("Radius")) { @@ -436,33 +412,27 @@ void RenderablePlanetProjection::imageProjectGPU( _fboProgramObject->deactivate(); _projectionComponent.imageProjectEnd(); + glBindVertexArray(0); } -void RenderablePlanetProjection::attitudeParameters(double time) { +glm::mat4 RenderablePlanetProjection::attitudeParameters(double time, const glm::vec3& up) +{ // precomputations for shader - _instrumentMatrix = SpiceManager::ref().positionTransformMatrix( - _projectionComponent.instrumentId(), _mainFrame, time + glm::dmat3 instrumentMatrix = SpiceManager::ref().positionTransformMatrix( + _projectionComponent.instrumentId(), + MainFrame, + time ); - _transform = glm::mat4(_stateMatrix); - - glm::dvec3 bs = glm::dvec3(0.0); - try { - SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( - _projectionComponent.instrumentId() - ); - bs = std::move(res.boresightVector); - } - catch (const SpiceManager::SpiceException& e) { - LERRORC(e.component, e.what()); - return; - } + SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( + _projectionComponent.instrumentId() + ); double lightTime; glm::dvec3 p = SpiceManager::ref().targetPosition( _projectionComponent.projectorId(), _projectionComponent.projecteeId(), - _mainFrame, + MainFrame, _projectionComponent.aberration(), time, lightTime @@ -470,11 +440,11 @@ void RenderablePlanetProjection::attitudeParameters(double time) { const double distance = glm::length(p); const double radius = boundingSphere(); - _projectorMatrix = _projectionComponent.computeProjectorMatrix( + return _projectionComponent.computeProjectorMatrix( p, - bs, - _up, - _instrumentMatrix, + res.boresightVector, + up, + instrumentMatrix, _projectionComponent.fieldOfViewY(), _projectionComponent.aspectRatio(), static_cast(distance - radius), @@ -498,29 +468,33 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _projectionComponent.generateMipMap(); } - _camScaling = glm::vec2(1.f, 0.f); // Unit scaling - _up = data.camera.lookUpVectorCameraSpace(); - + glm::vec3 up = data.camera.lookUpVectorCameraSpace(); if (_projectionComponent.doesPerformProjection()) { - int nPerformedProjections = 0; + int nProjections = 0; for (const Image& img : _imageTimes) { - if (nPerformedProjections >= _maxProjectionsPerFrame) { + if (nProjections >= _maxProjectionsPerFrame) { break; } - RenderablePlanetProjection::attitudeParameters(img.timeRange.start); - std::shared_ptr t = - _projectionComponent.loadProjectionTexture(img.path); - imageProjectGPU(*t); - ++nPerformedProjections; + try { + glm::mat4 projectorMatrix = attitudeParameters(img.timeRange.start, up); + std::shared_ptr t = + _projectionComponent.loadProjectionTexture(img.path); + imageProjectGPU(*t, projectorMatrix); + ++nProjections; + } + catch (const SpiceManager::SpiceException& e) { + LERRORC(e.component, e.what()); + } } - _imageTimes.erase( - _imageTimes.begin(), - _imageTimes.begin() + nPerformedProjections - ); + _imageTimes.erase(_imageTimes.begin(), _imageTimes.begin() + nProjections); _projectionsInBuffer = static_cast(_imageTimes.size()); - } - attitudeParameters(data.time.j2000Seconds()); + try { + attitudeParameters(data.time.j2000Seconds(), up); + } + catch (const SpiceManager::SpiceException& e) { + LERRORC(e.component, e.what()); + } double lt; glm::dvec3 sunPos = SpiceManager::ref().targetPosition( @@ -537,19 +511,16 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _programObject->setUniform(_mainUniformCache.sunPos, static_cast(sunPos)); // Model transform and view transform needs to be in double precision - glm::dmat4 modelTransform = + glm::dmat4 trans = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation glm::dmat4(data.modelTransform.rotation) * // Spice rotation glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); - glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; + glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * trans; + _programObject->setUniform(_mainUniformCache.modelTransform, glm::mat4(trans)); _programObject->setUniform( - _mainUniformCache.modelTransform, - glm::mat4(modelTransform) - ); - _programObject->setUniform(_mainUniformCache - .modelViewProjectionTransform, + _mainUniformCache.modelViewProjectionTransform, data.camera.projectionMatrix() * glm::mat4(modelViewTransform) ); @@ -624,52 +595,42 @@ void RenderablePlanetProjection::update(const UpdateData& data) { const double integrateFromTime = data.previousFrameTime.j2000Seconds(); // Only project new images if time changed since last update. - if (time > integrateFromTime) { - if (openspace::ImageSequencer::ref().isReady()) { - if (_projectionComponent.doesPerformProjection()) { - std::vector newImageTimes; - openspace::ImageSequencer::ref().imagePaths( - newImageTimes, - _projectionComponent.projecteeId(), - _projectionComponent.instrumentId(), - time, - integrateFromTime - ); + if (time > integrateFromTime && ImageSequencer::ref().isReady() && + _projectionComponent.doesPerformProjection()) + { + std::vector newImageTimes= ImageSequencer::ref().imagePaths( + _projectionComponent.projecteeId(), + _projectionComponent.instrumentId(), + time, + integrateFromTime + ); - if (!newImageTimes.empty()) { - double firstNewImage = newImageTimes[0].timeRange.end; - // Make sure images are always projected in the correct order - // (Remove buffered images with a later timestamp) - clearProjectionBufferAfterTime(firstNewImage); - - // Now, insert the new images to the buffer - insertImageProjections(newImageTimes); + if (!newImageTimes.empty()) { + 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( + _imageTimes.begin(), + _imageTimes.end(), + [firstNewImage](const Image& image) { + return image.timeRange.end > firstNewImage; } + ); + if (it != _imageTimes.end()) { + _imageTimes.erase(it, _imageTimes.end()); } + + // Now, insert the new images to the buffer + _imageTimes.insert( + _imageTimes.end(), + newImageTimes.begin(), + newImageTimes.end() + ); + _projectionsInBuffer = static_cast(_imageTimes.size()); } } - _stateMatrix = data.modelTransform.rotation; -} - -void RenderablePlanetProjection::clearProjectionBufferAfterTime(double time) { - const auto& it = std::find_if( - _imageTimes.begin(), - _imageTimes.end(), - [time](const Image& image) { return image.timeRange.end > time; } - ); - if (it != _imageTimes.end()) { - _imageTimes.erase(it, _imageTimes.end()); - } -} - -void RenderablePlanetProjection::insertImageProjections(const std::vector& images) -{ - _imageTimes.insert(_imageTimes.end(), - images.begin(), - images.end() - ); - _projectionsInBuffer = static_cast(_imageTimes.size()); + _transform = glm::mat4(data.modelTransform.rotation); } void RenderablePlanetProjection::loadColorTexture() { @@ -687,7 +648,7 @@ void RenderablePlanetProjection::loadColorTexture() { ghoul::opengl::convertTextureFormat(*_baseTexture, Texture::Format::RGB); _baseTexture->uploadTexture(); _baseTexture->setWrapping( - { Texture::WrappingMode::Repeat, Texture::WrappingMode::MirroredRepeat} + { Texture::WrappingMode::Repeat, Texture::WrappingMode::MirroredRepeat } ); _baseTexture->setFilter(Texture::FilterMode::LinearMipMap); } diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.h b/modules/spacecraftinstruments/rendering/renderableplanetprojection.h index 7b36109f3a..863bb0365a 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.h +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.h @@ -56,17 +56,13 @@ public: static documentation::Documentation Documentation(); -protected: +private: void loadColorTexture(); void loadHeightTexture(); - void attitudeParameters(double time); - -private: - void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture); - - void clearProjectionBufferAfterTime(double time); - void insertImageProjections(const std::vector& images); + glm::mat4 attitudeParameters(double time, const glm::vec3& up); + void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture, + const glm::mat4& projectorMatrix); ProjectionComponent _projectionComponent; @@ -85,7 +81,7 @@ private: projectionFading, baseTexture, projectionTexture, heightTexture) _mainUniformCache; - UniformCache(projectionTexture, projectorMatrix, modelTransform, scaling, boresight, + UniformCache(projectionTexture, projectorMatrix, modelTransform, boresight, radius, segments) _fboUniformCache; std::unique_ptr _baseTexture; @@ -100,13 +96,8 @@ private: std::unique_ptr _geometry; - glm::vec2 _camScaling = glm::vec2(0.f); - glm::vec3 _up = glm::vec3(0.f); glm::mat4 _transform = glm::mat4(1.f); glm::mat4 _projectorMatrix = glm::mat4(1.f); - - glm::dmat3 _stateMatrix = glm::dmat3(1.0); - glm::dmat3 _instrumentMatrix = glm::dmat3(1.0); glm::vec3 _boresight = glm::vec3(0.f); std::vector _imageTimes; diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp index 88a3251e7d..bed2e9ca8b 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp @@ -25,14 +25,13 @@ #include #include +#include #include #include #include #include #include #include -#include -#include namespace { constexpr const char* ProgramName = "ShadowCylinderProgram"; @@ -179,7 +178,6 @@ RenderableShadowCylinder::RenderableShadowCylinder(const ghoul::Dictionary& dict _shadowColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_shadowColor); - _terminatorType.addOptions({ { static_cast(SpiceManager::TerminatorType::Umbral), "Umbral" }, { static_cast(SpiceManager::TerminatorType::Penumbral), "Penumbral" } @@ -321,9 +319,7 @@ void RenderableShadowCylinder::createCylinder(double time) { res.terminatorPoints.begin(), res.terminatorPoints.end(), std::back_inserter(terminatorPoints), - [](const glm::dvec3& p) { - return p * 1000.0; - } + [](const glm::dvec3& p) { return p * 1000.0; } ); double lt; @@ -364,7 +360,7 @@ void RenderableShadowCylinder::createCylinder(double time) { GL_ARRAY_BUFFER, 0, _vertices.size() * sizeof(CylinderVBOLayout), - &_vertices[0] + _vertices.data() ); glEnableVertexAttribArray(0); diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.h b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.h index c6caaf4f8d..8583a80e3e 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.h +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.h @@ -32,7 +32,6 @@ #include #include #include - #include #include diff --git a/modules/spacecraftinstruments/shaders/crawlingline_fs.glsl b/modules/spacecraftinstruments/shaders/crawlingline_fs.glsl index 08c86633b5..110e92ab7a 100644 --- a/modules/spacecraftinstruments/shaders/crawlingline_fs.glsl +++ b/modules/spacecraftinstruments/shaders/crawlingline_fs.glsl @@ -24,15 +24,14 @@ #include "fragment.glsl" -in vec4 vs_positionScreenSpace; +in float vs_depth; in vec4 vs_color; -uniform float _alpha; - +uniform float alpha; Fragment getFragment() { - Fragment frag; - frag.color = vec4(vs_color.rgb, vs_color.a * _alpha); - frag.depth = vs_positionScreenSpace.w; - return frag; + Fragment frag; + frag.color = vec4(vs_color.rgb, vs_color.a * alpha); + frag.depth = vs_depth; + return frag; } diff --git a/modules/spacecraftinstruments/shaders/crawlingline_vs.glsl b/modules/spacecraftinstruments/shaders/crawlingline_vs.glsl index 551a19ee5a..96eb1f63c5 100644 --- a/modules/spacecraftinstruments/shaders/crawlingline_vs.glsl +++ b/modules/spacecraftinstruments/shaders/crawlingline_vs.glsl @@ -30,15 +30,15 @@ layout(location = 0) in vec3 in_position; layout(location = 1) in vec4 in_color; out vec4 vs_color; -out vec4 vs_positionScreenSpace; +out float vs_depth; uniform mat4 modelViewProjection; - void main() { - vec4 positionClipSpace = modelViewProjection * vec4(in_position, 1.0); - vs_positionScreenSpace = z_normalization(positionClipSpace); - gl_Position = vs_positionScreenSpace; + vec4 positionClipSpace = modelViewProjection * vec4(in_position, 1.0); + vec4 p = z_normalization(positionClipSpace); + vs_depth = p.w; + gl_Position = p; - vs_color = in_color; + vs_color = in_color; } diff --git a/modules/spacecraftinstruments/shaders/dilation_fs.glsl b/modules/spacecraftinstruments/shaders/dilation_fs.glsl index 18df1d1f08..4d07e62ef3 100644 --- a/modules/spacecraftinstruments/shaders/dilation_fs.glsl +++ b/modules/spacecraftinstruments/shaders/dilation_fs.glsl @@ -30,64 +30,62 @@ out vec4 color; uniform sampler2D tex; uniform sampler2D stencil; -// We conside the 8-neighborhood of a texel, so going a stepsize of '1' in both -// directions +// We conside the 8-neighborhood of a texel, so going a stepsize of '1' in both directions vec2 offsets[8] = vec2[]( - vec2(-1.0, -1.0), - vec2(-1.0, 0.0), - vec2(-1.0, 1.0), - vec2(0.0, -1.0), - vec2(0.0, 1.0), - vec2(1.0, -1.0), - vec2(1.0, 0.0), - vec2(1.0, 1.0) + vec2(-1.0, -1.0), + vec2(-1.0, 0.0), + vec2(-1.0, 1.0), + vec2( 0.0, -1.0), + vec2( 0.0, 1.0), + vec2( 1.0, -1.0), + vec2( 1.0, 0.0), + vec2( 1.0, 1.0) ); -// Collect the contributing colors from the neighboring texels and return the -// averaged value of all texels that passed the masking test based on 'stencil' +// Collect the contributing colors from the neighboring texels and return the averaged +// value of all texels that passed the masking test based on 'stencil' vec3 gatherNeighboringColors() { - vec2 texSize = textureSize(tex, 0); + vec2 texSize = textureSize(tex, 0); - // The total number of contributing texels - int nContributions = 0; + // The total number of contributing texels + int nContributions = 0; - // The summed color of all contributing texels - vec3 totalColor = vec3(0.0); + // The summed color of all contributing texels + vec3 totalColor = vec3(0.0); - for (int i = 0; i < 8; i++) { - // gl_FragCoord is in pixel coordinates; the ProjectionComponent sets - // the viewport such that pixels=texels, so we can use gl_FragCoord as an - // integer texel coordinate - // First offsetting them, then dividing by the texture size to get to [0,1] - vec2 samplePosition = (gl_FragCoord.xy + offsets[i]) / texSize; + for (int i = 0; i < 8; i++) { + // gl_FragCoord is in pixel coordinates; the ProjectionComponent sets the viewport + // such that pixels=texels, so we can use gl_FragCoord as an integer texel coordinate + // First offsetting them, then dividing by the texture size to get to [0,1] + vec2 samplePosition = (gl_FragCoord.xy + offsets[i]) / texSize; - // The stencelling determines the areas that we have to enlarge, such that we - // do not enlarge a previously enlarged area - if (texture(stencil, samplePosition).r != 0.0) { - totalColor += texture(tex, samplePosition).rgb; - nContributions++; - } + // The stencelling determines the areas that we have to enlarge, such that we do not + // enlarge a previously enlarged area + if (texture(stencil, samplePosition).r != 0.0) { + totalColor += texture(tex, samplePosition).rgb; + nContributions++; } + } - // GLSL normally doesn't have a problem taking vec3(0.0)/0.0 but we don't want to - // tempt the compiler gods - if (nContributions > 0) { - return totalColor / nContributions; - } - else { - return vec3(0.0); - } + // GLSL normally doesn't have a problem taking vec3(0.0)/0.0 but we don't want to tempt + // the compiler gods + if (nContributions > 0) { + return totalColor / nContributions; + } + else { + return vec3(0.0); + } } void main() { - if (texture(stencil, vs_uv).r == 0.0) { - // This means that the current fragment/texel we are looking at has not been - // projected on and we only want to do the dilation into these texels - color = vec4(gatherNeighboringColors(), 1.0); - } - else { - // We are in a region where an image has been projected, so we can reuse the - // already sampled version - color = texture(tex, vs_uv); - } + if (texture(stencil, vs_uv).r == 0.0) { + // This means that the current fragment/texel we are looking at has not been projected + // on and we only want to do the dilation into these texels + color = vec4(gatherNeighboringColors(), 1.0); + } + else { + // We are in a region where an image has been projected, so we can reuse the already + // sampled version + color = texture(tex, vs_uv); + } } diff --git a/modules/spacecraftinstruments/shaders/dilation_vs.glsl b/modules/spacecraftinstruments/shaders/dilation_vs.glsl index f0e692aab0..047e690d42 100644 --- a/modules/spacecraftinstruments/shaders/dilation_vs.glsl +++ b/modules/spacecraftinstruments/shaders/dilation_vs.glsl @@ -29,6 +29,6 @@ layout(location = 0) in vec2 in_position; out vec2 vs_uv; void main() { - vs_uv = (in_position + vec2(1.0)) / vec2(2.0); - gl_Position = vec4(in_position, 0.0, 1.0); + vs_uv = (in_position + vec2(1.0)) / vec2(2.0); + gl_Position = vec4(in_position, 0.0, 1.0); } diff --git a/modules/spacecraftinstruments/shaders/fov_fs.glsl b/modules/spacecraftinstruments/shaders/fov_fs.glsl index f05491be6f..b01a1f7aaf 100644 --- a/modules/spacecraftinstruments/shaders/fov_fs.glsl +++ b/modules/spacecraftinstruments/shaders/fov_fs.glsl @@ -25,11 +25,11 @@ #include "fragment.glsl" in vec4 vs_color; -in vec4 vs_positionScreenSpace; +in float vs_depth; Fragment getFragment() { - Fragment frag; - frag.color = vs_color; - frag.depth = vs_positionScreenSpace.w; - return frag; + Fragment frag; + frag.color = vs_color; + frag.depth = vs_depth; + return frag; } diff --git a/modules/spacecraftinstruments/shaders/fov_vs.glsl b/modules/spacecraftinstruments/shaders/fov_vs.glsl index 8d067e7645..63053b2bf5 100644 --- a/modules/spacecraftinstruments/shaders/fov_vs.glsl +++ b/modules/spacecraftinstruments/shaders/fov_vs.glsl @@ -30,12 +30,11 @@ layout(location = 0) in vec3 in_point_position; layout (location = 1) in int colorInformation; out vec4 vs_color; -out vec4 vs_positionScreenSpace; +out float vs_depth; uniform mat4 modelViewProjectionTransform; - -uniform vec3 defaultColorStart; -uniform vec3 defaultColorEnd; +uniform vec3 colorStart; +uniform vec3 colorEnd; uniform vec3 activeColor; uniform vec3 targetInFieldOfViewColor; uniform vec3 intersectionStartColor; @@ -52,39 +51,46 @@ const int VertexColorTypeIntersectionStart = 4; const int VertexColorTypeIntersectionEnd = 5; const int VertexColorTypeSquare = 6; - void main() { - vec4 position = vec4(in_point_position, 1); - vec4 positionClipSpace = modelViewProjectionTransform * position; + vec4 positionClipSpace = modelViewProjectionTransform * vec4(in_point_position, 1.0); - vs_positionScreenSpace = z_normalization(positionClipSpace); - gl_Position = vs_positionScreenSpace; + vec4 pos = z_normalization(positionClipSpace); + vs_depth = pos.w; + gl_Position = pos; - vec3 color; - switch (colorInformation) { - case VertexColorTypeDefaultStart: - color = defaultColorStart; - break; - case VertexColorTypeDefaultEnd: - color = defaultColorEnd; - break; - case VertexColorTypeInFieldOfView: - color = activeColor * interpolation + targetInFieldOfViewColor * (1 - interpolation); - break; - case VertexColorTypeActive: - color = activeColor; - break; - case VertexColorTypeIntersectionStart: - color = intersectionStartColor; - break; - case VertexColorTypeIntersectionEnd: - color = activeColor * interpolation + intersectionEndColor * (1 - interpolation); - break; - case VertexColorTypeSquare: - color = activeColor * interpolation + squareColor * (1 - interpolation); - break; - default: - color = vec3(1.0, 0.0, 1.0); - } - vs_color = vec4(color, 1.0); + vec3 color; + switch (colorInformation) { + case VertexColorTypeDefaultStart: + vs_color = vec4(colorStart, 1.0); + break; + case VertexColorTypeDefaultEnd: + vs_color = vec4(colorEnd, 1.0); + break; + case VertexColorTypeInFieldOfView: + vs_color = vec4( + activeColor * interpolation + targetInFieldOfViewColor * (1.0 - interpolation), + 1.0 + ); + break; + case VertexColorTypeActive: + vs_color = vec4(activeColor, 1.0); + break; + case VertexColorTypeIntersectionStart: + vs_color = vec4(intersectionStartColor, 1.0); + break; + case VertexColorTypeIntersectionEnd: + vs_color = vec4( + activeColor * interpolation + intersectionEndColor * (1.0 - interpolation), + 1.0 + ); + break; + case VertexColorTypeSquare: + vs_color = vec4( + activeColor * interpolation + squareColor * (1.0 - interpolation), + 1.0 + ); + break; + default: + vs_color = vec4(1.0, 0.0, 1.0, 1.0); + } } diff --git a/modules/spacecraftinstruments/shaders/renderableModelDepth_fs.glsl b/modules/spacecraftinstruments/shaders/renderableModelDepth_fs.glsl index 9d01c9a7c3..7aa6626a90 100644 --- a/modules/spacecraftinstruments/shaders/renderableModelDepth_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModelDepth_fs.glsl @@ -27,6 +27,5 @@ out vec4 fragColor; void main() { - fragColor = vec4(1.0); - //gl_FragDepth = gl_FragCoord.z; + fragColor = vec4(1.0); } diff --git a/modules/spacecraftinstruments/shaders/renderableModelDepth_vs.glsl b/modules/spacecraftinstruments/shaders/renderableModelDepth_vs.glsl index 731c82ef9a..1c332f1a46 100644 --- a/modules/spacecraftinstruments/shaders/renderableModelDepth_vs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModelDepth_vs.glsl @@ -31,8 +31,6 @@ layout(location = 0) in vec4 in_position; uniform mat4 ProjectorMatrix; uniform mat4 ModelTransform; - void main() { - gl_Position = ProjectorMatrix * ModelTransform * - psc_to_meter(in_position, vec2(1.0, 0.0)); + gl_Position = ProjectorMatrix * ModelTransform * psc_to_meter(in_position, vec2(1.0, 0.0)); } diff --git a/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl b/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl index 4d8563d5a2..e1c7c4e283 100644 --- a/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl @@ -24,7 +24,6 @@ #version __CONTEXT__ -in vec4 vs_position; in vec4 vs_ndc; in vec4 vs_normal; @@ -35,54 +34,41 @@ layout (location = 1) out vec4 stencil; uniform sampler2D projectionTexture; uniform sampler2D depthTexture; - uniform bool needShadowMap; - -uniform mat4 ModelTransform; uniform vec3 boresight; -uniform vec4 debugColor; bool inRange(float x, float a, float b) { - return (x >= a && x <= b); + return (x >= a && x <= b); } void main() { - vec3 n = normalize(vs_normal.xyz); - vec4 projected = vs_ndc; - vec2 uv = vec2(0.5) * projected.xy + vec2(0.5); + vec3 n = normalize(vs_normal.xyz); + vec2 uv = vec2(0.5) * vs_ndc.xy + vec2(0.5); - if (needShadowMap) { - float thisDepth = projected.z * 0.5 + 0.5; - float closestDepth = texture(depthTexture, uv).r; - const float epsilon = 0.001; + if (needShadowMap) { + float thisDepth = vs_ndc.z * 0.5 + 0.5; + float closestDepth = texture(depthTexture, uv).r; + const float epsilon = 0.001; - if (inRange(uv.x, 0.0, 1.0) && inRange(uv.y, 0.0, 1.0) && - dot(n, boresight) < 0 && thisDepth <= closestDepth + epsilon) - { - // color = texture(projectionTexture, projected.xy); - color = texture(projectionTexture, vec2(1.0) - uv); - color.a = 1.0; - stencil = vec4(1.0); - } - else { - discard; - // color = vec4(vec3(0.0), 0.0); - // stencil = vec4(0.0); - } + if (inRange(uv.x, 0.0, 1.0) && inRange(uv.y, 0.0, 1.0) && + dot(n, boresight) < 0 && thisDepth <= closestDepth + epsilon) + { + color = texture(projectionTexture, vec2(1.0) - uv); + color.a = 1.0; + stencil = vec4(1.0); } else { - if (inRange(uv.x, 0.0, 1.0) && inRange(uv.y, 0.0, 1.0) && - dot(n, boresight) < 0) - { - // color = texture(projectionTexture, projected.xy); - color = texture(projectionTexture, vec2(1.0) - uv); - color.a = 1.0; - stencil = vec4(1.0); - } - else { - discard; - // color = vec4(0.0); - // stencil = vec4(0.0); - } + discard; } + } + else { + if (inRange(uv.x, 0.0, 1.0) && inRange(uv.y, 0.0, 1.0) && dot(n, boresight) < 0) { + color = texture(projectionTexture, vec2(1.0) - uv); + color.a = 1.0; + stencil = vec4(1.0); + } + else { + discard; + } + } } diff --git a/modules/spacecraftinstruments/shaders/renderableModelProjection_vs.glsl b/modules/spacecraftinstruments/shaders/renderableModelProjection_vs.glsl index 5d9ed84f35..be246fa5b0 100644 --- a/modules/spacecraftinstruments/shaders/renderableModelProjection_vs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModelProjection_vs.glsl @@ -30,26 +30,20 @@ layout(location = 0) in vec4 in_position; layout(location = 1) in vec2 in_st; layout(location = 2) in vec3 in_normal; -out vec4 vs_position; -out vec4 vs_normal; -out vec2 vs_uv; out vec4 vs_ndc; +out vec4 vs_normal; uniform mat4 ProjectorMatrix; uniform mat4 ModelTransform; uniform mat4 meshTransform; uniform mat4 meshNormalTransform; -uniform vec3 boresight; - void main() { - vec4 raw_pos = psc_to_meter((meshTransform * in_position), vec2(1.0, 0.0)); - vs_position = ProjectorMatrix * ModelTransform * raw_pos; - vs_normal = normalize(ModelTransform * meshNormalTransform * vec4(in_normal,0)); - vs_ndc = vs_position / vs_position.w; + vec4 raw_pos = psc_to_meter(meshTransform * in_position, vec2(1.0, 0.0)); + vec4 position = ProjectorMatrix * ModelTransform * raw_pos; + vs_normal = normalize(ModelTransform * meshNormalTransform * vec4(in_normal, 0.0)); + vs_ndc = position / position.w; - //match clipping plane - vec2 texco = (in_st * 2) - 1; - vs_uv = texco; - gl_Position = vec4(texco, 0.0, 1.0); + vec2 texco = (in_st * 2.0) - 1.0; + gl_Position = vec4(texco, 0.0, 1.0); } diff --git a/modules/spacecraftinstruments/shaders/renderableModel_fs.glsl b/modules/spacecraftinstruments/shaders/renderableModel_fs.glsl index 23b3035869..7e8b2e1f55 100644 --- a/modules/spacecraftinstruments/shaders/renderableModel_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModel_fs.glsl @@ -27,64 +27,63 @@ in vec2 vs_st; in vec3 vs_normalViewSpace; -in vec4 vs_positionScreenSpace; +in float vs_depth; in vec4 vs_positionCameraSpace; uniform sampler2D baseTexture; uniform sampler2D projectionTexture; - -uniform bool _performShading; -uniform float _projectionFading; +uniform bool performShading; +uniform float projectionFading; uniform vec3 directionToSunViewSpace; +const vec3 specularAlbedo = vec3(1.0); + +const float ambientIntensity = 0.15; +const float diffuseIntensity = 1.0; +const float specularIntensity = 0.0; +const float specularPower = 100.0; Fragment getFragment() { - vec4 textureColor = texture(baseTexture, vs_st); - vec4 projectionColor = texture(projectionTexture, vs_st); - if (projectionColor.a > 0.0) { - textureColor.rgb = mix( - textureColor.rgb, - projectionColor.rgb, - _projectionFading * projectionColor.a - ); - } + vec4 textureColor = texture(baseTexture, vs_st); + vec4 projectionColor = texture(projectionTexture, vs_st); + if (projectionColor.a > 0.0) { + textureColor.rgb = mix( + textureColor.rgb, + projectionColor.rgb, + projectionFading * projectionColor.a + ); + } + + vec3 diffuseAlbedo = textureColor.rgb; + + Fragment frag; + if (performShading) { + // Some of these values could be passed in as uniforms + const vec3 lightColorAmbient = vec3(1.0); + const vec3 lightColor = vec3(1.0); - vec3 diffuseAlbedo = textureColor.rgb; - vec3 specularAlbedo = vec3(1.0); + vec3 n = normalize(vs_normalViewSpace); + vec3 l = directionToSunViewSpace; + vec3 c = normalize(vs_positionCameraSpace.xyz); + vec3 r = reflect(l, n); - Fragment frag; - if (_performShading) { - // Some of these values could be passed in as uniforms - const vec3 lightColorAmbient = vec3(1.0); - const vec3 lightColor = vec3(1.0); - - vec3 n = normalize(vs_normalViewSpace); - vec3 l = directionToSunViewSpace; - vec3 c = normalize(vs_positionCameraSpace.xyz); - vec3 r = reflect(l, n); + float diffuseCosineFactor = dot(n,l); + float specularCosineFactor = dot(c,r); - const float ambientIntensity = 0.15; - const float diffuseIntensity = 1.0; - const float specularIntensity = 0.0; + vec3 ambientColor = ambientIntensity * lightColorAmbient * diffuseAlbedo; + vec3 diffuseColor = + diffuseIntensity * lightColor * diffuseAlbedo * max(diffuseCosineFactor, 0.0); + vec3 specularColor = specularIntensity * lightColor * specularAlbedo * + pow(max(specularCosineFactor, 0.0), specularPower); - float diffuseCosineFactor = dot(n,l); - float specularCosineFactor = dot(c,r); - const float specularPower = 100.0; + frag.color.rgb = ambientColor + diffuseColor + specularColor; + } + else { + frag.color.rgb = diffuseAlbedo; + } - vec3 ambientColor = ambientIntensity * lightColorAmbient * diffuseAlbedo; - vec3 diffuseColor = - diffuseIntensity * lightColor * diffuseAlbedo * max(diffuseCosineFactor, 0.0); - vec3 specularColor = specularIntensity * lightColor * specularAlbedo * - pow(max(specularCosineFactor, 0.0), specularPower); - - frag.color.rgb = ambientColor + diffuseColor + specularColor; - } - else { - frag.color.rgb = diffuseAlbedo; - } - - frag.color.a = 1.0; - frag.depth = vs_positionScreenSpace.w; - // frag.depth = 0.0; - return frag; + frag.color.a = 1.0; + frag.depth = vs_depth; + // frag.depth = 0.0; + return frag; } diff --git a/modules/spacecraftinstruments/shaders/renderableModel_vs.glsl b/modules/spacecraftinstruments/shaders/renderableModel_vs.glsl index 388b589732..7f6244f3b7 100644 --- a/modules/spacecraftinstruments/shaders/renderableModel_vs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModel_vs.glsl @@ -32,27 +32,25 @@ layout(location = 2) in vec3 in_normal; out vec2 vs_st; out vec3 vs_normalViewSpace; -out vec4 vs_positionScreenSpace; +out float vs_depth; out vec4 vs_positionCameraSpace; uniform mat4 modelViewTransform; uniform mat4 projectionTransform; uniform vec3 cameraDirectionWorldSpace; -uniform float _magnification; uniform mat4 meshTransform; uniform mat4 meshNormalTransform; - void main() { - vec4 position = meshTransform * in_position; // Position already in homogenous coordinates - position.xyz *= pow(10, _magnification); - vs_positionCameraSpace = modelViewTransform * position; - vec4 positionClipSpace = projectionTransform * vs_positionCameraSpace; + vec4 position = meshTransform * in_position; + vs_positionCameraSpace = modelViewTransform * position; + vec4 positionClipSpace = projectionTransform * vs_positionCameraSpace; - vs_st = in_st; - vs_positionScreenSpace = z_normalization(positionClipSpace); - gl_Position = vs_positionScreenSpace; - - // The normal transform should be the transposed inverse of the model transform? - vs_normalViewSpace = normalize(mat3(modelViewTransform) * (mat3(meshNormalTransform) * in_normal)); + vs_st = in_st; + vec4 p = z_normalization(positionClipSpace); + vs_depth = p.w; + gl_Position = p; + + // The normal transform should be the transposed inverse of the model transform? + vs_normalViewSpace = normalize(mat3(modelViewTransform) * (mat3(meshNormalTransform) * in_normal)); } diff --git a/modules/spacecraftinstruments/shaders/renderablePlanetProjection_fs.glsl b/modules/spacecraftinstruments/shaders/renderablePlanetProjection_fs.glsl index dcba10ec68..083ad3bccf 100644 --- a/modules/spacecraftinstruments/shaders/renderablePlanetProjection_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderablePlanetProjection_fs.glsl @@ -32,61 +32,57 @@ layout (location = 0) out vec4 color; layout (location = 1) out vec4 stencil; uniform sampler2D projectionTexture; - uniform mat4 ProjectorMatrix; uniform mat4 ModelTransform; - -uniform vec2 _scaling; -uniform vec3 _radius; -uniform int _segments; - +uniform vec3 radius; +uniform int segments; uniform vec3 boresight; -#define M_PI 3.14159265358979323846 +const float M_PI = 3.14159265358979323846; vec4 uvToModel(vec2 uv, vec3 radius, float segments) { - float fj = uv.x * segments; - float fi = (1.0 - uv.y) * segments; + float fj = uv.x * segments; + float fi = (1.0 - uv.y) * segments; - float theta = fi * float(M_PI) / segments; // 0 -> PI - float phi = fj * float(M_PI) * 2.0f / segments; + float theta = fi * M_PI / segments; // 0 -> PI + float phi = fj * M_PI * 2.0 / segments; - float x = radius[0] * sin(theta) * cos(phi); - float y = radius[1] * sin(theta) * sin(phi); - float z = radius[2] * cos(theta); - - return vec4(x, y, z, 0.0); + float x = radius.x * sin(theta) * cos(phi); + float y = radius.y * sin(theta) * sin(phi); + float z = radius.z * cos(theta); + + return vec4(x, y, z, 0.0); } -bool inRange(float x, float a, float b){ - return (x >= a && x <= b); +bool inRange(float x, float a, float b) { + return (x >= a && x <= b); } void main() { - vec2 uv = (vs_position + vec2(1.0)) / vec2(2.0); + vec2 uv = (vs_position + vec2(1.0)) / vec2(2.0); - vec4 vertex = uvToModel(uv, _radius, _segments); + vec4 vertex = uvToModel(uv, radius, segments); - vec4 raw_pos = psc_to_meter(vertex, _scaling); - vec4 projected = ProjectorMatrix * ModelTransform * raw_pos; + vec4 raw_pos = psc_to_meter(vertex, vec2(1.0, 0.0)); + vec4 projected = ProjectorMatrix * ModelTransform * raw_pos; - projected.x /= projected.w; - projected.y /= projected.w; + projected.x /= projected.w; + projected.y /= projected.w; - projected = projected * 0.5 + vec4(0.5); + projected = projected * 0.5 + vec4(0.5); - vec3 normal = normalize((ModelTransform * vec4(vertex.xyz, 0.0)).xyz); + vec3 normal = normalize((ModelTransform * vec4(vertex.xyz, 0.0)).xyz); - vec3 v_b = normalize(boresight); + vec3 v_b = normalize(boresight); - if ((inRange(projected.x, 0.0, 1.0) && inRange(projected.y, 0.0, 1.0)) && - dot(v_b, normal) < 0.0) - { - color = texture(projectionTexture, vec2(projected.x, projected.y)); - stencil = vec4(1.0); - } - else { - color = vec4(0.0); - stencil = vec4(0.0); - } + if ((inRange(projected.x, 0.0, 1.0) && inRange(projected.y, 0.0, 1.0)) && + dot(v_b, normal) < 0.0) + { + color = texture(projectionTexture, vec2(projected.x, projected.y)); + stencil = vec4(1.0); + } + else { + color = vec4(0.0); + stencil = vec4(0.0); + } } diff --git a/modules/spacecraftinstruments/shaders/renderablePlanetProjection_vs.glsl b/modules/spacecraftinstruments/shaders/renderablePlanetProjection_vs.glsl index 7d138ee0ed..e64cd57333 100644 --- a/modules/spacecraftinstruments/shaders/renderablePlanetProjection_vs.glsl +++ b/modules/spacecraftinstruments/shaders/renderablePlanetProjection_vs.glsl @@ -29,6 +29,6 @@ layout(location = 0) in vec2 in_position; out vec2 vs_position; void main() { - vs_position = in_position; - gl_Position = vec4(in_position, 0.0, 1.0); + vs_position = in_position; + gl_Position = vec4(in_position, 0.0, 1.0); } diff --git a/modules/spacecraftinstruments/shaders/renderablePlanet_fs.glsl b/modules/spacecraftinstruments/shaders/renderablePlanet_fs.glsl index 6b65b27563..1613a67c52 100644 --- a/modules/spacecraftinstruments/shaders/renderablePlanet_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderablePlanet_fs.glsl @@ -25,53 +25,45 @@ #include "PowerScaling/powerScaling_fs.hglsl" #include "fragment.glsl" -in vec4 vs_positionScreenSpace; -in vec4 vs_normal; +in vec3 vs_normal; in vec2 vs_st; +in float vs_depth; uniform sampler2D baseTexture; uniform sampler2D projectionTexture; -uniform bool _meridianShift; -uniform float _ambientBrightness; - -uniform float _projectionFading; - -uniform bool _hasBaseMap; - +uniform bool meridianShift; +uniform float ambientBrightness; +uniform float projectionFading; +uniform bool hasBaseMap; uniform vec4 objpos; uniform vec3 sun_pos; - Fragment getFragment() { - vec2 st = vs_st; - if (_meridianShift) { - st.s += 0.5; - } + vec2 st = vs_st; + if (meridianShift) { + st.s += 0.5; + } - vec3 n = normalize(vs_normal.xyz); + vec3 n = normalize(vs_normal); + vec3 l_dir = normalize(sun_pos - objpos.xyz); + float intensity = min(max(5.0 * dot(n, l_dir), ambientBrightness), 1.0); - vec3 l_pos = sun_pos; // sun - vec3 l_dir = normalize(l_pos - objpos.xyz); - float intensity = min(max(5 * dot(n,l_dir), _ambientBrightness), 1); + vec4 textureColor = vec4(0.2, 0.2, 0.2, 1.0); + if (hasBaseMap) { + textureColor = texture(baseTexture, st); + } + vec4 projectionColor = texture(projectionTexture, vs_st); + if (projectionColor.a != 0.0) { + textureColor.rgb = mix( + textureColor.rgb, + projectionColor.rgb, + min(projectionFading, projectionColor.a) + ); + } - vec4 ambient = vec4(0.0, 0.0, 0.0, 1.0); + Fragment frag; + frag.color = max(intensity * textureColor, vec4(0.0, 0.0, 0.0, 1.0)); + frag.depth = vs_depth; - vec4 textureColor = vec4(0.2, 0.2, 0.2, 1.0); - if (_hasBaseMap) { - textureColor = texture(baseTexture, st); - } - vec4 projectionColor = texture(projectionTexture, vs_st); - if (projectionColor.a != 0.0) { - textureColor.rgb = mix( - textureColor.rgb, - projectionColor.rgb, - min(_projectionFading, projectionColor.a) - ); - } - - Fragment frag; - frag.color = max(intensity * textureColor, ambient); - frag.depth = vs_positionScreenSpace.w; - - return frag; + return frag; } diff --git a/modules/spacecraftinstruments/shaders/renderablePlanet_vs.glsl b/modules/spacecraftinstruments/shaders/renderablePlanet_vs.glsl index 123d70eb92..d6fc01ccbc 100644 --- a/modules/spacecraftinstruments/shaders/renderablePlanet_vs.glsl +++ b/modules/spacecraftinstruments/shaders/renderablePlanet_vs.glsl @@ -30,43 +30,42 @@ layout(location = 0) in vec4 in_position; layout(location = 1) in vec2 in_st; layout(location = 2) in vec3 in_normal; -out vec4 vs_normal; +out vec3 vs_normal; out vec2 vs_st; -out vec4 vs_positionScreenSpace; +out float vs_depth; uniform mat4 modelTransform; uniform mat4 modelViewProjectionTransform; - -uniform bool _hasHeightMap; -uniform float _heightExaggeration; +uniform bool hasHeightMap; +uniform float heightExaggeration; uniform sampler2D heightTexture; - -uniform bool _meridianShift; +uniform bool meridianShift; void main() { - vs_st = in_st; + vs_st = in_st; - vec4 tmp = in_position; - - // this is wrong for the normal. - // The normal transform is the transposed inverse of the model transform - vs_normal = normalize(modelTransform * vec4(in_normal,0)); - - if (_hasHeightMap) { - vec2 st = vs_st; - if (_meridianShift) { - st += vec2(0.5, 0.0); - } - float height = texture(heightTexture, st).s; - vec3 displacementDirection = (normalize(tmp.xyz)); - float displacementFactor = height * _heightExaggeration; - tmp.xyz += displacementDirection * displacementFactor; + vec3 tmp = in_position.xyz; + + // This is wrong for the normal. + // The normal transform is the transposed inverse of the model transform + vs_normal = normalize(modelTransform * vec4(in_normal, 0.0)).xyz; + + if (hasHeightMap) { + vec2 st = vs_st; + if (meridianShift) { + st += vec2(0.5, 0.0); } + float height = texture(heightTexture, st).s; + vec3 displacementDirection = normalize(tmp); + float displacementFactor = height * heightExaggeration; + tmp += displacementDirection * displacementFactor; + } - // convert from psc to homogeneous coordinates - vec4 position = vec4(tmp.xyz, 1); - vec4 positionClipSpace = modelViewProjectionTransform * position; - vs_positionScreenSpace = z_normalization(positionClipSpace); + // convert from psc to homogeneous coordinates + vec4 position = vec4(tmp, 1.0); + vec4 positionClipSpace = modelViewProjectionTransform * position; + vec4 p = z_normalization(positionClipSpace); - gl_Position = vs_positionScreenSpace; + vs_depth = p.w; + gl_Position = p; } diff --git a/modules/spacecraftinstruments/shaders/terminatorshadow_fs.glsl b/modules/spacecraftinstruments/shaders/terminatorshadow_fs.glsl index eaef27c5c9..dd3d748a97 100644 --- a/modules/spacecraftinstruments/shaders/terminatorshadow_fs.glsl +++ b/modules/spacecraftinstruments/shaders/terminatorshadow_fs.glsl @@ -22,18 +22,16 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "PowerScaling/powerScaling_fs.hglsl" #include "fragment.glsl" -in vec4 vs_positionScreenSpace; in vec3 vs_color; +in float vs_depth; uniform float opacity; Fragment getFragment() { - Fragment frag; - frag.color = vec4(vs_color, opacity); - frag.depth = vs_positionScreenSpace.w; - - return frag; + Fragment frag; + frag.color = vec4(vs_color, opacity); + frag.depth = vs_depth; + return frag; } diff --git a/modules/spacecraftinstruments/shaders/terminatorshadow_vs.glsl b/modules/spacecraftinstruments/shaders/terminatorshadow_vs.glsl index ac79d14c86..cf50d23cfb 100644 --- a/modules/spacecraftinstruments/shaders/terminatorshadow_vs.glsl +++ b/modules/spacecraftinstruments/shaders/terminatorshadow_vs.glsl @@ -29,23 +29,23 @@ layout(location = 0) in vec4 in_point_position; out vec3 vs_color; -out vec4 vs_positionScreenSpace; +out float vs_depth; uniform mat4 modelViewProjectionTransform; - uniform vec3 shadowColor; void main() { - if (mod(gl_VertexID, 2) == 0.0) { - vs_color = shadowColor; - } - else { - vs_color = vec3(0.0); - } - - // Transform the damn psc to homogenous coordinate - vec4 position = vec4(in_point_position.xyz * pow(10, in_point_position.w), 1.0); - vec4 positionClipSpace = modelViewProjectionTransform * position; - vs_positionScreenSpace = z_normalization(positionClipSpace); - gl_Position = vs_positionScreenSpace; + if (mod(gl_VertexID, 2) == 0.0) { + vs_color = shadowColor; + } + else { + vs_color = vec3(0.0); + } + + // Transform the damn psc to homogenous coordinate + vec4 position = vec4(in_point_position.xyz * pow(10, in_point_position.w), 1.0); + vec4 positionClipSpace = modelViewProjectionTransform * position; + vec4 p = z_normalization(positionClipSpace); + vs_depth = p.w; + gl_Position = p; } diff --git a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp index c0bfebbfa1..3781b8595d 100644 --- a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp +++ b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp @@ -31,16 +31,11 @@ #include #include #include -#include #include #include #include #include -#include #include -#include -#include -#include namespace openspace { @@ -102,7 +97,7 @@ bool SpacecraftInstrumentsModule::addFrame(std::string body, std::string frame) return false; } else { - _frameByBody.emplace_back(body, frame); + _frameByBody.emplace_back(std::move(body), std::move(frame)); return true; } } diff --git a/modules/spacecraftinstruments/util/hongkangparser.cpp b/modules/spacecraftinstruments/util/hongkangparser.cpp index 65b19e9a5c..c0063b3af8 100644 --- a/modules/spacecraftinstruments/util/hongkangparser.cpp +++ b/modules/spacecraftinstruments/util/hongkangparser.cpp @@ -53,11 +53,8 @@ namespace { return 0.0; } - double ephemerisTimeFromMissionElapsedTime(const std::string& line, - double metReference) - { - std::string::size_type sz; - return ephemerisTimeFromMissionElapsedTime(std::stod(line, &sz), metReference); + double ephemerisTimeFromMissionElapsedTime(const std::string& line, double met) { + return ephemerisTimeFromMissionElapsedTime(std::stod(line), met); } } // namespace @@ -73,10 +70,10 @@ HongKangParser::HongKangParser(std::string name, std::string fileName, , _spacecraft(std::move(spacecraft)) , _potentialTargets(std::move(potentialTargets)) { - //get the different instrument types - //for each decoder (assuming might have more if hong makes changes) + // get the different instrument types + // for each decoder (assuming might have more if hong makes changes) for (std::string_view decoderType : translationDictionary.keys()) { - //create dictionary containing all {playbookKeys , spice IDs} + // create dictionary containing all {playbookKeys , spice IDs} if (decoderType == "Instrument") { if (!translationDictionary.hasKey(decoderType) || !translationDictionary.hasValue(decoderType)) @@ -101,8 +98,8 @@ HongKangParser::HongKangParser(std::string name, std::string fileName, decoderDictionary, std::string(decoderType) ); - //insert decoder to map - this will be used in the parser to determine - //behavioral characteristics of each instrument + // insert decoder to map - this will be used in the parser to determine + // behavioral characteristics of each instrument _fileTranslation[std::string(key)] = std::move(decoder); } } @@ -135,7 +132,7 @@ std::string HongKangParser::findPlaybookSpecifiedTarget(std::string line) { } bool HongKangParser::create() { - //check input for errors. + // check input for errors. const bool hasObserver = SpiceManager::ref().hasNaifId(_spacecraft); if (!hasObserver) { throw ghoul::RuntimeError( @@ -164,13 +161,12 @@ bool HongKangParser::create() { constexpr const double Exposure = 0.01; - std::string previousTarget; std::string previousCamera; double captureStart = -1.0; - std::string cameraTarget = "VOID"; + std::string cameraTarget = "VOID"; std::string line; while (!file.eof()) { @@ -185,22 +181,21 @@ bool HongKangParser::create() { const double time = ephemerisTimeFromMissionElapsedTime(met, _metRef); if (foundEvent) { - //store the time, this is used for nextCaptureTime() + // store the time, this is used for nextCaptureTime() _captureProgression.push_back(time); if (it->second->decoderType() == "CAMERA") { - if (captureStart == -1) { + if (captureStart == -1.0) { //encountered new camera sequence- store start time captureStart = time; previousCamera = it->first; } - //always store individual image for camera + // always store individual image for camera std::vector cameraSpiceID = it->second->translations(); - //rely on playboook mdl column to determine target + // rely on playboook mdl column to determine target cameraTarget = findPlaybookSpecifiedTarget(line); - //fill image - + // fill image Image image = { TimeRange(time, time + Exposure), _defaultCaptureImage.string(), @@ -210,15 +205,14 @@ bool HongKangParser::create() { false }; - // IFF spaccraft has decided to switch target, store in target + // IFF spacecraft has decided to switch target, store in target // map (used for: 'next observation focus') if (previousTarget != image.target) { previousTarget = image.target; _targetTimes.emplace_back(time, image.target); } - // store actual image in map. All targets get _only_ their - // corresp. subset. + // 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); @@ -235,7 +229,7 @@ bool HongKangParser::create() { std::streampos len = file.tellg(); std::string linePeek; while (!file.eof()) { - //continue grabbing next line until we find what we need + // 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); @@ -246,7 +240,7 @@ bool HongKangParser::create() { std::string scannerTarget = findPlaybookSpecifiedTarget(line); TimeRange scanRange = { scanStart, scanStop }; - ghoul_assert(scanRange.isDefined(), "Invalid time range!"); + ghoul_assert(scanRange.isDefined(), "Invalid time range"); _instrumentTimes.emplace_back(it->first, scanRange); // store individual image @@ -263,13 +257,12 @@ bool HongKangParser::create() { break; } } - //go back to stored position in file + // go back to stored position in file file.seekg(len, std::ios_base::beg); } } else { - // we have reached the end of a scan or consecutive capture - // sequence! + // we have reached the end of a scan or consecutive capture sequence if (captureStart != -1) { // end of capture sequence for camera, store end time of this sequence TimeRange cameraRange = { captureStart, time }; diff --git a/modules/spacecraftinstruments/util/hongkangparser.h b/modules/spacecraftinstruments/util/hongkangparser.h index 8923682911..4a1f03c42e 100644 --- a/modules/spacecraftinstruments/util/hongkangparser.h +++ b/modules/spacecraftinstruments/util/hongkangparser.h @@ -33,7 +33,6 @@ namespace openspace { class HongKangParser : public SequenceParser { public: - HongKangParser(); HongKangParser(std::string name, std::string fileName, std::string spacecraft, const ghoul::Dictionary& translationDictionary, std::vector potentialTargets); diff --git a/modules/spacecraftinstruments/util/imagesequencer.cpp b/modules/spacecraftinstruments/util/imagesequencer.cpp index 07cc83dfab..c994c78868 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.cpp +++ b/modules/spacecraftinstruments/util/imagesequencer.cpp @@ -41,6 +41,7 @@ ImageSequencer& ImageSequencer::ref() { ghoul_assert(_instance != nullptr, "Instance has not been initialized"); return *_instance; } + void ImageSequencer::initialize() { ghoul_assert(_instance == nullptr, "Instance already has been initialized"); _instance = new ImageSequencer; @@ -52,11 +53,11 @@ void ImageSequencer::deinitialize() { _instance = nullptr; } -bool ImageSequencer::isReady() { +bool ImageSequencer::isReady() const { return _hasData; } -std::pair ImageSequencer::nextTarget(double time) { +std::pair ImageSequencer::nextTarget(double time) const { const auto it = std::lower_bound( _targetTimes.begin(), _targetTimes.end(), @@ -72,7 +73,7 @@ std::pair ImageSequencer::nextTarget(double time) { } } -std::pair ImageSequencer::currentTarget(double time) { +std::pair ImageSequencer::currentTarget(double time) const { const auto it = std::lower_bound( _targetTimes.begin(), _targetTimes.end(), @@ -80,7 +81,7 @@ std::pair ImageSequencer::currentTarget(double time) { [](const std::pair& a, double b) { return a.first < b; } ); - if (it != _targetTimes.end() && it != _targetTimes.begin()){ + if (it != _targetTimes.end() && it != _targetTimes.begin()) { return *std::prev(it); } else { @@ -88,51 +89,25 @@ std::pair ImageSequencer::currentTarget(double time) { } } -std::pair> ImageSequencer::incidentTargetList( - double time, - int range) -{ - std::pair> incidentTargets; - - auto it = std::lower_bound( - _targetTimes.begin(), - _targetTimes.end(), - time, - [](const std::pair& a, double b) { return a.first < b; } - ); - - if (it != _targetTimes.end() && it != _targetTimes.begin()){ - // move the iterator to the first element of the range - std::advance(it, -(range + 1)); - - // now extract incident range - for (int i = 0; i < 2 * range + 1; i++){ - incidentTargets.first = it->first; - incidentTargets.second.push_back(it->second); - it++; - if (it == _targetTimes.end()) { - break; - } - } - } - - return incidentTargets; -} - -double ImageSequencer::intervalLength(double time) { - const double upcoming = nextCaptureTime(time); - if (_nextCapture != upcoming) { - _nextCapture = upcoming; - _intervalLength = upcoming - time; - } - return _intervalLength; -} - -double ImageSequencer::nextCaptureTime(double currentTime) { +double ImageSequencer::prevCaptureTime(double time) const { const auto it = std::lower_bound( _captureProgression.begin(), _captureProgression.end(), - currentTime + time + ); + if (it != _captureProgression.end() && it != _captureProgression.begin()) { + return *std::prev(it); + } + else { + return 0.0; + } +} + +double ImageSequencer::nextCaptureTime(double time) const { + const auto it = std::lower_bound( + _captureProgression.begin(), + _captureProgression.end(), + time ); if (it != _captureProgression.end()) { return *it; @@ -142,10 +117,10 @@ double ImageSequencer::nextCaptureTime(double currentTime) { } } -Image ImageSequencer::latestImageForInstrument(const std::string& instrumentID) { +Image ImageSequencer::latestImageForInstrument(const std::string& instrumentID) const { const auto it = _latestImages.find(instrumentID); if (it != _latestImages.end()) { - return _latestImages[instrumentID]; + return _latestImages.at(instrumentID); } else { return Image(); @@ -177,23 +152,24 @@ std::vector> ImageSequencer::activeInstruments(doub } } } - // return entire map, seen in GUI. + // return entire map, seen in GUI return _switchingMap; } -bool ImageSequencer::isInstrumentActive(double time, const std::string& instrumentID) { +bool ImageSequencer::isInstrumentActive(double time, const std::string& instrument) const +{ for (const std::pair& i : _instrumentTimes) { - //check if this instrument is in range - if (i.second.includes(time)) { - //if so, then get the corresponding spiceID - const std::vector& ids = - _fileTranslation[i.first]->translations(); - //check which specific subinstrument is firing - for (const std::string& s : ids) { - if (s == instrumentID) { - return true; - } - } + // check if this instrument is in range + if (!i.second.includes(time)) { + continue; + } + + // if so, then get the corresponding spiceID + const std::vector& is = _fileTranslation.at(i.first)->translations(); + // check which specific subinstrument is firing + const auto it = std::find(is.begin(), is.end(), instrument); + if (it != is.end()) { + return true; } } return false; @@ -203,50 +179,47 @@ float ImageSequencer::instrumentActiveTime(double time, const std::string& instrumentID) const { for (const std::pair& i : _instrumentTimes) { - //check if this instrument is in range - if (i.second.includes(time)){ - //if so, then get the corresponding spiceID - const std::vector& ids = - _fileTranslation.at(i.first)->translations(); + // check if this instrument is in range + if (!i.second.includes(time)) { + continue; + } + // if so, then get the corresponding spiceID + const std::vector& is = _fileTranslation.at(i.first)->translations(); - // check which specific subinstrument is firing - for (const std::string& s : ids) { - if (s == instrumentID) { - return static_cast( - (time - i.second.start) / (i.second.end - i.second.start) - ); - } - } + // check which specific subinstrument is firing + const auto it = std::find(is.begin(), is.end(), instrumentID); + if (it != is.end()) { + return static_cast( + (time - i.second.start) / (i.second.end - i.second.start) + ); } } return -1.f; } -bool ImageSequencer::imagePaths(std::vector& captures, - const std::string& projectee, - const std::string& instrumentRequest, - double time, double sinceTime) +std::vector ImageSequencer::imagePaths(const std::string& projectee, + const std::string& instrument, double time, + double sinceTime) { // TODO: Check how this works with time jumps // check if this instance is either in range or // a valid candidate to recieve data - const bool instrumentActive = isInstrumentActive(time, instrumentRequest); + const bool instrumentActive = isInstrumentActive(time, instrument); const bool hasCurrentTime = _subsetMap[projectee]._range.includes(time); const bool hasSinceTime = _subsetMap[projectee]._range.includes(sinceTime); if (!instrumentActive || (!hasCurrentTime && !hasSinceTime)) { - return false; + return std::vector(); } - // for readability we store the iterators auto begin = _subsetMap[projectee]._subset.begin(); - auto end = _subsetMap[projectee]._subset.end(); + auto end = _subsetMap[projectee]._subset.end(); // create temporary storage - std::vector captureTimes; + std::vector captures; // what to look for Image findPrevious, findCurrent; findPrevious.timeRange.start = sinceTime; @@ -259,59 +232,52 @@ bool ImageSequencer::imagePaths(std::vector& captures, auto curr = std::lower_bound(begin, end, findCurrent , compareTime); auto prev = std::lower_bound(begin, end, findPrevious, compareTime); - if (curr == begin || curr == end || prev == begin || prev == end || prev >= curr) { - return false; - } - - if (curr->timeRange.start < prev->timeRange.start) { - return false; + if (curr == begin || curr == end || prev == begin || prev == end || prev >= curr || + curr->timeRange.start < prev->timeRange.start) + { + return std::vector(); } std::copy_if( prev, curr, - back_inserter(captureTimes), - [instrumentRequest](const Image& i) { - return i.activeInstruments[0] == instrumentRequest; - } + back_inserter(captures), + [instrument](const Image& i) { return i.activeInstruments[0] == instrument; } ); - captures = captureTimes; if (!captures.empty()) { _latestImages[captures.back().activeInstruments.front()] = captures.back(); } std::vector toDelete; - for (auto it = captures.begin(); it != captures.end(); ++it) { - if (it->isPlaceholder) { - double beforeDist = std::numeric_limits::max(); - if (it != captures.begin()) { - beforeDist = std::abs( - std::prev(it)->timeRange.start - it->timeRange.start - ); - } + for (std::vector::iterator it = captures.begin(); it != captures.end(); ++it) { + if (!it->isPlaceholder) { + continue; + } - double nextDist = std::numeric_limits::max(); - if (it != captures.end() - 1) { - nextDist = std::abs( - std::next(it)->timeRange.start - it->timeRange.start - ); - } + double beforeDist = std::numeric_limits::max(); + if (it != captures.begin()) { + beforeDist = std::abs(std::prev(it)->timeRange.start - it->timeRange.start); + } - if (beforeDist < 1.0 || nextDist < 1.0) { - toDelete.push_back(static_cast(std::distance(captures.begin(), it))); - } + double nextDist = std::numeric_limits::max(); + if (it != captures.end() - 1) { + nextDist = std::abs(std::next(it)->timeRange.start - it->timeRange.start); + } + + if (beforeDist < 1.0 || nextDist < 1.0) { + toDelete.push_back(static_cast(std::distance(captures.begin(), it))); } } 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 + // 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); captures.erase(captures.begin() + v); } - return true; + return captures; } void ImageSequencer::sortData() { @@ -348,15 +314,12 @@ void ImageSequencer::sortData() { } void ImageSequencer::runSequenceParser(SequenceParser& parser) { - // get new data - std::map>& translations = - parser.translations(); - std::map& imageData = parser.getSubsetMap(); + std::map>& translations = parser.translations(); + std::map& imageData = parser.subsetMap(); const std::vector>& instrumentTimes = - parser.getInstrumentTimes(); - const std::vector>& targetTimes = - parser.getTargetTimes(); - const std::vector& captureProgression = parser.getCaptureProgression(); + parser.instrumentTimes(); + const std::vector>& targetTimes = parser.targetTimes(); + const std::vector& captureProgression = parser.captureProgression(); // check for sanity if (imageData.empty() || instrumentTimes.empty() || captureProgression.empty()) { @@ -382,11 +345,9 @@ void ImageSequencer::runSequenceParser(SequenceParser& parser) { // simple search function double min = 10; - auto findMin = [&](const std::vector& vector) -> double { - for (size_t i = 1; i < vector.size(); ++i) { - double e = std::abs( - vector[i].timeRange.start - vector[i - 1].timeRange.start - ); + auto findMin = [&](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); min = std::min(e, min); } return min; @@ -394,7 +355,6 @@ void ImageSequencer::runSequenceParser(SequenceParser& parser) { // find the smallest separation of images in time double epsilon; - //epsilon = findMin(source); epsilon = findMin(destination); // set epsilon as 1% smaller than min epsilon -= min * 0.01; @@ -409,8 +369,7 @@ void ImageSequencer::runSequenceParser(SequenceParser& parser) { } } } - // pad image data with predictions (ie - where no actual images, - // add placeholder) + // pad image data with predictions (ie - where no actual images, add placeholder) _subsetMap[key]._subset.insert( _subsetMap[key]._subset.end(), source.begin(), @@ -425,11 +384,7 @@ void ImageSequencer::runSequenceParser(SequenceParser& parser) { instrumentTimes.begin(), instrumentTimes.end() ); - _targetTimes.insert( - _targetTimes.end(), - targetTimes.begin(), - targetTimes.end() - ); + _targetTimes.insert(_targetTimes.end(), targetTimes.begin(), targetTimes.end()); _captureProgression.insert( _captureProgression.end(), captureProgression.begin(), diff --git a/modules/spacecraftinstruments/util/imagesequencer.h b/modules/spacecraftinstruments/util/imagesequencer.h index 6f5361a38d..539198cd43 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.h +++ b/modules/spacecraftinstruments/util/imagesequencer.h @@ -38,25 +38,25 @@ class Time; class SequenceParser; /** -* The ImageSequencer singleton main function is to manage the timekeeping and distribution -* of large image data-sets across all openspace renderable instances, both for past and -* future unmanned-spacecraft missions. To load the instance with data the client must -* provide a parser inherited from the abstract base class SequenceParser. Hence, there is -* no restriction imposed on data input, whether its data in the form of existing images or -* in the form of a planned observation schedule. Notably, in order for the sequencer to -* function the client must provide or write a parser that fills the ImageSequencers -* private members. -* -* \see SequenceParser -* \see ImageSequencer::runSequenceParser(SequenceParser* parser) -* std::map -*/ + * The ImageSequencer singleton function is to manage the timekeeping and distribution of + * large image data-sets across all openspace renderable instances, both for past and + * future unmanned-spacecraft missions. To load the instance with data the client must + * provide a parser inherited from the abstract base class SequenceParser. Hence, there is + * no restriction imposed on data input, whether its data in the form of existing images or + * in the form of a planned observation schedule. Notably, in order for the sequencer to + * function the client must provide or write a parser that fills the ImageSequencers + * private members. + * + * \see SequenceParser + * \see ImageSequencer::runSequenceParser(SequenceParser* parser) + */ class ImageSequencer { public: /** - * Singelton instantiation + * Singleton instantiation */ static ImageSequencer* _instance; + /** * Returns the reference to the singleton ImageSequencer object that must have been * initialized by a call to the initialize method earlier. @@ -64,18 +64,21 @@ public: * \return The ImageSequencer singleton */ static ImageSequencer& ref(); + /** * Initializer that initializes the static member. */ static void initialize(); + /** * Deinitializes that deinitializes the static member. */ static void deinitialize(); + /** * Returns true if sequencer has been loaded with data. */ - bool isReady(); + bool isReady() const; /** * Runs parser and recieves the datastructures filled by it. @@ -86,30 +89,22 @@ public: /** * Retrieves the next upcoming target in time. */ - std::pair nextTarget(double time); + std::pair nextTarget(double time) const; /** * Retrieves the most current target in time. */ - std::pair currentTarget(double time); + std::pair currentTarget(double time) const; /** - * Retrieves current target and (in the list) adjacent targets, the number to retrieve - * is user set + * Retrieves the time of the previous image capture. */ - std::pair> incidentTargetList(double time, - int range = 2); + double prevCaptureTime(double time) const; /** * Retrieves the next upcoming time of image capture. */ - double nextCaptureTime(double time); - - /** - * Retrieves the time interval length between the current time and an upcoming - * capture. - */ - double intervalLength(double time); + double nextCaptureTime(double time) const; /** * Returns a vector with key instrument names whose value indicate whether an @@ -118,56 +113,54 @@ public: std::vector> activeInstruments(double time); /** - * Retrieves the relevant data from a specific subset based on the what instance - * makes the request. If an instance is not registered in the class then the singleton + * Retrieves the relevant data from a specific subset based on the what instance makes + * the request. If an instance is not registered in the class then the singleton * returns false and no projections will occur. */ - bool imagePaths(std::vector& captures, const std::string& projectee, - const std::string& instrumentRequest, double time, double sinceTime); + std::vector imagePaths(const std::string& projectee, + const std::string& instrument, double time, double sinceTime); /** - * returns true if instrumentID is within a capture range. + * Returns true if instrumentID is within a capture range. */ - bool isInstrumentActive(double time, const std::string& instrumentID); + bool isInstrumentActive(double time, const std::string& instrument) const; float instrumentActiveTime(double time, const std::string& instrumentID) const; /** - * returns latest captured image + * Returns latest captured image */ - Image latestImageForInstrument(const std::string& instrumentID); + Image latestImageForInstrument(const std::string& instrumentID) const; private: void sortData(); /** - * _fileTranslation handles any types of ambiguities between the data and - * spice/openspace -calls. This map is composed of a key that is a string in - * the data to be translated and a Decoder that holds the corresponding - * translation provided through a modfile. + * This handles any types of ambiguities between the data and SPICE calls. This map is + * composed of a key that is a string in the data to be translated and a Decoder that + * holds the corresponding translation provided through as asset. * \see Decoder - * \see (projection mod files) */ std::map> _fileTranslation; /** - * This is the main container of image data. The key is the target name, - * the value is a subset of images. + * This is the main container of image data. The key is the target name, the value is + * a subset of images. * \see SequenceParser */ std::map _subsetMap; /** - * In order for the simulation to know when to turn on/off any instrument within - * all instruments in the spacecraft payload, the key is the data-file given - * instrument name. + * In order for the simulation to know when to turn on/off any instrument within all + * instruments in the spacecraft payload, the key is the data-file given instrument + * name. */ std::vector> _switchingMap; /** * This datastructure holds the specific times when the spacecraft switches from - * observing one inertial body to the next. This happens a lot in such missions - * and the coupling of target with specific time is usually therefore not 1:1. + * observing one inertial body to the next. This happens a lot in such missions and + * the coupling of target with specific time is usually therefore not 1:1. */ std::vector> _targetTimes; @@ -184,12 +177,15 @@ private: // time between current simulation time and an upcoming capture double _intervalLength = 0.0; + // next consecutive capture in time double _nextCapture = 0.0; + // default capture image std::string _defaultCaptureImage; std::map _latestImages; + // if no data, no run bool _hasData = false; }; diff --git a/modules/spacecraftinstruments/util/instrumentdecoder.cpp b/modules/spacecraftinstruments/util/instrumentdecoder.cpp index a17d11f1f2..2e61b5474d 100644 --- a/modules/spacecraftinstruments/util/instrumentdecoder.cpp +++ b/modules/spacecraftinstruments/util/instrumentdecoder.cpp @@ -57,7 +57,7 @@ InstrumentDecoder::InstrumentDecoder(const ghoul::Dictionary& dictionary) { _stopCommand = *p.stopCommand; } else { - LWARNING("Scanner must provide stop command, please check mod file."); + LWARNING("Scanner must provide stop command, please check asset file"); } _spiceIDs = p.spice; diff --git a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp index 3bf21f551f..ac37fd32ad 100644 --- a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp +++ b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -36,10 +37,16 @@ namespace { constexpr const char* _loggerCat = "InstrumentTimesParser"; - constexpr const char* KeyTargetBody = "Target.Body"; + constexpr const char* KeyTargetBody = "Target"; constexpr const char* KeyInstruments = "Instruments"; constexpr const char* KeyInstrument = "Instrument"; constexpr const char* KeyInstrumentFiles = "Files"; + + struct [[codegen::Dictionary(InstrumentTimesParser)]] Parameters { + std::string target; + std::map instruments; + }; +#include "instrumenttimesparser_codegen.cpp" } // namespace namespace openspace { @@ -50,18 +57,16 @@ InstrumentTimesParser::InstrumentTimesParser(std::string name, std::string seque , _name(std::move(name)) , _fileName(std::move(sequenceSource)) { + const Parameters p = codegen::bake(inputDict); - _target = inputDict.value(KeyTargetBody); - ghoul::Dictionary instruments = inputDict.value(KeyInstruments); - - for (std::string_view key : instruments.keys()) { - ghoul::Dictionary instrument = instruments.value(key); - ghoul::Dictionary files = instrument.value(KeyInstrumentFiles); - _fileTranslation[std::string(key)] = - Decoder::createFromDictionary(instrument, KeyInstrument); + _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); for (size_t i = 0; i < files.size(); i++) { std::string filename = files.value(std::to_string(i + 1)); - _instrumentFiles[std::string(key)].push_back(std::move(filename)); + _instrumentFiles[ps.first].push_back(std::move(filename)); } } } @@ -92,47 +97,46 @@ bool InstrumentTimesParser::create() { TimeRange instrumentActiveTimeRange; bool successfulRead = true; while (std::getline(inFile, line)) { - if (std::regex_match(line, matches, _pattern)) { - if (matches.size() != 3) { - LERROR( - "Bad event data formatting. Must \ - have regex 3 matches (source string, start time, stop time)." - ); - successfulRead = false; - break; - } - - TimeRange captureTimeRange; - try { // parse date strings - std::string start = matches[1].str(); - std::string stop = matches[2].str(); - captureTimeRange.start = - SpiceManager::ref().ephemerisTimeFromDate(start); - captureTimeRange.end = - SpiceManager::ref().ephemerisTimeFromDate(stop); - } - catch (const SpiceManager::SpiceException& e) { - LERROR(e.what()); - successfulRead = false; - break; - } - - instrumentActiveTimeRange.include(captureTimeRange); - - //_instrumentTimes.push_back({ instrumentID, timeRange }); - _targetTimes.emplace_back(captureTimeRange.start, _target); - _captureProgression.push_back(captureTimeRange.start); - - Image image = { - captureTimeRange, - std::string(), - { instrumentID }, - _target, - true, - false - }; - _subsetMap[_target]._subset.push_back(std::move(image)); + if (!std::regex_match(line, matches, _pattern)) { + continue; } + + if (matches.size() != 3) { + LERROR( + "Bad event data formatting. Must have regex 3 matches " + "(source string, start time, stop time)" + ); + successfulRead = false; + break; + } + + TimeRange tr; + try { // parse date strings + std::string start = matches[1].str(); + std::string stop = matches[2].str(); + tr.start = SpiceManager::ref().ephemerisTimeFromDate(start); + tr.end = SpiceManager::ref().ephemerisTimeFromDate(stop); + } + catch (const SpiceManager::SpiceException& e) { + LERROR(e.what()); + successfulRead = false; + break; + } + + instrumentActiveTimeRange.include(tr); + + _targetTimes.emplace_back(tr.start, _target); + _captureProgression.push_back(tr.start); + + Image image = { + tr, + std::string(), + { instrumentID }, + _target, + true, + false + }; + _subsetMap[_target]._subset.push_back(std::move(image)); } if (successfulRead){ _subsetMap[_target]._range.include(instrumentActiveTimeRange); diff --git a/modules/spacecraftinstruments/util/labelparser.cpp b/modules/spacecraftinstruments/util/labelparser.cpp index c06152e2b7..e9469306c1 100644 --- a/modules/spacecraftinstruments/util/labelparser.cpp +++ b/modules/spacecraftinstruments/util/labelparser.cpp @@ -36,7 +36,7 @@ namespace { constexpr const char* _loggerCat = "LabelParser"; - constexpr const char* keySpecs = "Read"; + constexpr const char* keySpecs = "Read"; constexpr const char* keyConvert = "Convert"; } // namespace @@ -44,8 +44,7 @@ namespace openspace { LabelParser::LabelParser(std::string name, std::string fileName, const ghoul::Dictionary& dictionary) - : _name(std::move(name)) - , _fileName(std::move(fileName)) + : _fileName(std::move(fileName)) { // get the different instrument types // for each decoder (assuming might have more if hong makes changes) @@ -121,7 +120,6 @@ std::string LabelParser::decode(const std::string& line) { if (value != std::string::npos) { std::string toTranslate = line.substr(value); return _fileTranslation[toTranslate]->translations()[0]; - } } return ""; @@ -146,10 +144,7 @@ bool LabelParser::create() { return false; } - std::string previousTarget; std::string lblName; - - namespace fs = std::filesystem; for (const fs::directory_entry& e : fs::recursive_directory_iterator(sequenceDir)) { if (!e.is_regular_file()) { @@ -163,8 +158,7 @@ bool LabelParser::create() { continue; } - std::string extension = std::filesystem::path(path).extension().string(); - + std::filesystem::path extension = std::filesystem::path(path).extension(); if (extension != ".lbl" && extension != ".LBL") { continue; } @@ -179,8 +173,6 @@ bool LabelParser::create() { int count = 0; // open up label files - //TimeRange instrumentRange; - double startTime = 0.0; double stopTime = 0.0; std::string line; @@ -193,14 +185,14 @@ bool LabelParser::create() { std::string read = line.substr(0, line.find_first_of('=')); - _detectorType = "CAMERA"; //default value + _detectorType = "CAMERA"; // default value constexpr const char* ErrorMsg = "Unrecognized '{}' in line {} in file {}. The 'Convert' table must " "contain the identity tranformation for all values encountered in the " "label files, for example: ROSETTA = {{ \"ROSETTA\" }}"; - /* Add more */ + // Add more if (read == "TARGET_NAME") { _target = decode(line); if (_target.empty()) { @@ -237,7 +229,7 @@ bool LabelParser::create() { startTime = SpiceManager::ref().ephemerisTimeFromDate(start); count++; - getline(file, line); + std::getline(file, line); line.erase(std::remove(line.begin(), line.end(), '"'), line.end()); line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); @@ -319,20 +311,23 @@ bool LabelParser::create() { } ); + std::string previousTarget; for (const Image& image : tmp) { - if (previousTarget != image.target) { - previousTarget = image.target; - _targetTimes.emplace_back(image.timeRange.start , image.target); - std::sort( - _targetTimes.begin(), - _targetTimes.end(), - [](const std::pair &a, - const std::pair &b) -> bool - { - return a.first < b.first; - } - ); + if (previousTarget == image.target) { + continue; } + + previousTarget = image.target; + _targetTimes.emplace_back(image.timeRange.start , image.target); + std::sort( + _targetTimes.begin(), + _targetTimes.end(), + [](const std::pair& a, + const std::pair& b) -> bool + { + return a.first < b.first; + } + ); } for (const std::pair& target : _subsetMap) { diff --git a/modules/spacecraftinstruments/util/labelparser.h b/modules/spacecraftinstruments/util/labelparser.h index 4e9667f2e8..7478fb236f 100644 --- a/modules/spacecraftinstruments/util/labelparser.h +++ b/modules/spacecraftinstruments/util/labelparser.h @@ -36,30 +36,17 @@ public: bool create() override; - // temporary need to figure this out - //std::map translations() { return _fileTranslation; }; - private: - void createImage(Image& image, double startTime, double stopTime, - std::vector instr, std::string target, std::string path); - std::string encode(const std::string& line) const; std::string decode(const std::string& line); - bool augmentWithSpice(Image& image, std::string spacecraft, - std::vector payload, std::vector potentialTargets); - - std::string _name; std::string _fileName; - std::string _spacecraft; std::vector _specsOfInterest; std::string _target; std::string _instrumentID; std::string _instrumentHostID; std::string _detectorType; - std::string _sequenceID; - bool _badDecoding = false; }; } // namespace openspace diff --git a/modules/spacecraftinstruments/util/projectioncomponent.cpp b/modules/spacecraftinstruments/util/projectioncomponent.cpp index 5d9c993ce6..5ae79ed728 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.cpp +++ b/modules/spacecraftinstruments/util/projectioncomponent.cpp @@ -30,11 +30,8 @@ #include #include #include -#include -#include #include #include -#include #include #include #include @@ -43,11 +40,8 @@ #include #include #include -#include namespace { - constexpr const char* keyTranslation = "DataInputTranslation"; - constexpr const char* keyTimesTranslation = "TimesDataInputTranslation"; constexpr const char* placeholderFile = "${DATA}/placeholder.png"; constexpr const char* _loggerCat = "ProjectionComponent"; @@ -157,6 +151,10 @@ namespace { // as planets usually have 2x1 aspect ratios, whereas this does not hold for // non-planet objects (comets, asteroids, etc). The default value is '1.0' std::optional aspectRatio; + + std::optional dataInputTranslation; + + std::optional timesDataInputTranslation; }; #include "projectioncomponent_codegen.cpp" } // namespace @@ -232,25 +230,25 @@ void ProjectionComponent::initialize(const std::string& identifier, throw ghoul::RuntimeError("Missing SequenceType"); } - ghoul::Dictionary translationDictionary; - if (dictionary.hasValue(keyTranslation)) { - translationDictionary = dictionary.value(keyTranslation); + ghoul::Dictionary translations; + if (p.dataInputTranslation.has_value()) { + translations = *p.dataInputTranslation; } else { - LWARNING("No playbook translation provided, spice calls must match playbook!"); + LWARNING("No playbook translation provided, SPICE calls must match playbook"); return; } std::vector> parsers; - for (std::string& sequenceSource : sequenceSources) { + for (std::string& source : sequenceSources) { switch (*p.sequenceType) { case Parameters::Type::Playbook: parsers.push_back( std::make_unique( identifier, - std::move(sequenceSource), + std::move(source), _projectorID, - translationDictionary, + translations, _potentialTargets ) ); @@ -259,8 +257,8 @@ void ProjectionComponent::initialize(const std::string& identifier, parsers.push_back( std::make_unique( identifier, - std::move(sequenceSource), - translationDictionary + std::move(source), + translations ) ); break; @@ -269,8 +267,8 @@ void ProjectionComponent::initialize(const std::string& identifier, parsers.push_back( std::make_unique( identifier, - std::move(sequenceSource), - translationDictionary + std::move(source), + translations ) ); @@ -280,7 +278,7 @@ void ProjectionComponent::initialize(const std::string& identifier, identifier, absPath(*p.eventFile).string(), _projectorID, - translationDictionary, + translations, _potentialTargets ) ); @@ -293,8 +291,8 @@ void ProjectionComponent::initialize(const std::string& identifier, parsers.push_back( std::make_unique( identifier, - std::move(sequenceSource), - translationDictionary + std::move(source), + translations ) ); break; @@ -303,18 +301,18 @@ void ProjectionComponent::initialize(const std::string& identifier, parsers.push_back( std::make_unique( identifier, - std::move(sequenceSource), - translationDictionary + std::move(source), + translations ) ); if (!p.timesSequence.has_value()) { throw ghoul::RuntimeError("Could not find required TimesSequence"); } + ghoul::Dictionary timesTranslationDictionary; - if (dictionary.hasValue(keyTimesTranslation)) { - timesTranslationDictionary = - dictionary.value(keyTimesTranslation); + if (p.timesDataInputTranslation.has_value()) { + timesTranslationDictionary = *p.timesDataInputTranslation; } parsers.push_back( @@ -331,11 +329,11 @@ void ProjectionComponent::initialize(const std::string& identifier, for (std::unique_ptr& parser : parsers) { bool success = parser->create(); - if (!success) { - LERROR("One or more sequence loads failed; please check mod files"); + if (success) { + ImageSequencer::ref().runSequenceParser(*parser); } else { - ImageSequencer::ref().runSequenceParser(*parser); + LERROR("One or more sequence loads failed; please check asset files"); } } parsers.clear(); @@ -365,11 +363,9 @@ bool ProjectionComponent::initializeGL() { success &= auxiliaryRendertarget(); success &= depthRendertarget(); - using std::unique_ptr; using ghoul::opengl::Texture; - using ghoul::io::TextureReader; - unique_ptr texture = TextureReader::ref().loadTexture( + std::unique_ptr texture = ghoul::io::TextureReader::ref().loadTexture( absPath(placeholderFile).string() ); if (texture) { @@ -387,12 +383,12 @@ bool ProjectionComponent::initializeGL() { ); const GLfloat plane[] = { - -1, -1, - 1, 1, - -1, 1, - -1, -1, - 1, -1, - 1, 1, + -1.0, -1.0, + 1.0, 1.0, + -1.0, 1.0, + -1.0, -1.0, + 1.0, -1.0, + 1.0, 1.0, }; glGenVertexArrays(1, &_dilation.vao); @@ -402,22 +398,14 @@ bool ProjectionComponent::initializeGL() { glBindBuffer(GL_ARRAY_BUFFER, _dilation.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(plane), plane, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer( - 0, - 2, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 2, - nullptr - ); - + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); } return success; } -bool ProjectionComponent::deinitialize() { +void ProjectionComponent::deinitialize() { _projectionTexture = nullptr; glDeleteFramebuffers(1, &_fboID); @@ -430,8 +418,6 @@ bool ProjectionComponent::deinitialize() { _dilation.program = nullptr; _dilation.texture = nullptr; } - - return true; } bool ProjectionComponent::isReady() const { @@ -443,11 +429,8 @@ void ProjectionComponent::imageProjectBegin() { glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); if (_textureSizeDirty) { - LDEBUG( - fmt::format( - "Changing texture size to {}", ghoul::to_string(_textureSize.value()) - ) - ); + glm::ivec2 size = _textureSize; + LDEBUG(fmt::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 @@ -469,35 +452,21 @@ void ProjectionComponent::imageProjectBegin() { } auto copyFramebuffers = [](Texture* src, Texture* dst, const std::string& msg) { - glFramebufferTexture( - GL_READ_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - *src, - 0 - ); + glFramebufferTexture(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, *src, 0); GLenum status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { LERROR(fmt::format( - "Read Buffer ({}): {}", - msg, - FramebufferObject::errorChecking(status) + "Read Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } - glFramebufferTexture( - GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - *dst, - 0 - ); + glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, *dst, 0); status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { LERROR(fmt::format( - "Draw Buffer ({}): {}", - msg, - FramebufferObject::errorChecking(status) + "Draw Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -512,35 +481,21 @@ void ProjectionComponent::imageProjectBegin() { }; auto copyDepthBuffer = [](Texture* src, Texture* dst, const std::string& msg) { - glFramebufferTexture( - GL_READ_FRAMEBUFFER, - GL_DEPTH_ATTACHMENT, - *src, - 0 - ); + glFramebufferTexture(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, *src, 0); GLenum status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { LERROR(fmt::format( - "Read Buffer ({}): {}", - msg, - FramebufferObject::errorChecking(status) + "Read Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } - glFramebufferTexture( - GL_DRAW_FRAMEBUFFER, - GL_DEPTH_ATTACHMENT, - *dst, - 0 - ); + glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, *dst, 0); status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { LERROR(fmt::format( - "Draw Buffer ({}): {}", - msg, - FramebufferObject::errorChecking(status) + "Draw Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -580,11 +535,7 @@ void ProjectionComponent::imageProjectBegin() { } if (_shadowing.isEnabled) { - copyDepthBuffer( - oldDepthTexture.get(), - _shadowing.texture.get(), - "Shadowing" - ); + copyDepthBuffer(oldDepthTexture.get(), _shadowing.texture.get(), "Shadowing"); } glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); @@ -671,7 +622,7 @@ void ProjectionComponent::depthMapRenderBegin() { 0, 0, static_cast(_shadowing.texture->width()), static_cast(_shadowing.texture->height()) - ); + ); glClear(GL_DEPTH_BUFFER_BIT); } @@ -729,7 +680,8 @@ bool ProjectionComponent::depthRendertarget() { GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, *_shadowing.texture, - 0); + 0 + ); glDrawBuffer(GL_NONE); @@ -816,9 +768,9 @@ glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3 loc, glm:: glm::vec3& boreSight) { - //rotate boresight into correct alignment - boreSight = instrumentMatrix*aim; - glm::vec3 uptmp(instrumentMatrix*glm::dvec3(up)); + // rotate boresight into correct alignment + boreSight = instrumentMatrix * aim; + glm::vec3 uptmp = instrumentMatrix * glm::dvec3(up); // create view matrix glm::vec3 e3 = glm::normalize(-boreSight); @@ -836,7 +788,7 @@ glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3 loc, glm:: glm::radians(fieldOfViewY), aspectRatio, nearPlane, farPlane ); - return projProjectionMatrix*projViewMatrix; + return projProjectionMatrix * projViewMatrix; } bool ProjectionComponent::doesPerformProjection() const { @@ -914,15 +866,13 @@ void ProjectionComponent::clearAllProjections() { } glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(m_viewport[0], m_viewport[1], - m_viewport[2], m_viewport[3]); + glViewport(m_viewport[0], m_viewport[1], m_viewport[2], m_viewport[3]); _clearAllProjections = false; _mipMapDirty = true; } void ProjectionComponent::generateMipMap() { - _projectionTexture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); _mipMapDirty = false; } @@ -931,17 +881,13 @@ std::shared_ptr ProjectionComponent::loadProjectionTextu const std::string& texturePath, bool isPlaceholder) { - using std::unique_ptr; using ghoul::opengl::Texture; - using ghoul::io::TextureReader; - if (isPlaceholder) { return _placeholderTexture; } - - unique_ptr texture = TextureReader::ref().loadTexture( + std::unique_ptr texture = ghoul::io::TextureReader::ref().loadTexture( absPath(texturePath).string() ); if (texture) { @@ -977,23 +923,16 @@ bool ProjectionComponent::generateProjectionLayerTexture(const glm::ivec2& size) if (_dilation.texture) { _dilation.texture->uploadTexture(); - //_dilation.texture->setFilter( - // ghoul::opengl::Texture::FilterMode::AnisotropicMipMap - //); } _dilation.stencilTexture = std::make_unique( glm::uvec3(size, 1), ghoul::opengl::Texture::Format::Red, - // @TODO: Remove the static cast ---abock static_cast(ghoul::opengl::Texture::Format::Red) ); if (_dilation.stencilTexture) { _dilation.stencilTexture->uploadTexture(); - //_dilation.texture->setFilter( - // ghoul::opengl::Texture::FilterMode::AnisotropicMipMap - //); } } @@ -1014,7 +953,6 @@ bool ProjectionComponent::generateDepthTexture(const glm::ivec2& size) { } return _shadowing.texture != nullptr; - } } // namespace openspace diff --git a/modules/spacecraftinstruments/util/projectioncomponent.h b/modules/spacecraftinstruments/util/projectioncomponent.h index 322b9eaf5b..be96533758 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.h +++ b/modules/spacecraftinstruments/util/projectioncomponent.h @@ -50,7 +50,7 @@ public: void initialize(const std::string& identifier, const ghoul::Dictionary& dictionary); bool initializeGL(); - bool deinitialize(); + void deinitialize(); bool isReady() const; diff --git a/modules/spacecraftinstruments/util/scannerdecoder.cpp b/modules/spacecraftinstruments/util/scannerdecoder.cpp index c7ccf2bc50..53aef7b2bf 100644 --- a/modules/spacecraftinstruments/util/scannerdecoder.cpp +++ b/modules/spacecraftinstruments/util/scannerdecoder.cpp @@ -26,15 +26,19 @@ #include +namespace { + std::string Type = "SCANNER"; +} // namespace + namespace openspace { -ScannerDecoder::ScannerDecoder(const ghoul::Dictionary& dictionary) : _type("SCANNER") { +ScannerDecoder::ScannerDecoder(const ghoul::Dictionary& dictionary) { for (size_t k = 0; k < dictionary.size(); k++) { _spiceIDs.push_back(dictionary.value(std::to_string(k + 1))); } } const std::string& ScannerDecoder::decoderType() const { - return _type; + return Type; } const std::vector& ScannerDecoder::spiceIDs() const { diff --git a/modules/spacecraftinstruments/util/scannerdecoder.h b/modules/spacecraftinstruments/util/scannerdecoder.h index 75b0f2e663..15b19cc1ef 100644 --- a/modules/spacecraftinstruments/util/scannerdecoder.h +++ b/modules/spacecraftinstruments/util/scannerdecoder.h @@ -37,11 +37,9 @@ public: virtual const std::string& decoderType() const override; const std::vector& spiceIDs() const; - const std::string& stopCommand() const; void setStopCommand(std::string stopCommand); private: - std::string _type; std::string _abort; std::vector _spiceIDs; }; diff --git a/modules/spacecraftinstruments/util/sequenceparser.cpp b/modules/spacecraftinstruments/util/sequenceparser.cpp index 59ebc56128..c8ea3d79ed 100644 --- a/modules/spacecraftinstruments/util/sequenceparser.cpp +++ b/modules/spacecraftinstruments/util/sequenceparser.cpp @@ -27,26 +27,23 @@ #include #include #include -#include namespace openspace { -std::map& SequenceParser::getSubsetMap() { +std::map& SequenceParser::subsetMap() { return _subsetMap; } const std::vector>& -SequenceParser::getInstrumentTimes() const +SequenceParser::instrumentTimes() const { return _instrumentTimes; } -const std::vector>& -SequenceParser::getTargetTimes() const -{ +const std::vector>& SequenceParser::targetTimes() const { return _targetTimes; } -const std::vector& SequenceParser::getCaptureProgression() const { +const std::vector& SequenceParser::captureProgression() const { return _captureProgression; } diff --git a/modules/spacecraftinstruments/util/sequenceparser.h b/modules/spacecraftinstruments/util/sequenceparser.h index d90005da5a..ba4162034d 100644 --- a/modules/spacecraftinstruments/util/sequenceparser.h +++ b/modules/spacecraftinstruments/util/sequenceparser.h @@ -26,9 +26,8 @@ #define __OPENSPACE_MODULE_SPACECRAFTINSTRUMENTS___SEQUENCEPARSER___H__ #include -#include #include - +#include #include #include #include @@ -40,11 +39,12 @@ class SequenceParser { public: virtual ~SequenceParser() = default; virtual bool create() = 0; - std::map& getSubsetMap(); - const std::vector>& getInstrumentTimes() const; - const std::vector>& getTargetTimes() const ; + + std::map& subsetMap(); + const std::vector>& instrumentTimes() const; + const std::vector>& targetTimes() const ; std::map>& translations(); - const std::vector& getCaptureProgression() const; + const std::vector& captureProgression() const; protected: std::map _subsetMap; diff --git a/modules/spacecraftinstruments/util/targetdecoder.cpp b/modules/spacecraftinstruments/util/targetdecoder.cpp index 4f69884f77..ee8ff4c514 100644 --- a/modules/spacecraftinstruments/util/targetdecoder.cpp +++ b/modules/spacecraftinstruments/util/targetdecoder.cpp @@ -26,21 +26,24 @@ #include +namespace { + std::string Type = "TARGET"; +} // namespace + namespace openspace { -TargetDecoder::TargetDecoder(const ghoul::Dictionary& dictionary) : _type("TARGET") { +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); if (dictionary.hasKey(key) && dictionary.hasValue(key)) { - std::string readMe = dictionary.value(key); - _names[i] = readMe; + _names[i] = dictionary.value(key);; } } } const std::string& TargetDecoder::decoderType() const { - return _type; + return Type; } const std::vector& TargetDecoder::translations() const { diff --git a/modules/spacecraftinstruments/util/targetdecoder.h b/modules/spacecraftinstruments/util/targetdecoder.h index e26f9ebb7c..0894b2a36c 100644 --- a/modules/spacecraftinstruments/util/targetdecoder.h +++ b/modules/spacecraftinstruments/util/targetdecoder.h @@ -37,7 +37,6 @@ public: virtual const std::vector& translations() const override; private: - std::string _type; std::vector _names; }; diff --git a/modules/touch/shaders/marker_fs.glsl b/modules/touch/shaders/marker_fs.glsl index 6b09a05a8e..26e79d594c 100644 --- a/modules/touch/shaders/marker_fs.glsl +++ b/modules/touch/shaders/marker_fs.glsl @@ -27,30 +27,28 @@ in vec2 out_position; -uniform float radius; uniform float opacity; uniform float thickness; uniform vec3 color; - Fragment getFragment() { - // calculate normal from texture coordinates - vec3 n; - n.xy = gl_PointCoord.st * vec2(2.0, -2.0) + vec2(-1.0, 1.0); - float mag = dot(n.xy, n.xy); - if (mag > 1.0) { - // kill pixels outside circle - discard; - } - n.z = sqrt(1.0 - mag); - - // calculate lighting - vec3 light_dir = vec3(0.0, 0.0, 1.0); - float diffuse = max(0.0, dot(light_dir, n)); - float alpha = min(pow(sqrt(mag), thickness), opacity); + // calculate normal from texture coordinates + vec3 n; + n.xy = gl_PointCoord.st * vec2(2.0, -2.0) + vec2(-1.0, 1.0); + float mag = dot(n.xy, n.xy); + if (mag > 1.0) { + // kill pixels outside circle + discard; + } + n.z = sqrt(1.0 - mag); + + // calculate lighting + vec3 light_dir = vec3(0.0, 0.0, 1.0); + float diffuse = max(0.0, dot(light_dir, n)); + float alpha = min(pow(sqrt(mag), thickness), opacity); - Fragment frag; - frag.color = vec4(color * diffuse, alpha); - frag.depth = 1.0; - return frag; + Fragment frag; + frag.color = vec4(color * diffuse, alpha); + frag.depth = 1.0; + return frag; } diff --git a/modules/touch/shaders/marker_vs.glsl b/modules/touch/shaders/marker_vs.glsl index b57089428c..ea92dadaa3 100644 --- a/modules/touch/shaders/marker_vs.glsl +++ b/modules/touch/shaders/marker_vs.glsl @@ -30,10 +30,9 @@ out vec2 out_position; uniform float radius; - void main() { - out_position = in_position; + out_position = in_position; - gl_PointSize = radius; - gl_Position = vec4(in_position, -1.0, 1.0); + gl_PointSize = radius; + gl_Position = vec4(in_position, -1.0, 1.0); } diff --git a/modules/webbrowser/include/browserclient.h b/modules/webbrowser/include/browserclient.h index 7cc98ef6c5..f884a110bc 100644 --- a/modules/webbrowser/include/browserclient.h +++ b/modules/webbrowser/include/browserclient.h @@ -43,7 +43,6 @@ class WebKeyboardHandler; class BrowserClient : public CefClient { public: - class NoContextMenuHandler : public CefContextMenuHandler { bool RunContextMenu(CefRefPtr browser, CefRefPtr frame, CefRefPtr params, CefRefPtr model, diff --git a/modules/webbrowser/include/browserinstance.h b/modules/webbrowser/include/browserinstance.h index 8ff3349fcf..f0a99f3a34 100644 --- a/modules/webbrowser/include/browserinstance.h +++ b/modules/webbrowser/include/browserinstance.h @@ -62,6 +62,7 @@ public: ~BrowserInstance(); void loadUrl(std::string url); + /** * Load a local file. * @@ -79,14 +80,14 @@ public: void reshape(const glm::ivec2& windowSize); /** - * encapsulate renderHandler's draw method + * Encapsulate renderHandler's draw method */ void draw(); void close(bool force = false); #ifdef WIN32 void sendTouchEvent(const CefTouchEvent& event) const; -#endif +#endif // WIN32 bool sendKeyEvent(const CefKeyEvent& event); bool sendMouseClickEvent(const CefMouseEvent& event, @@ -96,7 +97,7 @@ public: bool sendMouseMoveEvent(const CefMouseEvent& event); /** - * send scroll wheel event to browser + * Send scroll wheel event to browser * * \param event Key event with position * \param delta The scroll amount in pixels @@ -104,10 +105,7 @@ public: */ bool sendMouseWheelEvent(const CefMouseEvent& event, const glm::ivec2& delta); - /** - * Set the browser zoom level. - * 1.0 = default, 2.0 = double, etc. - */ + /// Set the browser zoom level. 1.0 = default, 2.0 = double, etc. void setZoom(float ratio); void reloadBrowser(); @@ -116,7 +114,7 @@ public: const CefRefPtr& getBrowser() const; - bool hasContent(int x, int y); + bool hasContent(const glm::ivec2& pos) const; bool _shouldReshape = false; diff --git a/modules/webbrowser/include/eventhandler.h b/modules/webbrowser/include/eventhandler.h index 36758e0627..1ef3f35fa6 100644 --- a/modules/webbrowser/include/eventhandler.h +++ b/modules/webbrowser/include/eventhandler.h @@ -79,19 +79,16 @@ private: /** * Create a mouse event on the current cursor position. - * - * \return */ CefMouseEvent mouseEvent(KeyModifier mods = KeyModifier::NoModifier); #ifdef WIN32 /** - * Build a CEF touch event based on our internal structure + * Build a CEF touch event based on our internal structure. * - * Note: as of 02/21/2020 we are using an older version of CEF on OSX - * than WIN32. - * This version does not handle the CefTouchEvent type and does - * not have any internal touch handling. + * Note: As of 2020-02-21 we are using an older version of CEF on OSX than WIN32. This + * version does not handle the CefTouchEvent type and does not have any internal + * touch handling */ CefTouchEvent touchEvent(const TouchInput& input, const cef_touch_event_type_t eventType) const; @@ -117,12 +114,11 @@ private: MouseButtonState _leftButton; MouseButtonState _rightButton; - //This vector assumes first element to be the active one: + // This vector assumes first element to be the active one: std::vector _validTouchStates; /** - * determines if a click should be sent as a double click or not - * @return + * Determines if a click should be sent as a double click or not */ bool isDoubleClick(const MouseButtonState& button) const; }; diff --git a/modules/webbrowser/src/browserclient.cpp b/modules/webbrowser/src/browserclient.cpp index b8c550128c..1250f06adb 100644 --- a/modules/webbrowser/src/browserclient.cpp +++ b/modules/webbrowser/src/browserclient.cpp @@ -65,11 +65,10 @@ CefRefPtr BrowserClient::GetKeyboardHandler() { return _keyboardHandler; } -bool BrowserClient::NoContextMenuHandler::RunContextMenu( - CefRefPtr, - CefRefPtr, - CefRefPtr, - CefRefPtr, +bool BrowserClient::NoContextMenuHandler::RunContextMenu(CefRefPtr, + CefRefPtr, + CefRefPtr, + CefRefPtr, CefRefPtr) { // Disable the context menu. diff --git a/modules/webbrowser/src/browserinstance.cpp b/modules/webbrowser/src/browserinstance.cpp index 0fdc01a1c9..66f8dae363 100644 --- a/modules/webbrowser/src/browserinstance.cpp +++ b/modules/webbrowser/src/browserinstance.cpp @@ -98,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(fmt::format("Could not find path '{}', verify that it is correct", path)); return false; } @@ -143,18 +143,17 @@ bool BrowserInstance::sendKeyEvent(const CefKeyEvent& event) { bool BrowserInstance::sendMouseClickEvent(const CefMouseEvent& event, CefBrowserHost::MouseButtonType button, - bool mouseUp, - int clickCount) + bool mouseUp, int clickCount) { _browser->GetHost()->SendMouseClickEvent(event, button, mouseUp, clickCount); - return hasContent(event.x, event.y); + return hasContent(glm::ivec2(event.x, event.y)); } #ifdef WIN32 void BrowserInstance::sendTouchEvent(const CefTouchEvent& event) const{ _browser->GetHost()->SendTouchEvent(event); } -#endif +#endif // WIN32 bool BrowserInstance::sendMouseMoveEvent(const CefMouseEvent& event) { constexpr const bool DidNotLeaveWindow = false; @@ -167,7 +166,7 @@ bool BrowserInstance::sendMouseWheelEvent(const CefMouseEvent& event, const glm::ivec2& delta) { _browser->GetHost()->SendMouseWheelEvent(event, delta.x, delta.y); - return hasContent(event.x, event.y); + return hasContent(glm::ivec2(event.x, event.y)); } void BrowserInstance::setZoom(float ratio) { @@ -175,7 +174,7 @@ void BrowserInstance::setZoom(float ratio) { // Zooming in CEF is non-linear according to this: // https://www.magpcss.org/ceforum/viewtopic.php?f=6&t=11491 - _zoomLevel = glm::log(static_cast(ratio * dpiScaling))/glm::log(1.2); + _zoomLevel = glm::log(ratio * dpiScaling) / glm::log(1.2); _browser->GetHost()->SetZoomLevel(_zoomLevel); } @@ -189,8 +188,8 @@ void BrowserInstance::selectAll() { } } -bool BrowserInstance::hasContent(int x, int y) { - return _renderHandler->hasContent(x, y); +bool BrowserInstance::hasContent(const glm::ivec2& pos) const { + return _renderHandler->hasContent(pos.x, pos.y); } } // namespace openspace diff --git a/modules/webbrowser/src/cefhost.cpp b/modules/webbrowser/src/cefhost.cpp index 49bbf51c99..0465400715 100644 --- a/modules/webbrowser/src/cefhost.cpp +++ b/modules/webbrowser/src/cefhost.cpp @@ -32,7 +32,7 @@ #ifdef __APPLE__ #include -#endif +#endif // __APPLE__ namespace { constexpr const char* _loggerCat = "CefHost"; @@ -40,41 +40,38 @@ namespace { namespace openspace { -CefHost::CefHost(const std::string& helperLocation) { +CefHost::CefHost([[maybe_unused]] const std::string& helperLocation) { LDEBUG("Initializing CEF..."); CefSettings settings; #ifndef __APPLE__ - // Apple will always look for helper in a fixed location. + // Apple will always look for helper in a fixed location CefString(&settings.browser_subprocess_path).FromString(helperLocation); -#else - // Silence a warning about unused variable - (void)helperLocation; -#endif +#endif // __APPLE__ settings.windowless_rendering_enabled = true; attachDebugSettings(settings); #ifdef WIN32 - // Enable High-DPI support on Windows 7 or newer. + // Enable High-DPI support on Windows 7 or newer CefEnableHighDPISupport(); -#endif +#endif // WIN32 #ifdef __APPLE__ - // Load the CEF framework library at runtime instead of linking directly - // as required by the macOS sandbox implementation. + // Load the CEF framework library at runtime instead of linking directly as required + // by the macOS sandbox implementation CefScopedLibraryLoader library_loader; if (!library_loader.LoadInMain()) { return; } -#endif +#endif // __APPLE__ CefRefPtr app(new WebBrowserApp); CefMainArgs args; CefInitialize(args, settings, app.get(), nullptr); - LDEBUG("Initializing CEF... done!"); + LDEBUG("Initializing CEF... done"); } CefHost::~CefHost() { diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index 39e6b591df..6a7cd15a0f 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -28,18 +28,7 @@ #ifdef WIN32 #include -#endif - -namespace { - -void launchBrowser(const std::string& url) { - LDEBUGC("DefaultBrowserLauncher", "Launching default browser: " + url); -#ifdef WIN32 - ShellExecuteA(nullptr, nullptr, url.c_str(), nullptr, nullptr, SW_SHOW); -#endif -} - -} // namespace +#endif // WIN32 namespace openspace { @@ -51,7 +40,11 @@ bool DefaultBrowserLauncher::OnBeforePopup(CefRefPtr, CefRefPtremplace_back( [this](double x, double y) -> bool { if (_browserInstance) { - const glm::ivec2 delta(x, y); - return mouseWheelCallback(delta); + return mouseWheelCallback(glm::ivec2(x, y)); } return false; } @@ -201,10 +197,7 @@ void EventHandler::initialize() { } const glm::vec2 windowPos = input.currentWindowCoordinates(); - const bool hasContent = _browserInstance->hasContent( - static_cast(windowPos.x), - static_cast(windowPos.y) - ); + const bool hasContent = _browserInstance->hasContent(windowPos); if (!hasContent) { return false; } @@ -238,10 +231,7 @@ void EventHandler::initialize() { global::callback::touchUpdated->emplace_back( [&](TouchInput input) -> bool { - if (!_browserInstance) { - return false; - } - if (_validTouchStates.empty()) { + if (!_browserInstance || _validTouchStates.empty()) { return false; } @@ -250,28 +240,27 @@ void EventHandler::initialize() { _validTouchStates.cend(), [&](const TouchInput& state){ return state.fingerId == input.fingerId && - state.touchDeviceId == input.touchDeviceId; + state.touchDeviceId == input.touchDeviceId; } ); if (it == _validTouchStates.cbegin()) { #ifdef WIN32 - CefTouchEvent event = touchEvent( input, cef_touch_event_type_t::CEF_TET_MOVED ); _browserInstance->sendTouchEvent(event); -#else +#else // ^^^^ WIN32 // !WIN32 vvvv glm::vec2 windowPos = input.currentWindowCoordinates(); _mousePosition.x = windowPos.x; _mousePosition.y = windowPos.y; _leftButton.down = true; _browserInstance->sendMouseMoveEvent(mouseEvent()); -#endif +#endif // WIN32 return true; } - else if (it != _validTouchStates.cend()){ + else if (it != _validTouchStates.cend()) { return true; } return false; @@ -305,7 +294,7 @@ void EventHandler::initialize() { cef_touch_event_type_t::CEF_TET_RELEASED ); _browserInstance->sendTouchEvent(event); -#endif +#endif // WIN32 _validTouchStates.erase(found); #ifndef WIN32 if (_validTouchStates.empty()) { @@ -320,7 +309,7 @@ void EventHandler::initialize() { BrowserInstance::SingleClick ); } -#endif +#endif // WIN32 } ); } @@ -362,11 +351,8 @@ bool EventHandler::mouseButtonCallback(MouseButton button, MouseAction action, } bool EventHandler::isDoubleClick(const MouseButtonState& button) const { - // check time - using namespace std::chrono; - - auto now = high_resolution_clock::now(); - milliseconds maxTimeDifference(doubleClickTime()); + auto now = std::chrono::high_resolution_clock::now(); + std::chrono::milliseconds maxTimeDifference(doubleClickTime()); auto requiredTime = button.lastClickTime + maxTimeDifference; if (requiredTime < now) { return false; @@ -419,11 +405,11 @@ bool EventHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction act CefKeyEvent keyEvent; // TODO(klas): Use something less platform specific? - keyEvent.windows_key_code = mapFromGlfwToWindows(key); - keyEvent.native_key_code = mapFromGlfwToNative(key); + keyEvent.windows_key_code = mapFromGlfwToWindows(key); + keyEvent.native_key_code = mapFromGlfwToNative(key); keyEvent.unmodified_character = mapFromGlfwToUnmodifiedCharacter(key); - keyEvent.modifiers = mapToCefModifiers(modifier); - keyEvent.type = keyEventType(action); + keyEvent.modifiers = mapToCefModifiers(modifier); + keyEvent.type = keyEventType(action); return _browserInstance->sendKeyEvent(keyEvent); } @@ -467,7 +453,7 @@ CefMouseEvent EventHandler::mouseEvent(KeyModifier mods) { #ifdef WIN32 CefTouchEvent EventHandler::touchEvent(const TouchInput& input, - const cef_touch_event_type_t eventType) const + const cef_touch_event_type_t eventType) const { const glm::vec2 windowPos = input.currentWindowCoordinates(); CefTouchEvent event = {}; @@ -475,19 +461,19 @@ CefTouchEvent EventHandler::touchEvent(const TouchInput& input, event.x = windowPos.x; event.y = windowPos.y; event.type = eventType; - const std::vector>& keyModVec = + const std::vector>& keyMods = global::navigationHandler->inputState().pressedKeys(); - for (const std::pair& keyModPair : keyModVec) { - const KeyModifier mods = keyModPair.second; + for (const std::pair& p : keyMods) { + const KeyModifier mods = p.second; event.modifiers |= static_cast(mapToCefModifiers(mods)); } event.pointer_type = cef_pointer_type_t::CEF_POINTER_TYPE_TOUCH; return event; } -#endif +#endif // WIN32 void EventHandler::setBrowserInstance(BrowserInstance* browserInstance) { - LDEBUG("Setting browser instance."); + LDEBUG("Setting browser instance"); _browserInstance = browserInstance; } diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index a2c4df95fe..b4e3a87765 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -27,11 +27,13 @@ #include #include #include +#include #include #include #include #include #include +#include namespace { constexpr const char* _loggerCat = "ScreenSpaceBrowser"; @@ -41,6 +43,7 @@ namespace { "Browser Dimensions", "Set the dimensions of the web browser windows." }; + const openspace::properties::Property::PropertyInfo UrlInfo = { "Url", "URL", @@ -53,6 +56,12 @@ namespace { "Reload the web browser" }; + struct [[codegen::Dictionary(ScreenSpaceBrowser)]] Parameters { + std::optional identifier; + std::optional url; + }; +#include "screenspacebrowser_codegen.cpp" + } // namespace namespace openspace { @@ -65,31 +74,24 @@ void ScreenSpaceBrowser::ScreenSpaceRenderHandler::setTexture(GLuint t) { _texture = t; } -ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) +ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary& dictionary) : ScreenSpaceRenderable(dictionary) , _url(UrlInfo) , _dimensions(DimensionsInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(3000.f)) , _reload(ReloadInfo) { + const Parameters p = codegen::bake(dictionary); - std::string identifier; - if (dictionary.hasValue(KeyIdentifier)) { - identifier = dictionary.value(KeyIdentifier); - } - else { - identifier = "ScreenSpaceBrowser"; - } + std::string identifier = p.identifier.value_or("ScreenSpaceBrowser"); identifier = makeUniqueIdentifier(identifier); setIdentifier(identifier); - if (dictionary.hasValue(UrlInfo.identifier)) { - _url = dictionary.value(UrlInfo.identifier); - } + _url = p.url.value_or(_url); glm::vec2 windowDimensions = global::windowDelegate->currentSubwindowSize(); _dimensions = windowDimensions; - _renderHandler = new ScreenSpaceRenderHandler(); + _renderHandler = new ScreenSpaceRenderHandler; _keyboardHandler = new WebKeyboardHandler(); _browserInstance = std::make_unique( _renderHandler, @@ -112,7 +114,7 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) bool ScreenSpaceBrowser::initializeGL() { _texture = std::make_unique( - glm::uvec3(_dimensions.value(), 1.0f) + glm::uvec3(_dimensions.value(), 1.f) ); _renderHandler->setTexture(*_texture); @@ -128,9 +130,7 @@ bool ScreenSpaceBrowser::deinitializeGL() { _renderHandler->setTexture(0); _texture = nullptr; - std::string urlString; - _url.getStringValue(urlString); - LDEBUG(fmt::format("Deinitializing ScreenSpaceBrowser: {}", urlString)); + LDEBUG(fmt::format("Deinitializing ScreenSpaceBrowser: {}", _url.value())); _browserInstance->close(true); @@ -150,6 +150,7 @@ void ScreenSpaceBrowser::render() { if (!_renderHandler->isTextureReady()) { return; } + _renderHandler->updateTexture(); draw( globalRotationMatrix() * diff --git a/modules/webbrowser/src/webbrowserapp.cpp b/modules/webbrowser/src/webbrowserapp.cpp index 6ba297f9cc..2e9d085d92 100644 --- a/modules/webbrowser/src/webbrowserapp.cpp +++ b/modules/webbrowser/src/webbrowserapp.cpp @@ -23,7 +23,6 @@ ****************************************************************************************/ #include "include/webbrowserapp.h" -//#include namespace openspace { diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index 622c888385..3b68498d42 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -141,8 +141,7 @@ void WebBrowserModule::internalInitialize(const ghoul::Dictionary& dictionary) { } const bool isMaster = global::windowDelegate->isMaster(); - - if (!_enabled || (!isMaster) ) { + if (!_enabled || (!isMaster)) { return; } @@ -189,7 +188,7 @@ void WebBrowserModule::removeBrowser(BrowserInstance* browser) { _browsers.erase(p); } else { - LWARNING("Could not find browser in list of browsers."); + LWARNING("Could not find browser in list of browsers"); } if (_browsers.empty()) { @@ -215,17 +214,14 @@ bool WebBrowserModule::isEnabled() const { return _enabled; } -/** - * Logic for the webbrowser performance hotfix, - * described in more detail in globalscallbacks.h. - */ +/// Logic for the webbrowser performance hotfix, described in globalscallbacks.h namespace webbrowser { - /** -* The time interval to describe how often the CEF message loop needs to -* be pumped to work properly. A value of 10000 us updates CEF a 100 times -* per second which is enough for fluid interaction without wasting resources -*/ +/** + * The time interval to describe how often the CEF message loop needs to be pumped to work + * properly. A value of 10000 us updates CEF a 100 times per second which is enough for + * fluid interaction without wasting resources + */ std::chrono::microseconds interval = std::chrono::microseconds(10000); std::chrono::time_point latestCall; CefHost* cefHost = nullptr; @@ -246,7 +242,7 @@ void update() { latestCall = timeAfter; } } -} + +} // namespace webbrowser } // namespace openspace - diff --git a/modules/webbrowser/webbrowsermodule.h b/modules/webbrowser/webbrowsermodule.h index d67f85fbb8..19c66fd418 100644 --- a/modules/webbrowser/webbrowsermodule.h +++ b/modules/webbrowser/webbrowsermodule.h @@ -42,11 +42,12 @@ namespace webbrowser { extern std::chrono::time_point latestCall; extern CefHost* cefHost; void update(); -} +} // namespace webbrowser class WebBrowserModule : public OpenSpaceModule { public: static constexpr const char* Name = "WebBrowser"; + WebBrowserModule(); virtual ~WebBrowserModule() = default; diff --git a/modules/webgui/webguimodule.cpp b/modules/webgui/webguimodule.cpp index 087114f250..bb7020a158 100644 --- a/modules/webgui/webguimodule.cpp +++ b/modules/webgui/webguimodule.cpp @@ -25,6 +25,8 @@ #include #include +#include +#include #include #include #include @@ -33,9 +35,12 @@ #include #include #include +#include namespace { constexpr const char* _loggerCat = "WebGuiModule"; + constexpr const char* DefaultAddress = "localhost"; + constexpr const int DefaultPort = 4680; constexpr openspace::properties::Property::PropertyInfo ServerProcessEnabledInfo = { "ServerProcessEnabled", @@ -68,9 +73,7 @@ namespace { "The node js command to invoke." }; - constexpr openspace::properties::Property::PropertyInfo - DirectoriesInfo = - { + constexpr openspace::properties::Property::PropertyInfo DirectoriesInfo = { "Directories", "Directories", "Directories from which to to serve static content, as a string list " @@ -78,9 +81,7 @@ namespace { "even is the directory.", }; - constexpr openspace::properties::Property::PropertyInfo - DefaultEndpointInfo = - { + constexpr openspace::properties::Property::PropertyInfo DefaultEndpointInfo = { "DefaultEndpoint", "Default Endpoint", "The 'default' endpoint. " @@ -88,9 +89,7 @@ namespace { }; - constexpr openspace::properties::Property::PropertyInfo - ServedDirectoriesInfo = - { + constexpr openspace::properties::Property::PropertyInfo ServedDirectoriesInfo = { "ServedDirectories", "ServedDirectories", "Directories that are currently served. This value is set by the server process, " @@ -99,9 +98,18 @@ namespace { "Manual changes to this property have no effect." }; - constexpr const char* DefaultAddress = "localhost"; - constexpr const int DefaultPort = 4680; -} + struct [[codegen::Dictionary(WebGuiModule)]] Parameters { + // [[codegen::verbatim(PortInfo.description)]] + std::optional port; + + // [[codegen::verbatim(AddressInfo.description)]] + std::optional address; + + // [[codegen::verbatim(WebSocketInterfaceInfo.description)]] + std::optional webSocketInterface; + }; +#include "webguimodule_codegen.cpp" +} // namespace namespace openspace { @@ -114,7 +122,7 @@ WebGuiModule::WebGuiModule() , _defaultEndpoint(DefaultEndpointInfo) , _port(PortInfo, DefaultPort) , _address(AddressInfo, DefaultAddress) - , _webSocketInterface(WebSocketInterfaceInfo, "") + , _webSocketInterface(WebSocketInterfaceInfo) { addProperty(_enabled); addProperty(_entryPoint); @@ -142,34 +150,23 @@ WebGuiModule::CallbackHandle WebGuiModule::addEndpointChangeCallback(EndpointCal void WebGuiModule::removeEndpointChangeCallback(CallbackHandle handle) { const auto it = std::find_if( - _endpointChangeCallbacks.begin(), - _endpointChangeCallbacks.end(), + _endpointChangeCallbacks.cbegin(), + _endpointChangeCallbacks.cend(), [handle](const std::pair& cb) { return cb.first == handle; } ); - ghoul_assert( - it != _endpointChangeCallbacks.end(), - "handle must be a valid callback handle" - ); - + ghoul_assert(it != _endpointChangeCallbacks.cend(), "Must be valid callback handle"); _endpointChangeCallbacks.erase(it); } void WebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) { - if (configuration.hasValue(PortInfo.identifier)) { - _port = configuration.value(PortInfo.identifier); - } + const Parameters p = codegen::bake(configuration); - if (configuration.hasValue(AddressInfo.identifier)) { - _address = configuration.value(AddressInfo.identifier); - } - - if (configuration.hasValue(WebSocketInterfaceInfo.identifier)) { - _webSocketInterface = - configuration.value(WebSocketInterfaceInfo.identifier); - } + _port = p.port.value_or(_port); + _address = p.address.value_or(_address); + _webSocketInterface = p.webSocketInterface.value_or(_webSocketInterface); auto startOrStop = [this]() { if (_enabled && !_entryPoint.value().empty()) { @@ -193,7 +190,7 @@ void WebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) { _defaultEndpoint.onChange(restartIfEnabled); _servedDirectories.onChange([this]() { std::unordered_map newEndpoints; - std::vector list = _servedDirectories.value(); + std::vector list = _servedDirectories; if (!list.empty()) { for (size_t i = 0; i < list.size() - 1; i += 2) { newEndpoints[list[i]] = newEndpoints[list[i + 1]]; @@ -234,15 +231,15 @@ void WebGuiModule::startProcess() { _endpoints.clear(); ServerModule* serverModule = global::moduleEngine->module(); - const ServerInterface* serverInterface = - serverModule->serverInterfaceByIdentifier(_webSocketInterface); + const ServerInterface* serverInterface = serverModule->serverInterfaceByIdentifier( + _webSocketInterface + ); if (!serverInterface) { - LERROR("Missing server interface. Server process could not start."); + LERROR("Missing server interface. Server process could not start"); return; } const int webSocketPort = serverInterface->port(); - #ifdef _MSC_VER const std::filesystem::path node = absPath("${MODULE_WEBGUI}/ext/nodejs/node.exe"); #else @@ -251,10 +248,10 @@ void WebGuiModule::startProcess() { std::string formattedDirectories = "["; - std::vector directories = _directories.value(); + std::vector directories = _directories; for (size_t i = 0; i < directories.size(); ++i) { std::string arg = directories[i]; - if (i & 1) { + if (i % 2 == 1) { arg = absPath(arg).string(); } formattedDirectories += "\\\"" + escapedJson(escapedJson(arg)) + "\\\""; @@ -264,18 +261,17 @@ void WebGuiModule::startProcess() { } formattedDirectories += "]"; - const std::string defaultEndpoint = _defaultEndpoint.value().empty() ? - "" : - " --redirect \"" + _defaultEndpoint.value() + "\""; + std::string defaultEndpoint; + if (!_defaultEndpoint.value().empty()) { + defaultEndpoint = fmt::format("--redirect \"{}\"", _defaultEndpoint.value()); + } - const std::string command = "\"" + node.string() + "\" " - + "\"" + absPath(_entryPoint.value()).string() + "\"" + - " --directories \"" + formattedDirectories + "\"" + - defaultEndpoint + - " --http-port \"" + std::to_string(_port.value()) + "\" " + - " --ws-address \"" + _address.value() + "\"" + - " --ws-port " + std::to_string(webSocketPort) + - " --auto-close --local"; + const std::string command = fmt::format( + "\"{}\" \"{}\" --directories \"{}\" {} --http-port \"{}\" --ws-address \"{}\" " + "--ws-port {} --auto-close --local", + node.string(), absPath(_entryPoint.value()).string(), formattedDirectories, + defaultEndpoint, _port.value(), _address.value(), webSocketPort + ); _process = std::make_unique( command, @@ -292,7 +288,7 @@ void WebGuiModule::startProcess() { } void WebGuiModule::stopProcess() { - for (const auto& e : _endpoints) { + for (const std::pair& e : _endpoints) { notifyEndpointListeners(e.first, false); } _endpoints.clear(); diff --git a/modules/webgui/webguimodule.h b/modules/webgui/webguimodule.h index a7fbc0fff6..08cc047552 100644 --- a/modules/webgui/webguimodule.h +++ b/modules/webgui/webguimodule.h @@ -33,8 +33,8 @@ #include #include #include -#include #include +#include namespace openspace { diff --git a/src/documentation/documentationengine.cpp b/src/documentation/documentationengine.cpp index edbba70d3f..e5c1a61ce4 100644 --- a/src/documentation/documentationengine.cpp +++ b/src/documentation/documentationengine.cpp @@ -49,7 +49,7 @@ DocumentationEngine* DocumentationEngine::_instance = nullptr; DocumentationEngine::DuplicateDocumentationException::DuplicateDocumentationException( Documentation doc) : ghoul::RuntimeError(fmt::format( - "Duplicate Documentation with name '{}' and id '{}'",doc.name, doc.id + "Duplicate Documentation with name '{}' and id '{}'", doc.name, doc.id )) , documentation(std::move(doc)) {} diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 1e489a4bb6..83cfb75836 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -1024,18 +1024,18 @@ void FramebufferRenderer::updateDeferredcastData() { for (Deferredcaster* caster : deferredcasters) { DeferredcastData data = { nextId++, "HELPER" }; - std::string vsPath = caster->deferredcastVSPath(); - std::string fsPath = caster->deferredcastFSPath(); - std::string deferredShaderPath = caster->deferredcastPath(); + std::filesystem::path vsPath = caster->deferredcastVSPath(); + std::filesystem::path fsPath = caster->deferredcastFSPath(); + std::filesystem::path deferredShaderPath = caster->deferredcastPath(); ghoul::Dictionary dict; dict.setValue("rendererData", _rendererData); //dict.setValue("fragmentPath", fsPath); dict.setValue("id", data.id); - std::string helperPath = caster->helperPath(); + std::filesystem::path helperPath = caster->helperPath(); ghoul::Dictionary helpersDict; if (!helperPath.empty()) { - helpersDict.setValue("0", helperPath); + helpersDict.setValue("0", helperPath.string()); } dict.setValue("helperPaths", helpersDict); @@ -1044,8 +1044,8 @@ void FramebufferRenderer::updateDeferredcastData() { try { _deferredcastPrograms[caster] = ghoul::opengl::ProgramObject::Build( "Deferred " + std::to_string(data.id) + " raycast", - absPath(vsPath), - absPath(deferredShaderPath), + vsPath, + deferredShaderPath, dict ); diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index e0ea8c6aa6..8c34a1c5b4 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -557,10 +557,7 @@ void RenderEngine::initializeGL() { { ZoneScopedN("Log") LINFO("Initializing Log"); - std::unique_ptr log = std::make_unique( - ScreenLogTimeToLive, - ghoul::logging::LogLevel::Warning - ); + std::unique_ptr log = std::make_unique(ScreenLogTimeToLive); _log = log.get(); ghoul::logging::LogManager::ref().addLog(std::move(log)); } diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index c8864fe1a6..490f8781d4 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -42,8 +42,8 @@ #include namespace { - constexpr const std::array UniformNames = { - "MultiplyColor", "Alpha", "ModelTransform", "ViewProjectionMatrix", "texture1" + constexpr const std::array UniformNames = { + "color", "opacity", "mvpMatrix", "tex" }; constexpr openspace::properties::Property::PropertyInfo EnabledInfo = { @@ -570,12 +570,10 @@ void ScreenSpaceRenderable::draw(glm::mat4 modelTransform) { _shader->activate(); _shader->setUniform(_uniformCache.color, _multiplyColor); - _shader->setUniform(_uniformCache.alpha, _opacity); - _shader->setUniform(_uniformCache.modelTransform, modelTransform); - + _shader->setUniform(_uniformCache.opacity, _opacity); _shader->setUniform( - _uniformCache.viewProj, - global::renderEngine->scene()->camera()->viewProjectionMatrix() + _uniformCache.mvp, + global::renderEngine->scene()->camera()->viewProjectionMatrix() * modelTransform ); ghoul::opengl::TextureUnit unit; From 6cf6e450fbbc461ee2bfb7cfb958286ca8c6b0f3 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 25 May 2021 17:50:31 +0200 Subject: [PATCH 38/43] Address MacOS compile issues, make ISS model scene graph node visible --- apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp | 2 +- .../solarsystem/planets/earth/satellites/misc/iss.asset | 9 ++++----- ext/ghoul | 2 +- include/openspace/network/messagestructures.h | 2 +- .../atmosphere/rendering/atmospheredeferredcaster.cpp | 5 ++++- modules/base/rendering/renderablemodel.cpp | 2 +- modules/base/rendering/renderablemodel.h | 1 - .../rendering/renderablebillboardscloud.cpp | 1 - modules/digitaluniverse/rendering/renderabledumeshes.cpp | 1 - modules/digitaluniverse/rendering/renderabledumeshes.h | 1 - modules/globebrowsing/src/globelabelscomponent.cpp | 1 - modules/space/rendering/renderablehabitablezone.cpp | 2 +- modules/space/speckloader.cpp | 4 ++-- .../spacecraftinstruments/rendering/renderablefov.cpp | 7 ------- modules/spacecraftinstruments/util/imagesequencer.h | 6 ------ .../spacecraftinstruments/util/instrumenttimesparser.cpp | 2 -- modules/sync/tasks/syncassettask.cpp | 1 - modules/volume/rendering/renderabletimevaryingvolume.cpp | 4 ---- modules/webbrowser/src/defaultbrowserlauncher.cpp | 2 +- modules/webgui/webguimodule.cpp | 1 + src/rendering/helper.cpp | 1 - 21 files changed, 17 insertions(+), 40 deletions(-) diff --git a/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp index 072022c65a..c2573cc381 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp @@ -63,7 +63,7 @@ namespace { int startIndex = 0; std::string token = "${USER_ASSETS}/"; if (path.find(token) == 0) { - startIndex = token.length(); + startIndex = static_cast(token.length()); } const size_t slash = path.find_first_of('/', startIndex); const bool endOfPath = (slash == std::string::npos); 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 78a6d1d949..0a316f386d 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset @@ -46,12 +46,12 @@ local initializeAndAddNodes = function() } local parentNode = { - Identifier = "ISSparentNode", + Identifier = "ISSModel", Parent = iss.Identifier, Transform = { Rotation = { Type = "FixedRotation", - Attached = "ISSparentNode", + Attached = "ISSModel", XAxis = { 0.01, -1.0, 0.56 }, XAxisOrthogonal = true, YAxis = transforms.EarthInertial.Identifier @@ -73,9 +73,8 @@ local initializeAndAddNodes = function() DisableFaceCulling = true }, GUI = { - Name = "ISSparentNode", - Path = "/Solar System/Planets/Earth/Satellites/ISS", - Hidden = true, + Name = "ISS Model", + Path = "/Solar System/Planets/Earth/Satellites/ISS" } } diff --git a/ext/ghoul b/ext/ghoul index d8430b5ac9..eef92b2f8f 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit d8430b5ac92329716f78093e5e8ff9a5cc63652e +Subproject commit eef92b2f8f0982b9d6eaff38213d21aaf2dcdd90 diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index b2dec16915..effe727cbe 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -53,9 +53,9 @@ struct CameraKeyframe { bool&& followNodeRot, float&& scale) : _position(pos) , _rotation(rot) + , _followNodeRotation(followNodeRot) , _focusNode(focusNode) , _scale(scale) - , _followNodeRotation(followNodeRot) {} glm::dvec3 _position = glm::dvec3(0.0); diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index b2948125fe..b26103a2fd 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -114,7 +114,10 @@ namespace { return; } - std::vector px(size.x * size.y * 3, unsigned char(255)); + std::vector px( + size.x * size.y * 3, + static_cast(255) + ); if (colorBufferAttachment != GL_DEPTH_ATTACHMENT) { glReadBuffer(colorBufferAttachment); diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index 48ee1f6dc8..56e7b12635 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -262,8 +262,8 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) glm::dmat3(1.0) ) , _rotationVec(RotationVecInfo, glm::dvec3(0.0), glm::dvec3(0.0), glm::dvec3(360.0)) - , _enableOpacityBlending(EnableOpacityBlendingInfo, false) , _disableDepthTest(DisableDepthTestInfo, false) + , _enableOpacityBlending(EnableOpacityBlendingInfo, false) , _blendingFuncOption( BlendingOptionInfo, properties::OptionProperty::DisplayType::Dropdown diff --git a/modules/base/rendering/renderablemodel.h b/modules/base/rendering/renderablemodel.h index d1d2cbc9fa..39b9d3200d 100644 --- a/modules/base/rendering/renderablemodel.h +++ b/modules/base/rendering/renderablemodel.h @@ -88,7 +88,6 @@ private: properties::BoolProperty _enableAnimation; properties::FloatProperty _ambientIntensity; - properties::FloatProperty _diffuseIntensity; properties::FloatProperty _specularIntensity; diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index 41fd2f8e23..c9c54ee569 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -67,7 +67,6 @@ namespace { "hasColorMap", "enabledRectSizeControl", "hasDvarScaling" }; - constexpr int8_t CurrentCacheVersion = 1; constexpr double PARSEC = 0.308567756E17; constexpr const int RenderOptionViewDirection = 0; diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index 11a2c5ddd9..d62af2fc38 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -59,7 +59,6 @@ namespace { constexpr const int RenderOptionViewDirection = 0; constexpr const int RenderOptionPositionNormal = 1; - constexpr const int8_t CurrentCacheVersion = 1; constexpr const double PARSEC = 0.308567756E17; constexpr openspace::properties::Property::PropertyInfo TextColorInfo = { diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.h b/modules/digitaluniverse/rendering/renderabledumeshes.h index 020e76d0c1..f159488469 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.h +++ b/modules/digitaluniverse/rendering/renderabledumeshes.h @@ -139,7 +139,6 @@ private: std::vector _fullData; speck::Labelset _labelset; - int _nValuesPerAstronomicalObject = 0; std::unordered_map _meshColorMap; std::unordered_map _renderingMeshesMap; diff --git a/modules/globebrowsing/src/globelabelscomponent.cpp b/modules/globebrowsing/src/globelabelscomponent.cpp index 7a09a11a7c..fe26da6e43 100644 --- a/modules/globebrowsing/src/globelabelscomponent.cpp +++ b/modules/globebrowsing/src/globelabelscomponent.cpp @@ -51,7 +51,6 @@ namespace { constexpr const char* _loggerCat = "GlobeLabels"; constexpr const double LabelFadeOutLimitAltitudeMeters = 25000.0; - constexpr const double RangeAngularCoefConst = 0.8; constexpr const float MinOpacityValueConst = 0.009f; enum LabelRenderingAlignmentType { diff --git a/modules/space/rendering/renderablehabitablezone.cpp b/modules/space/rendering/renderablehabitablezone.cpp index d540d75906..33776b2041 100644 --- a/modules/space/rendering/renderablehabitablezone.cpp +++ b/modules/space/rendering/renderablehabitablezone.cpp @@ -40,7 +40,7 @@ #include namespace { - constexpr const char _loggerCat[] = "RenderableHabitableZone"; + constexpr const char* _loggerCat = "RenderableHabitableZone"; constexpr const std::array UniformNames = { "modelViewProjectionTransform", "opacity", "width", "transferFunctionTexture", diff --git a/modules/space/speckloader.cpp b/modules/space/speckloader.cpp index 1e35654b7f..996ba3ab73 100644 --- a/modules/space/speckloader.cpp +++ b/modules/space/speckloader.cpp @@ -421,7 +421,7 @@ std::optional loadCachedFile(std::filesystem::path path) { uint64_t nEntries; file.read(reinterpret_cast(&nEntries), sizeof(uint64_t)); result.entries.reserve(nEntries); - for (int i = 0; i < nEntries; i += 1) { + for (uint64_t i = 0; i < nEntries; i += 1) { Dataset::Entry e; file.read(reinterpret_cast(&e.position.x), sizeof(float)); file.read(reinterpret_cast(&e.position.y), sizeof(float)); @@ -797,7 +797,7 @@ ColorMap loadFile(std::filesystem::path path, SkipAllZeroLines) { } } - if (nColorLines != res.entries.size()) { + if (nColorLines != static_cast(res.entries.size())) { LWARNINGC("SpeckLoader", fmt::format( "While loading color map, the expected number of color values '{}' was " "different from the actual number of color values '{}'", diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index 3894fbeb42..3c9c7bcb5c 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -56,13 +56,6 @@ namespace { "corners of the field of view." }; - constexpr openspace::properties::Property::PropertyInfo DrawSolidInfo = { - "SolidDraw", - "Solid Draw", - "This value determines whether the field of view should be rendered as a solid " - "or as lines only." - }; - constexpr openspace::properties::Property::PropertyInfo StandoffDistanceInfo = { "StandOffDistance", "Standoff Distance Factor", diff --git a/modules/spacecraftinstruments/util/imagesequencer.h b/modules/spacecraftinstruments/util/imagesequencer.h index 539198cd43..9e258310ca 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.h +++ b/modules/spacecraftinstruments/util/imagesequencer.h @@ -175,12 +175,6 @@ private: */ std::vector _captureProgression; - // time between current simulation time and an upcoming capture - double _intervalLength = 0.0; - - // next consecutive capture in time - double _nextCapture = 0.0; - // default capture image std::string _defaultCaptureImage; diff --git a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp index ac37fd32ad..1289b1054f 100644 --- a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp +++ b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp @@ -37,8 +37,6 @@ namespace { constexpr const char* _loggerCat = "InstrumentTimesParser"; - constexpr const char* KeyTargetBody = "Target"; - constexpr const char* KeyInstruments = "Instruments"; constexpr const char* KeyInstrument = "Instrument"; constexpr const char* KeyInstrumentFiles = "Files"; diff --git a/modules/sync/tasks/syncassettask.cpp b/modules/sync/tasks/syncassettask.cpp index 5c15a7d3e0..cfdfd11e43 100644 --- a/modules/sync/tasks/syncassettask.cpp +++ b/modules/sync/tasks/syncassettask.cpp @@ -44,7 +44,6 @@ #include namespace { - constexpr const char* KeyAsset = "Asset"; constexpr std::chrono::milliseconds ProgressPollInterval(200); struct [[codegen::Dictionary(SyncAssetTask)]] Parameters { diff --git a/modules/volume/rendering/renderabletimevaryingvolume.cpp b/modules/volume/rendering/renderabletimevaryingvolume.cpp index 199b622775..88d24850e7 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.cpp +++ b/modules/volume/rendering/renderabletimevaryingvolume.cpp @@ -49,13 +49,9 @@ namespace { constexpr const char* _loggerCat = "RenderableTimeVaryingVolume"; -} // namespace - -namespace { const char* KeyStepSize = "StepSize"; const char* KeyGridType = "GridType"; - const char* KeyTransferFunction = "TransferFunction"; const float SecondsInOneDay = 60 * 60 * 24; constexpr const float VolumeMaxOpacity = 500; diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index 6a7cd15a0f..fe61d423e6 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -33,7 +33,7 @@ namespace openspace { bool DefaultBrowserLauncher::OnBeforePopup(CefRefPtr, CefRefPtr, - const CefString& targetUrl, const CefString&, + const CefString&, const CefString&, CefLifeSpanHandler::WindowOpenDisposition, bool, const CefPopupFeatures&, CefWindowInfo&, CefRefPtr&, CefBrowserSettings&, diff --git a/modules/webgui/webguimodule.cpp b/modules/webgui/webguimodule.cpp index bb7020a158..edd45b9846 100644 --- a/modules/webgui/webguimodule.cpp +++ b/modules/webgui/webguimodule.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include namespace { diff --git a/src/rendering/helper.cpp b/src/rendering/helper.cpp index 39cf1bcb97..cfa790b3d0 100644 --- a/src/rendering/helper.cpp +++ b/src/rendering/helper.cpp @@ -126,7 +126,6 @@ void main() { } // namespace -#pragma optimize ("", off) namespace openspace::rendering::helper { namespace detail { From ac50e6695854b888e3a66c2dddc251e0e1f1b699 Mon Sep 17 00:00:00 2001 From: Micah Acinapura Date: Tue, 25 May 2021 12:41:01 -0400 Subject: [PATCH 39/43] Create include.cmake enabling vislab module by default --- modules/vislab/include.cmake | 1 + 1 file changed, 1 insertion(+) create mode 100644 modules/vislab/include.cmake diff --git a/modules/vislab/include.cmake b/modules/vislab/include.cmake new file mode 100644 index 0000000000..ffea0ac430 --- /dev/null +++ b/modules/vislab/include.cmake @@ -0,0 +1 @@ +set(DEFAULT_MODULE ON) From d2f953088503f5200325396debf81e44eb08e70d Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 25 May 2021 20:11:26 +0200 Subject: [PATCH 40/43] Windows fix --- modules/webbrowser/src/defaultbrowserlauncher.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index fe61d423e6..027eb8edf9 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -33,7 +33,8 @@ namespace openspace { bool DefaultBrowserLauncher::OnBeforePopup(CefRefPtr, CefRefPtr, - const CefString&, const CefString&, + [[ maybe_unused ]] const CefString& targetUrl, + const CefString&, CefLifeSpanHandler::WindowOpenDisposition, bool, const CefPopupFeatures&, CefWindowInfo&, CefRefPtr&, CefBrowserSettings&, From cb17bd757072bd2101edae32220119d16ddfe2e0 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 25 May 2021 22:06:49 +0200 Subject: [PATCH 41/43] Remove warnings --- ext/ghoul | 2 +- .../openspace/documentation/documentation.h | 2 +- include/openspace/scene/profile.h | 2 +- include/openspace/util/timeline.h | 4 +-- include/openspace/util/timemanager.h | 2 +- modules/base/rendering/renderablemodel.cpp | 10 ++++--- modules/base/rendering/renderableplane.cpp | 28 +++++++++++-------- modules/base/rendering/renderabletrail.cpp | 4 +-- modules/globebrowsing/globebrowsingmodule.cpp | 6 +++- modules/globebrowsing/src/renderableglobe.cpp | 12 ++++++-- modules/globebrowsing/src/ringscomponent.cpp | 16 +++++------ modules/globebrowsing/src/ringscomponent.h | 4 +-- .../globebrowsing/src/tiletextureinitdata.cpp | 2 +- .../globebrowsing/src/tiletextureinitdata.h | 2 +- .../server/include/topics/luascripttopic.h | 3 +- modules/server/src/topics/luascripttopic.cpp | 2 +- .../rendering/renderableconstellationbounds.h | 2 +- modules/space/speckloader.h | 4 +-- modules/space/translation/tletranslation.cpp | 2 +- src/interaction/keybindingmanager_lua.inl | 4 +-- src/interaction/navigationhandler_lua.inl | 19 +++++++++---- src/util/versionchecker.cpp | 7 +++-- 22 files changed, 81 insertions(+), 58 deletions(-) diff --git a/ext/ghoul b/ext/ghoul index eef92b2f8f..5bc318245d 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit eef92b2f8f0982b9d6eaff38213d21aaf2dcdd90 +Subproject commit 5bc318245db24ed93ed48b72d6eaab3c0b88346c diff --git a/include/openspace/documentation/documentation.h b/include/openspace/documentation/documentation.h index 39ed62320e..a5c17c8622 100644 --- a/include/openspace/documentation/documentation.h +++ b/include/openspace/documentation/documentation.h @@ -93,7 +93,7 @@ struct TestResult { /// Is \c true if the TestResult is positive, \c false otherwise - bool success; + bool success = false; /// Contains a list of offenses that were found in the test. Is empty if /// TestResult::Success is \c true std::vector offenses; diff --git a/include/openspace/scene/profile.h b/include/openspace/scene/profile.h index 28a3a360eb..e1565b1dc7 100644 --- a/include/openspace/scene/profile.h +++ b/include/openspace/scene/profile.h @@ -92,7 +92,7 @@ public: Relative }; - Type type; + Type type = Type::Absolute; std::string value; }; struct CameraNavState { diff --git a/include/openspace/util/timeline.h b/include/openspace/util/timeline.h index 1f2936cf40..60e71f25cc 100644 --- a/include/openspace/util/timeline.h +++ b/include/openspace/util/timeline.h @@ -47,8 +47,8 @@ struct Keyframe : public KeyframeBase { Keyframe(size_t i, double t, T d); Keyframe(Keyframe const&) = default; - Keyframe(Keyframe&&) = default; - Keyframe& operator=(Keyframe&&) = default; + Keyframe(Keyframe&&) noexcept = default; + Keyframe& operator=(Keyframe&&) noexcept = default; Keyframe& operator=(Keyframe const&) = default; T data; }; diff --git a/include/openspace/util/timemanager.h b/include/openspace/util/timemanager.h index 1e213abb0a..d7500939c6 100644 --- a/include/openspace/util/timemanager.h +++ b/include/openspace/util/timemanager.h @@ -40,7 +40,7 @@ namespace openspace { struct TimeKeyframeData { Time time; - double delta; + double delta = 0.0; bool pause = false; bool jump = false; }; diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index 56e7b12635..e3d774bc70 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -203,13 +203,13 @@ namespace { std::optional animationMode; // [[codegen::verbatim(AmbientIntensityInfo.description)]] - std::optional ambientIntensity; + std::optional ambientIntensity; // [[codegen::verbatim(DiffuseIntensityInfo.description)]] - std::optional diffuseIntensity; + std::optional diffuseIntensity; // [[codegen::verbatim(SpecularIntensityInfo.description)]] - std::optional specularIntensity; + std::optional specularIntensity; // [[codegen::verbatim(ShadingInfo.description)]] std::optional performShading; @@ -385,7 +385,9 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) throw ghoul::MissingCaseException(); } - _geometry->setTimeScale(convertTime(1.0, timeUnit, TimeUnit::Second)); + _geometry->setTimeScale(static_cast( + convertTime(1.0, timeUnit, TimeUnit::Second)) + ); } else { throw ghoul::MissingCaseException(); diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 52cbaf638e..8af691c8cb 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -45,9 +45,9 @@ namespace { constexpr const char* ProgramName = "Plane"; - enum BlendMode { - BlendModeNormal = 0, - BlendModeAdditive + enum class BlendMode { + Normal = 0, + Additive }; constexpr openspace::properties::Property::PropertyInfo BillboardInfo = { @@ -121,15 +121,15 @@ RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) _billboard = p.billboard.value_or(_billboard); _blendMode.addOptions({ - { BlendModeNormal, "Normal" }, - { BlendModeAdditive, "Additive"} + { static_cast(BlendMode::Normal), "Normal" }, + { static_cast(BlendMode::Additive), "Additive"} }); _blendMode.onChange([&]() { switch (_blendMode) { - case BlendModeNormal: + case static_cast(BlendMode::Normal): setRenderBinFromOpacity(); break; - case BlendModeAdditive: + case static_cast(BlendMode::Additive): setRenderBin(Renderable::RenderBin::PreDeferredTransparent); break; default: @@ -138,17 +138,17 @@ RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) }); _opacity.onChange([&]() { - if (_blendMode == BlendModeNormal) { + if (_blendMode == static_cast(BlendMode::Normal)) { setRenderBinFromOpacity(); } }); if (p.blendMode.has_value()) { if (*p.blendMode == Parameters::BlendMode::Normal) { - _blendMode = BlendModeNormal; + _blendMode = static_cast(BlendMode::Normal); } else if (*p.blendMode == Parameters::BlendMode::Additive) { - _blendMode = BlendModeAdditive; + _blendMode = static_cast(BlendMode::Additive); } } @@ -264,10 +264,14 @@ void RenderablePlane::render(const RenderData& data, RendererTasks&) { RenderEngine::RendererImplementation::ABuffer; if (usingABufferRenderer) { - _shader->setUniform("additiveBlending", _blendMode == BlendModeAdditive); + _shader->setUniform( + "additiveBlending", + _blendMode == static_cast(BlendMode::Additive) + ); } - bool additiveBlending = (_blendMode == BlendModeAdditive) && usingFramebufferRenderer; + bool additiveBlending = + (_blendMode == static_cast(BlendMode::Additive)) && usingFramebufferRenderer; if (additiveBlending) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index 889772bc58..11bcd6a06f 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -432,10 +432,10 @@ void RenderableTrail::render(const RenderData& data, RendererTasks&) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); } - const bool renderLines = (_appearance.renderingModes == RenderingModeLines) | + const bool renderLines = (_appearance.renderingModes == RenderingModeLines) || (_appearance.renderingModes == RenderingModeLinesPoints); - const bool renderPoints = (_appearance.renderingModes == RenderingModePoints) | + const bool renderPoints = (_appearance.renderingModes == RenderingModePoints) || (_appearance.renderingModes == RenderingModeLinesPoints); if (renderLines) { diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index 912efc92f2..89b7fe275b 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -124,12 +124,16 @@ namespace { int iDataset = -1; std::array IdentifierBuffer; std::fill(IdentifierBuffer.begin(), IdentifierBuffer.end(), '\0'); - sscanf( + int ret = sscanf( subDatasets[i], "SUBDATASET_%i_%256[^=]", &iDataset, IdentifierBuffer.data() ); + if (ret != 2) { + LERROR("Error parsing dataset"); + continue; + } if (iDataset != currentLayerNumber) { diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index adc0ca2516..04052bee2b 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -727,7 +727,10 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask // Render from light source point of view renderChunks(lightRenderData, rendererTask, {}, true); if (_hasRings && _ringsComponent.isEnabled()) { - _ringsComponent.draw(lightRenderData, RingsComponent::GeometryOnly); + _ringsComponent.draw( + lightRenderData, + RingsComponent::RenderPass::GeometryOnly + ); } glEnable(GL_BLEND); @@ -739,7 +742,7 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask if (_hasRings && _ringsComponent.isEnabled()) { _ringsComponent.draw( data, - RingsComponent::GeometryAndShading, + RingsComponent::RenderPass::GeometryAndShading, _shadowComponent.shadowMapData() ); } @@ -747,7 +750,10 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask else { renderChunks(data, rendererTask); if (_hasRings && _ringsComponent.isEnabled()) { - _ringsComponent.draw(data, RingsComponent::GeometryAndShading); + _ringsComponent.draw( + data, + RingsComponent::RenderPass::GeometryAndShading + ); } } } diff --git a/modules/globebrowsing/src/ringscomponent.cpp b/modules/globebrowsing/src/ringscomponent.cpp index 9a57781935..b65eab725d 100644 --- a/modules/globebrowsing/src/ringscomponent.cpp +++ b/modules/globebrowsing/src/ringscomponent.cpp @@ -382,14 +382,13 @@ void RingsComponent::deinitializeGL() { _geometryOnlyShader = nullptr; } -void RingsComponent::draw(const RenderData& data, - const RingsComponent::RenderPass renderPass, +void RingsComponent::draw(const RenderData& data, RenderPass renderPass, const ShadowComponent::ShadowMapData& shadowData) { - if (renderPass == GeometryAndShading) { + if (renderPass == RenderPass::GeometryAndShading) { _shader->activate(); } - else if (renderPass == GeometryOnly) { + else if (renderPass == RenderPass::GeometryOnly) { _geometryOnlyShader->activate(); } @@ -408,7 +407,7 @@ void RingsComponent::draw(const RenderData& data, ghoul::opengl::TextureUnit ringTextureUnlitUnit; ghoul::opengl::TextureUnit ringTextureColorUnit; ghoul::opengl::TextureUnit ringTextureTransparencyUnit; - if (renderPass == GeometryAndShading) { + if (renderPass == RenderPass::GeometryAndShading) { if (_isAdvancedTextureEnabled) { _shader->setUniform( _uniformCacheAdvancedRings.modelViewProjectionMatrix, @@ -542,7 +541,7 @@ void RingsComponent::draw(const RenderData& data, glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } - else if (renderPass == GeometryOnly) { + else if (renderPass == RenderPass::GeometryOnly) { _geometryOnlyShader->setUniform( _geomUniformCache.modelViewProjectionMatrix, modelViewProjectionTransform @@ -568,12 +567,11 @@ void RingsComponent::draw(const RenderData& data, glEnable(GL_CULL_FACE); - if (renderPass == GeometryAndShading) { + if (renderPass == RenderPass::GeometryAndShading) { _shader->deactivate(); global::renderEngine->openglStateCache().resetBlendState(); - //global::renderEngine->openglStateCache().resetDepthState(); } - else if (renderPass == GeometryOnly) { + else if (renderPass == RenderPass::GeometryOnly) { _geometryOnlyShader->deactivate(); } } diff --git a/modules/globebrowsing/src/ringscomponent.h b/modules/globebrowsing/src/ringscomponent.h index c19a8565b9..6c9acc4fd3 100644 --- a/modules/globebrowsing/src/ringscomponent.h +++ b/modules/globebrowsing/src/ringscomponent.h @@ -50,7 +50,7 @@ namespace documentation { struct Documentation; } class RingsComponent : public properties::PropertyOwner { public: - enum RenderPass { + enum class RenderPass { GeometryOnly, GeometryAndShading }; @@ -63,7 +63,7 @@ public: bool isReady() const; - void draw(const RenderData& data, const RingsComponent::RenderPass renderPass, + void draw(const RenderData& data, RenderPass renderPass, const ShadowComponent::ShadowMapData& shadowData = {} ); void update(const UpdateData& data); diff --git a/modules/globebrowsing/src/tiletextureinitdata.cpp b/modules/globebrowsing/src/tiletextureinitdata.cpp index b47d838548..04137f7d6f 100644 --- a/modules/globebrowsing/src/tiletextureinitdata.cpp +++ b/modules/globebrowsing/src/tiletextureinitdata.cpp @@ -192,7 +192,7 @@ TileTextureInitData TileTextureInitData::operator=(const TileTextureInitData& rh return rhs; } -TileTextureInitData TileTextureInitData::operator=(TileTextureInitData&& rhs) { +TileTextureInitData TileTextureInitData::operator=(TileTextureInitData&& rhs) noexcept { if (this == &rhs) { return *this; } diff --git a/modules/globebrowsing/src/tiletextureinitdata.h b/modules/globebrowsing/src/tiletextureinitdata.h index 2a311a81f5..46d0ea0215 100644 --- a/modules/globebrowsing/src/tiletextureinitdata.h +++ b/modules/globebrowsing/src/tiletextureinitdata.h @@ -49,7 +49,7 @@ public: TileTextureInitData(TileTextureInitData&& original) = default; TileTextureInitData operator=(const TileTextureInitData& rhs); - TileTextureInitData operator=(TileTextureInitData&& rhs); + TileTextureInitData operator=(TileTextureInitData&& rhs) noexcept; ~TileTextureInitData() = default; diff --git a/modules/server/include/topics/luascripttopic.h b/modules/server/include/topics/luascripttopic.h index 7ed757e3dd..49b81f37f4 100644 --- a/modules/server/include/topics/luascripttopic.h +++ b/modules/server/include/topics/luascripttopic.h @@ -36,8 +36,9 @@ public: void handleJson(const nlohmann::json& json) override; bool isDone() const override; + private: - void runScript(const std::string& script, bool returnValue); + void runScript(std::string script, bool returnValue); bool _waitingForReturnValue = true; }; diff --git a/modules/server/src/topics/luascripttopic.cpp b/modules/server/src/topics/luascripttopic.cpp index b718ea4838..d2140b6e75 100644 --- a/modules/server/src/topics/luascripttopic.cpp +++ b/modules/server/src/topics/luascripttopic.cpp @@ -176,7 +176,7 @@ void LuaScriptTopic::handleJson(const nlohmann::json& json) { } } -void LuaScriptTopic::runScript(const std::string& script, bool shouldReturn) { +void LuaScriptTopic::runScript(std::string script, bool shouldReturn) { scripting::ScriptEngine::ScriptCallback callback; if (shouldReturn) { callback = [this](ghoul::Dictionary data) { diff --git a/modules/space/rendering/renderableconstellationbounds.h b/modules/space/rendering/renderableconstellationbounds.h index c6ea6e606c..5af808d7c5 100644 --- a/modules/space/rendering/renderableconstellationbounds.h +++ b/modules/space/rendering/renderableconstellationbounds.h @@ -66,7 +66,7 @@ private: struct ConstellationBound { std::string constellationAbbreviation; ///< The abbreviation of the constellation std::string constellationFullName; - bool isEnabled; + bool isEnabled = false; GLsizei startIndex; ///< The index of the first vertex describing the bounds GLsizei nVertices; ///< The number of vertices describing the bounds }; diff --git a/modules/space/speckloader.h b/modules/space/speckloader.h index 20fb087719..a733b3f02c 100644 --- a/modules/space/speckloader.h +++ b/modules/space/speckloader.h @@ -38,13 +38,13 @@ BooleanType(SkipAllZeroLines); struct Dataset { struct Variable { - int index; + int index = -1; std::string name; }; std::vector variables; struct Texture { - int index; + int index = -1; std::string file; }; std::vector textures; diff --git a/modules/space/translation/tletranslation.cpp b/modules/space/translation/tletranslation.cpp index 36082a69c8..fec5d05143 100644 --- a/modules/space/translation/tletranslation.cpp +++ b/modules/space/translation/tletranslation.cpp @@ -204,7 +204,7 @@ namespace { // mu = G*M_earth double period = std::chrono::seconds(std::chrono::hours(24)).count() / meanMotion; - const double pisq = glm::pi() * glm::pi(); + constexpr const double pisq = glm::pi() * glm::pi(); double semiMajorAxis = pow((muEarth * period*period) / (4 * pisq), 1.0 / 3.0); // We need the semi major axis in km instead of m diff --git a/src/interaction/keybindingmanager_lua.inl b/src/interaction/keybindingmanager_lua.inl index 5627bd26aa..e5da1e3e30 100644 --- a/src/interaction/keybindingmanager_lua.inl +++ b/src/interaction/keybindingmanager_lua.inl @@ -40,7 +40,7 @@ int bindKey(lua_State* L) { int nArguments = ghoul::lua::checkArgumentsAndThrow(L, { 2, 5 }, "lua::bindKey"); const std::string& key = ghoul::lua::value(L, 1); - const std::string& command = ghoul::lua::value(L, 2); + std::string command = ghoul::lua::value(L, 2); if (command.empty()) { lua_settop(L, 0); @@ -85,7 +85,7 @@ int bindKeyLocal(lua_State* L) { int nArguments = ghoul::lua::checkArgumentsAndThrow(L, { 2, 5 }, "lua::bindKeyLocal"); const std::string& key = ghoul::lua::value(L, 1); - const std::string& command = ghoul::lua::value(L, 2); + std::string command = ghoul::lua::value(L, 2); if (command.empty()) { return ghoul::lua::luaError(L, "Command string is empty"); diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 58ca4737f2..b31d487e58 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -228,8 +228,15 @@ int joystickAxis(lua_State* L) { const bool invert = info.invert; const bool normalize = info.normalize; const bool isSticky = info.isSticky; - const float sensitivity = info.sensitivity; - ghoul::lua::push(L, ghoul::to_string(info.type), invert, normalize, isSticky, sensitivity); + const double sensitivity = info.sensitivity; + ghoul::lua::push( + L, + ghoul::to_string(info.type), + invert, + normalize, + isSticky, + sensitivity + ); ghoul_assert(lua_gettop(L) == 5, "Incorrect number of items left on stack"); return 5; @@ -268,8 +275,8 @@ int bindJoystickButton(lua_State* L) { ); const int button = ghoul::lua::value(L, 1); - const std::string& command = ghoul::lua::value(L, 2); - const std::string& documentation = ghoul::lua::value(L, 3); + std::string command = ghoul::lua::value(L, 2); + std::string documentation = ghoul::lua::value(L, 3); interaction::JoystickAction action = interaction::JoystickAction::Press; if (n >= 4) { @@ -282,10 +289,10 @@ int bindJoystickButton(lua_State* L) { global::navigationHandler->bindJoystickButtonCommand( button, - std::move(command), + command, action, interaction::JoystickCameraStates::ButtonCommandRemote(isRemote), - std::move(documentation) + documentation ); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); diff --git a/src/util/versionchecker.cpp b/src/util/versionchecker.cpp index 6eddfd9644..6ee129c32e 100644 --- a/src/util/versionchecker.cpp +++ b/src/util/versionchecker.cpp @@ -43,9 +43,10 @@ void VersionChecker::requestLatestVersion(const std::string& url) { HttpRequest::RequestOptions opt; opt.requestTimeoutSeconds = 0; - const std::string fullUrl = url + - "?client_version=" + OPENSPACE_VERSION_NUMBER + - "&commit_hash=" + OPENSPACE_GIT_COMMIT; + std::string fullUrl = fmt::format( + "{}?client_version={}&commit_hash={}", + url, OPENSPACE_VERSION_NUMBER, OPENSPACE_GIT_COMMIT + ); if (_request) { _request->cancel(); From 63cbf270ee155c1635f205f11ab7e57c0ac5bced Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 25 May 2021 23:10:12 +0200 Subject: [PATCH 42/43] Adapt to changes in codegen that require specifying the identifier in the codegen::doc function --- .../atmosphere/rendering/renderableatmosphere.cpp | 4 +--- modules/base/dashboard/dashboarditemangle.cpp | 4 +--- modules/base/dashboard/dashboarditemdate.cpp | 4 +--- modules/base/dashboard/dashboarditemdistance.cpp | 4 +--- modules/base/dashboard/dashboarditemframerate.cpp | 4 +--- .../base/dashboard/dashboarditempropertyvalue.cpp | 4 +--- .../dashboard/dashboarditemsimulationincrement.cpp | 4 +--- modules/base/dashboard/dashboarditemspacing.cpp | 4 +--- modules/base/dashboard/dashboarditemtext.cpp | 4 +--- modules/base/dashboard/dashboarditemvelocity.cpp | 4 +--- modules/base/lightsource/cameralightsource.cpp | 4 +--- modules/base/lightsource/scenegraphlightsource.cpp | 4 +--- modules/base/rendering/grids/renderableboxgrid.cpp | 4 +--- modules/base/rendering/grids/renderablegrid.cpp | 4 +--- .../base/rendering/grids/renderableradialgrid.cpp | 4 +--- .../rendering/grids/renderablesphericalgrid.cpp | 4 +--- modules/base/rendering/renderablecartesianaxes.cpp | 4 +--- modules/base/rendering/renderabledisc.cpp | 4 +--- modules/base/rendering/renderablelabels.cpp | 2 +- modules/base/rendering/renderablemodel.cpp | 4 +--- modules/base/rendering/renderablenodeline.cpp | 4 +--- modules/base/rendering/renderableplane.cpp | 4 +--- .../base/rendering/renderableplaneimagelocal.cpp | 5 +++-- .../base/rendering/renderableplaneimageonline.cpp | 5 +++-- modules/base/rendering/renderablesphere.cpp | 4 +--- modules/base/rendering/renderabletrail.cpp | 4 +--- modules/base/rendering/renderabletrailorbit.cpp | 5 +++-- .../base/rendering/renderabletrailtrajectory.cpp | 5 +++-- modules/base/rendering/screenspacedashboard.cpp | 4 +--- modules/base/rendering/screenspaceimagelocal.cpp | 4 +--- modules/base/rendering/screenspaceimageonline.cpp | 4 +--- modules/base/rotation/constantrotation.cpp | 4 +--- modules/base/rotation/fixedrotation.cpp | 4 +--- modules/base/rotation/luarotation.cpp | 4 +--- modules/base/rotation/staticrotation.cpp | 4 +--- modules/base/rotation/timelinerotation.cpp | 4 +--- modules/base/scale/luascale.cpp | 4 +--- modules/base/scale/nonuniformstaticscale.cpp | 4 +--- modules/base/scale/staticscale.cpp | 4 +--- modules/base/scale/timedependentscale.cpp | 4 +--- modules/base/timeframe/timeframeinterval.cpp | 4 +--- modules/base/timeframe/timeframeunion.cpp | 6 ++---- modules/base/translation/luatranslation.cpp | 4 +--- modules/base/translation/statictranslation.cpp | 4 +--- modules/base/translation/timelinetranslation.cpp | 4 +--- .../debugging/rendering/renderabledebugplane.cpp | 4 +--- .../rendering/renderablebillboardscloud.cpp | 4 +--- .../rendering/renderabledumeshes.cpp | 4 +--- .../rendering/renderableplanescloud.cpp | 4 +--- .../digitaluniverse/rendering/renderablepoints.cpp | 4 +--- .../exoplanets/rendering/renderableorbitdisc.cpp | 4 +--- .../tasks/exoplanetsdatapreparationtask.cpp | 4 +--- modules/gaia/rendering/renderablegaiastars.cpp | 4 +--- modules/gaia/tasks/constructoctreetask.cpp | 4 +--- modules/gaia/tasks/readfitstask.cpp | 4 +--- modules/gaia/tasks/readspecktask.cpp | 4 +--- .../src/dashboarditemglobelocation.cpp | 4 +--- modules/globebrowsing/src/globelabelscomponent.cpp | 4 +--- modules/globebrowsing/src/globetranslation.cpp | 4 +--- modules/globebrowsing/src/layer.cpp | 4 +--- modules/globebrowsing/src/layeradjustment.cpp | 4 +--- modules/globebrowsing/src/renderableglobe.cpp | 4 +--- modules/globebrowsing/src/ringscomponent.cpp | 4 +--- modules/globebrowsing/src/shadowcomponent.cpp | 4 +--- .../tasks/kameleondocumentationtask.cpp | 4 +--- .../tasks/kameleonmetadatatojsontask.cpp | 4 +--- .../tasks/kameleonvolumetorawtask.cpp | 4 +--- modules/space/rendering/planetgeometry.cpp | 4 +--- .../rendering/renderableconstellationbounds.cpp | 7 ++----- .../space/rendering/renderablehabitablezone.cpp | 5 +++-- .../space/rendering/renderableorbitalkepler.cpp | 4 +--- modules/space/rendering/renderablerings.cpp | 4 +--- modules/space/rendering/renderablesatellites.cpp | 5 +++-- modules/space/rendering/renderablesmallbody.cpp | 5 +++-- modules/space/rendering/renderablestars.cpp | 4 +--- modules/space/rendering/simplespheregeometry.cpp | 4 +--- modules/space/rotation/spicerotation.cpp | 4 +--- modules/space/translation/horizonstranslation.cpp | 4 +--- modules/space/translation/keplertranslation.cpp | 4 +--- modules/space/translation/spicetranslation.cpp | 4 +--- modules/space/translation/tletranslation.cpp | 4 +--- .../dashboard/dashboarditeminstruments.cpp | 4 +--- .../rendering/renderablecrawlingline.cpp | 4 +--- .../rendering/renderablefov.cpp | 4 +--- .../rendering/renderablemodelprojection.cpp | 4 +--- .../rendering/renderableplanetprojection.cpp | 4 +--- .../rendering/renderableshadowcylinder.cpp | 4 +--- .../util/projectioncomponent.cpp | 4 +--- modules/spout/renderableplanespout.cpp | 4 +--- modules/spout/screenspacespout.cpp | 4 +--- modules/sync/syncs/httpsynchronization.cpp | 4 +--- modules/sync/syncs/urlsynchronization.cpp | 4 +--- modules/sync/tasks/syncassettask.cpp | 4 +--- .../vislab/rendering/renderabledistancelabel.cpp | 4 +--- modules/volume/rawvolumemetadata.cpp | 4 +--- .../rendering/renderabletimevaryingvolume.cpp | 4 +--- modules/volume/tasks/generaterawvolumetask.cpp | 4 +--- src/engine/configuration.cpp | 5 +++-- src/engine/logfactory.cpp | 4 +--- src/interaction/navigationhandler.cpp | 4 +--- src/mission/mission.cpp | 4 +--- src/rendering/dashboarditem.cpp | 4 +--- src/rendering/dashboardtextitem.cpp | 4 +--- src/rendering/renderable.cpp | 4 +--- src/rendering/screenspacerenderable.cpp | 4 +--- src/scene/lightsource.cpp | 4 +--- src/scene/rotation.cpp | 4 +--- src/scene/scale.cpp | 4 +--- src/scene/scenegraphnode.cpp | 4 +--- src/scene/timeframe.cpp | 4 +--- src/scene/translation.cpp | 4 +--- src/scripting/scriptscheduler.cpp | 14 +++++--------- src/util/resourcesynchronization.cpp | 4 +--- src/util/task.cpp | 4 +--- src/util/timerange.cpp | 4 +--- support/coding/codegen | 2 +- 116 files changed, 138 insertions(+), 345 deletions(-) diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index 8356dc06ce..e14ff893a7 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -220,9 +220,7 @@ namespace { namespace openspace { documentation::Documentation RenderableAtmosphere::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "atmosphere_renderable_atmosphere"; - return doc; + return codegen::doc("atmosphere_renderable_atmosphere"); } RenderableAtmosphere::RenderableAtmosphere(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index 5034b763dc..1e3ed867d8 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -112,9 +112,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemAngle::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_angle"; - return doc; + return codegen::doc("base_dashboarditem_angle"); } DashboardItemAngle::DashboardItemAngle(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemdate.cpp b/modules/base/dashboard/dashboarditemdate.cpp index 3a1a611f6d..f21b7db78c 100644 --- a/modules/base/dashboard/dashboarditemdate.cpp +++ b/modules/base/dashboard/dashboarditemdate.cpp @@ -65,9 +65,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemDate::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_date"; - return doc; + return codegen::doc("base_dashboarditem_date"); } DashboardItemDate::DashboardItemDate(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemdistance.cpp b/modules/base/dashboard/dashboarditemdistance.cpp index bfb364ad2d..86613fc95c 100644 --- a/modules/base/dashboard/dashboarditemdistance.cpp +++ b/modules/base/dashboard/dashboarditemdistance.cpp @@ -140,9 +140,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemDistance::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_distance"; - return doc; + return codegen::doc("base_dashboarditem_distance"); } DashboardItemDistance::DashboardItemDistance(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemframerate.cpp b/modules/base/dashboard/dashboarditemframerate.cpp index f16db9e6fb..283dcb4a52 100644 --- a/modules/base/dashboard/dashboarditemframerate.cpp +++ b/modules/base/dashboard/dashboarditemframerate.cpp @@ -148,9 +148,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemFramerate::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_framerate"; - return doc; + return codegen::doc("base_dashboarditem_framerate"); } DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditempropertyvalue.cpp b/modules/base/dashboard/dashboarditempropertyvalue.cpp index 663ff6d68f..cfec7d6e1f 100644 --- a/modules/base/dashboard/dashboarditempropertyvalue.cpp +++ b/modules/base/dashboard/dashboarditempropertyvalue.cpp @@ -62,9 +62,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemPropertyValue::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_propertyvalue"; - return doc; + return codegen::doc("base_dashboarditem_propertyvalue"); } DashboardItemPropertyValue::DashboardItemPropertyValue( diff --git a/modules/base/dashboard/dashboarditemsimulationincrement.cpp b/modules/base/dashboard/dashboarditemsimulationincrement.cpp index 6648503c41..1dbe386066 100644 --- a/modules/base/dashboard/dashboarditemsimulationincrement.cpp +++ b/modules/base/dashboard/dashboarditemsimulationincrement.cpp @@ -101,9 +101,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemSimulationIncrement::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_simulationincrement"; - return doc; + return codegen::doc("base_dashboarditem_simulationincrement"); } DashboardItemSimulationIncrement::DashboardItemSimulationIncrement( diff --git a/modules/base/dashboard/dashboarditemspacing.cpp b/modules/base/dashboard/dashboarditemspacing.cpp index 5b615f769b..83d32c5262 100644 --- a/modules/base/dashboard/dashboarditemspacing.cpp +++ b/modules/base/dashboard/dashboarditemspacing.cpp @@ -46,9 +46,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemSpacing::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_spacing"; - return doc; + return codegen::doc("base_dashboarditem_spacing"); } DashboardItemSpacing::DashboardItemSpacing(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemtext.cpp b/modules/base/dashboard/dashboarditemtext.cpp index 690da61c6a..321c746310 100644 --- a/modules/base/dashboard/dashboarditemtext.cpp +++ b/modules/base/dashboard/dashboarditemtext.cpp @@ -50,9 +50,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemText::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_text"; - return doc; + return codegen::doc("base_dashboarditem_text"); } DashboardItemText::DashboardItemText(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemvelocity.cpp b/modules/base/dashboard/dashboarditemvelocity.cpp index 587e83f4f3..c13782c8aa 100644 --- a/modules/base/dashboard/dashboarditemvelocity.cpp +++ b/modules/base/dashboard/dashboarditemvelocity.cpp @@ -83,9 +83,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemVelocity::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_dashboarditem_velocity"; - return doc; + return codegen::doc("base_dashboarditem_velocity"); } DashboardItemVelocity::DashboardItemVelocity(const ghoul::Dictionary& dictionary) diff --git a/modules/base/lightsource/cameralightsource.cpp b/modules/base/lightsource/cameralightsource.cpp index d878e5cf45..198fa95906 100644 --- a/modules/base/lightsource/cameralightsource.cpp +++ b/modules/base/lightsource/cameralightsource.cpp @@ -46,9 +46,7 @@ namespace { namespace openspace { documentation::Documentation CameraLightSource::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_camera_light_source"; - return doc; + return codegen::doc("base_camera_light_source"); } CameraLightSource::CameraLightSource() diff --git a/modules/base/lightsource/scenegraphlightsource.cpp b/modules/base/lightsource/scenegraphlightsource.cpp index 671f7efd75..5a2d32a39a 100644 --- a/modules/base/lightsource/scenegraphlightsource.cpp +++ b/modules/base/lightsource/scenegraphlightsource.cpp @@ -59,9 +59,7 @@ namespace { namespace openspace { documentation::Documentation SceneGraphLightSource::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_scene_graph_light_source"; - return doc; + return codegen::doc("base_scene_graph_light_source"); } SceneGraphLightSource::SceneGraphLightSource() diff --git a/modules/base/rendering/grids/renderableboxgrid.cpp b/modules/base/rendering/grids/renderableboxgrid.cpp index 9f35f6541b..9f14d86fdc 100644 --- a/modules/base/rendering/grids/renderableboxgrid.cpp +++ b/modules/base/rendering/grids/renderableboxgrid.cpp @@ -72,9 +72,7 @@ namespace { namespace openspace { documentation::Documentation RenderableBoxGrid::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_boxgrid"; - return doc; + return codegen::doc("base_renderable_boxgrid"); } RenderableBoxGrid::RenderableBoxGrid(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/grids/renderablegrid.cpp b/modules/base/rendering/grids/renderablegrid.cpp index c79f5785dc..6162afc5a6 100644 --- a/modules/base/rendering/grids/renderablegrid.cpp +++ b/modules/base/rendering/grids/renderablegrid.cpp @@ -82,9 +82,7 @@ namespace { namespace openspace { documentation::Documentation RenderableGrid::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_grid"; - return doc; + return codegen::doc("base_renderable_grid"); } RenderableGrid::RenderableGrid(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/grids/renderableradialgrid.cpp b/modules/base/rendering/grids/renderableradialgrid.cpp index fd2150e178..d5d4dac54d 100644 --- a/modules/base/rendering/grids/renderableradialgrid.cpp +++ b/modules/base/rendering/grids/renderableradialgrid.cpp @@ -103,9 +103,7 @@ namespace { namespace openspace { documentation::Documentation RenderableRadialGrid::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_radialgrid"; - return doc; + return codegen::doc("base_renderable_radialgrid"); } RenderableRadialGrid::RenderableRadialGrid(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/grids/renderablesphericalgrid.cpp b/modules/base/rendering/grids/renderablesphericalgrid.cpp index 75a2b27fbf..52485c23af 100644 --- a/modules/base/rendering/grids/renderablesphericalgrid.cpp +++ b/modules/base/rendering/grids/renderablesphericalgrid.cpp @@ -73,9 +73,7 @@ namespace { namespace openspace { documentation::Documentation RenderableSphericalGrid::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_sphericalgrid"; - return doc; + return codegen::doc("base_renderable_sphericalgrid"); } RenderableSphericalGrid::RenderableSphericalGrid(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderablecartesianaxes.cpp b/modules/base/rendering/renderablecartesianaxes.cpp index 2a6a985522..9b658ac953 100644 --- a/modules/base/rendering/renderablecartesianaxes.cpp +++ b/modules/base/rendering/renderablecartesianaxes.cpp @@ -75,9 +75,7 @@ namespace { namespace openspace { documentation::Documentation RenderableCartesianAxes::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_cartesianaxes"; - return doc; + return codegen::doc("base_renderable_cartesianaxes"); } RenderableCartesianAxes::RenderableCartesianAxes(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderabledisc.cpp b/modules/base/rendering/renderabledisc.cpp index f00b2134dc..37d1e4b116 100644 --- a/modules/base/rendering/renderabledisc.cpp +++ b/modules/base/rendering/renderabledisc.cpp @@ -82,9 +82,7 @@ namespace { namespace openspace { documentation::Documentation RenderableDisc::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_disc"; - return doc; + return codegen::doc("base_renderable_disc"); } RenderableDisc::RenderableDisc(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index 42c0ea0ab0..8c4b483efc 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -259,7 +259,7 @@ namespace { namespace openspace { documentation::Documentation RenderableLabels::Documentation() { - return codegen::doc(); + return codegen::doc("base_renderable_labels"); } RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index e3d774bc70..67db6e27ec 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -242,9 +242,7 @@ namespace { namespace openspace { documentation::Documentation RenderableModel::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_model"; - return doc; + return codegen::doc("base_renderable_model"); } RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderablenodeline.cpp b/modules/base/rendering/renderablenodeline.cpp index 0c6de14407..acb91f056f 100644 --- a/modules/base/rendering/renderablenodeline.cpp +++ b/modules/base/rendering/renderablenodeline.cpp @@ -104,9 +104,7 @@ namespace { namespace openspace { documentation::Documentation RenderableNodeLine::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_renderablenodeline"; - return doc; + return codegen::doc("base_renderable_renderablenodeline"); } RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 8af691c8cb..568092ac23 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -100,9 +100,7 @@ namespace { namespace openspace { documentation::Documentation RenderablePlane::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_plane"; - return doc; + return codegen::doc("base_renderable_plane"); } RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderableplaneimagelocal.cpp b/modules/base/rendering/renderableplaneimagelocal.cpp index e4edb680ed..7b48b72bb5 100644 --- a/modules/base/rendering/renderableplaneimagelocal.cpp +++ b/modules/base/rendering/renderableplaneimagelocal.cpp @@ -78,8 +78,9 @@ namespace { namespace openspace { documentation::Documentation RenderablePlaneImageLocal::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_plane_image_local"; + documentation::Documentation doc = codegen::doc( + "base_renderable_plane_image_local" + ); // @TODO cleanup // Insert the parents documentation entries until we have a verifier that can deal diff --git a/modules/base/rendering/renderableplaneimageonline.cpp b/modules/base/rendering/renderableplaneimageonline.cpp index a86fbd2f39..8ce7be472e 100644 --- a/modules/base/rendering/renderableplaneimageonline.cpp +++ b/modules/base/rendering/renderableplaneimageonline.cpp @@ -52,8 +52,9 @@ namespace { namespace openspace { documentation::Documentation RenderablePlaneImageOnline::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_plane_image_online"; + documentation::Documentation doc = codegen::doc( + "base_renderable_plane_image_online" + ); // @TODO cleanup // Insert the parents documentation entries until we have a verifier that can deal diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 0dae86d42c..0aebf68d93 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -162,9 +162,7 @@ namespace { namespace openspace { documentation::Documentation RenderableSphere::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_sphere"; - return doc; + return codegen::doc("base_renderable_sphere"); } RenderableSphere::RenderableSphere(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index 11bcd6a06f..44d04d553e 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -181,9 +181,7 @@ namespace { namespace openspace { documentation::Documentation RenderableTrail::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_renderabletrail"; - return doc; + return codegen::doc("base_renderable_renderabletrail"); } RenderableTrail::Appearance::Appearance() diff --git a/modules/base/rendering/renderabletrailorbit.cpp b/modules/base/rendering/renderabletrailorbit.cpp index 681c4e14d0..a80152e3eb 100644 --- a/modules/base/rendering/renderabletrailorbit.cpp +++ b/modules/base/rendering/renderabletrailorbit.cpp @@ -129,8 +129,9 @@ namespace { namespace openspace { documentation::Documentation RenderableTrailOrbit::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_renderabletrailorbit"; + documentation::Documentation doc = codegen::doc( + "base_renderable_renderabletrailorbit" + ); // Insert the parents documentation entries until we have a verifier that can deal // with class hierarchy diff --git a/modules/base/rendering/renderabletrailtrajectory.cpp b/modules/base/rendering/renderabletrailtrajectory.cpp index ecd770c3ea..061e4de74b 100644 --- a/modules/base/rendering/renderabletrailtrajectory.cpp +++ b/modules/base/rendering/renderabletrailtrajectory.cpp @@ -105,8 +105,9 @@ namespace { namespace openspace { documentation::Documentation RenderableTrailTrajectory::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_renderable_renderabletrailtrajectory"; + documentation::Documentation doc = codegen::doc( + "base_renderable_renderabletrailtrajectory" + ); // @TODO cleanup // Insert the parents documentation entries until we have a verifier that can deal diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index 4cb9cf591b..5c3ebae6eb 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -128,9 +128,7 @@ int removeDashboardItemsFromScreenSpace(lua_State* L) { } // namespace luascriptfunctions documentation::Documentation ScreenSpaceDashboard::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_screenspace_dashboard"; - return doc; + return codegen::doc("base_screenspace_dashboard"); } ScreenSpaceDashboard::ScreenSpaceDashboard(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index 48686c487b..d4cf2672c6 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -58,9 +58,7 @@ namespace { namespace openspace { documentation::Documentation ScreenSpaceImageLocal::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_screenspace_image_local"; - return doc; + return codegen::doc("base_screenspace_image_local"); } ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index 9754cc737a..8219965b11 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -58,9 +58,7 @@ namespace { namespace openspace { documentation::Documentation ScreenSpaceImageOnline::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_screenspace_image_online"; - return doc; + return codegen::doc("base_screenspace_image_online"); } ScreenSpaceImageOnline::ScreenSpaceImageOnline(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rotation/constantrotation.cpp b/modules/base/rotation/constantrotation.cpp index d72f524f40..cd14fdddc2 100644 --- a/modules/base/rotation/constantrotation.cpp +++ b/modules/base/rotation/constantrotation.cpp @@ -55,9 +55,7 @@ namespace { namespace openspace { documentation::Documentation ConstantRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_rotation_constant"; - return doc; + return codegen::doc("base_transform_rotation_constant"); } ConstantRotation::ConstantRotation(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp index 11324d7305..0182155221 100644 --- a/modules/base/rotation/fixedrotation.cpp +++ b/modules/base/rotation/fixedrotation.cpp @@ -231,9 +231,7 @@ namespace { namespace openspace { documentation::Documentation FixedRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_rotation_fixed"; - return doc; + return codegen::doc("base_transform_rotation_fixed"); } FixedRotation::FixedRotation(const ghoul::Dictionary& dictionary) diff --git a/modules/base/rotation/luarotation.cpp b/modules/base/rotation/luarotation.cpp index e685453327..86d9e8d619 100644 --- a/modules/base/rotation/luarotation.cpp +++ b/modules/base/rotation/luarotation.cpp @@ -56,9 +56,7 @@ namespace { namespace openspace { documentation::Documentation LuaRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_rotation_lua"; - return doc; + return codegen::doc("base_transform_rotation_lua"); } LuaRotation::LuaRotation() diff --git a/modules/base/rotation/staticrotation.cpp b/modules/base/rotation/staticrotation.cpp index 1da7e72f6f..550453f55e 100644 --- a/modules/base/rotation/staticrotation.cpp +++ b/modules/base/rotation/staticrotation.cpp @@ -67,9 +67,7 @@ namespace { namespace openspace { documentation::Documentation StaticRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_rotation_static"; - return doc; + return codegen::doc("base_transform_rotation_static"); } StaticRotation::StaticRotation() diff --git a/modules/base/rotation/timelinerotation.cpp b/modules/base/rotation/timelinerotation.cpp index 8a60f99c8b..aa96c4b0eb 100644 --- a/modules/base/rotation/timelinerotation.cpp +++ b/modules/base/rotation/timelinerotation.cpp @@ -42,9 +42,7 @@ namespace { namespace openspace { documentation::Documentation TimelineRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_rotation_keyframe"; - return doc; + return codegen::doc("base_transform_rotation_keyframe"); } TimelineRotation::TimelineRotation(const ghoul::Dictionary& dictionary) { diff --git a/modules/base/scale/luascale.cpp b/modules/base/scale/luascale.cpp index 7bbd761dad..f99600595e 100644 --- a/modules/base/scale/luascale.cpp +++ b/modules/base/scale/luascale.cpp @@ -55,9 +55,7 @@ namespace { namespace openspace { documentation::Documentation LuaScale::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_scale_lua"; - return doc; + return codegen::doc("base_scale_lua"); } LuaScale::LuaScale() diff --git a/modules/base/scale/nonuniformstaticscale.cpp b/modules/base/scale/nonuniformstaticscale.cpp index 19bc7ca349..62229c511c 100644 --- a/modules/base/scale/nonuniformstaticscale.cpp +++ b/modules/base/scale/nonuniformstaticscale.cpp @@ -45,9 +45,7 @@ namespace { namespace openspace { documentation::Documentation NonUniformStaticScale::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_scale_nonuniformstatic"; - return doc; + return codegen::doc("base_scale_nonuniformstatic"); } glm::dvec3 NonUniformStaticScale::scaleValue(const UpdateData&) const { diff --git a/modules/base/scale/staticscale.cpp b/modules/base/scale/staticscale.cpp index 59b5a96c57..57f5643e99 100644 --- a/modules/base/scale/staticscale.cpp +++ b/modules/base/scale/staticscale.cpp @@ -45,9 +45,7 @@ namespace { namespace openspace { documentation::Documentation StaticScale::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_scale_static"; - return doc; + return codegen::doc("base_scale_static"); } glm::dvec3 StaticScale::scaleValue(const UpdateData&) const { diff --git a/modules/base/scale/timedependentscale.cpp b/modules/base/scale/timedependentscale.cpp index 168146ef0c..567faef012 100644 --- a/modules/base/scale/timedependentscale.cpp +++ b/modules/base/scale/timedependentscale.cpp @@ -71,9 +71,7 @@ namespace { namespace openspace { documentation::Documentation TimeDependentScale::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_scale_timedependent"; - return doc; + return codegen::doc("base_scale_timedependent"); } TimeDependentScale::TimeDependentScale(const ghoul::Dictionary& dictionary) diff --git a/modules/base/timeframe/timeframeinterval.cpp b/modules/base/timeframe/timeframeinterval.cpp index e0a18079b2..01606bb174 100644 --- a/modules/base/timeframe/timeframeinterval.cpp +++ b/modules/base/timeframe/timeframeinterval.cpp @@ -68,9 +68,7 @@ namespace { namespace openspace { documentation::Documentation TimeFrameInterval::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_time_frame_interval"; - return doc; + return codegen::doc("base_time_frame_interval"); } bool TimeFrameInterval::isActive(const Time& time) const { diff --git a/modules/base/timeframe/timeframeunion.cpp b/modules/base/timeframe/timeframeunion.cpp index b630f940ea..2b6204af04 100644 --- a/modules/base/timeframe/timeframeunion.cpp +++ b/modules/base/timeframe/timeframeunion.cpp @@ -50,13 +50,11 @@ namespace { namespace openspace { documentation::Documentation TimeFrameUnion::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_time_frame_union"; - return doc; + return codegen::doc("base_time_frame_union"); } bool TimeFrameUnion::isActive(const Time& time) const { - for (const auto& tf : _timeFrames) { + for (const ghoul::mm_unique_ptr& tf : _timeFrames) { if (tf->isActive(time)) { return true; } diff --git a/modules/base/translation/luatranslation.cpp b/modules/base/translation/luatranslation.cpp index 4e2b527e5d..2f853e8394 100644 --- a/modules/base/translation/luatranslation.cpp +++ b/modules/base/translation/luatranslation.cpp @@ -56,9 +56,7 @@ namespace { namespace openspace { documentation::Documentation LuaTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_translation_lua"; - return doc; + return codegen::doc("base_transform_translation_lua"); } LuaTranslation::LuaTranslation() diff --git a/modules/base/translation/statictranslation.cpp b/modules/base/translation/statictranslation.cpp index b4987cccf3..54c8513dcf 100644 --- a/modules/base/translation/statictranslation.cpp +++ b/modules/base/translation/statictranslation.cpp @@ -45,9 +45,7 @@ namespace { namespace openspace { documentation::Documentation StaticTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_translation_static"; - return doc; + return codegen::doc("base_transform_translation_static"); } StaticTranslation::StaticTranslation() diff --git a/modules/base/translation/timelinetranslation.cpp b/modules/base/translation/timelinetranslation.cpp index 6067f91c5b..defe7e9eab 100644 --- a/modules/base/translation/timelinetranslation.cpp +++ b/modules/base/translation/timelinetranslation.cpp @@ -42,9 +42,7 @@ namespace { namespace openspace { documentation::Documentation TimelineTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_translation_keyframe"; - return doc; + return codegen::doc("base_transform_translation_keyframe"); } TimelineTranslation::TimelineTranslation(const ghoul::Dictionary& dictionary) { diff --git a/modules/debugging/rendering/renderabledebugplane.cpp b/modules/debugging/rendering/renderabledebugplane.cpp index 335e48b3b7..f2308c7ecd 100644 --- a/modules/debugging/rendering/renderabledebugplane.cpp +++ b/modules/debugging/rendering/renderabledebugplane.cpp @@ -100,9 +100,7 @@ namespace { namespace openspace { documentation::Documentation RenderableDebugPlane::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "debugging_renderable_debugplane"; - return doc; + return codegen::doc("debugging_renderable_debugplane"); } RenderableDebugPlane::RenderableDebugPlane(const ghoul::Dictionary& dictionary) diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index c9c54ee569..bc9df03ce1 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -338,9 +338,7 @@ namespace { namespace openspace { documentation::Documentation RenderableBillboardsCloud::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "digitaluniverse_RenderableBillboardsCloud"; - return doc; + return codegen::doc("digitaluniverse_RenderableBillboardsCloud"); } RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& dictionary) diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index d62af2fc38..14f3742c86 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -180,9 +180,7 @@ namespace { namespace openspace { documentation::Documentation RenderableDUMeshes::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "digitaluniverse_renderabledumeshes"; - return doc; + return codegen::doc("digitaluniverse_renderabledumeshes"); } RenderableDUMeshes::RenderableDUMeshes(const ghoul::Dictionary& dictionary) diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.cpp b/modules/digitaluniverse/rendering/renderableplanescloud.cpp index cbd9cc70dd..f7c44ec3cd 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.cpp +++ b/modules/digitaluniverse/rendering/renderableplanescloud.cpp @@ -246,9 +246,7 @@ namespace { namespace openspace { documentation::Documentation RenderablePlanesCloud::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "digitaluniverse_RenderablePlanesCloud"; - return doc; + return codegen::doc("digitaluniverse_RenderablePlanesCloud"); } RenderablePlanesCloud::RenderablePlanesCloud(const ghoul::Dictionary& dictionary) diff --git a/modules/digitaluniverse/rendering/renderablepoints.cpp b/modules/digitaluniverse/rendering/renderablepoints.cpp index b2f4813a8e..286e247d96 100644 --- a/modules/digitaluniverse/rendering/renderablepoints.cpp +++ b/modules/digitaluniverse/rendering/renderablepoints.cpp @@ -116,9 +116,7 @@ namespace { namespace openspace { documentation::Documentation RenderablePoints::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "digitaluniverse_renderablepoints"; - return doc; + return codegen::doc("digitaluniverse_renderablepoints"); } RenderablePoints::RenderablePoints(const ghoul::Dictionary& dictionary) diff --git a/modules/exoplanets/rendering/renderableorbitdisc.cpp b/modules/exoplanets/rendering/renderableorbitdisc.cpp index bc1d0299b2..8688d84e22 100644 --- a/modules/exoplanets/rendering/renderableorbitdisc.cpp +++ b/modules/exoplanets/rendering/renderableorbitdisc.cpp @@ -93,9 +93,7 @@ namespace { namespace openspace { documentation::Documentation RenderableOrbitDisc::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "exoplanets_renderableorbitdisc"; - return doc; + return codegen::doc("exoplanets_renderableorbitdisc"); } RenderableOrbitDisc::RenderableOrbitDisc(const ghoul::Dictionary& dictionary) diff --git a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp index ed571c9460..d817b86285 100644 --- a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp +++ b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp @@ -63,9 +63,7 @@ namespace { namespace openspace::exoplanets { documentation::Documentation ExoplanetsDataPreparationTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "exoplanets_data_preparation_task"; - return doc; + return codegen::doc("exoplanets_data_preparation_task"); } ExoplanetsDataPreparationTask::ExoplanetsDataPreparationTask( diff --git a/modules/gaia/rendering/renderablegaiastars.cpp b/modules/gaia/rendering/renderablegaiastars.cpp index 99a3a091ad..e1a12759f4 100644 --- a/modules/gaia/rendering/renderablegaiastars.cpp +++ b/modules/gaia/rendering/renderablegaiastars.cpp @@ -414,9 +414,7 @@ namespace { namespace openspace { documentation::Documentation RenderableGaiaStars::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "gaiamission_renderablegaiastars"; - return doc; + return codegen::doc("gaiamission_renderablegaiastars"); } RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) diff --git a/modules/gaia/tasks/constructoctreetask.cpp b/modules/gaia/tasks/constructoctreetask.cpp index 8b03780c94..1239a65960 100644 --- a/modules/gaia/tasks/constructoctreetask.cpp +++ b/modules/gaia/tasks/constructoctreetask.cpp @@ -653,9 +653,7 @@ bool ConstructOctreeTask::filterStar(const glm::vec2& range, float filterValue, } documentation::Documentation ConstructOctreeTask::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "gaiamission_constructoctreefrombin"; - return doc; + return codegen::doc("gaiamission_constructoctreefrombin"); } } // namespace openspace diff --git a/modules/gaia/tasks/readfitstask.cpp b/modules/gaia/tasks/readfitstask.cpp index 6404f576b2..a23d128073 100644 --- a/modules/gaia/tasks/readfitstask.cpp +++ b/modules/gaia/tasks/readfitstask.cpp @@ -337,9 +337,7 @@ int ReadFitsTask::writeOctantToFile(const std::vector& octantData, int in } documentation::Documentation ReadFitsTask::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "gaiamission_fitsfiletorawdata"; - return doc; + return codegen::doc("gaiamission_fitsfiletorawdata"); } } // namespace openspace diff --git a/modules/gaia/tasks/readspecktask.cpp b/modules/gaia/tasks/readspecktask.cpp index dc54605621..7a0b45917e 100644 --- a/modules/gaia/tasks/readspecktask.cpp +++ b/modules/gaia/tasks/readspecktask.cpp @@ -49,9 +49,7 @@ namespace { namespace openspace { documentation::Documentation ReadSpeckTask::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "gaiamission_speckfiletorawdata"; - return doc; + return codegen::doc("gaiamission_speckfiletorawdata"); } ReadSpeckTask::ReadSpeckTask(const ghoul::Dictionary& dictionary) { diff --git a/modules/globebrowsing/src/dashboarditemglobelocation.cpp b/modules/globebrowsing/src/dashboarditemglobelocation.cpp index fe51c0fb9f..0369043f4f 100644 --- a/modules/globebrowsing/src/dashboarditemglobelocation.cpp +++ b/modules/globebrowsing/src/dashboarditemglobelocation.cpp @@ -78,9 +78,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemGlobeLocation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_dashboarditem_globelocation"; - return doc; + return codegen::doc("globebrowsing_dashboarditem_globelocation"); } DashboardItemGlobeLocation::DashboardItemGlobeLocation( diff --git a/modules/globebrowsing/src/globelabelscomponent.cpp b/modules/globebrowsing/src/globelabelscomponent.cpp index fe26da6e43..f97a13fe4d 100644 --- a/modules/globebrowsing/src/globelabelscomponent.cpp +++ b/modules/globebrowsing/src/globelabelscomponent.cpp @@ -225,9 +225,7 @@ namespace { namespace openspace { documentation::Documentation GlobeLabelsComponent::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_globelabelscomponent"; - return doc; + return codegen::doc("globebrowsing_globelabelscomponent"); } GlobeLabelsComponent::GlobeLabelsComponent() diff --git a/modules/globebrowsing/src/globetranslation.cpp b/modules/globebrowsing/src/globetranslation.cpp index 6056b81a52..d1097c35de 100644 --- a/modules/globebrowsing/src/globetranslation.cpp +++ b/modules/globebrowsing/src/globetranslation.cpp @@ -98,9 +98,7 @@ namespace { namespace openspace::globebrowsing { documentation::Documentation GlobeTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_translation_globetranslation"; - return doc; + return codegen::doc("space_translation_globetranslation"); } GlobeTranslation::GlobeTranslation(const ghoul::Dictionary& dictionary) diff --git a/modules/globebrowsing/src/layer.cpp b/modules/globebrowsing/src/layer.cpp index 43039ef251..0d9e4fbb45 100644 --- a/modules/globebrowsing/src/layer.cpp +++ b/modules/globebrowsing/src/layer.cpp @@ -179,9 +179,7 @@ namespace { } // namespace documentation::Documentation Layer::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_layer"; - return doc; + return codegen::doc("globebrowsing_layer"); } Layer::Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, diff --git a/modules/globebrowsing/src/layeradjustment.cpp b/modules/globebrowsing/src/layeradjustment.cpp index 512fdaf88d..ac9da38447 100644 --- a/modules/globebrowsing/src/layeradjustment.cpp +++ b/modules/globebrowsing/src/layeradjustment.cpp @@ -70,9 +70,7 @@ namespace { namespace openspace::globebrowsing { documentation::Documentation LayerAdjustment::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_layeradjustment"; - return doc; + return codegen::doc("globebrowsing_layeradjustment"); } LayerAdjustment::LayerAdjustment() diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index 04052bee2b..02ef8d540c 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -490,9 +490,7 @@ Chunk::Chunk(const TileIndex& ti) {} documentation::Documentation RenderableGlobe::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_renderableglobe"; - return doc; + return codegen::doc("globebrowsing_renderableglobe"); } RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) diff --git a/modules/globebrowsing/src/ringscomponent.cpp b/modules/globebrowsing/src/ringscomponent.cpp index b65eab725d..e4b0a2310b 100644 --- a/modules/globebrowsing/src/ringscomponent.cpp +++ b/modules/globebrowsing/src/ringscomponent.cpp @@ -200,9 +200,7 @@ namespace { namespace openspace { documentation::Documentation RingsComponent::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_rings_component"; - return doc; + return codegen::doc("globebrowsing_rings_component"); } RingsComponent::RingsComponent(const ghoul::Dictionary& dictionary) diff --git a/modules/globebrowsing/src/shadowcomponent.cpp b/modules/globebrowsing/src/shadowcomponent.cpp index 4d45705b5f..f7c63a8df0 100644 --- a/modules/globebrowsing/src/shadowcomponent.cpp +++ b/modules/globebrowsing/src/shadowcomponent.cpp @@ -155,9 +155,7 @@ namespace { namespace openspace { documentation::Documentation ShadowComponent::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "globebrowsing_shadows_component"; - return doc; + return codegen::doc("globebrowsing_shadows_component"); } ShadowComponent::ShadowComponent(const ghoul::Dictionary& dictionary) diff --git a/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp b/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp index 1b4666e512..2d862da6a7 100644 --- a/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp +++ b/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp @@ -52,9 +52,7 @@ namespace { namespace openspace::kameleonvolume { documentation::Documentation KameleonDocumentationTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "kameleon_documentation_task"; - return doc; + return codegen::doc("kameleon_documentation_task"); } KameleonDocumentationTask::KameleonDocumentationTask(const ghoul::Dictionary& dictionary) diff --git a/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp b/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp index f9ef7dd3d7..af8d22baa8 100644 --- a/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp +++ b/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp @@ -46,9 +46,7 @@ namespace { namespace openspace::kameleonvolume { documentation::Documentation KameleonMetadataToJsonTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "kameleon_metadata_to_json_task"; - return doc; + return codegen::doc("kameleon_metadata_to_json_task"); } KameleonMetadataToJsonTask::KameleonMetadataToJsonTask( diff --git a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp index c4b4ef6747..76015be84c 100644 --- a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp +++ b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp @@ -79,9 +79,7 @@ namespace { namespace openspace::kameleonvolume { documentation::Documentation KameleonVolumeToRawTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "kameleon_metadata_to_json_task"; - return doc; + return codegen::doc("kameleon_metadata_to_json_task"); } KameleonVolumeToRawTask::KameleonVolumeToRawTask(const ghoul::Dictionary& dictionary) { diff --git a/modules/space/rendering/planetgeometry.cpp b/modules/space/rendering/planetgeometry.cpp index ec68224b61..8216093752 100644 --- a/modules/space/rendering/planetgeometry.cpp +++ b/modules/space/rendering/planetgeometry.cpp @@ -40,9 +40,7 @@ namespace { namespace openspace::planetgeometry { documentation::Documentation PlanetGeometry::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_geometry_planet"; - return doc; + return codegen::doc("space_geometry_planet"); } std::unique_ptr PlanetGeometry::createFromDictionary( diff --git a/modules/space/rendering/renderableconstellationbounds.cpp b/modules/space/rendering/renderableconstellationbounds.cpp index 76bd35bca5..a9193c6294 100644 --- a/modules/space/rendering/renderableconstellationbounds.cpp +++ b/modules/space/rendering/renderableconstellationbounds.cpp @@ -99,11 +99,8 @@ namespace { namespace openspace { documentation::Documentation RenderableConstellationBounds::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderable_constellationbounds"; - return doc; -} // namespace - + return codegen::doc("space_renderable_constellationbounds"); +} RenderableConstellationBounds::RenderableConstellationBounds( const ghoul::Dictionary& dictionary) diff --git a/modules/space/rendering/renderablehabitablezone.cpp b/modules/space/rendering/renderablehabitablezone.cpp index 33776b2041..27129f4079 100644 --- a/modules/space/rendering/renderablehabitablezone.cpp +++ b/modules/space/rendering/renderablehabitablezone.cpp @@ -96,8 +96,9 @@ namespace { namespace openspace { documentation::Documentation RenderableHabitableZone::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderablehabitablezone"; + documentation::Documentation doc = codegen::doc( + "space_renderablehabitablezone" + ); // @TODO cleanup // Insert the parents documentation entries until we have a verifier that can deal diff --git a/modules/space/rendering/renderableorbitalkepler.cpp b/modules/space/rendering/renderableorbitalkepler.cpp index 040354458d..e54329e9ab 100644 --- a/modules/space/rendering/renderableorbitalkepler.cpp +++ b/modules/space/rendering/renderableorbitalkepler.cpp @@ -262,9 +262,7 @@ namespace { namespace openspace { documentation::Documentation RenderableOrbitalKepler::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderableorbitalkepler"; - return doc; + return codegen::doc("space_renderableorbitalkepler"); } double RenderableOrbitalKepler::calculateSemiMajorAxis(double meanMotion) const { diff --git a/modules/space/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp index 383b6942ee..49d4b32450 100644 --- a/modules/space/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -103,9 +103,7 @@ namespace { namespace openspace { documentation::Documentation RenderableRings::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderable_rings"; - return doc; + return codegen::doc("space_renderable_rings"); } RenderableRings::RenderableRings(const ghoul::Dictionary& dictionary) diff --git a/modules/space/rendering/renderablesatellites.cpp b/modules/space/rendering/renderablesatellites.cpp index 15fb459236..7bd47a3648 100644 --- a/modules/space/rendering/renderablesatellites.cpp +++ b/modules/space/rendering/renderablesatellites.cpp @@ -64,8 +64,9 @@ namespace { namespace openspace { documentation::Documentation RenderableSatellites::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderablesatellites"; + documentation::Documentation doc = codegen::doc( + "space_renderablesatellites" + ); // Insert the parents documentation entries until we have a verifier that can deal // with class hierarchy diff --git a/modules/space/rendering/renderablesmallbody.cpp b/modules/space/rendering/renderablesmallbody.cpp index cd37e99256..3236bab79a 100644 --- a/modules/space/rendering/renderablesmallbody.cpp +++ b/modules/space/rendering/renderablesmallbody.cpp @@ -98,8 +98,9 @@ namespace { namespace openspace { documentation::Documentation RenderableSmallBody::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderablesmallbody"; + documentation::Documentation doc = codegen::doc( + "space_renderablesmallbody" + ); // Insert the parents documentation entries until we have a verifier that can deal // with class hierarchy diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index f5c747ed1a..adbb5a76fb 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -450,9 +450,7 @@ namespace { namespace openspace { documentation::Documentation RenderableStars::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_renderablestars"; - return doc; + return codegen::doc("space_renderablestars"); } RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) diff --git a/modules/space/rendering/simplespheregeometry.cpp b/modules/space/rendering/simplespheregeometry.cpp index 5c4ed12ef9..eb95f5153c 100644 --- a/modules/space/rendering/simplespheregeometry.cpp +++ b/modules/space/rendering/simplespheregeometry.cpp @@ -55,9 +55,7 @@ namespace { namespace openspace::planetgeometry { documentation::Documentation SimpleSphereGeometry::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_geometry_simplesphere"; - return doc; + return codegen::doc("space_geometry_simplesphere"); } SimpleSphereGeometry::SimpleSphereGeometry(const ghoul::Dictionary& dictionary) diff --git a/modules/space/rotation/spicerotation.cpp b/modules/space/rotation/spicerotation.cpp index 927c1c7ceb..963a87a11b 100644 --- a/modules/space/rotation/spicerotation.cpp +++ b/modules/space/rotation/spicerotation.cpp @@ -73,9 +73,7 @@ namespace { namespace openspace { documentation::Documentation SpiceRotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_transform_rotation_spice"; - return doc; + return codegen::doc("space_transform_rotation_spice"); } SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) diff --git a/modules/space/translation/horizonstranslation.cpp b/modules/space/translation/horizonstranslation.cpp index b84bc3c9c2..95bca1255d 100644 --- a/modules/space/translation/horizonstranslation.cpp +++ b/modules/space/translation/horizonstranslation.cpp @@ -58,9 +58,7 @@ namespace { namespace openspace { documentation::Documentation HorizonsTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "base_transform_translation_horizons"; - return doc; + return codegen::doc("base_transform_translation_horizons"); } HorizonsTranslation::HorizonsTranslation() diff --git a/modules/space/translation/keplertranslation.cpp b/modules/space/translation/keplertranslation.cpp index 865a2fe299..bdb62a1f3c 100644 --- a/modules/space/translation/keplertranslation.cpp +++ b/modules/space/translation/keplertranslation.cpp @@ -141,9 +141,7 @@ KeplerTranslation::RangeError::RangeError(std::string off) {} documentation::Documentation KeplerTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_transform_kepler"; - return doc; + return codegen::doc("space_transform_kepler"); } KeplerTranslation::KeplerTranslation() diff --git a/modules/space/translation/spicetranslation.cpp b/modules/space/translation/spicetranslation.cpp index 6426e0d85c..95fe2a70c6 100644 --- a/modules/space/translation/spicetranslation.cpp +++ b/modules/space/translation/spicetranslation.cpp @@ -84,9 +84,7 @@ namespace { namespace openspace { documentation::Documentation SpiceTranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_translation_spicetranslation"; - return doc; + return codegen::doc("space_translation_spicetranslation"); } SpiceTranslation::SpiceTranslation(const ghoul::Dictionary& dictionary) diff --git a/modules/space/translation/tletranslation.cpp b/modules/space/translation/tletranslation.cpp index fec5d05143..a1e43460ed 100644 --- a/modules/space/translation/tletranslation.cpp +++ b/modules/space/translation/tletranslation.cpp @@ -225,9 +225,7 @@ namespace { namespace openspace { documentation::Documentation TLETranslation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "space_transform_tle"; - return doc; + return codegen::doc("space_transform_tle"); } TLETranslation::TLETranslation(const ghoul::Dictionary& dictionary) { diff --git a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp index 1e1eceba13..69a86f3129 100644 --- a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp +++ b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp @@ -85,9 +85,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItemInstruments::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "spacecraftinstruments_dashboarditem_instuments"; - return doc; + return codegen::doc("spacecraftinstruments_dashboarditem_instuments"); } DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dictionary) diff --git a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp index 1d3071ef0d..f771037e29 100644 --- a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp +++ b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp @@ -73,9 +73,7 @@ namespace { namespace openspace { documentation::Documentation RenderableCrawlingLine::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_renderable_crawlingline"; - return doc; + return codegen::doc("newhorizons_renderable_crawlingline"); } RenderableCrawlingLine::RenderableCrawlingLine(const ghoul::Dictionary& dictionary) diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index 3c9c7bcb5c..775abfec35 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -185,9 +185,7 @@ namespace { namespace openspace { documentation::Documentation RenderableFov::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_renderable_fieldofview"; - return doc; + return codegen::doc("newhorizons_renderable_fieldofview"); } RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 1eb9c230ab..aa54052e7c 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -90,9 +90,7 @@ namespace { namespace openspace { documentation::Documentation RenderableModelProjection::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_renderable_modelprojection"; - return doc; + return codegen::doc("newhorizons_renderable_modelprojection"); } RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary) diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index ff1b7fbe51..6be4be39c5 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -162,9 +162,7 @@ namespace { namespace openspace { documentation::Documentation RenderablePlanetProjection::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_renderable_planetprojection"; - return doc; + return codegen::doc("newhorizons_renderable_planetprojection"); } RenderablePlanetProjection::RenderablePlanetProjection(const ghoul::Dictionary& dict) diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp index bed2e9ca8b..d935219104 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp @@ -143,9 +143,7 @@ namespace { namespace openspace { documentation::Documentation RenderableShadowCylinder::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_renderable_shadowcylinder"; - return doc; + return codegen::doc("newhorizons_renderable_shadowcylinder"); } RenderableShadowCylinder::RenderableShadowCylinder(const ghoul::Dictionary& dictionary) diff --git a/modules/spacecraftinstruments/util/projectioncomponent.cpp b/modules/spacecraftinstruments/util/projectioncomponent.cpp index 5ae79ed728..3e48f3eba8 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.cpp +++ b/modules/spacecraftinstruments/util/projectioncomponent.cpp @@ -162,9 +162,7 @@ namespace { namespace openspace { documentation::Documentation ProjectionComponent::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "newhorizons_projectioncomponent"; - return doc; + return codegen::doc("newhorizons_projectioncomponent"); } ProjectionComponent::ProjectionComponent() diff --git a/modules/spout/renderableplanespout.cpp b/modules/spout/renderableplanespout.cpp index 1344dea70f..141ba1298e 100644 --- a/modules/spout/renderableplanespout.cpp +++ b/modules/spout/renderableplanespout.cpp @@ -66,9 +66,7 @@ namespace { namespace openspace { documentation::Documentation RenderablePlaneSpout::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "spout_screenspace_spout"; - return doc; + return codegen::doc("spout_screenspace_spout"); } RenderablePlaneSpout::RenderablePlaneSpout(const ghoul::Dictionary& dictionary) diff --git a/modules/spout/screenspacespout.cpp b/modules/spout/screenspacespout.cpp index 4265a4ff7c..2aabb89cde 100644 --- a/modules/spout/screenspacespout.cpp +++ b/modules/spout/screenspacespout.cpp @@ -64,9 +64,7 @@ namespace { namespace openspace { documentation::Documentation ScreenSpaceSpout::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "spout_screenspace_spout"; - return doc; + return codegen::doc("spout_screenspace_spout"); } ScreenSpaceSpout::ScreenSpaceSpout(const ghoul::Dictionary& dictionary) diff --git a/modules/sync/syncs/httpsynchronization.cpp b/modules/sync/syncs/httpsynchronization.cpp index 85b262b40e..18f2a34c7f 100644 --- a/modules/sync/syncs/httpsynchronization.cpp +++ b/modules/sync/syncs/httpsynchronization.cpp @@ -59,9 +59,7 @@ namespace { namespace openspace { documentation::Documentation HttpSynchronization::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "http_synchronization"; - return doc; + return codegen::doc("http_synchronization"); } HttpSynchronization::HttpSynchronization(const ghoul::Dictionary& dict, diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index 4f38f6e73a..d53d79ca49 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -78,9 +78,7 @@ namespace { namespace openspace { documentation::Documentation UrlSynchronization::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "sync_synchronization_url"; - return doc; + return codegen::doc("sync_synchronization_url"); } UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dict, diff --git a/modules/sync/tasks/syncassettask.cpp b/modules/sync/tasks/syncassettask.cpp index cfdfd11e43..04ba0573d2 100644 --- a/modules/sync/tasks/syncassettask.cpp +++ b/modules/sync/tasks/syncassettask.cpp @@ -56,9 +56,7 @@ namespace { namespace openspace { documentation::Documentation SyncAssetTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "sync_asset_task"; - return doc; + return codegen::doc("sync_asset_task"); } SyncAssetTask::SyncAssetTask(const ghoul::Dictionary& dictionary) { diff --git a/modules/vislab/rendering/renderabledistancelabel.cpp b/modules/vislab/rendering/renderabledistancelabel.cpp index 8d8adaa56e..693da653ad 100644 --- a/modules/vislab/rendering/renderabledistancelabel.cpp +++ b/modules/vislab/rendering/renderabledistancelabel.cpp @@ -74,9 +74,7 @@ namespace { namespace openspace { documentation::Documentation RenderableDistanceLabel::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "vislab_renderable_distance_label"; - return doc; + return codegen::doc("vislab_renderable_distance_label"); } RenderableDistanceLabel::RenderableDistanceLabel(const ghoul::Dictionary& dictionary) diff --git a/modules/volume/rawvolumemetadata.cpp b/modules/volume/rawvolumemetadata.cpp index 85c0a05bbd..61d525b6a8 100644 --- a/modules/volume/rawvolumemetadata.cpp +++ b/modules/volume/rawvolumemetadata.cpp @@ -143,9 +143,7 @@ ghoul::Dictionary RawVolumeMetadata::dictionary() { } documentation::Documentation RawVolumeMetadata::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "volume_rawvolumemetadata"; - return doc; + return codegen::doc("volume_rawvolumemetadata"); } } // namespace openspace::volume diff --git a/modules/volume/rendering/renderabletimevaryingvolume.cpp b/modules/volume/rendering/renderabletimevaryingvolume.cpp index 88d24850e7..cd748315cb 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.cpp +++ b/modules/volume/rendering/renderabletimevaryingvolume.cpp @@ -146,9 +146,7 @@ namespace { namespace openspace::volume { documentation::Documentation RenderableTimeVaryingVolume::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "volume_renderable_timevaryingvolume"; - return doc; + return codegen::doc("volume_renderable_timevaryingvolume"); } RenderableTimeVaryingVolume::RenderableTimeVaryingVolume( diff --git a/modules/volume/tasks/generaterawvolumetask.cpp b/modules/volume/tasks/generaterawvolumetask.cpp index 5d43bbfd50..109703d6f6 100644 --- a/modules/volume/tasks/generaterawvolumetask.cpp +++ b/modules/volume/tasks/generaterawvolumetask.cpp @@ -72,9 +72,7 @@ namespace { namespace openspace::volume { documentation::Documentation GenerateRawVolumeTask::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "generate_raw_volume_task"; - return doc; + return codegen::doc("generate_raw_volume_task"); } GenerateRawVolumeTask::GenerateRawVolumeTask(const ghoul::Dictionary& dictionary) { diff --git a/src/engine/configuration.cpp b/src/engine/configuration.cpp index 9973dea4ca..f61dbc9ef7 100644 --- a/src/engine/configuration.cpp +++ b/src/engine/configuration.cpp @@ -348,7 +348,7 @@ 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(); + 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()); @@ -603,7 +603,8 @@ void parseLuaState(Configuration& configuration) { c.bypassLauncher = p.bypassLauncher.value_or(c.bypassLauncher); } -documentation::Documentation Configuration::Documentation = codegen::doc(); +documentation::Documentation Configuration::Documentation = + codegen::doc("core_configuration"); std::filesystem::path findConfiguration(const std::string& filename) { std::filesystem::path directory = absPath("${BIN}"); diff --git a/src/engine/logfactory.cpp b/src/engine/logfactory.cpp index 3faf5da2a5..7beffdaa8e 100644 --- a/src/engine/logfactory.cpp +++ b/src/engine/logfactory.cpp @@ -89,9 +89,7 @@ namespace { namespace openspace { documentation::Documentation LogFactoryDocumentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_logfactory"; - return doc; + return codegen::doc("core_logfactory"); } std::unique_ptr createLog(const ghoul::Dictionary& dictionary) { diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 44f2300d40..c28fca94c6 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -561,9 +561,7 @@ std::vector NavigationHandler::joystickButtonCommand(int button) co } documentation::Documentation NavigationHandler::NavigationState::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_navigation_state"; - return doc; + return codegen::doc("core_navigation_state"); } scripting::LuaLibrary NavigationHandler::luaLibrary() { diff --git a/src/mission/mission.cpp b/src/mission/mission.cpp index bfdaaafc38..fd469247e4 100644 --- a/src/mission/mission.cpp +++ b/src/mission/mission.cpp @@ -56,9 +56,7 @@ namespace { namespace openspace { documentation::Documentation MissionPhase::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_mission_mission"; - return doc; + return codegen::doc("core_mission_mission"); } MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) { diff --git a/src/rendering/dashboarditem.cpp b/src/rendering/dashboarditem.cpp index d0f7e6ff39..05b9954d14 100644 --- a/src/rendering/dashboarditem.cpp +++ b/src/rendering/dashboarditem.cpp @@ -67,9 +67,7 @@ namespace { namespace openspace { documentation::Documentation DashboardItem::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "dashboarditem"; - return doc; + return codegen::doc("dashboarditem"); } std::unique_ptr DashboardItem::createFromDictionary( diff --git a/src/rendering/dashboardtextitem.cpp b/src/rendering/dashboardtextitem.cpp index fae12f4403..cf811a6b2e 100644 --- a/src/rendering/dashboardtextitem.cpp +++ b/src/rendering/dashboardtextitem.cpp @@ -57,9 +57,7 @@ namespace { namespace openspace { documentation::Documentation DashboardTextItem::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "dashboardtextitem"; - return doc; + return codegen::doc("dashboardtextitem"); } DashboardTextItem::DashboardTextItem(const ghoul::Dictionary& dictionary, float fontSize, diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index b9c9f6459c..c9704ec821 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -78,9 +78,7 @@ namespace { namespace openspace { documentation::Documentation Renderable::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "renderable"; - return doc; + return codegen::doc("renderable"); } ghoul::mm_unique_ptr Renderable::createFromDictionary( diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index 490f8781d4..ef0b3b2673 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -268,9 +268,7 @@ namespace { namespace openspace { documentation::Documentation ScreenSpaceRenderable::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_screenspacerenderable"; - return doc; + return codegen::doc("core_screenspacerenderable"); } std::unique_ptr ScreenSpaceRenderable::createFromDictionary( diff --git a/src/scene/lightsource.cpp b/src/scene/lightsource.cpp index 597cff1265..4977e67c35 100644 --- a/src/scene/lightsource.cpp +++ b/src/scene/lightsource.cpp @@ -63,9 +63,7 @@ bool LightSource::isEnabled() const { } documentation::Documentation LightSource::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_light_source"; - return doc; + return codegen::doc("core_light_source"); } std::unique_ptr LightSource::createFromDictionary( diff --git a/src/scene/rotation.cpp b/src/scene/rotation.cpp index 637b60029e..bd11317587 100644 --- a/src/scene/rotation.cpp +++ b/src/scene/rotation.cpp @@ -48,9 +48,7 @@ namespace { namespace openspace { documentation::Documentation Rotation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_transform_rotation"; - return doc; + return codegen::doc("core_transform_rotation"); } ghoul::mm_unique_ptr Rotation::createFromDictionary( diff --git a/src/scene/scale.cpp b/src/scene/scale.cpp index 9ee249066a..7b0c88c3e8 100644 --- a/src/scene/scale.cpp +++ b/src/scene/scale.cpp @@ -47,9 +47,7 @@ namespace { namespace openspace { documentation::Documentation Scale::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_transform_scaling"; - return doc; + return codegen::doc("core_transform_scaling"); } ghoul::mm_unique_ptr Scale::createFromDictionary( diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index b1bfdbcf2e..e5891cf8a1 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -401,9 +401,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( } documentation::Documentation SceneGraphNode::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_scene_node"; - return doc; + return codegen::doc("core_scene_node"); } ghoul::opengl::ProgramObject* SceneGraphNode::_debugSphereProgram = nullptr; diff --git a/src/scene/timeframe.cpp b/src/scene/timeframe.cpp index ccf380c2c0..5df9d91022 100644 --- a/src/scene/timeframe.cpp +++ b/src/scene/timeframe.cpp @@ -47,9 +47,7 @@ namespace { namespace openspace { documentation::Documentation TimeFrame::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_time_frame"; - return doc; + return codegen::doc("core_time_frame"); } ghoul::mm_unique_ptr TimeFrame::createFromDictionary( diff --git a/src/scene/translation.cpp b/src/scene/translation.cpp index 878270f827..7a723f9c5e 100644 --- a/src/scene/translation.cpp +++ b/src/scene/translation.cpp @@ -46,9 +46,7 @@ namespace { namespace openspace { documentation::Documentation Translation::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_transform_translation"; - return doc; + return codegen::doc("core_transform_translation"); } ghoul::mm_unique_ptr Translation::createFromDictionary( diff --git a/src/scripting/scriptscheduler.cpp b/src/scripting/scriptscheduler.cpp index 7898b27c49..c80e1487fb 100644 --- a/src/scripting/scriptscheduler.cpp +++ b/src/scripting/scriptscheduler.cpp @@ -62,13 +62,9 @@ documentation::Documentation ScriptScheduler::Documentation() { // @TODO (abock, 2021-03-25) This is not really correct. This function currently // returns the documentation for the ScheduledScript, not for the ScriptScheduler // itself. This should be cleaned up a bit - documentation::Documentation doc = codegen::doc(); - doc.id = "core_scheduledscript"; - return doc; + return codegen::doc("core_scheduledscript"); } -using namespace openspace::interaction; - ScriptScheduler::ScheduledScript::ScheduledScript(const ghoul::Dictionary& dict) { const Parameters p = codegen::bake(dict); @@ -186,7 +182,7 @@ ScriptScheduler::progressTo(double newTime) } } -void ScriptScheduler::setTimeReferenceMode(KeyframeTimeRef refType) { +void ScriptScheduler::setTimeReferenceMode(interaction::KeyframeTimeRef refType) { _timeframeMode = refType; } @@ -216,15 +212,15 @@ std::vector ScriptScheduler::allScripts() cons } void ScriptScheduler::setModeApplicationTime() { - _timeframeMode = KeyframeTimeRef::Relative_applicationStart; + _timeframeMode = interaction::KeyframeTimeRef::Relative_applicationStart; } void ScriptScheduler::setModeRecordedTime() { - _timeframeMode = KeyframeTimeRef::Relative_recordedStart; + _timeframeMode = interaction::KeyframeTimeRef::Relative_recordedStart; } void ScriptScheduler::setModeSimulationTime() { - _timeframeMode = KeyframeTimeRef::Absolute_simTimeJ2000; + _timeframeMode = interaction::KeyframeTimeRef::Absolute_simTimeJ2000; } LuaLibrary ScriptScheduler::luaLibrary() { diff --git a/src/util/resourcesynchronization.cpp b/src/util/resourcesynchronization.cpp index 6d391f3701..45b655ea30 100644 --- a/src/util/resourcesynchronization.cpp +++ b/src/util/resourcesynchronization.cpp @@ -47,9 +47,7 @@ namespace { namespace openspace { documentation::Documentation ResourceSynchronization::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "resourceSynchronization"; - return doc; + return codegen::doc("resourceSynchronization"); } std::unique_ptr ResourceSynchronization::createFromDictionary( diff --git a/src/util/task.cpp b/src/util/task.cpp index e775dca720..00572e7800 100644 --- a/src/util/task.cpp +++ b/src/util/task.cpp @@ -43,9 +43,7 @@ namespace { namespace openspace { documentation::Documentation Task::documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_task"; - return doc; + return codegen::doc("core_task"); } std::unique_ptr Task::createFromDictionary(const ghoul::Dictionary& dictionary) { diff --git a/src/util/timerange.cpp b/src/util/timerange.cpp index f56b2e1b41..b2c36e467d 100644 --- a/src/util/timerange.cpp +++ b/src/util/timerange.cpp @@ -44,9 +44,7 @@ namespace { namespace openspace { documentation::Documentation TimeRange::Documentation() { - documentation::Documentation doc = codegen::doc(); - doc.id = "core_util_timerange"; - return doc; + return codegen::doc("core_util_timerange"); } TimeRange::TimeRange(double startTime, double endTime) diff --git a/support/coding/codegen b/support/coding/codegen index 481f12fd98..af8906ff56 160000 --- a/support/coding/codegen +++ b/support/coding/codegen @@ -1 +1 @@ -Subproject commit 481f12fd987596851324ff89fd981df75127789d +Subproject commit af8906ff56c4b02d2f4a30c02d56477225dd10ce From a1be8d16cff543a43764741fd3cef74bbd209715 Mon Sep 17 00:00:00 2001 From: Emma Broman Date: Wed, 26 May 2021 09:08:06 +0200 Subject: [PATCH 43/43] Fix forgotten identifier rename that lead to an error --- .../scene/solarsystem/planets/earth/satellites/misc/iss.asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 0a316f386d..2012885e73 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset @@ -140,7 +140,7 @@ asset.onInitialize(function () for _, node in ipairs(nodes) do openspace.addSceneGraphNode(node) end - openspace.setPropertyValueSingle("Scene.ISSparentNode.Rotation.yAxisInvertObject", true) + openspace.setPropertyValueSingle("Scene.ISSModel.Rotation.yAxisInvertObject", true) end)