From 9f1c4e847d7c37e75f0e73d051c8f7c758f20147 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 30 Aug 2018 11:38:47 -0400 Subject: [PATCH] Feature/globals (#690) * Move global objects out of OpenSpaceEngine * General cleanup of main.cpp * Add default_joystick asset to all scenes * No longer suppress mouse interaction on slave nodes * Window delegate uses function pointers rather than subclassing * Fix for false overwriting of ImGUI configuration file * Change default color and tilt angle of fisheye rendering * Restructured performance manager * Simplify screenshot handling --- apps/OpenSpace/main.cpp | 865 ++++++---- apps/Sync/main.cpp | 13 +- apps/TaskRunner/main.cpp | 17 +- apps/Wormhole/main.cpp | 2 +- data/assets/juno.scene | 1 + data/assets/newhorizons.scene | 1 + data/assets/osirisrex.scene | 1 + data/assets/rosetta.scene | 1 + .../scene/solarsystem/sun/transforms.asset | 2 +- data/assets/util/default_joystick.asset | 2 +- data/assets/voyager.scene | 1 + ext/sgct | 2 +- include/openspace/engine/configuration.h | 8 +- include/openspace/engine/globals.h | 138 ++ include/openspace/engine/globalscallbacks.h | 84 + include/openspace/engine/openspaceengine.h | 176 +-- include/openspace/engine/windowdelegate.h | 112 ++ .../engine/wrapper/sgctwindowwrapper.h | 99 -- .../openspace/engine/wrapper/windowwrapper.h | 322 ---- include/openspace/interaction/inputstate.h | 7 - .../openspace/interaction/keybindingmanager.h | 4 +- .../openspace/interaction/navigationhandler.h | 2 - include/openspace/mission/missionmanager.h | 6 +- .../performance/performancemanager.h | 7 +- .../performance/performancemeasurement.h | 16 +- include/openspace/rendering/abufferrenderer.h | 3 +- include/openspace/rendering/dashboard.h | 1 + .../openspace/rendering/framebufferrenderer.h | 3 +- include/openspace/rendering/renderengine.h | 17 - include/openspace/rendering/renderer.h | 3 +- .../rendering/atmospheredeferredcaster.cpp | 1 - .../rendering/renderableatmosphere.cpp | 33 +- modules/base/dashboard/dashboarditemangle.cpp | 14 +- modules/base/dashboard/dashboarditemdate.cpp | 12 +- .../base/dashboard/dashboarditemdistance.cpp | 14 +- .../base/dashboard/dashboarditemframerate.cpp | 22 +- .../base/dashboard/dashboarditemmission.cpp | 14 +- .../dashboarditemparallelconnection.cpp | 20 +- .../dashboard/dashboarditempropertyvalue.cpp | 8 +- .../dashboarditemsimulationincrement.cpp | 18 +- .../lightsource/scenegraphlightsource.cpp | 6 +- modules/base/rendering/renderablemodel.cpp | 6 +- modules/base/rendering/renderableplane.cpp | 11 +- .../rendering/renderableplaneimageonline.cpp | 4 +- modules/base/rendering/renderablesphere.cpp | 10 +- .../rendering/renderablesphericalgrid.cpp | 6 +- modules/base/rendering/renderabletrail.cpp | 8 +- .../base/rendering/screenspacedashboard.cpp | 14 +- .../base/rendering/screenspaceframebuffer.cpp | 8 +- .../base/rendering/screenspaceimagelocal.cpp | 6 + .../base/rendering/screenspaceimagelocal.h | 2 + .../base/rendering/screenspaceimageonline.cpp | 10 +- .../base/rendering/screenspaceimageonline.h | 2 + modules/cefwebgui/cefwebguimodule.cpp | 62 +- modules/debugging/rendering/debugrenderer.cpp | 4 +- .../rendering/renderabledebugplane.cpp | 8 +- .../rendering/renderablebillboardscloud.cpp | 14 +- .../rendering/renderabledumeshes.cpp | 12 +- .../rendering/renderableplanescloud.cpp | 10 +- .../rendering/renderablepoints.cpp | 14 +- .../rendering/renderablefieldlines.cpp | 7 +- .../renderablefieldlinessequence.cpp | 21 +- modules/galaxy/rendering/renderablegalaxy.cpp | 41 +- .../dashboard/dashboarditemglobelocation.cpp | 16 +- modules/globebrowsing/globebrowsingmodule.cpp | 59 +- .../globebrowsing/globebrowsingmodule_lua.inl | 26 +- modules/globebrowsing/globes/pointglobe.cpp | 4 +- .../rendering/layershadermanager.cpp | 9 +- .../tile/asynctiledataprovider.cpp | 4 +- .../tile/rawtiledatareader/gdalwrapper.cpp | 14 +- .../tile/tileprovider/defaulttileprovider.cpp | 4 +- .../sizereferencetileprovider.cpp | 4 +- .../tileprovider/temporaltileprovider.cpp | 4 +- .../tile/tileprovider/texttileprovider.cpp | 6 +- modules/imgui/imguimodule.cpp | 280 ++-- modules/imgui/src/gui.cpp | 29 +- modules/imgui/src/guiassetcomponent.cpp | 3 +- .../imgui/src/guiglobebrowsingcomponent.cpp | 12 +- modules/imgui/src/guiiswacomponent.cpp | 26 +- modules/imgui/src/guijoystickcomponent.cpp | 15 +- modules/imgui/src/guimissioncomponent.cpp | 10 +- modules/imgui/src/guiparallelcomponent.cpp | 33 +- modules/imgui/src/guiperformancecomponent.cpp | 13 +- modules/imgui/src/guispacetimecomponent.cpp | 65 +- modules/imgui/src/renderproperties.cpp | 6 +- modules/iswa/iswamodule.cpp | 9 +- modules/iswa/rendering/dataplane.cpp | 4 +- modules/iswa/rendering/datasphere.cpp | 4 +- modules/iswa/rendering/iswacygnet.cpp | 16 +- modules/iswa/rendering/iswakameleongroup.cpp | 6 +- modules/iswa/rendering/kameleonplane.cpp | 10 +- modules/iswa/rendering/screenspacecygnet.cpp | 12 +- modules/iswa/rendering/textureplane.cpp | 4 +- modules/iswa/util/iswamanager.cpp | 28 +- modules/iswa/util/iswamanager_lua.inl | 9 +- .../rendering/renderablekameleonvolume.cpp | 10 +- .../rendering/renderablemultiresvolume.cpp | 59 +- modules/server/servermodule.cpp | 7 +- modules/server/src/connection.cpp | 6 +- .../server/src/topics/authorizationtopic.cpp | 4 +- .../server/src/topics/getpropertytopic.cpp | 19 +- modules/server/src/topics/luascripttopic.cpp | 4 +- .../server/src/topics/setpropertytopic.cpp | 4 +- modules/server/src/topics/timetopic.cpp | 14 +- .../renderableconstellationbounds.cpp | 6 +- modules/space/rendering/renderableplanet.cpp | 12 +- modules/space/rendering/renderablerings.cpp | 8 +- modules/space/rendering/renderablestars.cpp | 10 +- .../dashboard/dashboarditeminstruments.cpp | 16 +- .../rendering/renderablecrawlingline.cpp | 8 +- .../rendering/renderablefov.cpp | 6 +- .../rendering/renderablemodelprojection.cpp | 11 +- .../rendering/renderableplaneprojection.cpp | 13 +- .../rendering/renderableplanetprojection.cpp | 6 +- .../rendering/renderableshadowcylinder.cpp | 6 +- .../util/imagesequencer.cpp | 1 - .../util/sequenceparser.cpp | 8 +- modules/sync/syncmodule.cpp | 8 +- modules/sync/syncs/urlsynchronization.cpp | 1 - modules/sync/tasks/syncassettask.cpp | 4 +- modules/touch/src/touchinteraction.cpp | 27 +- modules/touch/src/touchmarker.cpp | 7 +- modules/touch/src/tuioear.cpp | 4 +- modules/touch/touchmodule.cpp | 60 +- .../rendering/renderabletoyvolume.cpp | 10 +- .../rendering/renderabletimevaryingvolume.cpp | 14 +- modules/webbrowser/webbrowsermodule.cpp | 6 +- scripts/configuration_helper.lua | 6 +- src/CMakeLists.txt | 11 +- src/documentation/core_registration.cpp | 4 +- src/engine/configuration.cpp | 341 ++-- src/engine/configuration_doc.inl | 4 +- src/engine/globals.cpp | 236 +++ src/engine/globalscallbacks.cpp | 99 ++ src/engine/moduleengine_lua.inl | 4 +- src/engine/openspaceengine.cpp | 1400 ++++++----------- src/engine/openspaceengine_lua.inl | 44 +- src/engine/wrapper/sgctwindowwrapper.cpp | 302 ---- src/engine/wrapper/windowwrapper.cpp | 210 --- src/interaction/inputstate.cpp | 13 +- src/interaction/joystickcamerastates.cpp | 6 +- src/interaction/keybindingmanager.cpp | 24 +- src/interaction/keybindingmanager_lua.inl | 15 +- src/interaction/keyframenavigator.cpp | 6 +- src/interaction/navigationhandler.cpp | 12 +- src/interaction/navigationhandler_lua.inl | 22 +- src/interaction/touchbar.mm | 25 +- src/mission/missionmanager.cpp | 1 - src/mission/missionmanager_lua.inl | 12 +- src/network/networkengine.cpp | 20 +- src/network/parallelconnection.cpp | 4 +- src/network/parallelpeer.cpp | 78 +- src/network/parallelpeer_lua.inl | 16 +- src/performance/performancemanager.cpp | 100 +- src/performance/performancemeasurement.cpp | 20 +- src/query/query.cpp | 10 +- src/rendering/abufferrenderer.cpp | 20 +- src/rendering/dashboard.cpp | 2 + src/rendering/dashboard_lua.inl | 9 +- src/rendering/framebufferrenderer.cpp | 37 +- src/rendering/loadingscreen.cpp | 16 +- src/rendering/luaconsole.cpp | 36 +- src/rendering/renderengine.cpp | 203 +-- src/rendering/renderengine_lua.inl | 16 +- src/rendering/screenspacerenderable.cpp | 19 +- src/scene/assetmanager_lua.inl | 5 +- src/scene/scene.cpp | 4 +- src/scene/scene_lua.inl | 20 +- src/scene/sceneinitializer.cpp | 6 +- src/scripting/scriptengine.cpp | 10 +- src/scripting/scriptscheduler.cpp | 1 - src/scripting/scriptscheduler_lua.inl | 12 +- src/util/time.cpp | 1 - src/util/time_lua.inl | 59 +- src/util/timemanager.cpp | 14 +- tests/main.cpp | 28 +- tests/test_assetloader.inl | 11 +- 177 files changed, 3103 insertions(+), 3952 deletions(-) create mode 100644 include/openspace/engine/globals.h create mode 100644 include/openspace/engine/globalscallbacks.h create mode 100644 include/openspace/engine/windowdelegate.h delete mode 100644 include/openspace/engine/wrapper/sgctwindowwrapper.h delete mode 100644 include/openspace/engine/wrapper/windowwrapper.h create mode 100644 src/engine/globals.cpp create mode 100644 src/engine/globalscallbacks.cpp delete mode 100644 src/engine/wrapper/sgctwindowwrapper.cpp delete mode 100644 src/engine/wrapper/windowwrapper.cpp diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index e28195223a..b202b6659d 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -23,41 +23,36 @@ ****************************************************************************************/ #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 - #include - -#include #include - #include - -#include +#include #include #include - -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable : 4091) -#include -#pragma warning (pop) -#endif // _MSC_VER - +#include #endif // WIN32 #ifdef OPENVR_SUPPORT @@ -68,21 +63,54 @@ #include "SpoutLibrary.h" #endif // OPENSPACE_HAS_SPOUT - -#define DEVELOPER_MODE - namespace { constexpr const char* _loggerCat = "main"; +constexpr const char* SpoutTag = "Spout"; +constexpr const char* OpenVRTag = "OpenVR"; + sgct::Engine* SgctEngine; -openspace::interaction::JoystickInputStates joystickInputStates; +#ifdef OPENVR_SUPPORT +sgct::SGCTWindow* FirstOpenVRWindow = nullptr; +#endif -constexpr const char* OpenVRTag = "OpenVR"; -constexpr const char* SpoutTag = "Spout"; +// +// SPOUT-support +// +#ifdef OPENSPACE_HAS_SPOUT +/** + * This struct stores all information about a single render window. Depending on the + * frame setup, each window can be mono or stereo, the information of which is stored in + * the \c leftOrMain and \c right members respectively. + */ +struct SpoutWindow { + struct SpoutData { + SPOUTHANDLE handle = nullptr; + bool initialized = false; + }; + + /// The left framebuffer (or main, if there is no stereo rendering) + SpoutData leftOrMain; + + /// The right framebuffer + SpoutData right; + + /// The window ID of this windows + size_t windowId = size_t(-1); +}; + +/// The list of all windows with spout senders +std::vector SpoutWindows; + +#endif // OPENSPACE_HAS_SPOUT + + +// +// MiniDump generation +// #ifdef WIN32 - LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { SYSTEMTIME stLocalTime; GetLocalTime(&stLocalTime); @@ -135,6 +163,8 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { nullptr ); + CloseHandle(hDumpFile); + if (success) { LINFO("Created successfully"); } @@ -144,41 +174,11 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { return EXCEPTION_EXECUTE_HANDLER; } - #endif // WIN32 -#ifdef OPENVR_SUPPORT -sgct::SGCTWindow* FirstOpenVRWindow = nullptr; -#endif - -#ifdef OPENSPACE_HAS_SPOUT -/** - * This struct stores all information about a single render window. Depending on the - * frame setup, each window can be mono or stereo, the information of which is stored in - * the \c leftOrMain and \c right members respectively. - */ -struct SpoutWindow { - struct SpoutData { - SPOUTHANDLE handle = nullptr; - bool initialized = false; - }; - - /// The left framebuffer (or main, if there is no stereo rendering) - SpoutData leftOrMain; - - /// The right framebuffer - SpoutData right; - - /// The window ID of this windows - size_t windowId = size_t(-1); -}; - -/// The list of all windows with spout senders -std::vector SpoutWindows; - -#endif // OPENSPACE_HAS_SPOUT - - +// +// Detect OpenGL version +// std::pair supportedOpenGLVersion() { // Just create a window in order to retrieve the available OpenGL version before we // create the real window @@ -213,15 +213,20 @@ std::pair supportedOpenGLVersion() { return { major, minor }; } + +// +// Init function +// void mainInitFunc() { LTRACE("main::mainInitFunc(begin)"); LDEBUG("Initializing OpenSpace Engine started"); - OsEng.initialize(); + openspace::global::openSpaceEngine.initialize(); LDEBUG("Initializing OpenSpace Engine finished"); + LDEBUG("Initializing OpenGL in OpenSpace Engine started"); - OsEng.initializeGL(); + openspace::global::openSpaceEngine.initializeGL(); LDEBUG("Initializing OpenGL in OpenSpace Engine finished"); // Find if we have at least one OpenVR window @@ -236,32 +241,14 @@ void mainInitFunc() { SgctEngine->getNearClippingPlane(), SgctEngine->getFarClippingPlane() ); #else - LWARNING( - "OpenVR was requested, but OpenSpace was compiled without VR support." - ); + LWARNING("OpenVR was requested, but program was compiled without VR support"); #endif break; } } - // Set the clear color for all non-linear projection viewports - // @CLEANUP: Why is this necessary? We can set the clear color in the configuration - // files --- abock const size_t nWindows = SgctEngine->getNumberOfWindows(); - for (size_t i = 0; i < nWindows; ++i) { - sgct::SGCTWindow* w = SgctEngine->getWindowPtr(i); - const size_t nViewports = w->getNumberOfViewports(); - for (size_t j = 0; j < nViewports; ++j) { - sgct_core::Viewport* v = w->getViewport(j); - ghoul_assert(v != nullptr, "Number of reported viewports was incorrect"); - sgct_core::NonLinearProjection* p = v->getNonLinearProjectionPtr(); - if (p) { - p->setClearColor(glm::vec4(0.f, 0.f, 0.f, 1.f)); - } - } - } - for (size_t i = 0; i < nWindows; ++i) { const sgct::SGCTWindow* windowPtr = SgctEngine->getWindowPtr(i); @@ -275,9 +262,8 @@ void mainInitFunc() { w.windowId = i; const sgct::SGCTWindow::StereoMode sm = windowPtr->getStereoMode(); - const bool hasStereo = - (sm != sgct::SGCTWindow::No_Stereo) && - (sm < sgct::SGCTWindow::Side_By_Side_Stereo); + const bool hasStereo = (sm != sgct::SGCTWindow::No_Stereo) && + (sm < sgct::SGCTWindow::Side_By_Side_Stereo); if (hasStereo) { SpoutWindow::SpoutData& left = w.leftOrMain; @@ -308,146 +294,136 @@ void mainInitFunc() { SpoutWindows.push_back(std::move(w)); #else - LWARNING( - "Spout was requested, but OpenSpace was compiled without Spout support." - ); - + LWARNING("Spout was requested, but program was compiled without Spout support"); #endif // OPENSPACE_HAS_SPOUT } - std::string screenshotPath = "${SCREENSHOTS}"; - std::string screenshotNames = "OpenSpace"; - if (OsEng.configuration().shouldUseScreenshotDate) { + // + // Screenshots + // + + std::string screenshotPath = "${SCREENSHOTS}"; + if (openspace::global::configuration.shouldUseScreenshotDate) { std::time_t now = std::time(nullptr); std::tm* nowTime = std::localtime(&now); - char mbstr[100]; + char mbstr[128]; strftime(mbstr, sizeof(mbstr), "%Y-%m-%d-%H-%M", nowTime); screenshotPath += "/" + std::string(mbstr); + + FileSys.registerPathToken( + "${SCREENSHOTS}", + absPath(screenshotPath), + ghoul::filesystem::FileSystem::Override::Yes + ); } - FileSys.registerPathToken("${THIS_SCREENSHOT_PATH}", screenshotPath); for (size_t i = 0; i < nWindows; ++i) { - sgct_core::ScreenCapture* cpt0 = - SgctEngine->getWindowPtr(i)->getScreenCapturePointer(0); - sgct_core::ScreenCapture* cpt1 = - SgctEngine->getWindowPtr(i)->getScreenCapturePointer(1); + sgct::SGCTWindow* w = SgctEngine->getWindowPtr(i); + constexpr const char* screenshotNames = "OpenSpace"; + sgct_core::ScreenCapture* cpt0 = w->getScreenCapturePointer(0); + sgct_core::ScreenCapture* cpt1 = w->getScreenCapturePointer(1); if (cpt0) { - cpt0->setPathAndFileName( - absPath(screenshotPath), - screenshotNames - ); + cpt0->setPathAndFileName(absPath(screenshotPath), screenshotNames); } if (cpt1) { - cpt1->setPathAndFileName( - screenshotPath, - screenshotNames - ); + cpt1->setPathAndFileName(absPath(screenshotPath), screenshotNames); } } - OsEng.setJoystickInputStates(joystickInputStates); - LTRACE("main::mainInitFunc(end)"); } + + void mainPreSyncFunc() { LTRACE("main::mainPreSyncFunc(begin)"); - OsEng.preSynchronization(); + openspace::global::openSpaceEngine.preSynchronization(); // Query joystick status using namespace openspace::interaction; for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { - JoystickInputState& state = joystickInputStates[i]; + JoystickInputState& state = openspace::global::joystickInputStates[i]; int present = glfwJoystickPresent(i); - if (present == GLFW_TRUE) { - if (!state.isConnected) { - // Joystick was added - state.isConnected = true; - state.name = SgctEngine->getJoystickName(i); - - std::fill(state.axes.begin(), state.axes.end(), 0.f); - std::fill( - state.buttons.begin(), - state.buttons.end(), - JoystickAction::Idle - ); - } - - const float* axes = SgctEngine->getJoystickAxes(i, &state.nAxes); - if (state.nAxes > JoystickInputState::MaxAxes) { - LWARNING(fmt::format( - "Joystick/Gamepad {} has {} axes, but only {} axes are supported. " - "All excess axes are ignored", - state.name, - state.nAxes, - JoystickInputState::MaxAxes - )); - state.nAxes = JoystickInputState::MaxAxes; - } - std::memcpy(state.axes.data(), axes, state.nAxes * sizeof(float)); - - const unsigned char* buttons = SgctEngine->getJoystickButtons( - i, - &state.nButtons - ); - - if (state.nButtons > JoystickInputState::MaxButtons) { - LWARNING(fmt::format( - "Joystick/Gamepad {} has {} buttons, but only {} buttons are " - "supported. All excess buttons are ignored", - state.name, - state.nButtons, - JoystickInputState::MaxButtons - )); - state.nButtons = JoystickInputState::MaxButtons; - } - - for (int j = 0; j < state.nButtons; ++j) { - bool currentlyPressed = buttons[j] == GLFW_PRESS; - - if (currentlyPressed) { - switch (state.buttons[j]) { - case JoystickAction::Idle: - case JoystickAction::Release: - state.buttons[j] = JoystickAction::Press; - break; - case JoystickAction::Press: - case JoystickAction::Repeat: - state.buttons[j] = JoystickAction::Repeat; - break; - } - } - else { - switch (state.buttons[j]) { - case JoystickAction::Idle: - case JoystickAction::Release: - state.buttons[j] = JoystickAction::Idle; - break; - case JoystickAction::Press: - case JoystickAction::Repeat: - state.buttons[j] = JoystickAction::Release; - break; - } - } - } - } - else { + if (present == GLFW_FALSE) { state.isConnected = false; + continue; + } + + if (!state.isConnected) { + // Joystick was added + state.isConnected = true; + state.name = SgctEngine->getJoystickName(i); + + std::fill(state.axes.begin(), state.axes.end(), 0.f); + std::fill(state.buttons.begin(), state.buttons.end(), JoystickAction::Idle); + } + + const float* axes = SgctEngine->getJoystickAxes(i, &state.nAxes); + if (state.nAxes > JoystickInputState::MaxAxes) { + LWARNING(fmt::format( + "Joystick/Gamepad {} has {} axes, but only {} axes are supported. " + "All excess axes are ignored", + state.name, state.nAxes, JoystickInputState::MaxAxes + )); + state.nAxes = JoystickInputState::MaxAxes; + } + std::memcpy(state.axes.data(), axes, state.nAxes * sizeof(float)); + + const unsigned char* buttons = SgctEngine->getJoystickButtons(i, &state.nButtons); + + if (state.nButtons > JoystickInputState::MaxButtons) { + LWARNING(fmt::format( + "Joystick/Gamepad {} has {} buttons, but only {} buttons are " + "supported. All excess buttons are ignored", + state.name, state.nButtons, JoystickInputState::MaxButtons + )); + state.nButtons = JoystickInputState::MaxButtons; + } + + for (int j = 0; j < state.nButtons; ++j) { + const bool currentlyPressed = buttons[j] == GLFW_PRESS; + + if (currentlyPressed) { + switch (state.buttons[j]) { + case JoystickAction::Idle: + case JoystickAction::Release: + state.buttons[j] = JoystickAction::Press; + break; + case JoystickAction::Press: + case JoystickAction::Repeat: + state.buttons[j] = JoystickAction::Repeat; + break; + } + } + else { + switch (state.buttons[j]) { + case JoystickAction::Idle: + case JoystickAction::Release: + state.buttons[j] = JoystickAction::Idle; + break; + case JoystickAction::Press: + case JoystickAction::Repeat: + state.buttons[j] = JoystickAction::Release; + break; + } + } } } LTRACE("main::mainPreSyncFunc(end)"); } + + void mainPostSyncPreDrawFunc() { LTRACE("main::postSynchronizationPreDraw(begin)"); - OsEng.postSynchronizationPreDraw(); + openspace::global::openSpaceEngine.postSynchronizationPreDraw(); #ifdef OPENVR_SUPPORT if (FirstOpenVRWindow) { @@ -459,21 +435,17 @@ void mainPostSyncPreDrawFunc() { LTRACE("main::postSynchronizationPreDraw(end)"); } + + void mainRenderFunc() { LTRACE("main::mainRenderFunc(begin)"); - glm::mat4 viewMatrix = - SgctEngine->getCurrentViewMatrix() * - // User matrix - glm::translate( - glm::mat4(1.f), - SgctEngine->getDefaultUserPtr()->getPos() - ) - ; + glm::mat4 viewMatrix = SgctEngine->getCurrentViewMatrix() * + glm::translate(glm::mat4(1.f), SgctEngine->getDefaultUserPtr()->getPos()); glm::mat4 projectionMatrix = SgctEngine->getCurrentProjectionMatrix(); #ifdef OPENVR_SUPPORT - bool currentWindowIsHMD = FirstOpenVRWindow == SgctEngine->getCurrentWindowPtr(); + const bool currentWindowIsHMD = FirstOpenVRWindow == SgctEngine->getCurrentWindowPtr(); if (sgct::SGCTOpenVR::isHMDActive() && currentWindowIsHMD) { projectionMatrix = sgct::SGCTOpenVR::getHMDCurrentViewProjectionMatrix( SgctEngine->getCurrentFrustumMode() @@ -482,7 +454,7 @@ void mainRenderFunc() { #endif try { - OsEng.render( + openspace::global::openSpaceEngine.render( SgctEngine->getModelMatrix(), viewMatrix, projectionMatrix @@ -494,11 +466,13 @@ void mainRenderFunc() { LTRACE("main::mainRenderFunc(end)"); } + + void mainDraw2DFunc() { LTRACE("main::mainDraw2DFunc(begin)"); try { - OsEng.drawOverlays(); + openspace::global::openSpaceEngine.drawOverlays(); } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); @@ -512,6 +486,8 @@ void mainDraw2DFunc() { LTRACE("main::mainDraw2DFunc(end)"); } + + void mainPostDrawFunc() { LTRACE("main::mainPostDrawFunc(begin)"); @@ -522,13 +498,13 @@ void mainPostDrawFunc() { } #endif // OPENVR_SUPPORT - OsEng.postDraw(); + openspace::global::openSpaceEngine.postDraw(); #ifdef OPENSPACE_HAS_SPOUT for (const SpoutWindow& w : SpoutWindows) { sgct::SGCTWindow* window = SgctEngine->getWindowPtr(w.windowId); if (w.leftOrMain.initialized) { - GLuint texId = window->getFrameBufferTexture(sgct::Engine::LeftEye); + const GLuint texId = window->getFrameBufferTexture(sgct::Engine::LeftEye); glBindTexture(GL_TEXTURE_2D, texId); w.leftOrMain.handle->SendTexture( texId, @@ -539,7 +515,7 @@ void mainPostDrawFunc() { } if (w.right.initialized) { - GLuint texId = window->getFrameBufferTexture(sgct::Engine::RightEye); + const GLuint texId = window->getFrameBufferTexture(sgct::Engine::RightEye); glBindTexture(GL_TEXTURE_2D, texId); w.right.handle->SendTexture( texId, @@ -555,69 +531,70 @@ void mainPostDrawFunc() { LTRACE("main::mainPostDrawFunc(end)"); } -void mainExternalControlCallback(const char* receivedChars, int size) { - LTRACE("main::mainExternalControlCallback(begin)"); - if (SgctEngine->isMaster()) { - OsEng.externalControlCallback(receivedChars, size, 0); - } - LTRACE("main::mainExternalControlCallback(end)"); -} + void mainKeyboardCallback(int key, int, int action, int mods) { LTRACE("main::mainKeyboardCallback(begin)"); - if (SgctEngine->isMaster()) { - OsEng.keyboardCallback( - openspace::Key(key), - openspace::KeyModifier(mods), - openspace::KeyAction(action) - ); - } + openspace::global::openSpaceEngine.keyboardCallback( + openspace::Key(key), + openspace::KeyModifier(mods), + openspace::KeyAction(action) + ); LTRACE("main::mainKeyboardCallback(begin)"); } + + void mainMouseButtonCallback(int key, int action) { LTRACE("main::mainMouseButtonCallback(begin)"); - if (SgctEngine->isMaster()) { - OsEng.mouseButtonCallback( - openspace::MouseButton(key), - openspace::MouseAction(action) - ); - } + openspace::global::openSpaceEngine.mouseButtonCallback( + openspace::MouseButton(key), + openspace::MouseAction(action) + ); LTRACE("main::mainMouseButtonCallback(end)"); } + + void mainMousePosCallback(double x, double y) { - if (SgctEngine->isMaster()) { - OsEng.mousePositionCallback(x, y); - } + openspace::global::openSpaceEngine.mousePositionCallback(x, y); } + + void mainMouseScrollCallback(double posX, double posY) { LTRACE("main::mainMouseScrollCallback(begin"); - if (SgctEngine->isMaster()) { - OsEng.mouseScrollWheelCallback(posX, posY); - } + openspace::global::openSpaceEngine.mouseScrollWheelCallback(posX, posY); LTRACE("main::mainMouseScrollCallback(end)"); } + + void mainCharCallback(unsigned int codepoint, int mods) { - if (SgctEngine->isMaster()) { - OsEng.charCallback(codepoint, openspace::KeyModifier(mods)); - } + openspace::global::openSpaceEngine.charCallback( + codepoint, + openspace::KeyModifier(mods) + ); } + + void mainEncodeFun() { LTRACE("main::mainEncodeFun(begin)"); - OsEng.encode(); + openspace::global::openSpaceEngine.encode(); LTRACE("main::mainEncodeFun(end)"); } + + void mainDecodeFun() { LTRACE("main::mainDecodeFun(begin)"); - OsEng.decode(); + openspace::global::openSpaceEngine.decode(); LTRACE("main::mainDecodeFun(end)"); } + + void mainLogCallback(const char* msg) { std::string message = msg; if (message.empty() || message == ".") { @@ -629,19 +606,313 @@ void mainLogCallback(const char* msg) { LINFOC("SGCT", message.substr(0, message.size() - 1)); } -int main_main(int argc, char** argv) { - std::pair glVersion = supportedOpenGLVersion(); +} // namespace + + +void setSgctDelegateFunctions() { + openspace::WindowDelegate& sgctDelegate = openspace::global::windowDelegate; + sgctDelegate.terminate = []() { sgct::Engine::instance()->terminate(); }; + sgctDelegate.setBarrier = [](bool enabled) { + sgct::SGCTWindow::setBarrier(enabled); + }; + sgctDelegate.setSynchronization = [](bool enabled) { + sgct_core::ClusterManager::instance()->setUseIgnoreSync(enabled); + }; + sgctDelegate.clearAllWindows = [](const glm::vec4& clearColor) { + size_t n = sgct::Engine::instance()->getNumberOfWindows(); + for (size_t i = 0; i < n; ++i) { + glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLFWwindow* win = sgct::Engine::instance()->getWindowPtr(i)->getWindowHandle(); + glfwSwapBuffers(win); + } + }; + sgctDelegate.windowHasResized = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->isWindowResized(); + }; + sgctDelegate.averageDeltaTime = []() { return sgct::Engine::instance()->getAvgDt(); }; + sgctDelegate.deltaTime = []() { return sgct::Engine::instance()->getDt(); }; + sgctDelegate.applicationTime = []() { return sgct::Engine::getTime(); }; + sgctDelegate.mousePosition = []() { + int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); + double posX, posY; + sgct::Engine::instance()->getMousePos(id, &posX, &posY); + return glm::vec2(posX, posY); + }; + sgctDelegate.mouseButtons = [](int maxNumber) { + int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); + uint32_t result = 0; + for (int i = 0; i < maxNumber; ++i) { + bool button = (sgct::Engine::instance()->getMouseButton(id, i) != 0); + if (button) { + result |= (1 << i); + } + } + return result; + }; + sgctDelegate.currentWindowSize = []() { + return glm::ivec2( + sgct::Engine::instance()->getCurrentWindowPtr()->getXResolution(), + sgct::Engine::instance()->getCurrentWindowPtr()->getYResolution()); + }; + sgctDelegate.currentSubwindowSize = []() { + auto window = sgct::Engine::instance()->getCurrentWindowPtr(); + switch (window->getStereoMode()) { + case sgct::SGCTWindow::Side_By_Side_Stereo: + case sgct::SGCTWindow::Side_By_Side_Inverted_Stereo: + return glm::ivec2(window->getXResolution() / 2, window->getYResolution()); + case sgct::SGCTWindow::Top_Bottom_Stereo: + case sgct::SGCTWindow::Top_Bottom_Inverted_Stereo: + return glm::ivec2(window->getXResolution(), window->getYResolution() / 2); + default: + return glm::ivec2(window->getXResolution(), window->getYResolution()); + } + }; + sgctDelegate.currentWindowResolution = []() { + int x, y; + auto window = sgct::Engine::instance()->getCurrentWindowPtr(); + window->getFinalFBODimensions(x, y); + return glm::ivec2(x, y); + }; + sgctDelegate.currentDrawBufferResolution = []() { + sgct_core::Viewport* viewport = + sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); + if (viewport != nullptr) { + if (viewport->hasSubViewports() && viewport->getNonLinearProjectionPtr()) { + int res = viewport->getNonLinearProjectionPtr()->getCubemapResolution(); + return glm::ivec2(res, res); + } + else { + int x, y; + auto window = sgct::Engine::instance()->getCurrentWindowPtr(); + window->getFinalFBODimensions(x, y); + return glm::ivec2(x, y); + } + } + return glm::ivec2(-1, -1); + }; + sgctDelegate.currentViewportSize = []() { + sgct_core::Viewport* viewport = + sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); + if (viewport != nullptr) { + int x = 0; + int y = 0; + sgct::Engine::instance()->getCurrentViewportSize(x, y); + return glm::ivec2(x, y); + } + return glm::ivec2(-1, -1); + }; + sgctDelegate.dpiScaling = []() { + return glm::vec2( + sgct::Engine::instance()->getCurrentWindowPtr()->getXScale(), + sgct::Engine::instance()->getCurrentWindowPtr()->getYScale() + ); + }; + sgctDelegate.currentNumberOfAaSamples = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->getNumberOfAASamples(); + }; + sgctDelegate.isRegularRendering = []() { + sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr(); + ghoul_assert( + w->getNumberOfViewports() > 0, + "At least one viewport must exist at this time" + ); + sgct_core::Viewport* vp = w->getViewport(0); + sgct_core::NonLinearProjection* nlp = vp->getNonLinearProjectionPtr(); + return nlp == nullptr; + }; + sgctDelegate.hasGuiWindow = []() { + auto engine = sgct::Engine::instance(); + for (size_t i = 0; i < engine->getNumberOfWindows(); ++i) { + if (engine->getWindowPtr(i)->checkIfTagExists("GUI")) { + return true; + } + } + return false; + }; + sgctDelegate.isGuiWindow = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->checkIfTagExists("GUI"); + }; + sgctDelegate.isMaster = []() { return sgct::Engine::instance()->isMaster(); }; + sgctDelegate.isUsingSwapGroups = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->isUsingSwapGroups(); + }; + sgctDelegate.isSwapGroupMaster = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->isSwapGroupMaster(); + }; + sgctDelegate.viewProjectionMatrix = []() { + return sgct::Engine::instance()->getCurrentModelViewProjectionMatrix(); + }; + sgctDelegate.modelMatrix = []() { + return sgct::Engine::instance()->getModelMatrix(); + }; + sgctDelegate.setNearFarClippingPlane = [](float nearPlane, float farPlane) { + sgct::Engine::instance()->setNearAndFarClippingPlanes(nearPlane, farPlane); + }; + sgctDelegate.setEyeSeparationDistance = [](float distance) { + sgct::Engine::instance()->setEyeSeparation(distance); + }; + sgctDelegate.viewportPixelCoordinates = []() { + sgct::SGCTWindow* window = sgct::Engine::instance()->getCurrentWindowPtr(); + if (!window || !window->getCurrentViewport()) { + return glm::ivec4(0, 0, 0, 0); + } + else { + const int* data = sgct::Engine::instance()->getCurrentViewportPixelCoords(); + return glm::ivec4(data[0], data[2], data[1], data[3]); + } + }; + sgctDelegate.isExternalControlConnected = []() { + return sgct::Engine::instance()->isExternalControlConnected(); + }; + sgctDelegate.sendMessageToExternalControl = [](const std::vector& message) { + sgct::Engine::instance()->sendMessageToExternalControl( + message.data(), + static_cast(message.size()) + ); + }; + sgctDelegate.isSimpleRendering = []() { + return (sgct::Engine::instance()->getCurrentRenderTarget() != + sgct::Engine::NonLinearBuffer); + }; + sgctDelegate.isFisheyeRendering = []() { + sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr(); + return dynamic_cast( + w->getViewport(0)->getNonLinearProjectionPtr() + ) != nullptr; + }; + sgctDelegate.takeScreenshot = [](bool applyWarping) { + sgct::SGCTSettings::instance()->setCaptureFromBackBuffer(applyWarping); + sgct::Engine::instance()->takeScreenshot(); + }; + sgctDelegate.swapBuffer = []() { + GLFWwindow* w = glfwGetCurrentContext(); + glfwSwapBuffers(w); + glfwPollEvents(); + }; + sgctDelegate.nWindows = []() { + return static_cast(sgct::Engine::instance()->getNumberOfWindows()); + }; + sgctDelegate.currentWindowId = []() { + return sgct::Engine::instance()->getCurrentWindowPtr()->getId(); + }; +} + +int main(int argc, char** argv) { +#ifdef WIN32 + SetUnhandledExceptionFilter(generateMiniDump); +#endif // WIN32 + + // Initialize the LogManager and add the console log as this will be used every time + // and we need a fall back if something goes wrong between here and when we add the + // logs from the configuration file. If the user requested as specific loglevel in the + // configuration file, we will deinitialize this LogManager and reinitialize it later + // with the correct LogLevel + { + using namespace ghoul::logging; + LogManager::initialize(LogLevel::Debug, LogManager::ImmediateFlush::Yes); + LogMgr.addLog(std::make_unique()); +#ifdef WIN32 + if (IsDebuggerPresent()) { + LogMgr.addLog(std::make_unique()); + } +#endif // WIN32 + + } + + ghoul::initialize(); + + // + // Parse commandline arguments + // + ghoul::cmdparser::CommandlineParser parser( + std::string(argv[0]), + ghoul::cmdparser::CommandlineParser::AllowUnknownCommands::Yes + ); + + openspace::CommandlineArguments commandlineArguments; + parser.addCommand(std::make_unique>( + commandlineArguments.configurationName, "--file", "-f", + "Provides the path to the OpenSpace configuration file. Only the '${TEMPORARY}' " + "path token is available and any other path has to be specified relative to the " + "current working directory." + )); + + parser.addCommand(std::make_unique>( + commandlineArguments.configurationOverride, "--config", "-c", + "Provides the ability to pass arbitrary Lua code to the application that will be " + "evaluated after the configuration file has been loaded but before the other " + "commandline arguments are triggered. This can be used to manipulate the " + "configuration file without editing the file on disk, for example in a " + "planetarium environment. Please not that the Lua script must not contain any - " + "or they will be interpreted as a new command. Similar, in Bash, ${...} will be " + "evaluated before it is passed to OpenSpace." + )); + + std::vector sgctArguments = parser.setCommandLine({ argv, argv + argc }); + + bool showHelp = parser.execute(); + if (showHelp) { + parser.displayHelp(std::cout); + exit(EXIT_SUCCESS); + } + + // + // Set up SGCT functions for window delegate + // + setSgctDelegateFunctions(); // Create the OpenSpace engine and get arguments for the SGCT engine - std::vector sgctArguments; - bool requestQuit = false; + std::string windowConfiguration; try { - openspace::OpenSpaceEngine::create( - argc, argv, - std::make_unique(), - sgctArguments, - requestQuit + using namespace openspace; + + // Find configuration + std::string configurationFilePath = commandlineArguments.configurationName; + if (commandlineArguments.configurationName.empty()) { + LDEBUG("Finding configuration"); + configurationFilePath = configuration::findConfiguration(); + } + configurationFilePath = absPath(configurationFilePath); + + if (!FileSys.fileExists(configurationFilePath)) { + LFATALC("main", "Could not find configuration: " + configurationFilePath); + exit(EXIT_FAILURE); + } + LINFO(fmt::format("Configuration Path: '{}'", configurationFilePath)); + + // Loading configuration from disk + LDEBUG("Loading configuration from disk"); + global::configuration = configuration::loadConfigurationFromFile( + configurationFilePath ); + + // If the user requested a commandline-based configuation script that should + // overwrite some of the values, this is the time to do it + if (!commandlineArguments.configurationOverride.empty()) { + LDEBUG("Executing Lua script passed through the commandline:"); + LDEBUG(commandlineArguments.configurationOverride); + ghoul::lua::runScript( + global::configuration.state, + commandlineArguments.configurationOverride + ); + parseLuaState(global::configuration); + } + + // Determining SGCT configuration file + LDEBUG("SGCT Configuration file: " + global::configuration.windowConfiguration); + + windowConfiguration = openspace::global::configuration.windowConfiguration; + } + catch (const openspace::documentation::SpecificationError& e) { + LFATALC("main", "Loading of configuration file failed"); + for (const openspace::documentation::TestResult::Offense& o : e.result.offenses) { + LERRORC(o.offender, ghoul::to_string(o.reason)); + } + for (const openspace::documentation::TestResult::Warning& w : e.result.warnings) { + LWARNINGC(w.offender, ghoul::to_string(w.reason)); + } + exit(EXIT_FAILURE); } catch (const ghoul::RuntimeError& e) { // Write out all of the information about the exception and flush the logs @@ -651,42 +922,12 @@ int main_main(int argc, char** argv) { } return EXIT_FAILURE; } - catch (const ghoul::AssertionException& e) { - // We don't want to catch the assertion exception as we won't be able to add a - // breakpoint for debugging - LFATALC("Assertion failed", e.what()); - throw; - } - catch (const std::exception& e) { - LFATALC("Exception", e.what()); - if (ghoul::logging::LogManager::isInitialized()) { - LogMgr.flushLogs(); - } - return EXIT_FAILURE; - } - catch (...) { - LFATALC("Exception", "Unknown exception"); - if (ghoul::logging::LogManager::isInitialized()) { - LogMgr.flushLogs(); - } - return EXIT_FAILURE; - } - if (requestQuit) { - return EXIT_SUCCESS; - } - - LINFO(fmt::format( - "Detected OpenGL version: {}.{}", glVersion.first, glVersion.second - )); - - // Create sgct engine c arguments - int newArgc = static_cast(sgctArguments.size()); - - char** newArgv = new char*[newArgc]; - for (int i = 0; i < newArgc; ++i) { - newArgv[i] = const_cast(sgctArguments.at(i).c_str()); - } + // Prepend the outgoing sgctArguments with the program name + // as well as the configuration file that sgct is supposed to use + sgctArguments.insert(sgctArguments.begin(), argv[0]); + sgctArguments.insert(sgctArguments.begin() + 1, "-config"); + sgctArguments.insert(sgctArguments.begin() + 2, absPath(windowConfiguration)); // Need to set this before the creation of the sgct::Engine sgct::MessageHandler::instance()->setLogToConsole(false); @@ -699,10 +940,7 @@ int main_main(int argc, char** argv) { #endif LDEBUG("Creating SGCT Engine"); - SgctEngine = new sgct::Engine(newArgc, newArgv); - - // Deallocate sgct c arguments - delete[] newArgv; + SgctEngine = new sgct::Engine(sgctArguments); // Bind functions SgctEngine->setInitOGLFunction(mainInitFunc); @@ -715,7 +953,6 @@ int main_main(int argc, char** argv) { SgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback); SgctEngine->setMousePosCallbackFunction(mainMousePosCallback); SgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback); - SgctEngine->setExternalControlCallback(mainExternalControlCallback); SgctEngine->setCharCallbackFunction(mainCharCallback); // Disable the immediate exit of the application when the ESC key is pressed @@ -740,28 +977,29 @@ int main_main(int argc, char** argv) { { { 4, 5 }, sgct::Engine::RunMode::OpenGL_4_5_Core_Profile }, { { 4, 6 }, sgct::Engine::RunMode::OpenGL_4_6_Core_Profile } }; - ghoul_assert( - versionMapping.find(glVersion) != versionMapping.end(), - "Unknown OpenGL version. Missing statement in version mapping map" - ); - BooleanType(IsInitialized); - auto cleanup = [&](IsInitialized isInitialized){ + + std::pair version = supportedOpenGLVersion(); + LINFO(fmt::format("Detected OpenGL version: {}.{}", version.first, version.second)); + bool initSuccess = SgctEngine->init(versionMapping[version]); + + // Do not print message if slaves are waiting for the master + // Only timeout after 15 minutes + SgctEngine->setSyncParameters(false, 15.f * 60.f); + + auto cleanup = [&](bool isInitialized) { if (isInitialized) { - OsEng.deinitialize(); + openspace::global::openSpaceEngine.deinitializeGL(); + openspace::global::openSpaceEngine.deinitialize(); } // Clear function bindings to avoid crash after destroying the OpenSpace Engine sgct::MessageHandler::instance()->setLogToCallback(false); sgct::MessageHandler::instance()->setLogCallback(nullptr); - LDEBUG("Destroying OpenSpaceEngine"); - openspace::OpenSpaceEngine::destroy(); - LDEBUG("Destroying SGCT Engine"); delete SgctEngine; - #ifdef OPENVR_SUPPORT // Clean up OpenVR sgct::SGCTOpenVR::shutdown(); @@ -781,68 +1019,17 @@ int main_main(int argc, char** argv) { #endif // OPENSPACE_HAS_SPOUT }; - bool initSuccess = SgctEngine->init(versionMapping[glVersion]); - - // Do not print message if slaves are waiting for the master - // Only timeout after 15 minutes - SgctEngine->setSyncParameters(false, 15.f * 60.f); - if (!initSuccess) { LFATAL("Initializing failed"); - cleanup(IsInitialized::No); + cleanup(false); return EXIT_FAILURE; } - // Main loop LINFO("Starting rendering loop"); SgctEngine->render(); LINFO("Ending rendering loop"); - cleanup(IsInitialized::Yes); + cleanup(true); - // Exit program exit(EXIT_SUCCESS); } - -} // namespace - -int main(int argc, char** argv) { -#ifdef WIN32 - SetUnhandledExceptionFilter(generateMiniDump); -#endif // WIN32 - - // If we are working as a developer, we don't want to catch the exceptions in order to - // find the locations where the exceptions are raised. - // If we are not in developer mode, we want to catch and at least log the error before - // dying -#ifdef DEVELOPER_MODE - return main_main(argc, argv); -#else - // We wrap the actual main function in a try catch block so that we can get and print - // some additional information in case an exception is raised - try { - return main_main(argc, argv); - } - catch (const ghoul::RuntimeError& e) { - // Write out all of the information about the exception and flush the logs - LFATALC(e.component, e.message); - LogMgr.flushLogs(); - return EXIT_FAILURE; - } - catch (const ghoul::AssertionException& e) { - // We don't want to catch the assertion exception as we won't be able to add a - // breakpoint for debugging - LFATALC("Assertion failed", e.what()); - throw; - } catch (const std::exception& e) { - LFATALC("Exception", e.what()); - LogMgr.flushLogs(); - return EXIT_FAILURE; - } - catch (...) { - LFATALC("Exception", "Unknown exception"); - LogMgr.flushLogs(); - return EXIT_FAILURE; - } -#endif // DEVELOPER_MODE -} diff --git a/apps/Sync/main.cpp b/apps/Sync/main.cpp index f9d69dbd4c..cc8469710f 100644 --- a/apps/Sync/main.cpp +++ b/apps/Sync/main.cpp @@ -24,8 +24,10 @@ #include #include -#include +#include +#include #include +#include #include #include #include @@ -40,9 +42,12 @@ int main(int argc, char** argv) { using namespace openspace; - std::vector unusedStringlist; - bool unusedBool; - OpenSpaceEngine::create(argc, argv, nullptr, unusedStringlist, unusedBool); + ghoul::initialize(); + + std::string configFile = configuration::findConfiguration(); + global::configuration = configuration::loadConfigurationFromFile(configFile); + global::openSpaceEngine.initialize(); + TaskLoader taskLoader; std::vector> tasks = taskLoader.tasksFromFile( diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 28f8cc8af1..9088490c48 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -38,7 +38,9 @@ #include #include -#include +#include +#include +#include #include #include #include @@ -102,9 +104,12 @@ void performTasks(const std::string& path) { int main(int argc, char** argv) { using namespace openspace; - std::vector remainingArguments; - bool unusedBool; - OpenSpaceEngine::create(argc, argv, nullptr, remainingArguments, unusedBool); + ghoul::initialize(); + + std::string configFile = configuration::findConfiguration(); + global::configuration = configuration::loadConfigurationFromFile(configFile); + global::openSpaceEngine.initialize(); + ghoul::cmdparser::CommandlineParser commandlineParser( "OpenSpace TaskRunner", @@ -118,10 +123,10 @@ int main(int argc, char** argv) { "--task", "-t", "Provides the path to a task file to execute" - ) + ) ); - commandlineParser.setCommandLine(remainingArguments); + commandlineParser.setCommandLine({ argv, argv + argc }); commandlineParser.execute(); //FileSys.setCurrentDirectory(launchDirectory); diff --git a/apps/Wormhole/main.cpp b/apps/Wormhole/main.cpp index 92ab97ea96..0e948ceb54 100644 --- a/apps/Wormhole/main.cpp +++ b/apps/Wormhole/main.cpp @@ -33,7 +33,7 @@ #include #include -#include +#include #include #include diff --git a/data/assets/juno.scene b/data/assets/juno.scene index dfcf4081da..d6f107b070 100644 --- a/data/assets/juno.scene +++ b/data/assets/juno.scene @@ -12,6 +12,7 @@ assetHelper.requireAll(asset, 'scene/solarsystem/missions/juno') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') local junoAsset = asset.require('scene/solarsystem/missions/juno/juno') diff --git a/data/assets/newhorizons.scene b/data/assets/newhorizons.scene index 822f41a1b3..b495dcd029 100644 --- a/data/assets/newhorizons.scene +++ b/data/assets/newhorizons.scene @@ -14,6 +14,7 @@ asset.require('scene/solarsystem/missions/newhorizons/newhorizons') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') -- Custom Keybindings local Keybindings = { diff --git a/data/assets/osirisrex.scene b/data/assets/osirisrex.scene index dcdb949548..65cd714924 100644 --- a/data/assets/osirisrex.scene +++ b/data/assets/osirisrex.scene @@ -13,6 +13,7 @@ asset.require('scene/solarsystem/missions/osirisrex/osirisrex') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') -- Custom Keybindings local Keybindings = { diff --git a/data/assets/rosetta.scene b/data/assets/rosetta.scene index 7a068c01cc..9189a0bff9 100644 --- a/data/assets/rosetta.scene +++ b/data/assets/rosetta.scene @@ -15,6 +15,7 @@ asset.require('scene/solarsystem/missions/rosetta/rosetta') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') -- Custom Keybindings local Keybindings = { diff --git a/data/assets/scene/solarsystem/sun/transforms.asset b/data/assets/scene/solarsystem/sun/transforms.asset index cd59ad6fbf..b80dc222b9 100644 --- a/data/assets/scene/solarsystem/sun/transforms.asset +++ b/data/assets/scene/solarsystem/sun/transforms.asset @@ -6,6 +6,7 @@ asset.require("spice/base") -- Barycenter of the solar system, expressed in the Galactic frame local SolarSystemBarycenter = { Identifier = "SolarSystemBarycenter", + -- No parent; this node is attached to the scene graph root TimeFrame = { -- Using Spice kernels for 1850-2150 Type = "TimeFrameInterval", Start = "1850-JAN-01", @@ -16,7 +17,6 @@ local SolarSystemBarycenter = { Path = "/Solar System", Hidden = true } - -- No parent; this node is attached to the scene graph root } -- Spice frame for the Sun diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset index 8a67a4fa8e..2c55c2dc42 100644 --- a/data/assets/util/default_joystick.asset +++ b/data/assets/util/default_joystick.asset @@ -118,7 +118,7 @@ asset.onInitialize(function() 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"); + 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); diff --git a/data/assets/voyager.scene b/data/assets/voyager.scene index 10dbf3e924..519c671e14 100644 --- a/data/assets/voyager.scene +++ b/data/assets/voyager.scene @@ -19,6 +19,7 @@ asset.require('scene/solarsystem/missions/voyager/voyager2') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') local VoyagerAsset = asset.require('scene/solarsystem/missions/voyager/voyager1') diff --git a/ext/sgct b/ext/sgct index adde6768da..6a344742d7 160000 --- a/ext/sgct +++ b/ext/sgct @@ -1 +1 @@ -Subproject commit adde6768dafb6cb4654bb18e92906eaddc018b27 +Subproject commit 6a344742d7267d0966d381197c15e34e1afcf275 diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index dd9605b914..67bc81d08e 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -31,9 +31,9 @@ #include #include -namespace openspace { +namespace openspace::documentation { struct Documentation; } -namespace documentation { struct Documentation; } +namespace openspace::configuration { struct Configuration { std::string windowConfiguration = "${CONFIG}/single.xml"; @@ -46,8 +46,6 @@ struct Configuration { struct Logging { std::string level = "Info"; - std::string directory = "${BASE}"; - std::string performancePrefix = "PM-"; bool forceImmediateFlush = false; std::string capabilitiesVerbosity = "Default"; std::vector logs; @@ -134,6 +132,6 @@ Configuration loadConfigurationFromFile(const std::string& filename); void parseLuaState(Configuration& configuration); -} // namespace openspace +} // namespace openspace::configuration #endif // __OPENSPACE_CORE___CONFIGURATION___H__ diff --git a/include/openspace/engine/globals.h b/include/openspace/engine/globals.h new file mode 100644 index 0000000000..b5b82d6c5e --- /dev/null +++ b/include/openspace/engine/globals.h @@ -0,0 +1,138 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2018 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___GLOBALS___H__ +#define __OPENSPACE_CORE___GLOBALS___H__ + +#include +#include +#include + +namespace ghoul::fontrendering { class FontManager; } + +namespace openspace { + +class Dashboard; +class DeferredcasterManager; +class DownloadManager; +class LuaConsole; +class MissionManager; +class ModuleEngine; +class NetworkEngine; +class OpenSpaceEngine; +class ParallelPeer; +class RaycasterManager; +class RenderEngine; +class ScreenSpaceRenderable; +class SyncEngine; +class TimeManager; +class VirtualPropertyManager; +struct WindowDelegate; +namespace configuration { struct Configuration; } +namespace interaction { + struct JoystickInputStates; + class KeybindingManager; + class NavigationHandler; +} // namespace interaction +namespace performance { class PerformanceManager; } +namespace properties { class PropertyOwner; } +namespace scripting { + class ScriptEngine; + class ScriptScheduler; +} // namespace scripting + +namespace global { + +namespace detail { + +ghoul::fontrendering::FontManager& gFontManager(); +Dashboard& gDashboard(); +DeferredcasterManager& gDeferredcasterManager(); +DownloadManager& gDownloadManager(); +LuaConsole& gLuaConsole(); +MissionManager& gMissionManager(); +ModuleEngine& gModuleEngine(); +NetworkEngine& gNetworkEngine(); +OpenSpaceEngine& gOpenSpaceEngine(); +ParallelPeer& gParallelPeer(); +RaycasterManager& gRaycasterManager(); +RenderEngine& gRenderEngine(); +std::vector>& gScreenspaceRenderables(); +SyncEngine& gSyncEngine(); +TimeManager& gTimeManager(); +VirtualPropertyManager& gVirtualPropertyManager(); +WindowDelegate& gWindowDelegate(); +configuration::Configuration& gConfiguration(); +interaction::JoystickInputStates& gJoystickInputStates(); +interaction::KeybindingManager& gKeybindingManager(); +interaction::NavigationHandler& gNavigationHandler(); +performance::PerformanceManager& gPerformanceManager(); +properties::PropertyOwner& gRootPropertyOwner(); +properties::PropertyOwner& gScreenSpaceRootPropertyOwner(); +scripting::ScriptEngine& gScriptEngine(); +scripting::ScriptScheduler& gScriptScheduler(); + +} // namespace detail + +static ghoul::fontrendering::FontManager& fontManager = detail::gFontManager(); +static Dashboard& dashboard = detail::gDashboard(); +static DeferredcasterManager& deferredcasterManager = detail::gDeferredcasterManager(); +static DownloadManager& downloadManager = detail::gDownloadManager(); +static LuaConsole& luaConsole = detail::gLuaConsole(); +static MissionManager& missionManager = detail::gMissionManager(); +static ModuleEngine& moduleEngine = detail::gModuleEngine(); +static NetworkEngine& networkEngine = detail::gNetworkEngine(); +static OpenSpaceEngine& openSpaceEngine = detail::gOpenSpaceEngine(); +static ParallelPeer& parallelPeer = detail::gParallelPeer(); +static RaycasterManager& raycasterManager = detail::gRaycasterManager(); +static RenderEngine& renderEngine = detail::gRenderEngine(); +static std::vector>& screenSpaceRenderables = + detail::gScreenspaceRenderables(); +static SyncEngine& syncEngine = detail::gSyncEngine(); +static TimeManager& timeManager = detail::gTimeManager(); +static VirtualPropertyManager& virtualPropertyManager = detail::gVirtualPropertyManager(); +static WindowDelegate& windowDelegate = detail::gWindowDelegate(); +static configuration::Configuration& configuration = detail::gConfiguration(); +static interaction::JoystickInputStates& joystickInputStates = + detail::gJoystickInputStates(); +static interaction::KeybindingManager& keybindingManager = detail::gKeybindingManager(); +static interaction::NavigationHandler& navigationHandler = detail::gNavigationHandler(); +static performance::PerformanceManager& performanceManager = + detail::gPerformanceManager(); +static properties::PropertyOwner& rootPropertyOwner = detail::gRootPropertyOwner(); +static properties::PropertyOwner& screenSpaceRootPropertyOwner = + detail::gScreenSpaceRootPropertyOwner(); +static scripting::ScriptEngine& scriptEngine = detail::gScriptEngine(); +static scripting::ScriptScheduler& scriptScheduler = detail::gScriptScheduler(); + +void initialize(); +void initializeGL(); +void deinitialize(); +void deinitializeGL(); + +} // namespace global + +} // namespace openspace + +#endif // __OPENSPACE_CORE___GLOBALS___H__ diff --git a/include/openspace/engine/globalscallbacks.h b/include/openspace/engine/globalscallbacks.h new file mode 100644 index 0000000000..59f3d22e5d --- /dev/null +++ b/include/openspace/engine/globalscallbacks.h @@ -0,0 +1,84 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2018 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___GLOBALSCALLBACKS___H__ +#define __OPENSPACE_CORE___GLOBALSCALLBACKS___H__ + +#include +#include +#include +#include + +namespace openspace::global { + +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(); + +} // 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(); + +} // namespace callback + +} // namespace openspace::global + +#endif // __OPENSPACE_CORE___GLOBALSCALLBACKS___H__ diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 7d110db256..522594bfb2 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -29,46 +29,17 @@ #include #include #include -#include #include #include #include -namespace ghoul { class Dictionary; } -namespace ghoul::cmdparser { class CommandlineParser; } -namespace ghoul::fontrendering { class FontManager; } - namespace openspace { class AssetManager; -struct Configuration; -class Dashboard; -class DownloadManager; -class GUI; class LoadingScreen; -class LuaConsole; -class ModuleEngine; -class NetworkEngine; -class ParallelPeer; -class RenderEngine; class Scene; -class SyncEngine; -class TimeManager; -class VirtualPropertyManager; -class WindowWrapper; -namespace interaction { - struct JoystickInputStates; - class KeyBindingManager; - class NavigationHandler; -} // namespace interaction -namespace gui { class GUI; } -namespace properties { class PropertyOwner; } -namespace scripting { - struct LuaLibrary; - class ScriptEngine; - class ScriptScheduler; -} // namespace scripting +namespace scripting { struct LuaLibrary; } // Structure that is responsible for the delayed shutdown of the application struct ShutdownInformation { @@ -82,23 +53,20 @@ struct ShutdownInformation { float timer = 0.f; }; +struct CommandlineArguments { + std::string configurationName; + std::string configurationOverride; +}; + class OpenSpaceEngine { public: - static void create(int argc, char** argv, - std::unique_ptr windowWrapper, - std::vector& sgctArguments, bool& requestClose, - bool consoleLog = true); + OpenSpaceEngine(); + ~OpenSpaceEngine(); - static void destroy(); - static OpenSpaceEngine& ref(); - static bool isCreated(); - - ~OpenSpaceEngine() = default; - - // callbacks void initialize(); void initializeGL(); void deinitialize(); + void deinitializeGL() {} void preSynchronization(); void postSynchronizationPreDraw(); void render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, @@ -110,78 +78,16 @@ public: void mouseButtonCallback(MouseButton button, MouseAction action); void mousePositionCallback(double x, double y); void mouseScrollWheelCallback(double posX, double posY); - void setJoystickInputStates(interaction::JoystickInputStates& states); void externalControlCallback(const char* receivedChars, int size, int clientId); void encode(); void decode(); - void scheduleLoadSingleAsset(std::string assetPath); void toggleShutdownMode(); - // On purpose, there is no function that returns a non-const reference to - // Configuration; that guards us against anyone in the program changing the - // configuration values underneath our feet - const Configuration& configuration() const; - // Guaranteed to return a valid pointer - LuaConsole& console(); AssetManager& assetManager(); - Dashboard& dashboard(); - DownloadManager& downloadManager(); - ModuleEngine& moduleEngine(); LoadingScreen& loadingScreen(); - NetworkEngine& networkEngine(); - ParallelPeer& parallelPeer(); - RenderEngine& renderEngine(); - TimeManager& timeManager(); - WindowWrapper& windowWrapper(); - ghoul::fontrendering::FontManager& fontManager(); - interaction::NavigationHandler& navigationHandler(); - interaction::KeyBindingManager& keyBindingManager(); - properties::PropertyOwner& rootPropertyOwner(); - properties::PropertyOwner& globalPropertyOwner(); - scripting::ScriptEngine& scriptEngine(); - scripting::ScriptScheduler& scriptScheduler(); - VirtualPropertyManager& virtualPropertyManager(); - - - // This method is only to be called from Modules - enum class CallbackOption { - Initialize = 0, // Callback for the end of the initialization - Deinitialize, // Callback for the end of the deinitialization - InitializeGL, // Callback for the end of the OpenGL initialization - DeinitializeGL, // Callback for the end of the OpenGL deinitialization - PreSync, // Callback for the end of the pre-sync function - PostSyncPreDraw, // Callback for the end of the post-sync-pre-draw function - Render, // Callback for the end of the render function - Draw2D, // Callback for the two-dimensional rendering functions - PostDraw // Callback for the end of the post-draw function - }; - - // Registers a callback for a specific CallbackOption - void registerModuleCallback(CallbackOption option, std::function function); - - // Registers a callback that is called when a new keyboard event is received - void registerModuleKeyboardCallback( - std::function function); - - // Registers a callback that is called when a new character event is received - void registerModuleCharCallback( - std::function function); - - // Registers a callback that is called when a new mouse button is received - void registerModuleMouseButtonCallback( - std::function function); - - // Registers a callback that is called when a new mouse movement is received - void registerModuleMousePositionCallback( - std::function function); - - // Registers a callback that is called when a scroll wheel change is received - void registerModuleMouseScrollWheelCallback( - std::function function - ); void writeSceneDocumentation(); void writeStaticDocumentation(); @@ -193,90 +99,26 @@ public: static scripting::LuaLibrary luaLibrary(); private: - OpenSpaceEngine(std::string programName, - std::unique_ptr windowWrapper); - void loadSingleAsset(const std::string& assetPath); - void gatherCommandlineArguments(); void loadFonts(); - void configureLogging(bool consoleLog); - void runGlobalCustomizationScripts(); void configureLogging(); - std::unique_ptr _configuration; - - // Components std::unique_ptr _scene; std::unique_ptr _assetManager; - std::unique_ptr _dashboard; - std::unique_ptr _downloadManager; - std::unique_ptr _console; - std::unique_ptr _moduleEngine; - std::unique_ptr _networkEngine; - std::unique_ptr _parallelPeer; - std::unique_ptr _renderEngine; - std::unique_ptr _syncEngine; - std::unique_ptr _timeManager; - std::unique_ptr _windowWrapper; - std::unique_ptr _commandlineParser; - std::unique_ptr _fontManager; - std::unique_ptr _navigationHandler; - std::unique_ptr _keyBindingManager; - - std::unique_ptr _scriptEngine; - std::unique_ptr _scriptScheduler; - std::unique_ptr _virtualPropertyManager; - - // Others - std::unique_ptr _rootPropertyOwner; - std::unique_ptr _globalPropertyOwner; - std::unique_ptr _loadingScreen; - struct { - properties::StringProperty versionString; - properties::StringProperty sourceControlInformation; - } _versionInformation; - bool _hasScheduledAssetLoading = false; std::string _scheduledAssetPathToLoad; - struct { - std::vector> initialize; - std::vector> deinitialize; - - std::vector> initializeGL; - std::vector> deinitializeGL; - - std::vector> preSync; - std::vector> postSyncPreDraw; - std::vector> render; - std::vector> draw2D; - std::vector> postDraw; - - std::vector> keyboard; - std::vector> character; - - std::vector> mouseButton; - std::vector> mousePosition; - std::vector> mouseScrollWheel; - } _moduleCallbacks; - ShutdownInformation _shutdown; // The first frame might take some more time in the update loop, so we need to know to // disable the synchronization; otherwise a hardware sync will kill us after 1 minute bool _isFirstRenderingFirstFrame = true; - - glm::dvec2 _mousePosition; - - static OpenSpaceEngine* _engine; }; -#define OsEng (openspace::OpenSpaceEngine::ref()) - } // namespace openspace #endif // __OPENSPACE_CORE___OPENSPACEENGINE___H__ diff --git a/include/openspace/engine/windowdelegate.h b/include/openspace/engine/windowdelegate.h new file mode 100644 index 0000000000..9062dced0a --- /dev/null +++ b/include/openspace/engine/windowdelegate.h @@ -0,0 +1,112 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2018 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE__WINDOWDELEGATE___H__ +#define __OPENSPACE_CORE__WINDOWDELEGATE___H__ + +#include +#include + +namespace openspace { + +struct WindowDelegate { + void (*terminate)() = [](){}; + + void (*setBarrier)(bool enabled) = [](bool) {}; + + void (*setSynchronization)(bool enabled) = [](bool) {}; + + void (*clearAllWindows)(const glm::vec4& clearColor) = [](const glm::vec4&) {}; + + bool (*windowHasResized)() = []() { return false; }; + + double (*averageDeltaTime)() = []() { return 0.0; }; + + double (*deltaTime)() = []() { return 0.0; }; + + double (*applicationTime)() = []() { return 0.0; }; + + glm::vec2 (*mousePosition)() = []() { return glm::vec2(0.f); }; + + uint32_t (*mouseButtons)(int maxNumber) = [](int) { return uint32_t(0); }; + + glm::ivec2 (*currentWindowSize)() = []() { return glm::ivec2(0); }; + + glm::ivec2 (*currentSubwindowSize)() = []() { return glm::ivec2(0); }; + + glm::ivec2 (*currentWindowResolution)() = []() { return glm::ivec2(0); }; + + glm::ivec2 (*currentDrawBufferResolution)() = []() { return glm::ivec2(0); }; + + glm::ivec2 (*currentViewportSize)() = []() { return glm::ivec2(0); }; + + glm::vec2 (*dpiScaling)() = []() { return glm::vec2(1.f); }; + + int (*currentNumberOfAaSamples)() = []() { return 1; }; + + bool (*isRegularRendering)() = []() { return true; }; + + bool (*hasGuiWindow)() = []() { return false; }; + + bool (*isGuiWindow)() = []() { return false; }; + + bool (*isMaster)() = []() { return false; }; + + int (*clusterId)() = []() { return 0; }; + + bool (*isUsingSwapGroups)() = []() { return false; }; + + bool (*isSwapGroupMaster)() = []() { return false; }; + + glm::mat4 (*viewProjectionMatrix)() = []() { return glm::mat4(1.f); }; + + glm::mat4 (*modelMatrix)() = []() { return glm::mat4(1.f); }; + + void (*setNearFarClippingPlane)(float near, float far) = [](float, float) {}; + + void (*setEyeSeparationDistance)(float distance) = [](float) {}; + + glm::ivec4 (*viewportPixelCoordinates)() = []() { return glm::ivec4(0, 0, 0, 0); }; + + bool (*isExternalControlConnected)() = []() { return false; }; + + void (*sendMessageToExternalControl)(const std::vector& message) = + [](const std::vector&) {}; + + bool (*isSimpleRendering)() = []() { return true; }; + + bool (*isFisheyeRendering)() = []() { return false; }; + + void (*takeScreenshot)(bool applyWarping) = [](bool) { }; + + void (*swapBuffer)() = []() {}; + + int (*nWindows)() = []() { return 0; }; + + int (*currentWindowId)() = []() { return 0; }; +}; + +} // namespace openspace + +#endif // __OPENSPACE_CORE__WINDOWDELEGATE___H__ diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h deleted file mode 100644 index c27aa006f3..0000000000 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ /dev/null @@ -1,99 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2018 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#ifndef __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ -#define __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ - -#include - -#include -#include - -namespace openspace { - -/** - * WindowWrapper subclass wrapping the Simple Graphics Cluster Toolkit, forwarding all - * method calls to the specific functions in the Engine and SGCTWindow classes. - * - * \sa https://c-student.itn.liu.se/wiki/develop:sgct:sgct - */ -class SGCTWindowWrapper : public WindowWrapper { -public: - SGCTWindowWrapper(); - - void terminate() override; - void setBarrier(bool enabled) override; - void setSynchronization(bool enabled) override; - void clearAllWindows(const glm::vec4& clearColor) override; - bool windowHasResized() const override; - - double averageDeltaTime() const override; - double deltaTime() const override; - double applicationTime() const override; - glm::vec2 mousePosition() const override; - uint32_t mouseButtons(int maxNumber) const override; - glm::ivec2 currentWindowSize() const override; - glm::ivec2 currentSubwindowSize() const override; - glm::ivec2 currentWindowResolution() const override; - glm::ivec2 currentDrawBufferResolution() const override; - glm::ivec2 getCurrentViewportSize() const override; - glm::vec2 dpiScaling() const override; - int currentNumberOfAaSamples() const override; - - bool isRegularRendering() const override; - bool hasGuiWindow() const override; - bool isGuiWindow() const override; - bool isMaster() const override; - int clusterId() const override; - bool isUsingSwapGroups() const override; - bool isSwapGroupMaster() const override; - - glm::mat4 viewProjectionMatrix() const override; - glm::mat4 modelMatrix() const override; - void setNearFarClippingPlane(float nearPlane, float farPlane) override; - void setEyeSeparationDistance(float distance) override; - - glm::ivec4 viewportPixelCoordinates() const override; - - bool isExternalControlConnected() const override; - void sendMessageToExternalControl(const std::vector& message) const override; - - bool isSimpleRendering() const override; - bool isFisheyeRendering() const override; - - void takeScreenshot(bool applyWarping = false) const override; - - void swapBuffer() const override; - - int nWindows() const override; - int currentWindowId() const override; - -private: - properties::FloatProperty _eyeSeparation; - properties::BoolProperty _showStatsGraph; -}; - -} // namespace openspace - -#endif // __OPENSPACE_CORE___SGCTWINDOWWRAPPER___H__ diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h deleted file mode 100644 index 2c5dea6a2a..0000000000 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ /dev/null @@ -1,322 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2018 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#ifndef __OPENSPACE_CORE___WINDOWWRAPPER___H__ -#define __OPENSPACE_CORE___WINDOWWRAPPER___H__ - -#include - -#include -#include - -namespace openspace { - -namespace scripting { struct LuaLibrary; } - -/** - * A WindowWrapper is a class that handles the abstraction between OpenSpace and a - * specific window creation framework.
- * Every new windowing framework needs to have its own WindowWrapper subclass exposing the - * required features. - */ -class WindowWrapper : public properties::PropertyOwner { -public: - /// Default constructor - WindowWrapper(); - - /** - * Returns the Lua library that contains all Lua functions available to affect the - * windowing system. - */ - static scripting::LuaLibrary luaLibrary(); - - /** - * This method closes the application by calling the necessary terminate function of - * the window management system - */ - virtual void terminate(); - - /** - * This method enables or disables a framelock barrier. If the specific windowing - * framework does not provide a framelock, this method defaults to a no-op. - * \param enabled If true the framelock is enabled, false - * disables it - */ - virtual void setBarrier(bool enabled); - - /** - * This method enables or disables a framelock barrier. If the specific windowing - * framework does not provide a framelock, this method defaults to a no-op. - * \param enabled If true the framelock is enabled, false - * disables it - */ - virtual void setSynchronization(bool enabled); - - /** - * This method clears all the rendering windows with the specified \p clearColor. In - * most OpenGL cases, this will end up with one or mode glClear calls. - * This method defaults to a no-op. - * \param clearColor The color with which to clear all windows - */ - virtual void clearAllWindows(const glm::vec4& clearColor); - - /** - * Returns whether the current window has been resized recently. On default, this - * method always returns false. - * \return true if the current window has been resized recently, - * false otherwise - */ - virtual bool windowHasResized() const; - - /** - * Returns the average frametime in seconds. On default, this method returns - * 0.0. - * \return The average frametime in seconds - */ - virtual double averageDeltaTime() const; - - /** - * Returns the frametime in seconds. On default, this method returns 0.0. - * \return The frametime in seconds - */ - virtual double deltaTime() const; - - /** - * Returns the time that has passed (in seconds) since application start - * \return The time that has passed (in seconds) since application start - * @return [description] - */ - virtual double applicationTime() const; - - /** - * Returns the location of the mouse cursor in pixel screen coordinates. On default, - * this method returns 0,0. - * \return The location of the mouse cursor in pixel screen coordinates - */ - virtual glm::vec2 mousePosition() const; - - /** - * Returns a bitmask of the status of all available mouse buttons. Bit i - * is 1 if mouse button i is pressed down; - * false otherwise. On default, this method returns that none of the - * buttons is pressed. - * \param maxNumber The maximum number of mouse buttons that should be queried - * \return A bitmask showing the status of all mouse buttons (up to \p maxNumber) - */ - virtual uint32_t mouseButtons(int maxNumber = 8) const; - - /** - * Returns the size of the currently active window in pixel coordinates. On default, - * this method returns a window size of 0,0. - * \return The size of the currently active window in pixel coordinates - */ - virtual glm::ivec2 currentWindowSize() const; - - /** - * Returns the size of the currently active subwindow in pixel coordinates. On default, - * this method returns the same a currentWindowSize. A subwindow is the part of a - * window that is used for one of the eyes in stereoscopic side-by-side/top-bottom - * rendering. - * \return The size of the currently active subwindow in pixel coordinates - */ - virtual glm::ivec2 currentSubwindowSize() const; - - /** - * Returns the resolution of the currently active window in pixel coordinates. On - * default, this method returns the same size as #currentWindowSize. - * \return The resolution of the currently active window in pixel coordinates - */ - virtual glm::ivec2 currentWindowResolution() const; - - /** - * Returns the resolution of the currently active framebuffer in pixel coordinates. - * On default, this method returns the same size as #currentWindowSize. - * \return The resolution of the currently active window in pixel coordinates - */ - virtual glm::ivec2 currentDrawBufferResolution() const; - - /** - * Returns the resolution of the currently viewport resolution in pixel - * coordinates. - * \return The resolution of the currently viewport in pixel coordinates - */ - virtual glm::ivec2 getCurrentViewportSize() const; - - /** - * Returns the DPI scaling factor for the current window. This is normally 1 on all - * regular monitors and 2 on Retina screens. - * \return The DPI scaling factor for the current window - */ - virtual glm::vec2 dpiScaling() const; - - /** - * Returns the number of anti-aliasing samples used in the current window. - */ - virtual int currentNumberOfAaSamples() const; - - /** - * Returns true if the current rendering method is regular, i.e., it is - * a flat projection without non-linear distortions. Returns false in - * other cases, for example fisheye projections. On default, this method will return - * true. - * \return Whether the current rendering method is a regular method - */ - virtual bool isRegularRendering() const; - - /** - * Returns true if there is a dedicated GUI window. In these cases, the - * GUI elements will not be drawn on the non-GUI windows but only on the dedicated - * windows. - * \return Whether there are dedicated GUI windows - */ - virtual bool hasGuiWindow() const; - - /** - * Returns true if the current rendering window is a GUI-only window. In - * these cases, the regular rendering is suppressed, but input is still possible in - * the window - * \return Whether the current rendering window is GUI-only - */ - virtual bool isGuiWindow() const; - - /** - * Returns true if this application is the master for a clustered - * environment. - * \return Whether this applicaiton is the master for a clustered environment. - */ - virtual bool isMaster() const; - - /** - * Returns the unique identifier of this OpenSpace instance within the current cluster - * configuration. If this instance is not part of a cluster, this value is always 0. - * \return The cluster identifier of this OpenSpace instance - */ - virtual int clusterId() const; - - /** - * Returns true if the current rendering window is using swap groups. - */ - virtual bool isUsingSwapGroups() const; - - /** - * Returns true if the current rendering window is master of the swap its - * group. - */ - virtual bool isSwapGroupMaster() const; - - /** - * Returns the currently employed view-projection matrix. On default, this method will - * return the identity matrix. - * \return The currently employed view-projection matrix - */ - virtual glm::mat4 viewProjectionMatrix() const; - - /** - * Returns the currently employed model matrix. On default, this method will return - * the identity matrix. - * \return The currently employed model matrix - */ - virtual glm::mat4 modelMatrix() const; - - /** - * Sets the near and far clipping planes of the rendering window. This method defaults - * to a no-op. - * \param near The near clipping plane - * \param far The far clipping plane - */ - virtual void setNearFarClippingPlane(float near, float far); - - /** - * Sets the stereo eye separation distance for the render engine. - * \param distance The distance between eyes for stereo rendering. - */ - virtual void setEyeSeparationDistance(float distance); - - /** - * Returns the location and size of the current viewport (x, - * width, y, and height). If there is only a - * single viewport, x and y are 0 whereas - * width and height are equal to #currentWindowResolution. - * \return The location and size of the current viewport - */ - virtual glm::ivec4 viewportPixelCoordinates() const; - - /** - * Returns true if there is an external control connected, i.e., an - * application that can receive control commands. On default, this method will return - * false. - * \return If there is an external control connected - */ - virtual bool isExternalControlConnected() const; - - /** - * Sends a \p message to an external control. This method defaults to a no-op. - * \param message The message to be sent - */ - virtual void sendMessageToExternalControl(const std::vector& message) const; - - /** - * Returns true if the rendering is a single viewport with an single - * window; false otherwise. On default, this method returns - * true - * \returns true if the rendering is a single viewport with an single - * widnow; false otherwise - */ - virtual bool isSimpleRendering() const; - - /** - * Returns true if the rendering is being done using a Fisheye lens; - * false otherwise. On default, this method returns - * false - */ - virtual bool isFisheyeRendering() const; - - /** - * Advises the windowing system to take a screenshot. This method defaults to a no-op. - */ - virtual void takeScreenshot(bool applyWarping = false) const; - - /** - * Encourages the windowing system to swap the back- and front buffers - */ - virtual void swapBuffer() const; - - /** - * Returns the number of windows that are currently instantiated - */ - virtual int nWindows() const; - - /** - * Returns the id of the current window (in the range [0, nWindows -1]) - */ - virtual int currentWindowId() const; - - struct WindowWrapperException : public ghoul::RuntimeError { - explicit WindowWrapperException(const std::string& msg); - }; -}; - -} // namespace openspace - -#endif // __OPENSPACE_CORE___WINDOWWRAPPER___H__ diff --git a/include/openspace/interaction/inputstate.h b/include/openspace/interaction/inputstate.h index 3569db80eb..4c91dd5e86 100644 --- a/include/openspace/interaction/inputstate.h +++ b/include/openspace/interaction/inputstate.h @@ -43,8 +43,6 @@ public: void mousePositionCallback(double mouseX, double mouseY); void mouseScrollWheelCallback(double mouseScrollDelta); - void setJoystickInputStates(JoystickInputStates& states); - // Accessors const std::vector>& pressedKeys() const; bool isKeyPressed(std::pair keyModPair) const; @@ -55,7 +53,6 @@ public: double mouseScrollDelta() const; bool isMouseButtonPressed(MouseButton mouseButton) const; - const JoystickInputStates& joystickInputStates() const; float joystickAxis(int i) const; bool joystickButton(int i) const; @@ -67,10 +64,6 @@ private: std::vector _mouseButtonsDown; glm::dvec2 _mousePosition; double _mouseScrollDelta; - - // Input from joysticks - // The memory is owned by the outer most main (apps/OpenSpace/main.cpp right now) - JoystickInputStates* _joystickInputStates = nullptr; }; } // namespace openspace::interaction diff --git a/include/openspace/interaction/keybindingmanager.h b/include/openspace/interaction/keybindingmanager.h index 5f71eaa4e3..7ddcc2312a 100644 --- a/include/openspace/interaction/keybindingmanager.h +++ b/include/openspace/interaction/keybindingmanager.h @@ -39,7 +39,7 @@ namespace openspace::scripting { struct LuaLibrary; } namespace openspace::interaction { -class KeyBindingManager : public DocumentationGenerator { +class KeybindingManager : public DocumentationGenerator { public: BooleanType(IsLocalBind); BooleanType(IsSynchronized); @@ -50,7 +50,7 @@ public: std::string documentation; }; - KeyBindingManager(); + KeybindingManager(); void resetKeyBindings(); diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index 84d9636d6c..b434a60fc4 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -80,8 +80,6 @@ public: void mousePositionCallback(double x, double y); void mouseScrollWheelCallback(double pos); - void setJoystickInputStates(JoystickInputStates& states); - void setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, JoystickCameraStates::AxisInvert shouldInvert = JoystickCameraStates::AxisInvert::No, diff --git a/include/openspace/mission/missionmanager.h b/include/openspace/mission/missionmanager.h index 2052f1b451..83f714f280 100644 --- a/include/openspace/mission/missionmanager.h +++ b/include/openspace/mission/missionmanager.h @@ -37,9 +37,9 @@ namespace openspace { namespace scripting { struct LuaLibrary; } /** -* Singleton class keeping track of space missions. -*/ -class MissionManager : public ghoul::Singleton { + * Class keeping track of space missions. + */ +class MissionManager { public: struct MissionManagerException : public ghoul::RuntimeError { explicit MissionManagerException(std::string error); diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index 7c8558fef3..779149c4d5 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -42,11 +42,11 @@ public: static void CreateGlobalSharedMemory(); static void DestroyGlobalSharedMemory(); - PerformanceManager(std::string loggingDirectory = "${BASE}", - std::string prefix = "PM-"); - ~PerformanceManager(); + void setEnabled(bool enabled); + bool isEnabled() const; + void resetPerformanceMeasurements(); void storeIndividualPerformanceMeasurement(const std::string& identifier, @@ -74,6 +74,7 @@ public: PerformanceLayout* performanceData(); private: + bool _performanceMeasurementEnabled = false; bool _loggingEnabled = false; std::string _logDir; diff --git a/include/openspace/performance/performancemeasurement.h b/include/openspace/performance/performancemeasurement.h index 7ea34fe4cd..c0f1dfa9c4 100644 --- a/include/openspace/performance/performancemeasurement.h +++ b/include/openspace/performance/performancemeasurement.h @@ -25,8 +25,6 @@ #ifndef __OPENSPACE_CORE___PERFORMANCEMEASUREMENT___H__ #define __OPENSPACE_CORE___PERFORMANCEMEASUREMENT___H__ -#include -#include #include #include @@ -36,14 +34,11 @@ class PerformanceManager; class PerformanceMeasurement { public: - PerformanceMeasurement(std::string identifier, - std::shared_ptr manager); + PerformanceMeasurement(std::string identifier); ~PerformanceMeasurement(); private: std::string _identifier; - std::weak_ptr _manager; - std::chrono::high_resolution_clock::time_point _startTime; }; @@ -51,12 +46,9 @@ private: #define __LABEL_PerfMeasure(a) __MERGE_PerfMeasure(unique_name_, a) /// Declare a new variable for measuring the performance of the current block -#define PerfMeasure(name) \ - auto __LABEL_PerfMeasure(__LINE__) = \ - openspace::performance::PerformanceMeasurement(\ - (name), \ - OsEng.renderEngine().performanceManager() \ - ) +#define PerfMeasure(name) \ + auto __LABEL_PerfMeasure(__LINE__) = \ + openspace::performance::PerformanceMeasurement((name)) } // namespace openspace::performance diff --git a/include/openspace/rendering/abufferrenderer.h b/include/openspace/rendering/abufferrenderer.h index c00d41c25a..ae799eb4b3 100644 --- a/include/openspace/rendering/abufferrenderer.h +++ b/include/openspace/rendering/abufferrenderer.h @@ -76,8 +76,7 @@ public: void postRaycast(const RaycasterTask& raycasterTask); void update() override; - void render(Scene* scene, Camera* camera, float blackoutFactor, - bool doPerformanceMeasurements) override; + void render(Scene* scene, Camera* camera, float blackoutFactor) override; /** * Update render data diff --git a/include/openspace/rendering/dashboard.h b/include/openspace/rendering/dashboard.h index 0ad5f4a737..412417fbd3 100644 --- a/include/openspace/rendering/dashboard.h +++ b/include/openspace/rendering/dashboard.h @@ -41,6 +41,7 @@ class DashboardItem; class Dashboard : public properties::PropertyOwner { public: Dashboard(); + ~Dashboard(); void render(glm::vec2& penPosition); diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index fb0738f78d..2334b2d47b 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -92,8 +92,7 @@ public: void update() override; void performRaycasterTasks(const std::vector& tasks); void performDeferredTasks(const std::vector& tasks); - void render(Scene* scene, Camera* camera, float blackoutFactor, - bool doPerformanceMeasurements) override; + void render(Scene* scene, Camera* camera, float blackoutFactor) override; /** * Update render data diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index d162ddfdca..6254e51615 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -42,7 +42,6 @@ namespace ghoul::opengl { class ProgramObject; } namespace openspace { -namespace performance { class PerformanceManager; } namespace scripting { struct LuaLibrary; } class Camera; @@ -70,7 +69,6 @@ public: void initialize(); void initializeGL(); - void deinitialize(); void deinitializeGL(); void setScene(Scene* scene); @@ -79,9 +77,6 @@ public: const Renderer& renderer() const; RendererImplementation rendererImplementation() const; - RaycasterManager& raycasterManager(); - DeferredcasterManager& deferredcasterManager(); - void updateShaderPrograms(); void updateFade(); @@ -96,10 +91,6 @@ public: void renderEndscreen(); void postDraw(); - // Performance measurements - bool doesPerformanceMeasurements() const; - std::shared_ptr performanceManager(); - float globalBlackOutFactor(); void setGlobalBlackOutFactor(float opacity); @@ -161,8 +152,6 @@ public: glm::ivec2 renderingResolution() const; glm::ivec2 fontResolution() const; - properties::PropertyOwner& screenSpaceOwner(); - private: void setRenderer(std::unique_ptr renderer); RendererImplementation rendererFromString(const std::string& renderingMethod) const; @@ -173,14 +162,10 @@ private: void renderShutdownInformation(float timer, float fullTime); void renderDashboard(); - Camera* _camera = nullptr; Scene* _scene = nullptr; - std::unique_ptr _raycasterManager; - std::unique_ptr _deferredcasterManager; properties::BoolProperty _doPerformanceMeasurements; - std::shared_ptr _performanceManager; std::unique_ptr _renderer; RendererImplementation _rendererImplementation = RendererImplementation::Invalid; @@ -212,8 +197,6 @@ private: uint64_t _frameNumber = 0; std::vector _programs; - properties::PropertyOwner _screenSpaceOwner; - std::vector> _screenSpaceRenderables; std::shared_ptr _fontBig; std::shared_ptr _fontInfo; diff --git a/include/openspace/rendering/renderer.h b/include/openspace/rendering/renderer.h index 41015dc8cc..8ae5130954 100644 --- a/include/openspace/rendering/renderer.h +++ b/include/openspace/rendering/renderer.h @@ -71,8 +71,7 @@ public: virtual void update() = 0; - virtual void render(Scene* scene, Camera* camera, float blackoutFactor, - bool doPerformanceMeasurements) = 0; + virtual void render(Scene* scene, Camera* camera, float blackoutFactor) = 0; /** * Update render data * Responsible for calling renderEngine::setRenderData diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 05bb1571b0..8bf989aed3 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -60,7 +60,6 @@ #include #include -#include #include #include #include diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index 41c286aa14..c684f145a3 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -24,33 +24,28 @@ #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 -#include -#include -#include - #include - -#include #include +#include #ifdef WIN32 #define _USE_MATH_DEFINES @@ -673,9 +668,7 @@ RenderableAtmosphere::RenderableAtmosphere(const ghoul::Dictionary& dictionary) void RenderableAtmosphere::deinitialize() { if (_deferredcaster) { - OsEng.renderEngine().deferredcasterManager().detachDeferredcaster( - *_deferredcaster - ); + global::deferredcasterManager.detachDeferredcaster(*_deferredcaster); _deferredcaster = nullptr; } } @@ -718,9 +711,7 @@ void RenderableAtmosphere::initializeGL() { _deferredcaster->initialize(); } - OsEng.renderEngine().deferredcasterManager().attachDeferredcaster( - *_deferredcaster - ); + global::deferredcasterManager.attachDeferredcaster(*_deferredcaster); } return; diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index d8376f70f7..608199bf59 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -219,12 +219,12 @@ DashboardItemAngle::DashboardItemAngle(const ghoul::Dictionary& dictionary) } _fontName.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); _fontSize.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -356,7 +356,7 @@ DashboardItemAngle::DashboardItemAngle(const ghoul::Dictionary& dictionary) } addProperty(_destination.nodeName); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } std::pair DashboardItemAngle::positionAndLabel( @@ -364,7 +364,7 @@ std::pair DashboardItemAngle::positionAndLabel( { if (comp.type == Type::Node) { if (!comp.node) { - comp.node = OsEng.renderEngine().scene()->sceneGraphNode(comp.nodeName); + comp.node = global::renderEngine.scene()->sceneGraphNode(comp.nodeName); if (!comp.node) { LERRORC( @@ -380,9 +380,9 @@ std::pair DashboardItemAngle::positionAndLabel( case Type::Node: return { comp.node->worldPosition(), comp.node->guiName() }; case Type::Focus: - return { OsEng.navigationHandler().focusNode()->worldPosition(), "focus" }; + return { global::navigationHandler.focusNode()->worldPosition(), "focus" }; case Type::Camera: - return { OsEng.renderEngine().scene()->camera()->positionVec3(), "camera" }; + return { global::renderEngine.scene()->camera()->positionVec3(), "camera" }; default: return { glm::dvec3(0.0), "Unknown" }; } diff --git a/modules/base/dashboard/dashboarditemdate.cpp b/modules/base/dashboard/dashboarditemdate.cpp index 7276ba06f2..06f38b8d97 100644 --- a/modules/base/dashboard/dashboarditemdate.cpp +++ b/modules/base/dashboard/dashboarditemdate.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -94,7 +94,7 @@ DashboardItemDate::DashboardItemDate(const ghoul::Dictionary& dictionary) _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -104,11 +104,11 @@ DashboardItemDate::DashboardItemDate(const ghoul::Dictionary& dictionary) ); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemDate::render(glm::vec2& penPosition) { @@ -116,14 +116,14 @@ void DashboardItemDate::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format("Date: {} UTC", OsEng.timeManager().time().UTC()) + fmt::format("Date: {} UTC", global::timeManager.time().UTC()) ); } glm::vec2 DashboardItemDate::size() const { return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( *_font, - fmt::format("Date: {} UTC", OsEng.timeManager().time().UTC()) + fmt::format("Date: {} UTC", global::timeManager.time().UTC()) ).boundingBox; } diff --git a/modules/base/dashboard/dashboarditemdistance.cpp b/modules/base/dashboard/dashboarditemdistance.cpp index 32dba742db..3a3b484404 100644 --- a/modules/base/dashboard/dashboarditemdistance.cpp +++ b/modules/base/dashboard/dashboarditemdistance.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -219,12 +219,12 @@ DashboardItemDistance::DashboardItemDistance(const ghoul::Dictionary& dictionary } _fontName.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); _fontSize.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -356,7 +356,7 @@ DashboardItemDistance::DashboardItemDistance(const ghoul::Dictionary& dictionary _requestedUnit.setVisibility(properties::Property::Visibility::Hidden); addProperty(_requestedUnit); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } std::pair DashboardItemDistance::positionAndLabel( @@ -365,7 +365,7 @@ std::pair DashboardItemDistance::positionAndLabel( { if ((mainComp.type == Type::Node) || (mainComp.type == Type::NodeSurface)) { if (!mainComp.node) { - mainComp.node = OsEng.renderEngine().scene()->sceneGraphNode( + mainComp.node = global::renderEngine.scene()->sceneGraphNode( mainComp.nodeName ); @@ -402,11 +402,11 @@ std::pair DashboardItemDistance::positionAndLabel( } case Type::Focus: return { - OsEng.navigationHandler().focusNode()->worldPosition(), + global::navigationHandler.focusNode()->worldPosition(), "focus" }; case Type::Camera: - return { OsEng.renderEngine().scene()->camera()->positionVec3(), "camera" }; + return { global::renderEngine.scene()->camera()->positionVec3(), "camera" }; default: return { glm::dvec3(0.0), "Unknown" }; } diff --git a/modules/base/dashboard/dashboarditemframerate.cpp b/modules/base/dashboard/dashboarditemframerate.cpp index 4cb683499e..910a0f5890 100644 --- a/modules/base/dashboard/dashboarditemframerate.cpp +++ b/modules/base/dashboard/dashboarditemframerate.cpp @@ -26,8 +26,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -111,7 +111,7 @@ DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictiona _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -121,7 +121,7 @@ DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictiona ); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -152,7 +152,7 @@ DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictiona } addProperty(_frametimeType); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemFramerate::render(glm::vec2& penPosition) { @@ -164,7 +164,7 @@ void DashboardItemFramerate::render(glm::vec2& penPosition) { *_font, penPosition, fmt::format( - "Avg. Frametime: {:.5f}", OsEng.windowWrapper().averageDeltaTime() + "Avg. Frametime: {:.5f}", global::windowDelegate.averageDeltaTime() ) ); break; @@ -173,7 +173,7 @@ void DashboardItemFramerate::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format("FPS: {:3.2f}", 1.0 / OsEng.windowWrapper().deltaTime()) + fmt::format("FPS: {:3.2f}", 1.0 / global::windowDelegate.deltaTime()) ); break; case FrametimeType::FPSAvg: @@ -182,7 +182,7 @@ void DashboardItemFramerate::render(glm::vec2& penPosition) { *_font, penPosition, fmt::format( - "Avg. FPS: {:3.2f}", 1.0 / OsEng.windowWrapper().averageDeltaTime() + "Avg. FPS: {:3.2f}", 1.0 / global::windowDelegate.averageDeltaTime() ) ); break; @@ -198,21 +198,21 @@ glm::vec2 DashboardItemFramerate::size() const { return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( *_font, fmt::format( - "Avg. Frametime: {:.5f}", OsEng.windowWrapper().averageDeltaTime() + "Avg. Frametime: {:.5f}", global::windowDelegate.averageDeltaTime() ) ).boundingBox; case FrametimeType::FPS: return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( *_font, fmt::format( - "FPS: {:3.2f}", 1.0 / OsEng.windowWrapper().deltaTime() + "FPS: {:3.2f}", 1.0 / global::windowDelegate.deltaTime() ) ).boundingBox; case FrametimeType::FPSAvg: return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( *_font, fmt::format( - "Avg. FPS: %3.2f", 1.0 / OsEng.windowWrapper().averageDeltaTime() + "Avg. FPS: %3.2f", 1.0 / global::windowDelegate.averageDeltaTime() ) ).boundingBox; case FrametimeType::None: diff --git a/modules/base/dashboard/dashboarditemmission.cpp b/modules/base/dashboard/dashboarditemmission.cpp index 9c50bba9a0..f066e7a180 100644 --- a/modules/base/dashboard/dashboarditemmission.cpp +++ b/modules/base/dashboard/dashboarditemmission.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -113,7 +113,7 @@ DashboardItemMission::DashboardItemMission(const ghoul::Dictionary& dictionary) _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -123,17 +123,17 @@ DashboardItemMission::DashboardItemMission(const ghoul::Dictionary& dictionary) ); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemMission::render(glm::vec2& penPosition) { - if (MissionManager::ref().hasCurrentMission()) { - double currentTime = OsEng.timeManager().time().j2000Seconds(); - const Mission& mission = MissionManager::ref().currentMission(); + if (global::missionManager.hasCurrentMission()) { + double currentTime = global::timeManager.time().j2000Seconds(); + const Mission& mission = global::missionManager.currentMission(); if (!mission.phases().empty()) { static const glm::vec4 nextMissionColor(0.7f, 0.3f, 0.3f, 1.f); diff --git a/modules/base/dashboard/dashboarditemparallelconnection.cpp b/modules/base/dashboard/dashboarditemparallelconnection.cpp index 3b248df780..9fc9dff40a 100644 --- a/modules/base/dashboard/dashboarditemparallelconnection.cpp +++ b/modules/base/dashboard/dashboarditemparallelconnection.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -98,7 +98,7 @@ DashboardItemParallelConnection::DashboardItemParallelConnection( _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -108,17 +108,17 @@ DashboardItemParallelConnection::DashboardItemParallelConnection( ); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemParallelConnection::render(glm::vec2& penPosition) { - const ParallelConnection::Status status = OsEng.parallelPeer().status(); - const size_t nConnections = OsEng.parallelPeer().nConnections(); - const std::string& hostName = OsEng.parallelPeer().hostName(); + const ParallelConnection::Status status = global::parallelPeer.status(); + const size_t nConnections = global::parallelPeer.nConnections(); + const std::string& hostName = global::parallelPeer.hostName(); std::string connectionInfo; int nClients = static_cast(nConnections); @@ -166,9 +166,9 @@ void DashboardItemParallelConnection::render(glm::vec2& penPosition) { } glm::vec2 DashboardItemParallelConnection::size() const { - ParallelConnection::Status status = OsEng.parallelPeer().status(); - size_t nConnections = OsEng.parallelPeer().nConnections(); - const std::string& hostName = OsEng.parallelPeer().hostName(); + ParallelConnection::Status status = global::parallelPeer.status(); + size_t nConnections = global::parallelPeer.nConnections(); + const std::string& hostName = global::parallelPeer.hostName(); std::string connectionInfo; int nClients = static_cast(nConnections); diff --git a/modules/base/dashboard/dashboarditempropertyvalue.cpp b/modules/base/dashboard/dashboarditempropertyvalue.cpp index 5e133cd90e..a959ccf02b 100644 --- a/modules/base/dashboard/dashboarditempropertyvalue.cpp +++ b/modules/base/dashboard/dashboarditempropertyvalue.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -124,7 +124,7 @@ DashboardItemPropertyValue::DashboardItemPropertyValue( _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -134,7 +134,7 @@ DashboardItemPropertyValue::DashboardItemPropertyValue( ); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -151,7 +151,7 @@ DashboardItemPropertyValue::DashboardItemPropertyValue( } addProperty(_displayString); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemPropertyValue::render(glm::vec2& penPosition) { diff --git a/modules/base/dashboard/dashboarditemsimulationincrement.cpp b/modules/base/dashboard/dashboarditemsimulationincrement.cpp index f3c102733c..3edaeabebe 100644 --- a/modules/base/dashboard/dashboarditemsimulationincrement.cpp +++ b/modules/base/dashboard/dashboarditemsimulationincrement.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -136,7 +136,7 @@ DashboardItemSimulationIncrement::DashboardItemSimulationIncrement( _fontName = dictionary.value(FontNameInfo.identifier); } _fontName.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); @@ -144,7 +144,7 @@ DashboardItemSimulationIncrement::DashboardItemSimulationIncrement( _fontSize = static_cast(dictionary.value(FontSizeInfo.identifier)); } _fontSize.onChange([this](){ - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -173,12 +173,12 @@ DashboardItemSimulationIncrement::DashboardItemSimulationIncrement( _requestedUnit.setVisibility(properties::Property::Visibility::Hidden); addProperty(_requestedUnit); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { - const double targetDt = OsEng.timeManager().targetDeltaTime(); - const double currentDt = OsEng.timeManager().deltaTime(); + const double targetDt = global::timeManager.targetDeltaTime(); + const double currentDt = global::timeManager.deltaTime(); std::pair targetDeltaTime; std::pair currentDeltaTime; if (_doSimplification) { @@ -199,10 +199,10 @@ void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { } } - std::string pauseText = OsEng.timeManager().isPaused() ? " (Paused)" : ""; + std::string pauseText = global::timeManager.isPaused() ? " (Paused)" : ""; penPosition.y -= _font->height(); - if (targetDt != currentDt && !OsEng.timeManager().isPaused()) { + if (targetDt != currentDt && !global::timeManager.isPaused()) { // We are in the middle of a transition RenderFont( *_font, @@ -229,7 +229,7 @@ void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { } glm::vec2 DashboardItemSimulationIncrement::size() const { - double t = OsEng.timeManager().targetDeltaTime(); + double t = global::timeManager.targetDeltaTime(); std::pair deltaTime; if (_doSimplification) { deltaTime = simplifyTime(t); diff --git a/modules/base/lightsource/scenegraphlightsource.cpp b/modules/base/lightsource/scenegraphlightsource.cpp index 5d13ebd099..4da2606253 100644 --- a/modules/base/lightsource/scenegraphlightsource.cpp +++ b/modules/base/lightsource/scenegraphlightsource.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -110,14 +110,14 @@ SceneGraphLightSource::SceneGraphLightSource(const ghoul::Dictionary& dictionary _sceneGraphNodeReference.onChange([this]() { _sceneGraphNode = - OsEng.renderEngine().scene()->sceneGraphNode(_sceneGraphNodeReference); + global::renderEngine.scene()->sceneGraphNode(_sceneGraphNodeReference); }); } bool SceneGraphLightSource::initialize() { _sceneGraphNode = - OsEng.renderEngine().scene()->sceneGraphNode(_sceneGraphNodeReference); + global::renderEngine.scene()->sceneGraphNode(_sceneGraphNodeReference); return _sceneGraphNode != nullptr; } diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index 60485523f2..e58068f457 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -256,7 +256,7 @@ void RenderableModel::initializeGL() { _program = BaseModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/model_vs.glsl"), absPath("${MODULE_BASE}/shaders/model_fs.glsl") @@ -281,7 +281,7 @@ void RenderableModel::deinitializeGL() { BaseModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _program = nullptr; diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index c04a1332c9..b662d6c619 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -27,11 +27,10 @@ #include #include #include -#include +#include #include #include #include - #include #include #include @@ -168,7 +167,7 @@ void RenderablePlane::initializeGL() { _shader = BaseModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/plane_vs.glsl"), absPath("${MODULE_BASE}/shaders/plane_fs.glsl") @@ -187,7 +186,7 @@ void RenderablePlane::deinitializeGL() { BaseModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _shader = nullptr; @@ -240,10 +239,10 @@ void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->setUniform("texture1", unit); - bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() == + bool usingFramebufferRenderer = global::renderEngine.rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; - bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() == + bool usingABufferRenderer = global::renderEngine.rendererImplementation() == RenderEngine::RendererImplementation::ABuffer; if (usingABufferRenderer) { diff --git a/modules/base/rendering/renderableplaneimageonline.cpp b/modules/base/rendering/renderableplaneimageonline.cpp index 5c3b61a9a0..58d97e94cf 100644 --- a/modules/base/rendering/renderableplaneimageonline.cpp +++ b/modules/base/rendering/renderableplaneimageonline.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -148,7 +148,7 @@ void RenderablePlaneImageOnline::update(const UpdateData&) { std::future RenderablePlaneImageOnline::downloadImageToMemory(const std::string& url) { - return OsEng.downloadManager().fetchFile( + return global::downloadManager.fetchFile( url, [url](const DownloadManager::MemoryFile&) { LDEBUGC( diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 599ac27a60..141720fc0c 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -244,7 +244,7 @@ void RenderableSphere::initializeGL() { _shader = BaseModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/sphere_vs.glsl"), absPath("${MODULE_BASE}/shaders/sphere_fs.glsl") @@ -263,7 +263,7 @@ void RenderableSphere::deinitializeGL() { BaseModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _shader = nullptr; @@ -322,10 +322,10 @@ void RenderableSphere::render(const RenderData& data, RendererTasks&) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); - bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() == + bool usingFramebufferRenderer = global::renderEngine.rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; - bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() == + bool usingABufferRenderer = global::renderEngine.rendererImplementation() == RenderEngine::RendererImplementation::ABuffer; if (usingABufferRenderer) { diff --git a/modules/base/rendering/renderablesphericalgrid.cpp b/modules/base/rendering/renderablesphericalgrid.cpp index a66b7d57cb..2394b10feb 100644 --- a/modules/base/rendering/renderablesphericalgrid.cpp +++ b/modules/base/rendering/renderablesphericalgrid.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -179,7 +179,7 @@ void RenderableSphericalGrid::initializeGL() { _gridProgram = BaseModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/grid_vs.glsl"), absPath("${MODULE_BASE}/shaders/grid_fs.glsl") @@ -211,7 +211,7 @@ void RenderableSphericalGrid::deinitializeGL() { BaseModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _gridProgram = nullptr; diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index a3f43551f4..7d2c7aba4f 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -234,7 +234,7 @@ void RenderableTrail::initializeGL() { _programObject = BaseModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/renderabletrail_vs.glsl"), absPath("${MODULE_BASE}/shaders/renderabletrail_fs.glsl") @@ -251,7 +251,7 @@ void RenderableTrail::deinitializeGL() { BaseModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _programObject = nullptr; @@ -286,7 +286,7 @@ void RenderableTrail::render(const RenderData& data, RendererTasks&) { }; const bool usingFramebufferRenderer = - OsEng.renderEngine().rendererImplementation() == + global::renderEngine.rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; if (usingFramebufferRenderer) { diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index 791074709c..18bec7b85b 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -26,8 +26,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -70,7 +70,7 @@ int addDashboardItemToScreenSpace(lua_State* L) { return 0; } - ScreenSpaceRenderable* ssr = OsEng.renderEngine().screenSpaceRenderable(name); + ScreenSpaceRenderable* ssr = global::renderEngine.screenSpaceRenderable(name); if (!ssr) { return ghoul::lua::luaError(L, "Provided name is not a ScreenSpace item"); @@ -98,7 +98,7 @@ int removeDashboardItemsFromScreenSpace(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeDashboardItemsFromScreenSpace"); const std::string& name = ghoul::lua::value(L, 1); - ScreenSpaceRenderable* ssr = OsEng.renderEngine().screenSpaceRenderable(name); + ScreenSpaceRenderable* ssr = global::renderEngine.screenSpaceRenderable(name); if (!ssr) { return ghoul::lua::luaError(L, "Provided name is not a ScreenSpace item"); @@ -186,7 +186,7 @@ bool ScreenSpaceDashboard::initializeGL() { glm::vec2 penPosition = glm::vec2(10.f, _size.value().w ); if (_useMainDashboard) { - OsEng.dashboard().render(penPosition); + global::dashboard.render(penPosition); } else { _dashboard.render(penPosition); @@ -209,8 +209,8 @@ bool ScreenSpaceDashboard::isReady() const { } void ScreenSpaceDashboard::update() { - if (OsEng.windowWrapper().windowHasResized()) { - const glm::ivec2 size = OsEng.windowWrapper().currentWindowResolution(); + if (global::windowDelegate.windowHasResized()) { + const glm::ivec2 size = global::windowDelegate.currentWindowResolution(); _size = { 0.f, 0.f, size.x, size.y }; _originalViewportSize = size; createFramebuffer(); diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index e603515871..d2b54915a9 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -25,8 +25,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -77,7 +77,7 @@ ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictiona setGuiName("ScreenSpaceFramebuffer " + std::to_string(iIdentifier)); } - glm::vec2 resolution = OsEng.windowWrapper().currentWindowResolution(); + glm::vec2 resolution = global::windowDelegate.currentWindowResolution(); addProperty(_size); _size.set(glm::vec4(0, 0, resolution.x,resolution.y)); } @@ -103,7 +103,7 @@ bool ScreenSpaceFramebuffer::deinitializeGL() { } void ScreenSpaceFramebuffer::render() { - const glm::vec2& resolution = OsEng.windowWrapper().currentWindowResolution(); + const glm::vec2& resolution = global::windowDelegate.currentWindowResolution(); const glm::vec4& size = _size.value(); const float xratio = _originalViewportSize.x / (size.z - size.x); diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index daecff5142..cb369324f8 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -104,6 +104,12 @@ ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary } } +bool ScreenSpaceImageLocal::deinitializeGL() { + _texture = nullptr; + + return ScreenSpaceRenderable::deinitializeGL(); +} + void ScreenSpaceImageLocal::update() { if (_textureIsDirty && !_texturePath.value().empty()) { std::unique_ptr texture = diff --git a/modules/base/rendering/screenspaceimagelocal.h b/modules/base/rendering/screenspaceimagelocal.h index fbb92c4fcd..39bd4fe89e 100644 --- a/modules/base/rendering/screenspaceimagelocal.h +++ b/modules/base/rendering/screenspaceimagelocal.h @@ -39,6 +39,8 @@ class ScreenSpaceImageLocal : public ScreenSpaceRenderable { public: ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary); + bool deinitializeGL() override; + void update() override; static documentation::Documentation Documentation(); diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index 7f15266a39..df07281059 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -110,6 +110,12 @@ ScreenSpaceImageOnline::ScreenSpaceImageOnline(const ghoul::Dictionary& dictiona ScreenSpaceImageOnline::~ScreenSpaceImageOnline() {} // NOLINT +bool ScreenSpaceImageOnline::deinitializeGL() { + _texture = nullptr; + + return ScreenSpaceRenderable::deinitializeGL(); +} + void ScreenSpaceImageOnline::update() { if (_textureIsDirty) { if (!_imageFuture.valid()) { @@ -161,7 +167,7 @@ void ScreenSpaceImageOnline::update() { std::future ScreenSpaceImageOnline::downloadImageToMemory( const std::string& url) { - return OsEng.downloadManager().fetchFile( + return global::downloadManager.fetchFile( url, [url](const DownloadManager::MemoryFile&) { LDEBUGC( diff --git a/modules/base/rendering/screenspaceimageonline.h b/modules/base/rendering/screenspaceimageonline.h index 2b9d27c97f..ecd98fd15c 100644 --- a/modules/base/rendering/screenspaceimageonline.h +++ b/modules/base/rendering/screenspaceimageonline.h @@ -41,6 +41,8 @@ public: ScreenSpaceImageOnline(const ghoul::Dictionary& dictionary); ~ScreenSpaceImageOnline(); + bool deinitializeGL() override; + void update() override; static documentation::Documentation Documentation(); diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index a64613cd11..8a6289784f 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -26,6 +26,7 @@ #include "cefwebguimodule.h" #include +#include #include #include #include @@ -48,46 +49,39 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary&) { _guiInstance = std::make_shared(new GUIRenderHandler); _guiLocation = OsEng.configuration().cefWebGuiUrl; - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Initialize, - [this]() { - LDEBUGC("WebBrowser", fmt::format("Loading GUI from {}", _guiLocation)); - _guiInstance->loadUrl(_guiLocation); - WebBrowserModule* webBrowserModule = - OsEng.moduleEngine().module(); + global::callback::initialize.push_back([this]() { + LDEBUGC("WebBrowser", fmt::format("Loading GUI from {}", _guiLocation)); + _guiInstance->loadUrl(_guiLocation); + WebBrowserModule* webBrowserModule = + OsEng.moduleEngine().module(); - if (webBrowserModule) { - webBrowserModule->attachEventHandler(_guiInstance); - webBrowserModule->addBrowser(_guiInstance); - } + if (webBrowserModule) { + webBrowserModule->attachEventHandler(_guiInstance); + webBrowserModule->addBrowser(_guiInstance); } - ); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Render, - [this](){ - WindowWrapper& wrapper = OsEng.windowWrapper(); - if (wrapper.isMaster()) { - if (wrapper.windowHasResized()) { - _guiInstance->reshape(wrapper.currentWindowSize()); - } + }); - _guiInstance->draw(); + global::callback::render.push_back([this](){ + WindowWrapper& wrapper = OsEng.windowWrapper(); + if (wrapper.isMaster()) { + if (wrapper.windowHasResized()) { + _guiInstance->reshape(wrapper.currentWindowSize()); } - } - ); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Deinitialize, - [this]() { - _guiInstance->close(true); - WebBrowserModule* webBrowserModule = - OsEng.moduleEngine().module(); - if (webBrowserModule) { - webBrowserModule->removeBrowser(_guiInstance); - } - _guiInstance.reset(); + _guiInstance->draw(); } - ); + }); + + global::callback::deinitialize.push_back()[this]() { + _guiInstance->close(true); + WebBrowserModule* webBrowserModule = + OsEng.moduleEngine().module(); + + if (webBrowserModule) { + webBrowserModule->removeBrowser(_guiInstance); + } + _guiInstance.reset(); + }); } } // namespace openspace diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index b0b4903cb6..2f6842aa09 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -42,7 +42,7 @@ namespace openspace { DebugRenderer* DebugRenderer::_reference = nullptr; DebugRenderer::DebugRenderer() { - _programObject = OsEng.renderEngine().buildRenderProgram( + _programObject = global::renderEngine.buildRenderProgram( "BasicDebugShader", absPath("${MODULE_DEBUGGING}/rendering/debugshader_vs.glsl"), absPath("${MODULE_DEBUGGING}/rendering/debugshader_fs.glsl") diff --git a/modules/debugging/rendering/renderabledebugplane.cpp b/modules/debugging/rendering/renderabledebugplane.cpp index 3d4279a692..3297fc1fb8 100644 --- a/modules/debugging/rendering/renderabledebugplane.cpp +++ b/modules/debugging/rendering/renderabledebugplane.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -189,8 +189,7 @@ void RenderableDebugPlane::initializeGL() { createPlane(); if (!_shader) { - RenderEngine& renderEngine = OsEng.renderEngine(); - _shader = renderEngine.buildRenderProgram("PlaneProgram", + _shader = global::renderEngine.buildRenderProgram("PlaneProgram", absPath("${MODULE_BASE}/shaders/plane_vs.glsl"), absPath("${MODULE_BASE}/shaders/plane_fs.glsl") ); @@ -204,9 +203,8 @@ void RenderableDebugPlane::deinitializeGL() { glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shader) { - renderEngine.removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } } diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index fd7a1ac423..8e2137f466 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -27,9 +27,9 @@ #include #include #include +#include +#include #include -#include -#include #include #include #include @@ -432,7 +432,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di _renderOption.addOption(0, "Camera View Direction"); _renderOption.addOption(1, "Camera Position Normal"); _renderOption.set(1); - if (OsEng.windowWrapper().isFisheyeRendering()) { + if (global::windowDelegate.isFisheyeRendering()) { _renderOption.set(1); } else { @@ -645,7 +645,7 @@ void RenderableBillboardsCloud::initializeGL() { _program = DigitalUniverseModule::ProgramObjectManager.request( ProgramObjectName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramObjectName, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_fs.glsl"), @@ -675,7 +675,7 @@ void RenderableBillboardsCloud::initializeGL() { if (_hasLabel) { if (_font == nullptr) { size_t _fontSize = 50; - _font = OsEng.fontManager().font( + _font = global::fontManager.font( "Mono", static_cast(_fontSize), ghoul::fontrendering::FontManager::Outline::Yes, @@ -694,7 +694,7 @@ void RenderableBillboardsCloud::deinitializeGL() { DigitalUniverseModule::ProgramObjectManager.release( ProgramObjectName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _program = nullptr; @@ -749,7 +749,7 @@ void RenderableBillboardsCloud::renderBillboards(const RenderData& data, const glm::dmat4 projMatrix = glm::dmat4(data.camera.projectionMatrix()); _program->setUniform( "screenSize", - glm::vec2(OsEng.renderEngine().renderingResolution()) + glm::vec2(global::renderEngine.renderingResolution()) ); _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index e60f6b0eae..3c2987d323 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -28,8 +28,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include @@ -275,7 +275,7 @@ RenderableDUMeshes::RenderableDUMeshes(const ghoul::Dictionary& dictionary) _renderOption.addOption(0, "Camera View Direction"); _renderOption.addOption(1, "Camera Position Normal"); - if (OsEng.windowWrapper().isFisheyeRendering()) { + if (global::windowDelegate.isFisheyeRendering()) { _renderOption.set(1); } else { @@ -399,7 +399,7 @@ void RenderableDUMeshes::initializeGL() { _program = DigitalUniverseModule::ProgramObjectManager.request( ProgramObjectName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( "RenderableDUMeshes", absPath("${MODULE_DIGITALUNIVERSE}/shaders/dumesh_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/dumesh_fs.glsl") @@ -419,7 +419,7 @@ void RenderableDUMeshes::initializeGL() { if (_hasLabel) { if (!_font) { constexpr const int FontSize = 50; - _font = OsEng.fontManager().font( + _font = global::fontManager.font( "Mono", static_cast(FontSize), ghoul::fontrendering::FontManager::Outline::Yes, @@ -440,7 +440,7 @@ void RenderableDUMeshes::deinitializeGL() { DigitalUniverseModule::ProgramObjectManager.release( ProgramObjectName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); } diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.cpp b/modules/digitaluniverse/rendering/renderableplanescloud.cpp index c08c058307..05b8585360 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.cpp +++ b/modules/digitaluniverse/rendering/renderableplanescloud.cpp @@ -27,9 +27,9 @@ #include #include #include -#include -#include +#include #include +#include #include #include #include @@ -494,7 +494,7 @@ void RenderablePlanesCloud::initializeGL() { _program = DigitalUniverseModule::ProgramObjectManager.request( ProgramObjectName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( "RenderablePlanesCloud", absPath("${MODULE_DIGITALUNIVERSE}/shaders/plane_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/plane_fs.glsl") @@ -511,7 +511,7 @@ void RenderablePlanesCloud::initializeGL() { if (_hasLabel) { if (!_font) { constexpr const int FontSize = 30; - _font = OsEng.fontManager().font( + _font = global::fontManager.font( "Mono", static_cast(FontSize), ghoul::fontrendering::FontManager::Outline::Yes, @@ -537,7 +537,7 @@ void RenderablePlanesCloud::deinitializeGL() { DigitalUniverseModule::ProgramObjectManager.release( ProgramObjectName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); } diff --git a/modules/digitaluniverse/rendering/renderablepoints.cpp b/modules/digitaluniverse/rendering/renderablepoints.cpp index 30b6d5caa8..750021eee5 100644 --- a/modules/digitaluniverse/rendering/renderablepoints.cpp +++ b/modules/digitaluniverse/rendering/renderablepoints.cpp @@ -27,21 +27,21 @@ #include #include #include -#include -#include +#include #include +#include #include #include -#include #include #include +#include #include #include #include #include #include -#include #include +#include #include namespace { @@ -269,7 +269,7 @@ void RenderablePoints::initializeGL() { _program = DigitalUniverseModule::ProgramObjectManager.request( "RenderablePoints Sprite", []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( "RenderablePoints Sprite", absPath("${MODULE_DIGITALUNIVERSE}/shaders/points_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/points_sprite_fs.glsl") @@ -281,7 +281,7 @@ void RenderablePoints::initializeGL() { _program = DigitalUniverseModule::ProgramObjectManager.request( "RenderablePoints", []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( "RenderablePoints", absPath("${MODULE_DIGITALUNIVERSE}/shaders/points_vs.glsl"), absPath("${MODULE_DIGITALUNIVERSE}/shaders/points_sprite_fs.glsl") @@ -301,7 +301,7 @@ void RenderablePoints::deinitializeGL() { DigitalUniverseModule::ProgramObjectManager.release( _program->name(), [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); diff --git a/modules/fieldlines/rendering/renderablefieldlines.cpp b/modules/fieldlines/rendering/renderablefieldlines.cpp index 11ea853e6d..2707f5a232 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.cpp +++ b/modules/fieldlines/rendering/renderablefieldlines.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -200,7 +200,7 @@ void RenderableFieldlines::initializeGL() { throw ghoul::RuntimeError("Error initializing"); } - _program = OsEng.renderEngine().buildRenderProgram( + _program = global::renderEngine.buildRenderProgram( "Fieldline", absPath("${MODULE_FIELDLINES}/shaders/fieldline_vs.glsl"), absPath("${MODULE_FIELDLINES}/shaders/fieldline_fs.glsl"), @@ -214,9 +214,8 @@ void RenderableFieldlines::deinitializeGL() { glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_program) { - renderEngine.removeRenderProgram(_program.get()); + global::renderEngine.removeRenderProgram(_program.get()); _program = nullptr; } } diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index 2414cf829d..5ea3a24486 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -26,8 +26,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -347,7 +347,7 @@ void RenderableFieldlinesSequence::initializeGL() { setupProperties(); // Setup shader program - _shaderProgram = OsEng.renderEngine().buildRenderProgram( + _shaderProgram = global::renderEngine.buildRenderProgram( "FieldlinesSequence", absPath("${MODULE_FIELDLINESSEQUENCE}/shaders/fieldlinessequence_vs.glsl"), absPath("${MODULE_FIELDLINESSEQUENCE}/shaders/fieldlinessequence_fs.glsl") @@ -756,19 +756,19 @@ void RenderableFieldlinesSequence::definePropertyCallbackFunctions() { } _pFocusOnOriginBtn.onChange([this] { - SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(_identifier); + SceneGraphNode* node = global::renderEngine.scene()->sceneGraphNode(_identifier); if (!node) { LWARNING(fmt::format( "Could not find a node in scenegraph called '{}'", _identifier )); return; } - OsEng.navigationHandler().setFocusNode(node->parent()); - OsEng.navigationHandler().resetCameraDirection(); + global::navigationHandler.setFocusNode(node->parent()); + global::navigationHandler.resetCameraDirection(); }); _pJumpToStartBtn.onChange([this] { - OsEng.timeManager().setTimeNextFrame(_startTimes[0]); + global::timeManager.setTimeNextFrame(_startTimes[0]); }); } @@ -1023,9 +1023,8 @@ void RenderableFieldlinesSequence::deinitializeGL() { glDeleteBuffers(1, &_vertexMaskingBuffer); _vertexMaskingBuffer = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shaderProgram) { - renderEngine.removeRenderProgram(_shaderProgram.get()); + global::renderEngine.removeRenderProgram(_shaderProgram.get()); _shaderProgram = nullptr; } @@ -1090,12 +1089,12 @@ void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks& _shaderProgram->setUniform("particleSpeed", _pFlowSpeed); _shaderProgram->setUniform( "time", - OsEng.windowWrapper().applicationTime() * (_pFlowReversed ? -1 : 1) + global::windowDelegate.applicationTime() * (_pFlowReversed ? -1 : 1) ); bool additiveBlending = false; if (_pColorABlendEnabled) { - const auto renderer = OsEng.renderEngine().rendererImplementation(); + const auto renderer = global::renderEngine.rendererImplementation(); const bool usingFBufferRenderer = renderer == RenderEngine::RendererImplementation::Framebuffer; diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 66e5ce737e..5ffcc79942 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -25,33 +25,25 @@ #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 +#include #include #include - -#include - +#include #include - namespace { constexpr const char* GlslRayCastPath = "${MODULES}/toyvolume/shaders/rayCast.glsl"; constexpr const char* GlslBoundsVsPath = "${MODULES}/toyvolume/shaders/boundsVs.glsl"; @@ -175,14 +167,14 @@ void RenderableGalaxy::initializeGL() { _raycaster = std::make_unique(*_texture); _raycaster->initialize(); - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); auto onChange = [&](bool enabled) { if (enabled) { - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); } else { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); } }; @@ -250,8 +242,7 @@ void RenderableGalaxy::initializeGL() { GL_STATIC_DRAW ); - RenderEngine& renderEngine = OsEng.renderEngine(); - _pointsProgram = renderEngine.buildRenderProgram( + _pointsProgram = global::renderEngine.buildRenderProgram( "Galaxy points", absPath("${MODULE_GALAXY}/shaders/points.vs"), absPath("${MODULE_GALAXY}/shaders/points.fs") @@ -278,7 +269,7 @@ void RenderableGalaxy::initializeGL() { void RenderableGalaxy::deinitializeGL() { if (_raycaster) { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); _raycaster = nullptr; } } diff --git a/modules/globebrowsing/dashboard/dashboarditemglobelocation.cpp b/modules/globebrowsing/dashboard/dashboarditemglobelocation.cpp index fbf9728ae7..262206fa22 100644 --- a/modules/globebrowsing/dashboard/dashboarditemglobelocation.cpp +++ b/modules/globebrowsing/dashboard/dashboarditemglobelocation.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -116,7 +116,7 @@ DashboardItemGlobeLocation::DashboardItemGlobeLocation( : DashboardItem(dictionary) , _fontName(FontNameInfo, KeyFontMono) , _fontSize(FontSizeInfo, DefaultFontSize, 6.f, 144.f, 1.f) - , _font(OsEng.fontManager().font(KeyFontMono, 10)) + , _font(global::fontManager.font(KeyFontMono, 10)) { documentation::testSpecificationAndThrow( Documentation(), @@ -132,30 +132,30 @@ DashboardItemGlobeLocation::DashboardItemGlobeLocation( } _fontName.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); _fontSize.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemGlobeLocation::render(glm::vec2& penPosition) { using namespace globebrowsing; - SceneGraphNode* n = OsEng.navigationHandler().focusNode(); + SceneGraphNode* n = global::navigationHandler.focusNode(); const RenderableGlobe* globe = dynamic_cast(n->renderable()); if (!globe) { return; } - const glm::dvec3 cameraPosition = OsEng.navigationHandler().camera()->positionVec3(); + const glm::dvec3 cameraPosition = global::navigationHandler.camera()->positionVec3(); const glm::dmat4 inverseModelTransform = - OsEng.navigationHandler().focusNode()->inverseModelTransform(); + global::navigationHandler.focusNode()->inverseModelTransform(); const glm::dvec3 cameraPositionModelSpace = glm::dvec3(inverseModelTransform * glm::dvec4(cameraPosition, 1.0)); const SurfacePositionHandle posHandle = globe->calculateSurfacePositionHandle( diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index d77f6702d9..abd78cc7e3 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -130,49 +131,31 @@ namespace openspace { GlobeBrowsingModule::GlobeBrowsingModule() : OpenSpaceModule(Name) {} void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary&) { - // TODO: Remove dependency on OsEng. - // Instead, make this class implement an interface that OsEng depends on. - // Do not try to register module callbacks if OsEng does not exist, - // for example in the TaskRunner. - - if (!OpenSpaceEngine::isCreated()) { - return; - } - using namespace globebrowsing; // Initialize - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Initialize, - [&]() { - _tileCache = std::make_unique(); - addPropertySubOwner(*_tileCache); + global::callback::initializeGL.push_back([&]() { + _tileCache = std::make_unique(); + addPropertySubOwner(*_tileCache); + #ifdef GLOBEBROWSING_USE_GDAL - // Convert from MB to Bytes - GdalWrapper::create( - 16ULL * 1024ULL * 1024ULL, // 16 MB - static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024) - ); - addPropertySubOwner(GdalWrapper::ref()); + // Convert from MB to Bytes + GdalWrapper::create( + 16ULL * 1024ULL * 1024ULL, // 16 MB + static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024) + ); + addPropertySubOwner(GdalWrapper::ref()); #endif // GLOBEBROWSING_USE_GDAL - } - ); + }); + // Render - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Render, - [&]() { _tileCache->update(); } - ); + global::callback::render.push_back([&]() { _tileCache->update(); }); // Deinitialize - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Deinitialize, - [&]() { #ifdef GLOBEBROWSING_USE_GDAL - GdalWrapper::ref().destroy(); + global::callback::deinitialize.push_back([&]() { GdalWrapper::ref().destroy(); }); #endif // GLOBEBROWSING_USE_GDAL - } - ); // Get factories auto fRenderable = FactoryManager::ref().factory(); @@ -331,13 +314,13 @@ scripting::LuaLibrary GlobeBrowsingModule::luaLibrary() const { } void GlobeBrowsingModule::goToChunk(int x, int y, int level) { - Camera* cam = OsEng.navigationHandler().camera(); + Camera* cam = global::navigationHandler.camera(); goToChunk(*cam, globebrowsing::TileIndex(x,y,level), glm::vec2(0.5f, 0.5f), true); } void GlobeBrowsingModule::goToGeo(double latitude, double longitude) { using namespace globebrowsing; - Camera* cam = OsEng.navigationHandler().camera(); + Camera* cam = global::navigationHandler.camera(); goToGeodetic2(*cam, Geodetic2( Angle::fromDegrees(latitude).asRadians(), Angle::fromDegrees(longitude).asRadians()), true); @@ -348,7 +331,7 @@ void GlobeBrowsingModule::goToGeo(double latitude, double longitude, { using namespace globebrowsing; - Camera* cam = OsEng.navigationHandler().camera(); + Camera* cam = global::navigationHandler.camera(); goToGeodetic3( *cam, { @@ -427,9 +410,9 @@ void GlobeBrowsingModule::goToGeodetic2(Camera& camera, globebrowsing::Geodetic2 return; } - const glm::dvec3 cameraPosition = OsEng.navigationHandler().camera()->positionVec3(); + const glm::dvec3 cameraPosition = global::navigationHandler.camera()->positionVec3(); const glm::dmat4 inverseModelTransform = - OsEng.navigationHandler().focusNode()->inverseModelTransform(); + global::navigationHandler.focusNode()->inverseModelTransform(); const glm::dvec3 cameraPositionModelSpace = glm::dvec3(inverseModelTransform * glm::dvec4(cameraPosition, 1.0)); const SurfacePositionHandle posHandle = globe->calculateSurfacePositionHandle( @@ -512,7 +495,7 @@ GlobeBrowsingModule::castFocusNodeRenderableToGlobe() { using namespace globebrowsing; - const Renderable* renderable = OsEng.navigationHandler().focusNode()->renderable(); + const Renderable* renderable = global::navigationHandler.focusNode()->renderable(); if (!renderable) { return nullptr; } diff --git a/modules/globebrowsing/globebrowsingmodule_lua.inl b/modules/globebrowsing/globebrowsingmodule_lua.inl index d852355160..746fdb0017 100644 --- a/modules/globebrowsing/globebrowsingmodule_lua.inl +++ b/modules/globebrowsing/globebrowsingmodule_lua.inl @@ -28,8 +28,8 @@ #include #include -#include #include +#include #include #include #include @@ -52,7 +52,7 @@ int addLayer(lua_State* L) { const std::string& layerGroupName = ghoul::lua::value(L, 2); // Get the node and make sure it exists - SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode(globeName); + SceneGraphNode* n = global::renderEngine.scene()->sceneGraphNode(globeName); if (!n) { return ghoul::lua::luaError(L, "Unknown globe name: " + globeName); } @@ -102,7 +102,7 @@ int deleteLayer(lua_State* L) { lua_pop(L, 3); // Get the node and make sure it exists - SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode(globeName); + SceneGraphNode* n = global::renderEngine.scene()->sceneGraphNode(globeName); if (!n) { return ghoul::lua::luaError(L, "Unknown globe name: " + globeName); } @@ -133,7 +133,7 @@ int goToChunk(lua_State* L) { const int level = ghoul::lua::value(L, 3); lua_pop(L, 3); - OsEng.moduleEngine().module()->goToChunk(x, y, level); + global::moduleEngine.module()->goToChunk(x, y, level); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -146,11 +146,11 @@ int goToGeo(lua_State* L) { const double longitude = ghoul::lua::value(L, 2); if (nArguments == 2) { - OsEng.moduleEngine().module()->goToGeo(latitude, longitude); + global::moduleEngine.module()->goToGeo(latitude, longitude); } else if (nArguments == 3) { const double altitude = ghoul::lua::value(L, 3); - OsEng.moduleEngine().module()->goToGeo( + global::moduleEngine.module()->goToGeo( latitude, longitude, altitude @@ -181,7 +181,7 @@ int getGeoPosition(lua_State* L) { return ghoul::lua::luaError(L, "Name must be a RenderableGlobe"); } - GlobeBrowsingModule& mod = *(OsEng.moduleEngine().module()); + GlobeBrowsingModule& mod = *(global::moduleEngine.module()); glm::vec3 pos = mod.cartesianCoordinatesFromGeo( *globe, latitude, @@ -198,15 +198,15 @@ int getGeoPosition(lua_State* L) { int getGeoPositionForCamera(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::getGeoPositionForCamera"); - GlobeBrowsingModule* module = OsEng.moduleEngine().module(); + GlobeBrowsingModule* module = global::moduleEngine.module(); const RenderableGlobe* globe = module->castFocusNodeRenderableToGlobe(); if (!globe) { return ghoul::lua::luaError(L, "Focus node must be a RenderableGlobe"); } - const glm::dvec3 cameraPosition = OsEng.navigationHandler().camera()->positionVec3(); + const glm::dvec3 cameraPosition = global::navigationHandler.camera()->positionVec3(); const glm::dmat4 inverseModelTransform = - OsEng.navigationHandler().focusNode()->inverseModelTransform(); + global::navigationHandler.focusNode()->inverseModelTransform(); const glm::dvec3 cameraPositionModelSpace = glm::dvec3(inverseModelTransform * glm::dvec4(cameraPosition, 1.0)); const SurfacePositionHandle posHandle = globe->calculateSurfacePositionHandle( @@ -238,7 +238,7 @@ int loadWMSCapabilities(lua_State* L) { std::string globe = ghoul::lua::value(L, 2); std::string url = ghoul::lua::value(L, 3); - OsEng.moduleEngine().module()->loadWMSCapabilities( + global::moduleEngine.module()->loadWMSCapabilities( std::move(name), std::move(globe), std::move(url) @@ -259,7 +259,7 @@ int removeWMSServer(lua_State* L) { ghoul::lua::PopValue::Yes ); - OsEng.moduleEngine().module()->removeWMSServer(name); + global::moduleEngine.module()->removeWMSServer(name); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -274,7 +274,7 @@ int capabilities(lua_State* L) { ghoul::lua::PopValue::Yes ); GlobeBrowsingModule::Capabilities cap = - OsEng.moduleEngine().module()->capabilities(name); + global::moduleEngine.module()->capabilities(name); lua_newtable(L); for (unsigned long i = 0; i < cap.size(); ++i) { diff --git a/modules/globebrowsing/globes/pointglobe.cpp b/modules/globebrowsing/globes/pointglobe.cpp index 49254778f6..a408c7ff93 100644 --- a/modules/globebrowsing/globes/pointglobe.cpp +++ b/modules/globebrowsing/globes/pointglobe.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -67,7 +67,7 @@ PointGlobe::~PointGlobe() { } void PointGlobe::initialize() { - _programObject = OsEng.renderEngine().buildRenderProgram( + _programObject = global::renderEngine.buildRenderProgram( "PointGlobe", absPath("${MODULE_GLOBEBROWSING}/shaders/pointglobe_vs.glsl"), absPath("${MODULE_GLOBEBROWSING}/shaders/pointglobe_fs.glsl") diff --git a/modules/globebrowsing/rendering/layershadermanager.cpp b/modules/globebrowsing/rendering/layershadermanager.cpp index 98fd6ae5f6..124c45c12e 100644 --- a/modules/globebrowsing/rendering/layershadermanager.cpp +++ b/modules/globebrowsing/rendering/layershadermanager.cpp @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include #include @@ -141,8 +141,7 @@ LayerShaderManager::LayerShaderManager(std::string shaderName, std::string vsPat LayerShaderManager::~LayerShaderManager() { if (_programObject) { - RenderEngine& renderEngine = OsEng.renderEngine(); - renderEngine.removeRenderProgram(_programObject.get()); + global::renderEngine.removeRenderProgram(_programObject.get()); _programObject = nullptr; } } @@ -231,9 +230,9 @@ void LayerShaderManager::recompileShaderProgram( } // Remove old program - OsEng.renderEngine().removeRenderProgram(_programObject.get()); + global::renderEngine.removeRenderProgram(_programObject.get()); - _programObject = OsEng.renderEngine().buildRenderProgram( + _programObject = global::renderEngine.buildRenderProgram( _shaderName, absPath(_vsPath), absPath(_fsPath), diff --git a/modules/globebrowsing/tile/asynctiledataprovider.cpp b/modules/globebrowsing/tile/asynctiledataprovider.cpp index 44e758270c..e41f1b3574 100644 --- a/modules/globebrowsing/tile/asynctiledataprovider.cpp +++ b/modules/globebrowsing/tile/asynctiledataprovider.cpp @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include @@ -46,7 +46,7 @@ AsyncTileDataProvider::AsyncTileDataProvider(std::string name, , _rawTileDataReader(std::move(rawTileDataReader)) , _concurrentJobManager(LRUThreadPool(1, 10)) { - _globeBrowsingModule = OsEng.moduleEngine().module(); + _globeBrowsingModule = global::moduleEngine.module(); performReset(ResetRawTileDataReader::No); } diff --git a/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp b/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp index 983fbd1f01..3b9deaed67 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp @@ -26,8 +26,8 @@ #include -#include #include +#include #include #include @@ -131,12 +131,12 @@ GdalWrapper::GdalWrapper(size_t maximumCacheSize, size_t maximumMaximumCacheSize } void GdalWrapper::setGdalProxyConfiguration() { - if (OsEng.configuration().httpProxy.usingHttpProxy) { - const std::string address = OsEng.configuration().httpProxy.address; - const unsigned int port = OsEng.configuration().httpProxy.port; - const std::string user = OsEng.configuration().httpProxy.user; - const std::string password = OsEng.configuration().httpProxy.password; - std::string auth = OsEng.configuration().httpProxy.authentication; + if (global::configuration.httpProxy.usingHttpProxy) { + const std::string address = global::configuration.httpProxy.address; + const unsigned int port = global::configuration.httpProxy.port; + const std::string user = global::configuration.httpProxy.user; + const std::string password = global::configuration.httpProxy.password; + std::string auth = global::configuration.httpProxy.authentication; std::transform( auth.begin(), auth.end(), diff --git a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp index dbf83b9f72..8b446d8a48 100644 --- a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include @@ -64,7 +64,7 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) , _filePath(FilePathInfo, "") , _tilePixelSize(TilePixelSizeInfo, 32, 32, 2048) { - _tileCache = OsEng.moduleEngine().module()->tileCache(); + _tileCache = global::moduleEngine.module()->tileCache(); _name = "Name unspecified"; dictionary.getValue("Name", _name); std::string _loggerCat = "DefaultTileProvider : " + _name; diff --git a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp index 974d521077..5b93b6e325 100644 --- a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -48,7 +48,7 @@ SizeReferenceTileProvider::SizeReferenceTileProvider(const ghoul::Dictionary& di ) { _fontSize = 50; - _font = OsEng.fontManager().font("Mono", static_cast(_fontSize)); + _font = global::fontManager.font("Mono", static_cast(_fontSize)); if (dictionary.hasKeyAndValue(KeyRadii)) { _ellipsoid = dictionary.value(KeyRadii); diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp index 2553faf884..b9fcb14cf5 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include #include @@ -302,7 +302,7 @@ void TemporalTileProvider::ensureUpdated() { void TemporalTileProvider::update() { if (_successfulInitialization) { std::shared_ptr newCurrent = getTileProvider( - OsEng.timeManager().time() + global::timeManager.time() ); if (newCurrent) { _currentTileProvider = newCurrent; diff --git a/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp b/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp index 0c0906ef1d..6c34b18889 100644 --- a/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/texttileprovider.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include @@ -45,7 +45,7 @@ TextTileProvider::TextTileProvider(const TileTextureInitData& initData, size_t f : _initData(initData) , _fontSize(fontSize) { - _tileCache = OsEng.moduleEngine().module()->tileCache(); + _tileCache = global::moduleEngine.module()->tileCache(); } TextTileProvider::~TextTileProvider() {} // NOLINT @@ -53,7 +53,7 @@ TextTileProvider::~TextTileProvider() {} // NOLINT bool TextTileProvider::initialize() { bool res = TileProvider::initialize(); - _font = OsEng.fontManager().font("Mono", static_cast(_fontSize)); + _font = global::fontManager.font("Mono", static_cast(_fontSize)); _fontRenderer = FontRenderer::createDefault(); _fontRenderer->setFramebufferSize(glm::vec2(_initData.dimensions())); diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index 0fc6667b21..36116fc7f2 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -24,9 +24,10 @@ #include -#include +#include +#include #include -#include +#include #include #include #include @@ -41,164 +42,139 @@ namespace openspace { ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { addPropertySubOwner(gui); - // TODO: Remove dependency on OsEng. - // Instead, make this class implement an interface that OsEng depends on. - // Do not try to register module callbacks if OsEng does not exist, - // for example in the TaskRunner. + global::callback::initialize.push_back([&]() { + LDEBUGC("ImGUIModule", "Initializing GUI"); + gui.initialize(); - if (!OpenSpaceEngine::isCreated()) { - return; - } - - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Initialize, - [&](){ - LDEBUGC("ImGUIModule", "Initializing GUI"); - gui.initialize(); - - gui._globalProperty.setSource( - []() { - std::vector res = { - &(OsEng.windowWrapper()), - &(OsEng.navigationHandler()), - &(OsEng.timeManager()), - &(OsEng.renderEngine()), - &(OsEng.parallelPeer()), - &(OsEng.console()), - &(OsEng.dashboard()) - }; - return res; - } - ); - - gui._screenSpaceProperty.setSource( - []() { - return OsEng.renderEngine().screenSpaceOwner().propertySubOwners(); - } - ); - - gui._moduleProperty.setSource( - []() { - std::vector v; - v.push_back(&(OsEng.moduleEngine())); - return v; - } - ); - - gui._sceneProperty.setSource( - []() { - const Scene* scene = OsEng.renderEngine().scene(); - const std::vector& nodes = scene ? - scene->allSceneGraphNodes() : - std::vector(); - - return std::vector( - nodes.begin(), - nodes.end() - ); - } - ); - - gui._virtualProperty.setSource( - []() { - std::vector res = { - &(OsEng.virtualPropertyManager()) - }; - - return res; - } - ); - - gui._featuredProperties.setSource( - [](){ - std::vector nodes = - OsEng.renderEngine().scene()->allSceneGraphNodes(); - - nodes.erase( - std::remove_if( - nodes.begin(), - nodes.end(), - [](SceneGraphNode* n) { - const std::vector& tags = n->tags(); - const auto it = std::find( - tags.begin(), - tags.end(), - "GUI.Interesting" - ); - return it == tags.end(); - } - ), - nodes.end() - ); - return std::vector( - nodes.begin(), - nodes.end() - ); - } - ); + gui._globalProperty.setSource( + []() { + std::vector res = { + &global::navigationHandler, + &global::timeManager, + &global::renderEngine, + &global::parallelPeer, + &global::luaConsole, + &global::dashboard + }; + return res; } - ); + ); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Deinitialize, - [&](){ - LDEBUGC("ImGui", "Deinitialize GUI"); - gui.deinitialize(); + gui._screenSpaceProperty.setSource( + []() { + return global::screenSpaceRootPropertyOwner.propertySubOwners(); } - ); + ); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::InitializeGL, - [&](){ - LDEBUGC("ImGui", "Initializing GUI OpenGL"); - gui.initializeGL(); + gui._moduleProperty.setSource( + []() { + std::vector v; + v.push_back(&(global::moduleEngine)); + return v; } - ); + ); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::DeinitializeGL, - [&](){ - LDEBUGC("ImGui", "Deinitialize GUI OpenGL"); - gui.deinitializeGL(); - } - ); + gui._sceneProperty.setSource( + []() { + const Scene* scene = global::renderEngine.scene(); + const std::vector& nodes = scene ? + scene->allSceneGraphNodes() : + std::vector(); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Draw2D, - [&]() { - // TODO emiax: Make sure this is only called for one of the eyes, in the case - // of side-by-side / top-bottom stereo. - - WindowWrapper& wrapper = OsEng.windowWrapper(); - const bool showGui = wrapper.hasGuiWindow() ? wrapper.isGuiWindow() : true; - if (wrapper.isMaster() && showGui) { - const glm::ivec2 windowSize = wrapper.currentWindowSize(); - const glm::ivec2 resolution = wrapper.currentWindowResolution(); - - glm::vec2 mousePosition = wrapper.mousePosition(); - uint32_t mouseButtons = wrapper.mouseButtons(2); - - const double dt = std::max(wrapper.averageDeltaTime(), 0.0); - if (touchInput.active && mouseButtons == 0) { - mouseButtons = touchInput.action; - mousePosition = touchInput.pos; - } - // We don't do any collection of immediate mode user interface, so it - // is fine to open and close a frame immediately - gui.startFrame( - static_cast(dt), - glm::vec2(windowSize), - resolution / windowSize, - mousePosition, - mouseButtons + return std::vector( + nodes.begin(), + nodes.end() ); - - gui.endFrame(); - } } - ); + ); - OsEng.registerModuleKeyboardCallback( + gui._virtualProperty.setSource( + []() { + std::vector res = { + &global::virtualPropertyManager + }; + + return res; + } + ); + + gui._featuredProperties.setSource( + []() { + std::vector nodes = + global::renderEngine.scene()->allSceneGraphNodes(); + + nodes.erase( + std::remove_if( + nodes.begin(), + nodes.end(), + [](SceneGraphNode* n) { + const std::vector& tags = n->tags(); + const auto it = std::find( + tags.begin(), + tags.end(), + "GUI.Interesting" + ); + return it == tags.end(); + } + ), + nodes.end() + ); + return std::vector( + nodes.begin(), + nodes.end() + ); + } + ); + }); + + global::callback::deinitialize.push_back([&]() { + LDEBUGC("ImGui", "Deinitialize GUI"); + gui.deinitialize(); + }); + + global::callback::initializeGL.push_back([&]() { + LDEBUGC("ImGui", "Initializing GUI OpenGL"); + gui.initializeGL(); + }); + + global::callback::deinitializeGL.push_back([&]() { + LDEBUGC("ImGui", "Deinitialize GUI OpenGL"); + gui.deinitializeGL(); + }); + + global::callback::draw2D.push_back([&]() { + // TODO emiax: Make sure this is only called for one of the eyes, in the case + // of side-by-side / top-bottom stereo. + + WindowDelegate& delegate = global::windowDelegate; + const bool showGui = delegate.hasGuiWindow() ? delegate.isGuiWindow() : true; + if (delegate.isMaster() && showGui) { + const glm::ivec2 windowSize = delegate.currentWindowSize(); + const glm::ivec2 resolution = delegate.currentWindowResolution(); + + glm::vec2 mousePosition = delegate.mousePosition(); + uint32_t mouseButtons = delegate.mouseButtons(2); + + const double dt = std::max(delegate.averageDeltaTime(), 0.0); + if (touchInput.active && mouseButtons == 0) { + mouseButtons = touchInput.action; + mousePosition = touchInput.pos; + } + // We don't do any collection of immediate mode user interface, so it + // is fine to open and close a frame immediately + gui.startFrame( + static_cast(dt), + glm::vec2(windowSize), + resolution / windowSize, + mousePosition, + mouseButtons + ); + + gui.endFrame(); + } + }); + + global::callback::keyboard.push_back( [&](Key key, KeyModifier mod, KeyAction action) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -212,7 +188,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - OsEng.registerModuleCharCallback( + global::callback::character.push_back( [&](unsigned int codepoint, KeyModifier modifier) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -226,7 +202,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - OsEng.registerModuleMouseButtonCallback( + global::callback::mouseButton.push_back( [&](MouseButton button, MouseAction action) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -240,7 +216,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - OsEng.registerModuleMouseScrollWheelCallback( + global::callback::mouseScrollWheel.push_back( [&](double, double posY) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || diff --git a/modules/imgui/src/gui.cpp b/modules/imgui/src/gui.cpp index c498e5dd9b..5d091b0b17 100644 --- a/modules/imgui/src/gui.cpp +++ b/modules/imgui/src/gui.cpp @@ -26,16 +26,15 @@ #include #include -#include -#include +#include +#include #include -#include +#include #include #include #include #include #include -#include #include #include #include @@ -47,7 +46,7 @@ namespace { constexpr const char* configurationFile = "imgui.ini"; constexpr const char* GuiFont = "${FONTS}/arimo/Arimo-Regular.ttf"; constexpr const float FontSize = 14.f; - const ImVec2 Size = ImVec2(500, 500); + const glm::vec2 Size = { 500.f, 500.f }; char* iniFileBuffer = nullptr; @@ -61,7 +60,7 @@ namespace { return; } - OsEng.scriptEngine().queueScript( + openspace::global::scriptEngine.queueScript( fmt::format( "openspace.addScreenSpaceRenderable({{\ Type = 'ScreenSpaceImageLocal',\ @@ -74,7 +73,7 @@ namespace { } void addScreenSpaceRenderableOnline(std::string texturePath) { - OsEng.scriptEngine().queueScript( + openspace::global::scriptEngine.queueScript( fmt::format( "openspace.addScreenSpaceRenderable({{\ Type = 'ScreenSpaceImageOnline', URL = '{}'\ @@ -184,7 +183,7 @@ void GUI::initialize() { strcpy(iniFileBuffer, cachedFile.c_str()); #endif - int nWindows = OsEng.windowWrapper().nWindows(); + int nWindows = global::windowDelegate.nWindows(); _contexts.resize(nWindows); for (int i = 0; i < nWindows; ++i) { @@ -192,7 +191,7 @@ void GUI::initialize() { ImGui::SetCurrentContext(_contexts[i]); ImGuiIO& io = ImGui::GetIO(); - io.IniFilename = cachedFile.c_str(); + io.IniFilename = iniFileBuffer; io.DeltaTime = 1.f / 60.f; io.KeyMap[ImGuiKey_Tab] = static_cast(Key::Tab); io.KeyMap[ImGuiKey_LeftArrow] = static_cast(Key::Left); @@ -290,7 +289,7 @@ void GUI::initialize() { void GUI::deinitialize() { ImGui::Shutdown(); - int nWindows = OsEng.windowWrapper().nWindows(); + int nWindows = global::windowDelegate.nWindows(); for (int i = 0; i < nWindows; ++i) { ImGui::DestroyContext(_contexts[i]); } @@ -311,7 +310,7 @@ void GUI::initializeGL() { ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); - int nWindows = OsEng.windowWrapper().nWindows(); + int nWindows = global::windowDelegate.nWindows(); { unsigned char* texData; glm::ivec2 texSize; @@ -400,7 +399,7 @@ void GUI::startFrame(float deltaTime, const glm::vec2& windowSize, const glm::vec2& dpiScaling, const glm::vec2& mousePos, uint32_t mouseButtonsPressed) { - const int iWindow = OsEng.windowWrapper().currentWindowId(); + const int iWindow = global::windowDelegate.currentWindowId(); ImGui::SetCurrentContext(_contexts[iWindow]); ImGuiIO& io = ImGui::GetIO(); @@ -422,7 +421,7 @@ void GUI::endFrame() { ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); } - _performance.setEnabled(OsEng.renderEngine().doesPerformanceMeasurements()); + _performance.setEnabled(global::performanceManager.isEnabled()); if (_performance.isEnabled()) { _performance.render(); @@ -653,7 +652,7 @@ void GUI::render() { bool addDashboard = ImGui::Button("Add New Dashboard"); if (addDashboard) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.addScreenSpaceRenderable({ Type = 'ScreenSpaceDashboard' });", openspace::scripting::ScriptEngine::RemoteScripting::Yes ); @@ -661,7 +660,7 @@ void GUI::render() { bool addDashboardCopy = ImGui::Button("Add Copy of Main Dashboard"); if (addDashboardCopy) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.addScreenSpaceRenderable({ " "Type = 'ScreenSpaceDashboard', UseMainDashboard = true " "});", diff --git a/modules/imgui/src/guiassetcomponent.cpp b/modules/imgui/src/guiassetcomponent.cpp index e63a01bc60..56f7e8d412 100644 --- a/modules/imgui/src/guiassetcomponent.cpp +++ b/modules/imgui/src/guiassetcomponent.cpp @@ -26,6 +26,7 @@ #include +#include #include #include #include @@ -74,7 +75,7 @@ void GuiAssetComponent::render() { ImGui::Begin("Assets", &e); _isEnabled = e; - AssetManager& assetManager = OsEng.assetManager(); + AssetManager& assetManager = global::openSpaceEngine.assetManager(); std::string rootPath; diff --git a/modules/imgui/src/guiglobebrowsingcomponent.cpp b/modules/imgui/src/guiglobebrowsingcomponent.cpp index 14fd0d7c02..11c0ccef86 100644 --- a/modules/imgui/src/guiglobebrowsingcomponent.cpp +++ b/modules/imgui/src/guiglobebrowsingcomponent.cpp @@ -28,8 +28,8 @@ #include #include +#include #include -#include #include #include #include @@ -50,7 +50,7 @@ GuiGlobeBrowsingComponent::GuiGlobeBrowsingComponent() {} void GuiGlobeBrowsingComponent::render() { - GlobeBrowsingModule* module = OsEng.moduleEngine().module(); + GlobeBrowsingModule* module = global::moduleEngine.module(); using UrlInfo = GlobeBrowsingModule::UrlInfo; using Capabilities = GlobeBrowsingModule::Capabilities; using Layer = GlobeBrowsingModule::Layer; @@ -66,7 +66,7 @@ void GuiGlobeBrowsingComponent::render() { // Render the list of planets std::vector nodes = - OsEng.renderEngine().scene()->allSceneGraphNodes(); + global::renderEngine.scene()->allSceneGraphNodes(); nodes.erase( std::remove_if( @@ -124,7 +124,7 @@ void GuiGlobeBrowsingComponent::render() { // node // Check if the focus node is a RenderableGlobe - const SceneGraphNode* const focus = OsEng.navigationHandler().focusNode(); + const SceneGraphNode* const focus = global::navigationHandler.focusNode(); const auto it = std::find(nodes.cbegin(), nodes.cend(), focus); if (it != nodes.end()) { _currentNode = focus->identifier(); @@ -147,7 +147,7 @@ void GuiGlobeBrowsingComponent::render() { ImGui::SameLine(); bool selectFocusNode = ImGui::Button("From Focus"); if (selectFocusNode) { - const SceneGraphNode* const focus = OsEng.navigationHandler().focusNode(); + const SceneGraphNode* const focus = global::navigationHandler.focusNode(); const auto it = std::find(nodes.cbegin(), nodes.cend(), focus); if (it != nodes.end()) { _currentNode = focus->identifier(); @@ -324,7 +324,7 @@ void GuiGlobeBrowsingComponent::render() { std::remove(layerName.begin(), layerName.end(), ' '), layerName.end() ); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( fmt::format( "openspace.globebrowsing.addLayer(\ '{}', \ diff --git a/modules/imgui/src/guiiswacomponent.cpp b/modules/imgui/src/guiiswacomponent.cpp index 4560983675..17a543151d 100644 --- a/modules/imgui/src/guiiswacomponent.cpp +++ b/modules/imgui/src/guiiswacomponent.cpp @@ -31,7 +31,7 @@ #include #include -#include +#include #include namespace { @@ -70,7 +70,7 @@ void GuiIswaComponent::render() { ImGui::InputText("addCynget", addCygnetBuffer, AddCygnetBufferSize); if (ImGui::SmallButton("Add Cygnet")) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.addCygnet(" + std::string(addCygnetBuffer) + ");", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -83,12 +83,12 @@ void GuiIswaComponent::render() { openspace.iswa.addCygnet(-5, 'Data', 'GMData'); openspace.iswa.addCygnet(-6, 'Data', 'GMData'); )"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); } else { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.removeGroup('GMData');", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -102,12 +102,12 @@ void GuiIswaComponent::render() { openspace.iswa.addCygnet(-5, 'Texture', 'GMImage'); openspace.iswa.addCygnet(-6, 'Texture', 'GMImage'); )"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); } else { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.removeGroup('GMImage');", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -116,12 +116,12 @@ void GuiIswaComponent::render() { if(_ionData != oldIonDataValue) { if(_ionData) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.addCygnet(-10, 'Data', 'Ionosphere');", scripting::ScriptEngine::RemoteScripting::Yes ); } else { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.removeGroup('Ionosphere');", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -155,7 +155,7 @@ void GuiIswaComponent::render() { const int cdfOption = _cdfOptionsMap[groupName]; if (cdfOptionValue != cdfOption) { const std::string& date = cdfs[cdfOption].date; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.addKameleonPlanes('" + cdfs[cdfOption].group + "'," + @@ -163,11 +163,11 @@ void GuiIswaComponent::render() { ");", scripting::ScriptEngine::RemoteScripting::Yes ); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setTime('" + date + "');", scripting::ScriptEngine::RemoteScripting::Yes ); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setDeltaTime(0);", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -198,12 +198,12 @@ void GuiIswaComponent::render() { if (selected != info.selected) { const std::string idStr = std::to_string(id); if (info.selected) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.addScreenSpaceCygnet({CygnetId=" + idStr + "});", scripting::ScriptEngine::RemoteScripting::Yes ); } else { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.removeScreenSpaceCygnet(" + idStr + ");", scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/imgui/src/guijoystickcomponent.cpp b/modules/imgui/src/guijoystickcomponent.cpp index 999e3c6529..f550dc3d7b 100644 --- a/modules/imgui/src/guijoystickcomponent.cpp +++ b/modules/imgui/src/guijoystickcomponent.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -50,11 +50,8 @@ void GuiJoystickComponent::render() { _isEnabled = v; _isCollapsed = ImGui::IsWindowCollapsed(); - const JoystickInputStates& states = - OsEng.navigationHandler().inputState().joystickInputStates(); - - for (size_t i = 0; i < states.size(); ++i) { - const JoystickInputState& state = states[i]; + for (size_t i = 0; i < global::joystickInputStates.size(); ++i) { + const JoystickInputState& state = global::joystickInputStates[i]; if (!state.isConnected) { continue; } @@ -88,7 +85,7 @@ void GuiJoystickComponent::render() { ImGui::Text("%s", "Summed contributions"); ImGui::Text("%s", "Axes"); for (int i = 0; i < JoystickInputState::MaxAxes; ++i) { - float f = states.axis(i); + float f = global::joystickInputStates.axis(i); ImGui::SliderFloat( std::to_string(i).c_str(), &f, @@ -100,8 +97,8 @@ void GuiJoystickComponent::render() { for (int i = 0; i < JoystickInputState::MaxButtons; ++i) { ImGui::RadioButton( std::to_string(i).c_str(), - states.button(i, JoystickAction::Press) || - states.button(i, JoystickAction::Repeat) + global::joystickInputStates.button(i, JoystickAction::Press) || + global::joystickInputStates.button(i, JoystickAction::Repeat) ); } diff --git a/modules/imgui/src/guimissioncomponent.cpp b/modules/imgui/src/guimissioncomponent.cpp index a63a38d1f3..3274d5d4c5 100644 --- a/modules/imgui/src/guimissioncomponent.cpp +++ b/modules/imgui/src/guimissioncomponent.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -42,7 +42,7 @@ namespace { std::string missionHashname = "##" + mission.name(); - const double currentTime = OsEng.timeManager().time().j2000Seconds(); + const double currentTime = openspace::global::timeManager.time().j2000Seconds(); openspace::MissionPhase::Trace t = mission.phaseTrace(currentTime, 0); int treeOption = t.empty() ? 0 : ImGuiTreeNodeFlags_DefaultOpen; @@ -74,7 +74,7 @@ namespace { &v, s, e, - OsEng.timeManager().time().UTC().c_str() + openspace::global::timeManager.time().UTC().c_str() ); ImGui::SameLine(); ImGui::Text("%s", endTime.UTC().c_str()); @@ -98,7 +98,7 @@ GuiMissionComponent::GuiMissionComponent() {} void GuiMissionComponent::render() { - if (!MissionManager::ref().hasCurrentMission()) { + if (!global::missionManager.hasCurrentMission()) { return; } @@ -109,7 +109,7 @@ void GuiMissionComponent::render() { _isCollapsed = ImGui::IsWindowCollapsed(); - const Mission& currentMission = MissionManager::ref().currentMission(); + const Mission& currentMission = global::missionManager.currentMission(); renderMission(currentMission); ImGui::End(); diff --git a/modules/imgui/src/guiparallelcomponent.cpp b/modules/imgui/src/guiparallelcomponent.cpp index c095a80939..c2e36dc3e4 100644 --- a/modules/imgui/src/guiparallelcomponent.cpp +++ b/modules/imgui/src/guiparallelcomponent.cpp @@ -25,8 +25,7 @@ #include #include - -#include +#include #include #include #include @@ -51,7 +50,7 @@ void GuiParallelComponent::renderDisconnected() { const bool connect = ImGui::Button("Connect"); if (connect) { - OsEng.parallelPeer().connect(); + global::parallelPeer.connect(); } } @@ -60,12 +59,12 @@ void GuiParallelComponent::renderConnecting() { const bool cancel = ImGui::Button("Cancel connection"); if (cancel) { - OsEng.parallelPeer().disconnect(); + global::parallelPeer.disconnect(); } } void GuiParallelComponent::renderClientWithHost() { - ParallelPeer& parallel = OsEng.parallelPeer(); + ParallelPeer& parallel = global::parallelPeer; std::string connectionInfo = "Session hosted by \"" + parallel.hostName() + "\"\n"; const size_t nConnections = parallel.nConnections(); @@ -86,9 +85,9 @@ void GuiParallelComponent::renderClientWithHost() { ImGui::Text("%s", connectionInfo.c_str()); renderClientCommon(); - const size_t nTimeKeyframes = OsEng.timeManager().nKeyframes(); + const size_t nTimeKeyframes = global::timeManager.nKeyframes(); const size_t nCameraKeyframes = - OsEng.navigationHandler().keyframeNavigator().nKeyframes(); + global::navigationHandler.keyframeNavigator().nKeyframes(); std::string timeKeyframeInfo = "TimeKeyframes : " + std::to_string(nTimeKeyframes); std::string cameraKeyframeInfo = "CameraKeyframes : " + @@ -108,10 +107,8 @@ void GuiParallelComponent::renderClientWithHost() { } void GuiParallelComponent::renderClientWithoutHost() { - ParallelPeer& parallel = OsEng.parallelPeer(); - std::string connectionInfo = "Connected to parallel session with no host\n"; - const size_t nConnections = parallel.nConnections(); + const size_t nConnections = global::parallelPeer.nConnections(); if (nConnections > 2) { std::string c = std::to_string(nConnections - 1); @@ -131,23 +128,19 @@ void GuiParallelComponent::renderClientWithoutHost() { } void GuiParallelComponent::renderClientCommon() { - ParallelPeer& parallel = OsEng.parallelPeer(); - - const bool requestHostship = ImGui::Button("Request hostship"); if (requestHostship) { - parallel.requestHostship(); + global::parallelPeer.requestHostship(); } const bool disconnect = ImGui::Button("Disconnect"); if (disconnect) { - parallel.disconnect(); + global::parallelPeer.disconnect(); } } void GuiParallelComponent::renderHost() { - ParallelPeer& parallel = OsEng.parallelPeer(); - const size_t nConnections = parallel.nConnections(); + const size_t nConnections = global::parallelPeer.nConnections(); std::string connectionInfo; const size_t nClients = nConnections - 1; @@ -161,7 +154,7 @@ void GuiParallelComponent::renderHost() { const bool resignHostship = ImGui::Button("Resign hostship"); if (resignHostship) { - parallel.resignHostship(); + global::parallelPeer.resignHostship(); } } @@ -173,7 +166,7 @@ void GuiParallelComponent::render() { _isEnabled = v; _isCollapsed = ImGui::IsWindowCollapsed(); - ParallelConnection::Status status = OsEng.parallelPeer().status(); + ParallelConnection::Status status = global::parallelPeer.status(); switch (status) { case ParallelConnection::Status::Disconnected: @@ -193,7 +186,7 @@ void GuiParallelComponent::render() { break; } - GuiPropertyComponent::renderPropertyOwner(&OsEng.parallelPeer()); + GuiPropertyComponent::renderPropertyOwner(&global::parallelPeer); ImGui::End(); } diff --git a/modules/imgui/src/guiperformancecomponent.cpp b/modules/imgui/src/guiperformancecomponent.cpp index 81daa8820e..7a40cebcfa 100644 --- a/modules/imgui/src/guiperformancecomponent.cpp +++ b/modules/imgui/src/guiperformancecomponent.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -91,7 +91,7 @@ GuiPerformanceComponent::GuiPerformanceComponent() GuiPerformanceComponent::~GuiPerformanceComponent() {} // NOLINT void GuiPerformanceComponent::render() { - if (!OsEng.renderEngine().doesPerformanceMeasurements()) { + if (!global::performanceManager.isEnabled()) { return; } @@ -104,8 +104,7 @@ void GuiPerformanceComponent::render() { _isEnabled = v; _isCollapsed = ImGui::IsWindowCollapsed(); - PerformanceLayout* layout = - OsEng.renderEngine().performanceManager()->performanceData(); + PerformanceLayout* layout = global::performanceManager.performanceData(); v = _sceneGraphIsEnabled; ImGui::Checkbox("SceneGraph", &v); @@ -115,15 +114,15 @@ void GuiPerformanceComponent::render() { _functionsIsEnabled = v; v = _outputLogs; ImGui::Checkbox("Output Logs", &v); - OsEng.renderEngine().performanceManager()->setLogging(v); + global::performanceManager.setLogging(v); // Need to catch if it's unsuccessful - v = OsEng.renderEngine().performanceManager()->loggingEnabled(); + v = global::performanceManager.loggingEnabled(); _outputLogs = v; ImGui::Spacing(); if (ImGui::Button("Reset measurements")) { - OsEng.renderEngine().performanceManager()->resetPerformanceMeasurements(); + global::performanceManager.resetPerformanceMeasurements(); } if (_sceneGraphIsEnabled) { diff --git a/modules/imgui/src/guispacetimecomponent.cpp b/modules/imgui/src/guispacetimecomponent.cpp index a785795c07..22da5ba9a6 100644 --- a/modules/imgui/src/guispacetimecomponent.cpp +++ b/modules/imgui/src/guispacetimecomponent.cpp @@ -26,9 +26,8 @@ #include #include - -#include -#include +#include +#include #include #include #include @@ -80,7 +79,7 @@ void GuiSpaceTimeComponent::render() { _isCollapsed = ImGui::IsWindowCollapsed(); std::vector nodes = - OsEng.renderEngine().scene()->allSceneGraphNodes(); + global::renderEngine.scene()->allSceneGraphNodes(); std::sort( nodes.begin(), @@ -102,7 +101,7 @@ void GuiSpaceTimeComponent::render() { const bool pressed = ImGui::Button(n->guiName().c_str()); ImGui::SameLine(); if (pressed) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.setPropertyValue('NavigationHandler.Origin', '" + n->identifier() + "');", scripting::ScriptEngine::RemoteScripting::Yes @@ -114,7 +113,7 @@ void GuiSpaceTimeComponent::render() { ImGui::NewLine(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 10.f); - SceneGraphNode* currentFocus = OsEng.navigationHandler().focusNode(); + SceneGraphNode* currentFocus = global::navigationHandler.focusNode(); std::string nodeNames; for (SceneGraphNode* n : nodes) { @@ -131,7 +130,7 @@ void GuiSpaceTimeComponent::render() { const bool hasChanged = ImGui::Combo("", ¤tPosition, nodeNames.c_str()); if (hasChanged) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.setPropertyValue('NavigationHandler.Origin', '" + nodes[currentPosition]->identifier() + "');", scripting::ScriptEngine::RemoteScripting::Yes @@ -144,7 +143,7 @@ void GuiSpaceTimeComponent::render() { // To refocus, we are first clearing the origin property before setting it back // to its old value. The property mechanism's onChange does not fire if the same // value is set again, hence the need for the clearing - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( R"( local o = openspace.getPropertyValue('NavigationHandler.Origin'); openspace.setPropertyValue('NavigationHandler.Origin', ''); @@ -165,7 +164,7 @@ void GuiSpaceTimeComponent::render() { CaptionText("Time Controls"); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 10.f); - ImGui::Text("Current Date: %s", OsEng.timeManager().time().UTC().c_str()); + ImGui::Text("Current Date: %s", global::timeManager.time().UTC().c_str()); constexpr int BufferSize = 256; static char Buffer[BufferSize]; @@ -176,7 +175,7 @@ void GuiSpaceTimeComponent::render() { ImGuiInputTextFlags_EnterReturnsTrue ); if (dateChanged) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setTime(\"" + std::string(Buffer) + "\")", scripting::ScriptEngine::RemoteScripting::No ); @@ -193,10 +192,10 @@ void GuiSpaceTimeComponent::render() { auto incrementTime = [](float days) { using namespace std::chrono; - const float duration = OsEng.timeManager().defaultTimeInterpolationDuration(); + const float duration = global::timeManager.defaultTimeInterpolationDuration(); - const TimeKeyframeData predictedTime = OsEng.timeManager().interpolate( - OsEng.windowWrapper().applicationTime() + duration + const TimeKeyframeData predictedTime = global::timeManager.interpolate( + global::windowDelegate.applicationTime() + duration ); const double j2000 = predictedTime.time.j2000Seconds(); const long long seconds = duration_cast( @@ -207,7 +206,7 @@ void GuiSpaceTimeComponent::render() { j2000 - seconds : j2000 + seconds; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateTime(" + std::to_string(newTime) + ", " + std::to_string(duration) + ")", scripting::ScriptEngine::RemoteScripting::No @@ -246,7 +245,7 @@ void GuiSpaceTimeComponent::render() { // setTime doesn't like the T in it and wants a space instead nowTime[11] = ' '; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setTime(\"" + nowTime + "\")", scripting::ScriptEngine::RemoteScripting::No ); @@ -281,7 +280,7 @@ void GuiSpaceTimeComponent::render() { ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 20.f); // { - const float dt = static_cast(OsEng.timeManager().targetDeltaTime()); + const float dt = static_cast(global::timeManager.targetDeltaTime()); if (_firstFrame) { const std::pair& dtInfo = simplifyTime(dt); _deltaTime = static_cast(dtInfo.first); @@ -325,7 +324,7 @@ void GuiSpaceTimeComponent::render() { // If the value changed, we want to change the delta time to the new value double newDt = convertTime(_deltaTime, _deltaTimeUnit, TimeUnit::Second); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(newDt) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -374,14 +373,14 @@ void GuiSpaceTimeComponent::render() { TimeUnit::Second ); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setDeltaTime(" + std::to_string(newDeltaTime) + ")", scripting::ScriptEngine::RemoteScripting::No ); } if (!ImGui::IsItemActive() && !ImGui::IsItemClicked()) { if (_slidingDelta != 0.f) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setDeltaTime(" + std::to_string(_oldDeltaTime) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -402,12 +401,12 @@ void GuiSpaceTimeComponent::render() { if (accelerationDeltaChanged || ImGui::IsItemActive() || ImGui::IsItemClicked()) { // We want the value to change by _accelerationDelta every 100 real world ms const double newDeltaTime = convertTime( - _deltaTime + _accelerationDelta * OsEng.windowWrapper().deltaTime() * 10, + _deltaTime + _accelerationDelta * global::windowDelegate.deltaTime() * 10, static_cast(_deltaTimeUnit), TimeUnit::Second ); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.setDeltaTime(" + std::to_string(newDeltaTime) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -419,13 +418,13 @@ void GuiSpaceTimeComponent::render() { _deltaTime -= _slidingDelta; } - const bool isPaused = OsEng.timeManager().isPaused(); + const bool isPaused = global::timeManager.isPaused(); const bool pauseChanged = ImGui::Button( isPaused ? "Resume" : "Pause", { ImGui::GetWindowWidth() / 2 - 7.5f, 0.f } ); if (pauseChanged) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateTogglePause()", scripting::ScriptEngine::RemoteScripting::No ); @@ -436,7 +435,7 @@ void GuiSpaceTimeComponent::render() { { ImGui::GetWindowWidth() / 2 - 7.5f, 0.f } ); if (invert) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(-1 * openspace.time.deltaTime());", scripting::ScriptEngine::RemoteScripting::No ); @@ -444,7 +443,7 @@ void GuiSpaceTimeComponent::render() { const bool minusDs = ImGui::Button("-1d/s"); if (minusDs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(-24 * 60 * 60) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -453,7 +452,7 @@ void GuiSpaceTimeComponent::render() { const bool minusHs = ImGui::Button("-1h/s"); if (minusHs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(-60 * 60) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -462,7 +461,7 @@ void GuiSpaceTimeComponent::render() { const bool minusMs = ImGui::Button("-1min/s"); if (minusMs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(-60) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -471,7 +470,7 @@ void GuiSpaceTimeComponent::render() { const bool minusSs = ImGui::Button("-1s/s"); if (minusSs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(-1) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -480,7 +479,7 @@ void GuiSpaceTimeComponent::render() { const bool zero = ImGui::Button("0"); if (zero) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(0) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -490,7 +489,7 @@ void GuiSpaceTimeComponent::render() { const bool plusSs = ImGui::Button("+1s/s"); if (plusSs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(1) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -499,7 +498,7 @@ void GuiSpaceTimeComponent::render() { const bool plusMs = ImGui::Button("1min/s"); if (plusMs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(60) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -508,7 +507,7 @@ void GuiSpaceTimeComponent::render() { const bool plusHs = ImGui::Button("1h/s"); if (plusHs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(60 * 60) + ")", scripting::ScriptEngine::RemoteScripting::No ); @@ -517,7 +516,7 @@ void GuiSpaceTimeComponent::render() { const bool plusDs = ImGui::Button("1d/s"); if (plusDs) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.interpolateDeltaTime(" + std::to_string(24 * 60 * 60) + ")", scripting::ScriptEngine::RemoteScripting::No ); diff --git a/modules/imgui/src/renderproperties.cpp b/modules/imgui/src/renderproperties.cpp index 4e43d06b6e..1fdbd6be4e 100644 --- a/modules/imgui/src/renderproperties.cpp +++ b/modules/imgui/src/renderproperties.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -69,14 +69,14 @@ void renderTooltip(Property* prop, double delay) { } void executeScriptSingle(const std::string& id, const std::string& value) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.setPropertyValueSingle('" + id + "', " + value + ");", scripting::ScriptEngine::RemoteScripting::Yes ); } void executeScriptGroup(const std::string& id, const std::string& value) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.setPropertyValue('" + id + "', " + value + ");", scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/iswa/iswamodule.cpp b/modules/iswa/iswamodule.cpp index 284ad2822c..7699a8452b 100644 --- a/modules/iswa/iswamodule.cpp +++ b/modules/iswa/iswamodule.cpp @@ -33,6 +33,8 @@ #include +#include + #include #include #include @@ -45,12 +47,7 @@ namespace openspace { IswaModule::IswaModule() : OpenSpaceModule(Name) { - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Initialize, - [](){ - IswaManager::initialize(); - } - ); + global::callback::initialize.push_back([]() { IswaManager::initialize(); }); } void IswaModule::internalInitialize(const ghoul::Dictionary&) { diff --git a/modules/iswa/rendering/dataplane.cpp b/modules/iswa/rendering/dataplane.cpp index 5421658cc1..f493c91e27 100644 --- a/modules/iswa/rendering/dataplane.cpp +++ b/modules/iswa/rendering/dataplane.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -39,7 +39,7 @@ void DataPlane::initializeGL() { IswaCygnet::initialize(); if (!_shader) { - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "DataPlaneProgram", absPath("${MODULE_ISWA}/shaders/dataplane_vs.glsl"), absPath("${MODULE_ISWA}/shaders/dataplane_fs.glsl") diff --git a/modules/iswa/rendering/datasphere.cpp b/modules/iswa/rendering/datasphere.cpp index 3bb3ede5c1..ad28f7186f 100644 --- a/modules/iswa/rendering/datasphere.cpp +++ b/modules/iswa/rendering/datasphere.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -48,7 +48,7 @@ void DataSphere::initializeGL() { IswaCygnet::initializeGL(); if (!_shader) { - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "DataSphereProgram", absPath("${MODULE_ISWA}/shaders/datasphere_vs.glsl"), absPath("${MODULE_ISWA}/shaders/datasphere_fs.glsl") diff --git a/modules/iswa/rendering/iswacygnet.cpp b/modules/iswa/rendering/iswacygnet.cpp index 3c2b3f1705..a85f7d2488 100644 --- a/modules/iswa/rendering/iswacygnet.cpp +++ b/modules/iswa/rendering/iswacygnet.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -114,7 +114,7 @@ void IswaCygnet::initializeGL() { } else { _delete.onChange([this]() { deinitialize(); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + identifier() + "')", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -123,7 +123,7 @@ void IswaCygnet::initializeGL() { initializeTime(); createGeometry(); - downloadTextureResource(OsEng.timeManager().time().j2000Seconds()); + downloadTextureResource(global::timeManager.time().j2000Seconds()); } void IswaCygnet::deinitializeGL() { @@ -135,7 +135,7 @@ void IswaCygnet::deinitializeGL() { destroyGeometry(); if (_shader) { - OsEng.renderEngine().removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } } @@ -186,7 +186,7 @@ void IswaCygnet::update(const UpdateData&) { // the texture resource is downloaded ahead of time, so we need to // now if we are going backwards or forwards - _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); + _openSpaceTime = global::timeManager.time().j2000Seconds(); _realTime = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() ); @@ -211,7 +211,7 @@ void IswaCygnet::update(const UpdateData&) { updateTexture(); _textureDirty = false; - double clockwiseSign = (OsEng.timeManager().deltaTime() > 0) ? 1.0 : -1.0; + double clockwiseSign = (global::timeManager.deltaTime() > 0) ? 1.0 : -1.0; downloadTextureResource(_openSpaceTime + clockwiseSign * _data.updateTime); _lastUpdateRealTime = _realTime; _lastUpdateOpenSpaceTime = _openSpaceTime; @@ -233,7 +233,7 @@ void IswaCygnet::registerProperties() {} void IswaCygnet::unregisterProperties() {} void IswaCygnet::initializeTime() { - _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); + _openSpaceTime = global::timeManager.time().j2000Seconds(); _lastUpdateOpenSpaceTime = 0.0; _realTime = std::chrono::duration_cast( @@ -270,7 +270,7 @@ void IswaCygnet::initializeGroup() { groupEvent.subscribe(identifier(), "clearGroup", [&](ghoul::Dictionary) { LDEBUG(identifier() + " Event clearGroup"); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + identifier() + "')", scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/iswa/rendering/iswakameleongroup.cpp b/modules/iswa/rendering/iswakameleongroup.cpp index da112f6321..b3f44562b3 100644 --- a/modules/iswa/rendering/iswakameleongroup.cpp +++ b/modules/iswa/rendering/iswakameleongroup.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -149,7 +149,7 @@ void IswaKameleonGroup::updateFieldlineSeeds() { if (it == options.end() && std::get<2>(seedPath.second)) { LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -175,7 +175,7 @@ void IswaKameleonGroup::clearFieldlines() { if (std::get<2>(seedPath.second)) { LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/iswa/rendering/kameleonplane.cpp b/modules/iswa/rendering/kameleonplane.cpp index a662689a8e..e3bfbaa1c6 100644 --- a/modules/iswa/rendering/kameleonplane.cpp +++ b/modules/iswa/rendering/kameleonplane.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -112,7 +112,7 @@ void KameleonPlane::deinitializeGL() { void KameleonPlane::initializeGL() { if (!_shader) { - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "DataPlaneProgram", absPath("${MODULE_ISWA}/shaders/dataplane_vs.glsl"), absPath("${MODULE_ISWA}/shaders/dataplane_fs.glsl") @@ -272,7 +272,7 @@ void KameleonPlane::updateFieldlineSeeds() { seedPath.first ); if (it == selectedOptions.end() && std::get<2>(seedPath.second)) { - SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode( + SceneGraphNode* n = global::renderEngine.scene()->sceneGraphNode( std::get<0>(seedPath.second) ); if (!n) { @@ -280,14 +280,14 @@ void KameleonPlane::updateFieldlineSeeds() { } LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", scripting::ScriptEngine::RemoteScripting::Yes ); std::get<2>(seedPath.second) = false; // if this option was turned on } else if (it != selectedOptions.end() && !std::get<2>(seedPath.second)) { - SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode( + SceneGraphNode* n = global::renderEngine.scene()->sceneGraphNode( std::get<0>(seedPath.second) ); if (n) { diff --git a/modules/iswa/rendering/screenspacecygnet.cpp b/modules/iswa/rendering/screenspacecygnet.cpp index 772c624e5c..0bca650328 100644 --- a/modules/iswa/rendering/screenspacecygnet.cpp +++ b/modules/iswa/rendering/screenspacecygnet.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include @@ -40,10 +40,10 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) _downloadImage = true; _texturePath = IswaManager::ref().iswaUrl( _cygnetId, - OsEng.timeManager().time().j2000Seconds() + global::timeManager.time().j2000Seconds() ); - _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); + _openSpaceTime = global::timeManager.time().j2000Seconds(); _lastUpdateOpenSpaceTime = _openSpaceTime; _realTime = std::chrono::duration_cast( @@ -53,7 +53,7 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) _minRealTimeUpdateInterval = 100; _delete.onChange([this]() { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.iswa.removeScreenSpaceCygnet("+std::to_string(_cygnetId)+");", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -61,7 +61,7 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) } void ScreenSpaceCygnet::update() { - _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); + _openSpaceTime = global::timeManager.time().j2000Seconds(); _realTime = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() ); @@ -72,7 +72,7 @@ void ScreenSpaceCygnet::update() { if (timeToUpdate) { _texturePath = IswaManager::ref().iswaUrl( _cygnetId, - OsEng.timeManager().time().j2000Seconds() + global::timeManager.time().j2000Seconds() ); _lastUpdateRealTime = _realTime; _lastUpdateOpenSpaceTime = _openSpaceTime; diff --git a/modules/iswa/rendering/textureplane.cpp b/modules/iswa/rendering/textureplane.cpp index 530371ad16..0ef9e7293a 100644 --- a/modules/iswa/rendering/textureplane.cpp +++ b/modules/iswa/rendering/textureplane.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -39,7 +39,7 @@ TexturePlane::TexturePlane(const ghoul::Dictionary& dictionary) void TexturePlane::initializeGL() { if (!_shader) { - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "PlaneProgram", absPath("${MODULE_ISWA}/shaders/textureplane_vs.glsl"), absPath("${MODULE_ISWA}/shaders/textureplane_fs.glsl") diff --git a/modules/iswa/util/iswamanager.cpp b/modules/iswa/util/iswamanager.cpp index 6219f37fbe..18ddc10e43 100644 --- a/modules/iswa/util/iswamanager.cpp +++ b/modules/iswa/util/iswamanager.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include #include @@ -84,7 +84,7 @@ namespace { void createScreenSpace(int id) { std::string idStr = std::to_string(id); - OsEng.scriptEngine().queueScript( + openspace::global::scriptEngine.queueScript( "openspace.iswa.addScreenSpaceCygnet({CygnetId =" + idStr + "});", openspace::scripting::ScriptEngine::RemoteScripting::Yes ); @@ -105,7 +105,7 @@ IswaManager::IswaManager() _geom[CygnetGeometry::Plane] = "Plane"; _geom[CygnetGeometry::Sphere] = "Sphere"; - OsEng.downloadManager().fetchFile( + global::downloadManager.fetchFile( "http://iswa3.ccmc.gsfc.nasa.gov/IswaSystemWebApp/CygnetHealthServlet", [this](const DownloadManager::MemoryFile& file) { fillCygnetInfo(std::string(file.buffer)); @@ -160,7 +160,7 @@ void IswaManager::addIswaCygnet(int id, const std::string& type, std::string gro }; // Download metadata - OsEng.downloadManager().fetchFile( + global::downloadManager.fetchFile( _baseUrl + std::to_string(-id), metadataCallback, [id](const std::string& err) { @@ -191,7 +191,7 @@ void IswaManager::addKameleonCdf(std::string groupName, int pos) { std::future IswaManager::fetchImageCygnet(int id, double timestamp) { - return OsEng.downloadManager().fetchFile( + return global::downloadManager.fetchFile( iswaUrl(id, timestamp, "image"), [id](const DownloadManager::MemoryFile&) { LDEBUG( @@ -211,7 +211,7 @@ std::future IswaManager::fetchImageCygnet(int id, std::future IswaManager::fetchDataCygnet(int id, double timestamp) { - return OsEng.downloadManager().fetchFile( + return global::downloadManager.fetchFile( iswaUrl(id, timestamp, "data"), [id](const DownloadManager::MemoryFile&) { LDEBUG( @@ -305,7 +305,7 @@ std::shared_ptr IswaManager::downloadMetadata(int id) { std::shared_ptr metaFuture = std::make_shared(); metaFuture->id = id; - OsEng.downloadManager().fetchFile( + global::downloadManager.fetchFile( _baseUrl + std::to_string(-id), [&metaFuture](const DownloadManager::MemoryFile& file) { metaFuture->json = std::string(file.buffer, file.buffer + file.size); @@ -504,7 +504,7 @@ void IswaManager::createPlane(MetadataFuture& data) { data.name = name; - if (OsEng.renderEngine().scene()->sceneGraphNode(name)) { + if (global::renderEngine.scene()->sceneGraphNode(name)) { LERROR("A node with name \"" + name + "\" already exist"); return; } @@ -512,7 +512,7 @@ void IswaManager::createPlane(MetadataFuture& data) { std::string luaTable = jsonPlaneToLuaTable(data); if (!luaTable.empty()) { std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -537,14 +537,14 @@ void IswaManager::createSphere(MetadataFuture& data) { data.name = name; - if (OsEng.renderEngine().scene()->sceneGraphNode(name)) { + if (global::renderEngine.scene()->sceneGraphNode(name)) { LERROR("A node with name \"" + name +"\" already exist"); return; } std::string luaTable = jsonSphereToLuaTable(data); if (luaTable != "") { std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -570,7 +570,7 @@ void IswaManager::createKameleonPlane(CdfInfo info, std::string cut) { info.name = info.name + "-" + cut; - if (OsEng.renderEngine().scene()->sceneGraphNode(info.name)) { + if (global::renderEngine.scene()->sceneGraphNode(info.name)) { LERROR("A node with name \"" + info.name +"\" already exist"); return; } @@ -578,7 +578,7 @@ void IswaManager::createKameleonPlane(CdfInfo info, std::string cut) { std::string luaTable = parseKWToLuaTable(info, cut); if (!luaTable.empty()) { std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -617,7 +617,7 @@ void IswaManager::createFieldline(std::string name, std::string cdfPath, "}"; if (!luaTable.empty()) { std::string script = "openspace.addSceneGraphNode(" + luaTable + ");"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index 152302969d..512a781b3e 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -22,6 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include #include #include @@ -84,7 +85,7 @@ int iswa_addScreenSpaceCygnet(lua_State* L) { int updateInterval = info->updateInterval; info->selected = true; - if (OsEng.renderEngine().screenSpaceRenderable(name)) { + if (global::renderEngine.screenSpaceRenderable(name)) { LERROR("A cygnet with the name \"" + name +"\" already exist"); return 0; } else { @@ -95,7 +96,7 @@ int iswa_addScreenSpaceCygnet(lua_State* L) { std::unique_ptr s( ScreenSpaceRenderable::createFromDictionary(d) ); - OsEng.renderEngine().addScreenSpaceRenderable(std::move(s)); + global::renderEngine.addScreenSpaceRenderable(std::move(s)); } return 0; } @@ -122,7 +123,7 @@ int iswa_addScreenSpaceCygnet(lua_State* L) { int iswa_removeCygnet(lua_State* L) { std::string name = luaL_checkstring(L, -1); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.removeSceneGraphNode('" + name + "')", scripting::ScriptEngine::RemoteScripting::Yes ); @@ -148,7 +149,7 @@ int iswa_removeScrenSpaceCygnet(lua_State* L) { "openspace.unregisterScreenSpaceRenderable('" + cygnetInformation[id]->name + "');"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes ); diff --git a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp index ec72bc3547..a414fc48dd 100644 --- a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp +++ b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include @@ -264,14 +264,14 @@ void RenderableKameleonVolume::initializeGL() { _raycaster->initialize(); - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); auto onChange = [&](bool enabled) { if (enabled) { - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); } else { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); } }; @@ -436,7 +436,7 @@ void RenderableKameleonVolume::storeRaw(const std::string& path) { void RenderableKameleonVolume::deinitializeGL() { if (_raycaster) { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); _raycaster = nullptr; } } diff --git a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp index e43e53d2c7..21deca02bf 100644 --- a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp +++ b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp @@ -24,47 +24,38 @@ #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 +#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 #include - -#include +#include +#include namespace { constexpr const char* _loggerCat = "RenderableMultiresVolume"; @@ -426,14 +417,14 @@ void RenderableMultiresVolume::initializeGL() { ); _raycaster->initialize(); - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster); + global::raycasterManager.attachRaycaster(*_raycaster); auto onChange = [&](bool enabled) { if (enabled) { - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster); + global::raycasterManager.attachRaycaster(*_raycaster); } else { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster); + global::raycasterManager.detachRaycaster(*_raycaster); } }; diff --git a/modules/server/servermodule.cpp b/modules/server/servermodule.cpp index c792769416..49fbec2a53 100644 --- a/modules/server/servermodule.cpp +++ b/modules/server/servermodule.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -68,10 +68,7 @@ void ServerModule::internalInitialize(const ghoul::Dictionary&) { _servers.push_back(std::move(tcpServer)); _servers.push_back(std::move(wsServer)); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::PreSync, - [this]() { preSync(); } - ); + global::callback::preSync.push_back([this]() { preSync(); }); } void ServerModule::preSync() { diff --git a/modules/server/src/connection.cpp b/modules/server/src/connection.cpp index 489c26a26c..617868942e 100644 --- a/modules/server/src/connection.cpp +++ b/modules/server/src/connection.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include #include @@ -76,7 +76,7 @@ Connection::Connection(std::unique_ptr s, std::string address _topicFactory.registerClass(BounceTopicKey); // see if the default config for requiring auth (on) is overwritten - _requireAuthorization = OsEng.configuration().doesRequireSocketAuthentication; + _requireAuthorization = global::configuration.doesRequireSocketAuthentication; } void Connection::handleMessage(const std::string& message) { @@ -188,7 +188,7 @@ void Connection::setAuthorized(bool status) { } bool Connection::isWhitelisted() const { - const std::vector& wl = OsEng.configuration().clientAddressWhitelist; + const std::vector& wl = global::configuration.clientAddressWhitelist; return std::find(wl.begin(), wl.end(), _address) != wl.end(); } diff --git a/modules/server/src/topics/authorizationtopic.cpp b/modules/server/src/topics/authorizationtopic.cpp index 563d87d843..d3e17b6845 100644 --- a/modules/server/src/topics/authorizationtopic.cpp +++ b/modules/server/src/topics/authorizationtopic.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include namespace { @@ -84,7 +84,7 @@ void AuthorizationTopic::handleJson(const nlohmann::json& json) { } bool AuthorizationTopic::authorize(const std::string& key) { - _isAuthenticated = (key == OsEng.configuration().serverPasskey); + _isAuthenticated = (key == global::configuration.serverPasskey); return _isAuthenticated; } diff --git a/modules/server/src/topics/getpropertytopic.cpp b/modules/server/src/topics/getpropertytopic.cpp index fd4fb052c5..01daa0039c 100644 --- a/modules/server/src/topics/getpropertytopic.cpp +++ b/modules/server/src/topics/getpropertytopic.cpp @@ -27,9 +27,9 @@ #include #include #include -#include +#include #include -#include +#include #include #include #include @@ -64,11 +64,11 @@ void GetPropertyTopic::handleJson(const nlohmann::json& json) { } else if (requestedKey == AllScreenSpaceRenderablesValue) { response = wrappedPayload({ - { "value", OsEng.renderEngine().screenSpaceRenderables() } + { "value", global::renderEngine.screenSpaceRenderables() } }); } else if (requestedKey == RootPropertyOwner) { - response = wrappedPayload(OsEng.rootPropertyOwner()); + response = wrappedPayload(global::rootPropertyOwner); } else { response = propertyFromKey(requestedKey); @@ -85,12 +85,11 @@ json GetPropertyTopic::allProperties() { { "value", { - OsEng.renderEngine(), - OsEng.console(), - OsEng.parallelPeer(), - OsEng.windowWrapper(), - OsEng.navigationHandler(), - OsEng.virtualPropertyManager(), + global::renderEngine, + global::luaConsole, + global::parallelPeer, + global::navigationHandler, + global::virtualPropertyManager, } } }; diff --git a/modules/server/src/topics/luascripttopic.cpp b/modules/server/src/topics/luascripttopic.cpp index 809b0b2e1c..720b2f406e 100644 --- a/modules/server/src/topics/luascripttopic.cpp +++ b/modules/server/src/topics/luascripttopic.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include @@ -40,7 +40,7 @@ void LuaScriptTopic::handleJson(const nlohmann::json& json) { try { std::string script = json.at(ScriptKey).get(); LDEBUG("Queueing Lua script: " + script); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( std::move(script), scripting::ScriptEngine::RemoteScripting::No ); diff --git a/modules/server/src/topics/setpropertytopic.cpp b/modules/server/src/topics/setpropertytopic.cpp index a86cd14f1a..5405ca420d 100644 --- a/modules/server/src/topics/setpropertytopic.cpp +++ b/modules/server/src/topics/setpropertytopic.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -49,7 +49,7 @@ void SetPropertyTopic::handleJson(const nlohmann::json& json) { if (propertyKey == SpecialKeyTime) { Time newTime; newTime.setTime(value); - OsEng.timeManager().setTimeNextFrame(newTime); + global::timeManager.setTimeNextFrame(newTime); } else { properties::Property* prop = property(propertyKey); diff --git a/modules/server/src/topics/timetopic.cpp b/modules/server/src/topics/timetopic.cpp index ade34e357e..193747b852 100644 --- a/modules/server/src/topics/timetopic.cpp +++ b/modules/server/src/topics/timetopic.cpp @@ -25,7 +25,7 @@ #include "modules/server/include/topics/timetopic.h" #include -#include +#include #include #include #include @@ -53,10 +53,10 @@ TimeTopic::TimeTopic() TimeTopic::~TimeTopic() { if (_timeCallbackHandle != UnsetOnChangeHandle) { - OsEng.timeManager().removeTimeChangeCallback(_timeCallbackHandle); + global::timeManager.removeTimeChangeCallback(_timeCallbackHandle); } if (_deltaTimeCallbackHandle != UnsetOnChangeHandle) { - OsEng.timeManager().removeDeltaTimeChangeCallback(_deltaTimeCallbackHandle); + global::timeManager.removeDeltaTimeChangeCallback(_deltaTimeCallbackHandle); } } @@ -75,7 +75,7 @@ void TimeTopic::handleJson(const nlohmann::json& json) { LDEBUG("Subscribing to " + requestedKey); if (requestedKey == CurrentTimeKey) { - _timeCallbackHandle = OsEng.timeManager().addTimeChangeCallback([this]() { + _timeCallbackHandle = global::timeManager.addTimeChangeCallback([this]() { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); if (now - _lastUpdateTime > TimeUpdateInterval) { _connection->sendJson(currentTime()); @@ -85,7 +85,7 @@ void TimeTopic::handleJson(const nlohmann::json& json) { _connection->sendJson(currentTime()); } else if (requestedKey == DeltaTimeKey) { - _deltaTimeCallbackHandle = OsEng.timeManager().addDeltaTimeChangeCallback( + _deltaTimeCallbackHandle = global::timeManager.addDeltaTimeChangeCallback( [this]() { _connection->sendJson(deltaTime()); if (_timeCallbackHandle != UnsetOnChangeHandle) { @@ -103,12 +103,12 @@ void TimeTopic::handleJson(const nlohmann::json& json) { } json TimeTopic::currentTime() { - json timeJson = { { "time", OsEng.timeManager().time().ISO8601() } }; + json timeJson = { { "time", global::timeManager.time().ISO8601() } }; return wrappedPayload(timeJson); } json TimeTopic::deltaTime() { - json timeJson = { { "deltaTime", OsEng.timeManager().deltaTime() } }; + json timeJson = { { "deltaTime", global::timeManager.deltaTime() } }; return wrappedPayload(timeJson); } diff --git a/modules/space/rendering/renderableconstellationbounds.cpp b/modules/space/rendering/renderableconstellationbounds.cpp index 2ec9d82d0f..94cfb978a3 100644 --- a/modules/space/rendering/renderableconstellationbounds.cpp +++ b/modules/space/rendering/renderableconstellationbounds.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -185,7 +185,7 @@ RenderableConstellationBounds::RenderableConstellationBounds( } void RenderableConstellationBounds::initializeGL() { - _program = OsEng.renderEngine().buildRenderProgram( + _program = global::renderEngine.buildRenderProgram( "ConstellationBounds", absPath("${MODULE_SPACE}/shaders/constellationbounds_vs.glsl"), absPath("${MODULE_SPACE}/shaders/constellationbounds_fs.glsl") @@ -217,7 +217,7 @@ void RenderableConstellationBounds::deinitializeGL() { _vao = 0; if (_program) { - OsEng.renderEngine().removeRenderProgram(_program.get()); + global::renderEngine.removeRenderProgram(_program.get()); _program = nullptr; } } diff --git a/modules/space/rendering/renderableplanet.cpp b/modules/space/rendering/renderableplanet.cpp index 0507bf7239..90dd9e7631 100644 --- a/modules/space/rendering/renderableplanet.cpp +++ b/modules/space/rendering/renderableplanet.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -352,7 +352,7 @@ void RenderablePlanet::initializeGL() { _programObject = SpaceModule::ProgramObjectManager.request( ShadowNightProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ShadowNightProgramName, absPath("${MODULE_SPACE}/shaders/shadow_nighttexture_vs.glsl"), absPath("${MODULE_SPACE}/shaders/shadow_nighttexture_fs.glsl") @@ -364,7 +364,7 @@ void RenderablePlanet::initializeGL() { _programObject = SpaceModule::ProgramObjectManager.request( ShadowProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ShadowProgramName, absPath("${MODULE_SPACE}/shaders/shadow_vs.glsl"), absPath("${MODULE_SPACE}/shaders/shadow_fs.glsl") @@ -376,7 +376,7 @@ void RenderablePlanet::initializeGL() { _programObject = SpaceModule::ProgramObjectManager.request( NightProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( NightProgramName, absPath("${MODULE_SPACE}/shaders/nighttexture_vs.glsl"), absPath("${MODULE_SPACE}/shaders/nighttexture_fs.glsl") @@ -388,7 +388,7 @@ void RenderablePlanet::initializeGL() { _programObject = SpaceModule::ProgramObjectManager.request( PlainProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( PlainProgramName, absPath("${MODULE_SPACE}/shaders/renderableplanet_vs.glsl"), absPath("${MODULE_SPACE}/shaders/renderableplanet_fs.glsl") @@ -419,7 +419,7 @@ void RenderablePlanet::deinitializeGL() { SpaceModule::ProgramObjectManager.release( _programObject->name(), [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); diff --git a/modules/space/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp index 169627979b..9f9a3d58b1 100644 --- a/modules/space/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -182,7 +182,7 @@ bool RenderableRings::isReady() const { } void RenderableRings::initializeGL() { - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "RingProgram", absPath("${MODULE_SPACE}/shaders/rings_vs.glsl"), absPath("${MODULE_SPACE}/shaders/rings_fs.glsl") @@ -207,7 +207,7 @@ void RenderableRings::deinitializeGL() { _textureFile = nullptr; _texture = nullptr; - OsEng.renderEngine().removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } @@ -261,7 +261,7 @@ void RenderableRings::update(const UpdateData& data) { _textureIsDirty = false; } - _sunPosition = OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition() - + _sunPosition = global::renderEngine.scene()->sceneGraphNode("Sun")->worldPosition() - data.modelTransform.translation; } diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 35b4c51e6e..cb2453cef2 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include @@ -294,8 +294,7 @@ bool RenderableStars::isReady() const { } void RenderableStars::initializeGL() { - RenderEngine& renderEngine = OsEng.renderEngine(); - _program = renderEngine.buildRenderProgram("Star", + _program = global::renderEngine.buildRenderProgram("Star", absPath("${MODULE_SPACE}/shaders/star_vs.glsl"), absPath("${MODULE_SPACE}/shaders/star_fs.glsl"), absPath("${MODULE_SPACE}/shaders/star_ge.glsl") @@ -318,9 +317,8 @@ void RenderableStars::deinitializeGL() { _pointSpreadFunctionTexture = nullptr; _colorTexture = nullptr; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_program) { - renderEngine.removeRenderProgram(_program.get()); + global::renderEngine.removeRenderProgram(_program.get()); _program = nullptr; } } @@ -342,7 +340,7 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { _program->setUniform(_uniformCache.minBillboardSize, _minBillboardSize); _program->setUniform( _uniformCache.screenSize, - glm::vec2(OsEng.renderEngine().renderingResolution()) + glm::vec2(global::renderEngine.renderingResolution()) ); setPscUniforms(*_program.get(), data.camera, data.position); diff --git a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp index 8150de8c53..f6c2133e34 100644 --- a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp +++ b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -144,7 +144,7 @@ DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dict glm::vec3(0.f), glm::vec3(1.f) ) - , _font(OsEng.fontManager().font(KeyFontMono, 10)) + , _font(global::fontManager.font(KeyFontMono, 10)) { documentation::testSpecificationAndThrow( Documentation(), @@ -160,12 +160,12 @@ DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dict } _fontName.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontName); _fontSize.onChange([this]() { - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); }); addProperty(_fontSize); @@ -174,11 +174,11 @@ DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dict _activeFlash.setViewOption(properties::Property::ViewOptions::Color); addProperty(_activeFlash); - _font = OsEng.fontManager().font(_fontName, _fontSize); + _font = global::fontManager.font(_fontName, _fontSize); } void DashboardItemInstruments::render(glm::vec2& penPosition) { - double currentTime = OsEng.timeManager().time().j2000Seconds(); + double currentTime = global::timeManager.time().j2000Seconds(); if (!ImageSequencer::ref().isReady()) { return; @@ -228,7 +228,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { ); std::string str = SpiceManager::ref().dateFromEphemerisTime( - sequencer.nextCaptureTime(OsEng.timeManager().time().j2000Seconds()), + sequencer.nextCaptureTime(global::timeManager.time().j2000Seconds()), "YYYY MON DD HR:MN:SC" ); @@ -312,7 +312,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { glm::vec2 DashboardItemInstruments::size() const { glm::vec2 size = { 0.f, 0.f }; //return ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( - double currentTime = OsEng.timeManager().time().j2000Seconds(); + double currentTime = global::timeManager.time().j2000Seconds(); if (!ImageSequencer::ref().isReady()) { return { 0.f, 0.f }; diff --git a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp index 33dbf8d8f0..a7f8f54681 100644 --- a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp +++ b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -132,8 +132,7 @@ bool RenderableCrawlingLine::isReady() const { } void RenderableCrawlingLine::initializeGL() { - RenderEngine& renderEngine = OsEng.renderEngine(); - _program = renderEngine.buildRenderProgram( + _program = global::renderEngine.buildRenderProgram( "RenderableCrawlingLine", absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/crawlingline_vs.glsl"), absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/crawlingline_fs.glsl") @@ -168,9 +167,8 @@ void RenderableCrawlingLine::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_program) { - renderEngine.removeRenderProgram(_program.get()); + global::renderEngine.removeRenderProgram(_program.get()); _program = nullptr; } } diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index e4bfe2f4bc..80a414ce87 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -332,7 +332,7 @@ void RenderableFov::initializeGL() { SpacecraftInstrumentsModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_vs.glsl"), absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/fov_fs.glsl") @@ -480,7 +480,7 @@ void RenderableFov::deinitializeGL() { SpacecraftInstrumentsModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _program = nullptr; diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 7bb4fcc442..2df466d341 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -25,17 +25,15 @@ #include #include - #include #include -#include +#include #include #include #include #include #include #include - #include #include #include @@ -182,8 +180,7 @@ bool RenderableModelProjection::isReady() const { } void RenderableModelProjection::initializeGL() { - RenderEngine& renderEngine = OsEng.renderEngine(); - _programObject = renderEngine.buildRenderProgram( + _programObject = global::renderEngine.buildRenderProgram( "ModelShader", absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/renderableModel_vs.glsl"), absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/renderableModel_fs.glsl") @@ -241,7 +238,7 @@ void RenderableModelProjection::deinitializeGL() { _projectionComponent.deinitialize(); - OsEng.renderEngine().removeRenderProgram(_programObject.get()); + global::renderEngine.removeRenderProgram(_programObject.get()); _programObject = nullptr; } @@ -377,7 +374,7 @@ void RenderableModelProjection::update(const UpdateData& data) { // @TODO: Change this to remove PSC glm::dvec3 p = - OsEng.renderEngine().scene()->sceneGraphNode("Sun")->worldPosition() - + global::renderEngine.scene()->sceneGraphNode("Sun")->worldPosition() - data.modelTransform.translation; _sunPosition = diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index f722cf8276..ede68f199a 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -25,8 +25,7 @@ #include #include - -#include +#include #include #include #include @@ -79,8 +78,7 @@ void RenderablePlaneProjection::initializeGL() { glGenVertexArrays(1, &_quad); glGenBuffers(1, &_vertexPositionBuffer); - RenderEngine& renderEngine = OsEng.renderEngine(); - _shader = renderEngine.buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "Image Plane", absPath("${MODULE_BASE}/shaders/imageplane_vs.glsl"), absPath("${MODULE_BASE}/shaders/imageplane_fs.glsl") @@ -91,9 +89,8 @@ void RenderablePlaneProjection::initializeGL() { } void RenderablePlaneProjection::deinitializeGL() { - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shader) { - renderEngine.removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } @@ -258,8 +255,8 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime } if (!_moving) { - SceneGraphNode* thisNode = OsEng.renderEngine().scene()->sceneGraphNode(_name); - SceneGraphNode* newParent = OsEng.renderEngine().scene()->sceneGraphNode( + SceneGraphNode* thisNode = global::renderEngine.scene()->sceneGraphNode(_name); + SceneGraphNode* newParent = global::renderEngine.scene()->sceneGraphNode( _target.node ); if (thisNode && newParent) { diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index 0bd7fb8fd9..97c37f1bad 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -360,7 +360,7 @@ void RenderablePlanetProjection::initializeGL() { SpacecraftInstrumentsModule::ProgramObjectManager.request( ProjectiveProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProjectiveProgramName, absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/" "renderablePlanet_vs.glsl" @@ -450,7 +450,7 @@ void RenderablePlanetProjection::deinitializeGL() { SpacecraftInstrumentsModule::ProgramObjectManager.release( ProjectiveProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _programObject = nullptr; diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp index 32ef6be233..fd5762277a 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -284,7 +284,7 @@ void RenderableShadowCylinder::initializeGL() { _shader = SpacecraftInstrumentsModule::ProgramObjectManager.request( ProgramName, []() -> std::unique_ptr { - return OsEng.renderEngine().buildRenderProgram( + return global::renderEngine.buildRenderProgram( ProgramName, absPath( "${MODULE_SPACECRAFTINSTRUMENTS}/shaders/terminatorshadow_vs.glsl" @@ -303,7 +303,7 @@ void RenderableShadowCylinder::deinitializeGL() { SpacecraftInstrumentsModule::ProgramObjectManager.release( ProgramName, [](ghoul::opengl::ProgramObject* p) { - OsEng.renderEngine().removeRenderProgram(p); + global::renderEngine.removeRenderProgram(p); } ); _shader = nullptr; diff --git a/modules/spacecraftinstruments/util/imagesequencer.cpp b/modules/spacecraftinstruments/util/imagesequencer.cpp index 0043f5595a..d24687c879 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.cpp +++ b/modules/spacecraftinstruments/util/imagesequencer.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include diff --git a/modules/spacecraftinstruments/util/sequenceparser.cpp b/modules/spacecraftinstruments/util/sequenceparser.cpp index 3f9c885ff2..73268a88b8 100644 --- a/modules/spacecraftinstruments/util/sequenceparser.cpp +++ b/modules/spacecraftinstruments/util/sequenceparser.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include @@ -94,7 +94,7 @@ void writeToBuffer(std::vector& buffer, size_t& currentWriteL void SequenceParser::sendPlaybookInformation(const std::string& name) { std::string fullName = std::string(PlaybookIdentifierName) + "_" + name; - _messageIdentifier = OsEng.networkEngine().identifier(fullName); + _messageIdentifier = global::networkEngine.identifier(fullName); std::vector buffer(1024); size_t currentWriteLocation = 0; @@ -189,7 +189,7 @@ void SequenceParser::sendPlaybookInformation(const std::string& name) { buffer.resize(currentWriteLocation); //OsEng.networkEngine()->publishMessage(PlaybookIdentifier, buffer); - OsEng.networkEngine().setInitialConnectionMessage(_messageIdentifier, buffer); + global::networkEngine.setInitialConnectionMessage(_messageIdentifier, buffer); } -} +} // namespace openspace diff --git a/modules/sync/syncmodule.cpp b/modules/sync/syncmodule.cpp index 26d0001b53..eceb8a08da 100644 --- a/modules/sync/syncmodule.cpp +++ b/modules/sync/syncmodule.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -114,11 +114,7 @@ void SyncModule::internalInitialize(const ghoul::Dictionary& configuration) { _torrentClient.initialize(); - // Deinitialize - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Deinitialize, - [&]() { _torrentClient.deinitialize(); } - ); + global::callback::deinitialize.push_back([&]() { _torrentClient.deinitialize(); }); } void SyncModule::internalDeinitialize() { diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index d21be14d61..78ccd4e7af 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include diff --git a/modules/sync/tasks/syncassettask.cpp b/modules/sync/tasks/syncassettask.cpp index b0890bfef0..658e3309ab 100644 --- a/modules/sync/tasks/syncassettask.cpp +++ b/modules/sync/tasks/syncassettask.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -104,7 +104,7 @@ void SyncAssetTask::perform(const Task::ProgressCallback& progressCallback) { registerCoreClasses(scriptEngine); - for (OpenSpaceModule* m : OsEng.moduleEngine().modules()) { + for (OpenSpaceModule* m : global::moduleEngine.modules()) { scriptEngine.addLibrary(m->luaLibrary()); for (scripting::LuaLibrary& l : m->luaLibraries()) { diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 4168af4628..ffea749fa7 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -26,8 +26,8 @@ #include #include +#include #include -#include #include #include #include @@ -62,7 +62,8 @@ #pragma warning (pop) #endif // WIN32 -#include +#include +#include #include namespace { @@ -363,8 +364,7 @@ void TouchInteraction::updateStateFromInput(const std::vector& list, } //Code for lower-right corner double-tap to zoom-out - WindowWrapper& wrapper = OsEng.windowWrapper(); - glm::ivec2 res = wrapper.currentWindowSize(); + glm::ivec2 res = global::windowDelegate.currentWindowSize(); glm::dvec2 pos = glm::vec2( list.at(0).getScreenX(res.x), list.at(0).getScreenY(res.y) @@ -414,14 +414,13 @@ bool TouchInteraction::guiMode(const std::vector& list) { if (_ignoreGui) { return false; } - WindowWrapper& wrapper = OsEng.windowWrapper(); - glm::ivec2 res = wrapper.currentWindowSize(); + glm::ivec2 res = global::windowDelegate.currentWindowSize(); glm::dvec2 pos = glm::vec2( list.at(0).getScreenX(res.x), list.at(0).getScreenY(res.y) ); - ImGUIModule& module = *(OsEng.moduleEngine().module()); + ImGUIModule& module = *(global::moduleEngine.module()); _guiON = module.gui.isEnabled(); if (_tap && list.size() == 1 && @@ -637,7 +636,7 @@ void TouchInteraction::directControl(const std::vector& list) { // normalized -1 to 1 coordinates on screen screenPoints.emplace_back(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5)); } else { - OsEng.moduleEngine().module()->touchInput = { + global::moduleEngine.module()->touchInput = { true, glm::dvec2(0.0, 0.0), 1 @@ -695,7 +694,7 @@ void TouchInteraction::directControl(const std::vector& list) { else { // prevents touch to infinitely be active (due to windows bridge case where event // doesnt get consumed sometimes when LMA fails to converge) - OsEng.moduleEngine().module()->touchInput = { + global::moduleEngine.module()->touchInput = { true, glm::dvec2(0.0, 0.0), 1 @@ -715,7 +714,7 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { "Kerberos", "Hydra", "Charon", "Tethys", "OsirisRex", "Bennu" }; std::vector selectableNodes; - for (SceneGraphNode* node : OsEng.renderEngine().scene()->allSceneGraphNodes()) { + for (SceneGraphNode* node : global::renderEngine.scene()->allSceneGraphNodes()) { for (const std::string& name : selectables) { if (node->identifier() == name) { selectableNodes.push_back(node); @@ -1142,7 +1141,7 @@ void TouchInteraction::computeVelocities(const std::vector& list, setFocusNode(_pickingSelected); // cant do setFocusNode() since TouchInteraction is not subclass of // InteractionMode - OsEng.navigationHandler().setFocusNode(_focusNode); + global::navigationHandler.setFocusNode(_focusNode); // rotate camera to look at new focus, using slerp quat glm::dvec3 camToFocus = _focusNode->worldPosition() - @@ -1202,7 +1201,7 @@ void TouchInteraction::step(double dt) { // since functions cant be called directly (TouchInteraction not a subclass of // InteractionMode) - setFocusNode(OsEng.navigationHandler().focusNode()); + setFocusNode(global::navigationHandler.focusNode()); if (_focusNode && _camera) { // Create variables from current state dvec3 camPos = _camera->positionVec3(); @@ -1400,14 +1399,14 @@ void TouchInteraction::resetAfterInput() { _debugProperties.interactionMode = "None"; #endif if (_directTouchMode && !_selected.empty() && _lmSuccess) { - double spinDelta = _spinSensitivity / OsEng.windowWrapper().averageDeltaTime(); + double spinDelta = _spinSensitivity / global::windowDelegate.averageDeltaTime(); if (glm::length(_lastVel.orbit) > _orbitSpeedThreshold) { // allow node to start "spinning" after direct-manipulation finger is let go _vel.orbit = _lastVel.orbit * spinDelta; } } // Reset emulated mouse values - ImGUIModule& module = *(OsEng.moduleEngine().module()); + ImGUIModule& module = *(global::moduleEngine.module()); if (_guiON) { bool activeLastFrame = module.touchInput.action; module.touchInput.active = false; diff --git a/modules/touch/src/touchmarker.cpp b/modules/touch/src/touchmarker.cpp index 64787c1c2a..41693ef4cd 100644 --- a/modules/touch/src/touchmarker.cpp +++ b/modules/touch/src/touchmarker.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -95,7 +95,7 @@ void TouchMarker::initialize() { glGenVertexArrays(1, &_quad); // generate array glGenBuffers(1, &_vertexPositionBuffer); // generate buffer - _shader = OsEng.renderEngine().buildRenderProgram( + _shader = global::renderEngine.buildRenderProgram( "MarkerProgram", absPath("${MODULE_TOUCH}/shaders/marker_vs.glsl"), absPath("${MODULE_TOUCH}/shaders/marker_fs.glsl") @@ -111,9 +111,8 @@ void TouchMarker::deinitialize() { glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shader) { - renderEngine.removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } } diff --git a/modules/touch/src/tuioear.cpp b/modules/touch/src/tuioear.cpp index e5fd37b960..ebf4455e53 100644 --- a/modules/touch/src/tuioear.cpp +++ b/modules/touch/src/tuioear.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include diff --git a/modules/touch/touchmodule.cpp b/modules/touch/touchmodule.cpp index bae93f2a40..8e8e8f894d 100644 --- a/modules/touch/touchmodule.cpp +++ b/modules/touch/touchmodule.cpp @@ -24,15 +24,13 @@ #include -#include -#include +#include +#include +#include #include #include #include - #include -//#include - #include #include #include @@ -105,39 +103,25 @@ bool TouchModule::hasNewInput() { } } -TouchModule::TouchModule() - : OpenSpaceModule("Touch") -{ +TouchModule::TouchModule() : OpenSpaceModule("Touch") { addPropertySubOwner(touch); addPropertySubOwner(markers); - if (!OpenSpaceEngine::isCreated()) { - return; - } - - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::InitializeGL, - [&]() { + global::callback::initializeGL.push_back([&]() { LDEBUGC("TouchModule", "Initializing TouchMarker OpenGL"); markers.initialize(); - } - ); + }); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::DeinitializeGL, - [&]() { + global::callback::deinitializeGL.push_back([&]() { LDEBUGC("TouchMarker", "Deinitialize TouchMarker OpenGL"); markers.deinitialize(); - } - ); + }); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::PreSync, - [&]() { - touch.setCamera(OsEng.navigationHandler().camera()); - touch.setFocusNode(OsEng.navigationHandler().focusNode()); + global::callback::preSync.push_back([&]() { + touch.setCamera(global::navigationHandler.camera()); + touch.setFocusNode(global::navigationHandler.focusNode()); - if (hasNewInput() && OsEng.windowWrapper().isMaster()) { + if (hasNewInput() && global::windowDelegate.isMaster()) { touch.updateStateFromInput(listOfContactPoints, lastProcessed); } else if (listOfContactPoints.empty()) { @@ -149,21 +133,15 @@ TouchModule::TouchModule() for (const TuioCursor& c : listOfContactPoints) { lastProcessed.emplace_back(c.getSessionID(), c.getPath().back()); } - // used to save data from solver, only calculated for one frame when user chooses - // in GUI + // used to save data from solver, only calculated for one frame when user chooses + // in GUI touch.unitTest(); - // calculate the new camera state for this frame - touch.step(OsEng.windowWrapper().deltaTime()); - } - ); + // calculate the new camera state for this frame + touch.step(global::windowDelegate.deltaTime()); + }); + + global::callback::render.push_back([&]() { markers.render(listOfContactPoints); }); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Render, - [&]() { - // render markers, customizable through the GUI - markers.render(listOfContactPoints); - } - ); } } // namespace openspace diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index f63f52be53..1a6457d64d 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -112,14 +112,14 @@ void RenderableToyVolume::initializeGL() { _raycaster = std::make_unique(_color); _raycaster->initialize(); - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); std::function onChange = [&](bool enabled) { if (enabled) { - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); } else { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); } }; @@ -135,7 +135,7 @@ void RenderableToyVolume::initializeGL() { void RenderableToyVolume::deinitializeGL() { if (_raycaster) { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); _raycaster = nullptr; } } diff --git a/modules/volume/rendering/renderabletimevaryingvolume.cpp b/modules/volume/rendering/renderabletimevaryingvolume.cpp index ec0991e6e7..b9382bbcdd 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.cpp +++ b/modules/volume/rendering/renderabletimevaryingvolume.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include @@ -353,13 +353,13 @@ void RenderableTimeVaryingVolume::initializeGL() { ); _raycaster->initialize(); - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); onEnabledChange([&](bool enabled) { if (enabled) { - OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster.get()); } else { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); } }); @@ -422,7 +422,7 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimes if (_volumeTimesteps.empty()) { return nullptr; } - double currentTime = OsEng.timeManager().time().j2000Seconds(); + double currentTime = global::timeManager.time().j2000Seconds(); // Get the first item with time > currentTime auto currentTimestepIt = _volumeTimesteps.upper_bound(currentTime); @@ -483,7 +483,7 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::timestepFrom void RenderableTimeVaryingVolume::jumpToTimestep(int target) { Timestep* t = timestepFromIndex(target); if (t) { - OsEng.timeManager().setTimeNextFrame(t->metadata.time); + global::timeManager.setTimeNextFrame(t->metadata.time); } } @@ -544,7 +544,7 @@ bool RenderableTimeVaryingVolume::isReady() const { void RenderableTimeVaryingVolume::deinitializeGL() { if (_raycaster) { - OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster.get()); _raycaster = nullptr; } } diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index 009bedebda..aa9e012377 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -47,10 +48,7 @@ WebBrowserModule::WebBrowserModule() : OpenSpaceModule(WebBrowserModule::Name) { _cefHost = std::make_unique(std::move(helperLocation)); LDEBUG("Starting CEF... done!"); - OsEng.registerModuleCallback( - OpenSpaceEngine::CallbackOption::Deinitialize, - [this]() { deinitialize(); } - ); + global::callback::deinitialize.push_back([this]() { deinitialize(); }); } WebBrowserModule::~WebBrowserModule() {} diff --git a/scripts/configuration_helper.lua b/scripts/configuration_helper.lua index 949de0b289..300d4c8ebf 100644 --- a/scripts/configuration_helper.lua +++ b/scripts/configuration_helper.lua @@ -784,11 +784,11 @@ function sgct.config.fisheye(arg) end if arg["tilt"] == nil then - arg["tilt"] = 0 + arg["tilt"] = 90 end if arg["background"] == nil then - arg["background"] = { r = 0.1, g = 0.1, b = 0.1, a = 1.0 } + arg["background"] = { r = 0.0, g = 0.0, b = 0.0, a = 1.0 } end if (arg["tracked"] ~= nil and arg["tracked"] == true) then @@ -871,7 +871,7 @@ function sgct.config.cube(arg) res = 1024 - size = {640, 360} + size = { 640, 360 } arg["scene"] = generateScene(arg) arg["settings"] = generateSettings(arg) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 64ddcc3389..d184485d31 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -33,17 +33,15 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/documentation/verifier.cpp ${OPENSPACE_BASE_DIR}/src/engine/configuration.cpp ${OPENSPACE_BASE_DIR}/src/engine/configuration_doc.inl - # ${OPENSPACE_BASE_DIR}/src/engine/configurationmanager.cpp - # ${OPENSPACE_BASE_DIR}/src/engine/configurationmanager_doc.inl ${OPENSPACE_BASE_DIR}/src/engine/downloadmanager.cpp + ${OPENSPACE_BASE_DIR}/src/engine/globals.cpp + ${OPENSPACE_BASE_DIR}/src/engine/globalscallbacks.cpp ${OPENSPACE_BASE_DIR}/src/engine/logfactory.cpp ${OPENSPACE_BASE_DIR}/src/engine/moduleengine.cpp ${OPENSPACE_BASE_DIR}/src/engine/moduleengine_lua.inl ${OPENSPACE_BASE_DIR}/src/engine/openspaceengine.cpp ${OPENSPACE_BASE_DIR}/src/engine/syncengine.cpp ${OPENSPACE_BASE_DIR}/src/engine/virtualpropertymanager.cpp - ${OPENSPACE_BASE_DIR}/src/engine/wrapper/sgctwindowwrapper.cpp - ${OPENSPACE_BASE_DIR}/src/engine/wrapper/windowwrapper.cpp ${OPENSPACE_BASE_DIR}/src/interaction/camerainteractionstates.cpp ${OPENSPACE_BASE_DIR}/src/interaction/inputstate.cpp ${OPENSPACE_BASE_DIR}/src/interaction/joystickinputstate.cpp @@ -209,14 +207,15 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/documentation/verifier.inl ${OPENSPACE_BASE_DIR}/include/openspace/engine/configuration.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/downloadmanager.h + ${OPENSPACE_BASE_DIR}/include/openspace/engine/globals.h + ${OPENSPACE_BASE_DIR}/include/openspace/engine/globalscallbacks.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/logfactory.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/moduleengine.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/moduleengine.inl ${OPENSPACE_BASE_DIR}/include/openspace/engine/openspaceengine.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/syncengine.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/virtualpropertymanager.h - ${OPENSPACE_BASE_DIR}/include/openspace/engine/wrapper/sgctwindowwrapper.h - ${OPENSPACE_BASE_DIR}/include/openspace/engine/wrapper/windowwrapper.h + ${OPENSPACE_BASE_DIR}/include/openspace/engine/windowdelegate.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/delayedvariable.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/delayedvariable.inl ${OPENSPACE_BASE_DIR}/include/openspace/interaction/camerainteractionstates.h diff --git a/src/documentation/core_registration.cpp b/src/documentation/core_registration.cpp index e9dd870d24..54a4181d9f 100644 --- a/src/documentation/core_registration.cpp +++ b/src/documentation/core_registration.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -78,8 +77,7 @@ void registerCoreClasses(scripting::ScriptEngine& engine) { engine.addLibrary(SpiceManager::luaLibrary()); engine.addLibrary(Scene::luaLibrary()); engine.addLibrary(Time::luaLibrary()); - engine.addLibrary(WindowWrapper::luaLibrary()); - engine.addLibrary(interaction::KeyBindingManager::luaLibrary()); + engine.addLibrary(interaction::KeybindingManager::luaLibrary()); engine.addLibrary(interaction::NavigationHandler::luaLibrary()); engine.addLibrary(scripting::ScriptScheduler::luaLibrary()); engine.addLibrary(scripting::generalSystemCapabilities()); diff --git a/src/engine/configuration.cpp b/src/engine/configuration.cpp index f774bd0065..82851eddd0 100644 --- a/src/engine/configuration.cpp +++ b/src/engine/configuration.cpp @@ -92,176 +92,183 @@ namespace { constexpr const char* KeyShowNodeNames = "ShowNodeNames"; constexpr const char* KeyShowProgressbar = "ShowProgressbar"; constexpr const char* KeyModuleConfigurations = "ModuleConfigurations"; + + template + void getValue(ghoul::lua::LuaState& L, const char* name, T& value) { + using namespace openspace::configuration; + + auto it = std::find_if( + Configuration::Documentation.entries.begin(), + Configuration::Documentation.entries.end(), + [name](const openspace::documentation::DocumentationEntry& e) { + return e.key == name; + } + ); + + bool isOptional = + it != Configuration::Documentation.entries.end() + ? it->optional : + true; + + lua_getglobal(L, name); + if (isOptional && lua_isnil(L, -1)) { + return; + } + + if (!isOptional && lua_isnil(L, -1)) { + openspace::documentation::TestResult testResult = { + false, + { { + name, + openspace::documentation::TestResult::Offense::Reason::MissingKey + }}, + {} + }; + throw openspace::documentation::SpecificationError( + std::move(testResult), + "Configuration" + ); + } + + // NOLINTNEXTLINE + if constexpr (std::is_same_v>) { + ghoul::Dictionary d = ghoul::lua::value(L); + + std::vector res; + for (size_t i = 1; i <= d.size(); ++i) { + res.push_back(d.value(std::to_string(i))); + } + value = res; + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v>) { + ghoul::Dictionary d = ghoul::lua::value(L); + + std::map res; + for (size_t i = 0; i < d.size(); ++i) { + std::string key = d.keys()[i]; + std::string v = d.value(key); + res[std::move(key)] = std::move(v); + } + value = res; + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v>) { + ghoul::Dictionary d = ghoul::lua::value(L); + + std::map res; + for (size_t i = 0; i < d.size(); ++i) { + std::string key = d.keys()[i]; + ghoul::Dictionary v = d.value(key); + res[std::move(key)] = std::move(v); + } + value = res; + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v) { + Configuration::Logging& v = static_cast(value); + ghoul::Dictionary d = ghoul::lua::value(L); + + d.getValue(KeyLogLevel, v.level); + d.getValue(KeyImmediateFlush, v.forceImmediateFlush); + d.getValue(KeyCapabilitiesVerbosity, v.capabilitiesVerbosity); + + if (d.hasKeyAndValue(KeyLogs)) { + ghoul::Dictionary l = d.value(KeyLogs); + std::vector res; + for (size_t i = 1; i <= l.size(); ++i) { + res.push_back(l.value(std::to_string(i))); + } + v.logs = res; + } + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v) { + Configuration::DocumentationInfo& v = + static_cast(value); + ghoul::Dictionary d = ghoul::lua::value(L); + + d.getValue(KeyLuaDocumentation, v.lua); + d.getValue(KeyPropertyDocumentation, v.property); + d.getValue("ScenePropertyDocumentation", v.sceneProperty); + d.getValue(KeyKeyboardShortcuts, v.keyboard); + d.getValue(KeyDocumentation, v.documentation); + d.getValue(KeyFactoryDocumentation, v.factory); + d.getValue(KeyLicenseDocumentation, v.license); + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v) { + Configuration::LoadingScreen& v = + static_cast(value); + ghoul::Dictionary d = ghoul::lua::value(L); + + d.getValue(KeyShowMessage, v.isShowingMessages); + d.getValue(KeyShowNodeNames, v.isShowingNodeNames); + d.getValue(KeyShowProgressbar, v.isShowingProgressbar); + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v) { + Configuration::OpenGLDebugContext& v = + static_cast(value); + ghoul::Dictionary d = ghoul::lua::value(L); + + d.getValue(KeyActivate, v.isActive); + d.getValue(KeySynchronous, v.isSynchronous); + + if (d.hasKeyAndValue(KeyFilterIdentifier)) { + ghoul::Dictionary f = d.value(KeyFilterIdentifier); + + std::vector res; + for (size_t i = 1; i <= f.size(); ++i) { + Configuration::OpenGLDebugContext::IdentifierFilter filter; + ghoul::Dictionary fi = f.value(std::to_string(i)); + + double id = static_cast(filter.identifier); + fi.getValue(KeyIdentifier, id); + filter.identifier = static_cast(id); + fi.getValue(KeySource, filter.source); + fi.getValue(KeyType, filter.type); + + res.push_back(filter); + } + + v.identifierFilters = res; + } + + if (d.hasKeyAndValue(KeyFilterSeverity)) { + ghoul::Dictionary f = d.value(KeyFilterSeverity); + + std::vector res; + for (size_t i = 1; i <= f.size(); ++i) { + res.push_back(f.value(std::to_string(i))); + } + v.severityFilters = res; + } + } + // NOLINTNEXTLINE + else if constexpr (std::is_same_v) { + Configuration::HTTPProxy& v = static_cast(value); + ghoul::Dictionary d = ghoul::lua::value(L); + + d.getValue(KeyActivate, v.usingHttpProxy); + d.getValue(KeyAddress, v.address); + double p = static_cast(v.port); + d.getValue(KeyPort, p); + v.port = static_cast(p); + d.getValue(KeyAuthentication, v.authentication); + d.getValue(KeyUser, v.user); + d.getValue(KeyPassword, v.password); + } + else { + value = ghoul::lua::value(L); + } + } + } // namespace #include "configuration_doc.inl" -namespace openspace { - -template -void getValue(ghoul::lua::LuaState& L, const char* name, T& value) { - auto it = std::find_if( - Configuration::Documentation.entries.begin(), - Configuration::Documentation.entries.end(), - [name](const documentation::DocumentationEntry& e) { - return e.key == name; - } - ); - - bool isOptional = - it != Configuration::Documentation.entries.end() - ? it->optional : - true; - - lua_getglobal(L, name); - if (isOptional && lua_isnil(L, -1)) { - return; - } - - if (!isOptional && lua_isnil(L, -1)) { - documentation::TestResult testResult = { - false, - { { name, documentation::TestResult::Offense::Reason::MissingKey} }, - {} - }; - throw documentation::SpecificationError(std::move(testResult), "Configuration"); - } - - // NOLINTNEXTLINE - if constexpr (std::is_same_v>) { - ghoul::Dictionary d = ghoul::lua::value(L); - - std::vector res; - for (size_t i = 1; i <= d.size(); ++i) { - res.push_back(d.value(std::to_string(i))); - } - value = res; - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v>) { - ghoul::Dictionary d = ghoul::lua::value(L); - - std::map res; - for (size_t i = 0; i < d.size(); ++i) { - std::string key = d.keys()[i]; - std::string v = d.value(key); - res[std::move(key)] = std::move(v); - } - value = res; - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v>) { - ghoul::Dictionary d = ghoul::lua::value(L); - - std::map res; - for (size_t i = 0; i < d.size(); ++i) { - std::string key = d.keys()[i]; - ghoul::Dictionary v = d.value(key); - res[std::move(key)] = std::move(v); - } - value = res; - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v) { - Configuration::Logging& v = static_cast(value); - ghoul::Dictionary d = ghoul::lua::value(L); - - d.getValue(KeyLogLevel, v.level); - d.getValue(KeyLogDir, v.directory); - d.getValue(KeyPerformancePrefix, v.performancePrefix); - d.getValue(KeyImmediateFlush, v.forceImmediateFlush); - d.getValue(KeyCapabilitiesVerbosity, v.capabilitiesVerbosity); - - if (d.hasKeyAndValue(KeyLogs)) { - ghoul::Dictionary l = d.value(KeyLogs); - std::vector res; - for (size_t i = 1; i <= l.size(); ++i) { - res.push_back(l.value(std::to_string(i))); - } - v.logs = res; - } - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v) { - Configuration::DocumentationInfo& v = - static_cast(value); - ghoul::Dictionary d = ghoul::lua::value(L); - - d.getValue(KeyLuaDocumentation, v.lua); - d.getValue(KeyPropertyDocumentation, v.property); - d.getValue("ScenePropertyDocumentation", v.sceneProperty); - d.getValue(KeyKeyboardShortcuts, v.keyboard); - d.getValue(KeyDocumentation, v.documentation); - d.getValue(KeyFactoryDocumentation, v.factory); - d.getValue(KeyLicenseDocumentation, v.license); - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v) { - Configuration::LoadingScreen& v = - static_cast(value); - ghoul::Dictionary d = ghoul::lua::value(L); - - d.getValue(KeyShowMessage, v.isShowingMessages); - d.getValue(KeyShowNodeNames, v.isShowingNodeNames); - d.getValue(KeyShowProgressbar, v.isShowingProgressbar); - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v) { - Configuration::OpenGLDebugContext& v = - static_cast(value); - ghoul::Dictionary d = ghoul::lua::value(L); - - d.getValue(KeyActivate, v.isActive); - d.getValue(KeySynchronous, v.isSynchronous); - - if (d.hasKeyAndValue(KeyFilterIdentifier)) { - ghoul::Dictionary f = d.value(KeyFilterIdentifier); - - std::vector res; - for (size_t i = 1; i <= f.size(); ++i) { - Configuration::OpenGLDebugContext::IdentifierFilter filter; - ghoul::Dictionary fi = f.value(std::to_string(i)); - - double id = static_cast(filter.identifier); - fi.getValue(KeyIdentifier, id); - filter.identifier = static_cast(id); - fi.getValue(KeySource, filter.source); - fi.getValue(KeyType, filter.type); - - res.push_back(filter); - } - - v.identifierFilters = res; - } - - if (d.hasKeyAndValue(KeyFilterSeverity)) { - ghoul::Dictionary f = d.value(KeyFilterSeverity); - - std::vector res; - for (size_t i = 1; i <= f.size(); ++i) { - res.push_back(f.value(std::to_string(i))); - } - v.severityFilters = res; - } - } - // NOLINTNEXTLINE - else if constexpr (std::is_same_v) { - Configuration::HTTPProxy& v = static_cast(value); - ghoul::Dictionary d = ghoul::lua::value(L); - - d.getValue(KeyActivate, v.usingHttpProxy); - d.getValue(KeyAddress, v.address); - double p = static_cast(v.port); - d.getValue(KeyPort, p); - v.port = static_cast(p); - d.getValue(KeyAuthentication, v.authentication); - d.getValue(KeyUser, v.user); - d.getValue(KeyPassword, v.password); - } - else { - value = ghoul::lua::value(L); - } -} +namespace openspace::configuration { void parseLuaState(Configuration& configuration) { using namespace ghoul::lua; @@ -356,4 +363,4 @@ Configuration loadConfigurationFromFile(const std::string& filename) { return result; } -} // namespace openspace +} // namespace openspace::configuration diff --git a/src/engine/configuration_doc.inl b/src/engine/configuration_doc.inl index 2a87951fcf..87cb4b12c0 100644 --- a/src/engine/configuration_doc.inl +++ b/src/engine/configuration_doc.inl @@ -25,7 +25,7 @@ #include #include -namespace openspace { +namespace openspace::configuration { using namespace documentation; documentation::Documentation Configuration::Documentation = { @@ -482,4 +482,4 @@ documentation::Documentation Configuration::Documentation = { } }; -} // namespace openspace +} // namespace openspace::configuration diff --git a/src/engine/globals.cpp b/src/engine/globals.cpp new file mode 100644 index 0000000000..b20589d43f --- /dev/null +++ b/src/engine/globals.cpp @@ -0,0 +1,236 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2018 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace openspace::global { + +namespace detail { + +ghoul::fontrendering::FontManager& gFontManager() { + static ghoul::fontrendering::FontManager g({ 1536, 1536, 1 }); + return g; +} + +Dashboard& gDashboard() { + static Dashboard g; + return g; +} + +DeferredcasterManager& gDeferredcasterManager() { + static DeferredcasterManager g; + return g; +} + +DownloadManager& gDownloadManager() { + static DownloadManager g; + return g; +} + +LuaConsole& gLuaConsole() { + static LuaConsole g; + return g; +} + +MissionManager& gMissionManager() { + static MissionManager g; + return g; +} + +ModuleEngine& gModuleEngine() { + static ModuleEngine g; + return g; +} + +NetworkEngine& gNetworkEngine() { + static NetworkEngine g; + return g; +} + +OpenSpaceEngine& gOpenSpaceEngine() { + static OpenSpaceEngine g; + return g; +} + +ParallelPeer& gParallelPeer() { + static ParallelPeer g; + return g; +} + +RaycasterManager& gRaycasterManager() { + static RaycasterManager g; + return g; +} + +RenderEngine& gRenderEngine() { + static RenderEngine g; + return g; +} + +std::vector>& gScreenspaceRenderables() { + static std::vector> g; + return g; +} + +SyncEngine& gSyncEngine() { + static SyncEngine g(4096); + return g; +} + +TimeManager& gTimeManager() { + static TimeManager g; + return g; +} + +VirtualPropertyManager& gVirtualPropertyManager() { + static VirtualPropertyManager g; + return g; +} + +WindowDelegate& gWindowDelegate() { + static WindowDelegate g; + return g; +} + +configuration::Configuration& gConfiguration() { + static configuration::Configuration g; + return g; +} + +interaction::JoystickInputStates& gJoystickInputStates() { + static interaction::JoystickInputStates g; + return g; +} + +interaction::KeybindingManager& gKeybindingManager() { + static interaction::KeybindingManager g; + return g; +} + +interaction::NavigationHandler& gNavigationHandler() { + static interaction::NavigationHandler g; + return g; +} + +performance::PerformanceManager& gPerformanceManager() { + static performance::PerformanceManager g; + return g; +} + +properties::PropertyOwner& gRootPropertyOwner() { + static properties::PropertyOwner g({ "" }); + return g; +} + +properties::PropertyOwner& gScreenSpaceRootPropertyOwner() { + static properties::PropertyOwner g({ "ScreenSpace" }); + return g; +} + +scripting::ScriptEngine& gScriptEngine() { + static scripting::ScriptEngine g; + return g; +} + +scripting::ScriptScheduler& gScriptScheduler() { + static scripting::ScriptScheduler g; + return g; +} + +} // namespace detail + +void initialize() { + global::rootPropertyOwner.addPropertySubOwner(global::moduleEngine); + + global::navigationHandler.setPropertyOwner(&global::rootPropertyOwner); + // New property subowners also have to be added to the ImGuiModule callback! + global::rootPropertyOwner.addPropertySubOwner(global::navigationHandler); + global::rootPropertyOwner.addPropertySubOwner(global::timeManager); + + global::rootPropertyOwner.addPropertySubOwner(global::renderEngine); + global::rootPropertyOwner.addPropertySubOwner(global::screenSpaceRootPropertyOwner); + + global::rootPropertyOwner.addPropertySubOwner(global::parallelPeer); + global::rootPropertyOwner.addPropertySubOwner(global::luaConsole); + global::rootPropertyOwner.addPropertySubOwner(global::dashboard); + + global::syncEngine.addSyncable(&global::scriptEngine); +} + +void initializeGL() { + +} + +void deinitialize() { + for (std::unique_ptr& ssr : global::screenSpaceRenderables) { + ssr->deinitialize(); + } + + global::syncEngine.removeSyncables(global::timeManager.getSyncables()); + + global::moduleEngine.deinitialize(); + global::luaConsole.deinitialize(); + global::scriptEngine.deinitialize(); + global::fontManager.deinitialize(); +} + +void deinitializeGL() { + for (std::unique_ptr& ssr : global::screenSpaceRenderables) { + ssr->deinitializeGL(); + } + + global::renderEngine.deinitializeGL(); + global::moduleEngine.deinitializeGL(); +} + +} // namespace openspace::global diff --git a/src/engine/globalscallbacks.cpp b/src/engine/globalscallbacks.cpp new file mode 100644 index 0000000000..1a70f5a19b --- /dev/null +++ b/src/engine/globalscallbacks.cpp @@ -0,0 +1,99 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2018 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +namespace 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; +} + +} // namespace openspace::global::callback diff --git a/src/engine/moduleengine_lua.inl b/src/engine/moduleengine_lua.inl index 6855c76b70..d57f345f3e 100644 --- a/src/engine/moduleengine_lua.inl +++ b/src/engine/moduleengine_lua.inl @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include namespace openspace::luascriptfunctions { @@ -45,7 +45,7 @@ int isLoaded(lua_State* L) { ghoul::lua::PopValue::Yes ); - const std::vector& modules = OsEng.moduleEngine().modules(); + const std::vector& modules = global::moduleEngine.modules(); auto it = std::find_if( modules.begin(), diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index c6275ebe0c..dc80ecb1da 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -29,17 +29,19 @@ #include #include #include -#include +#include +#include #include #include #include #include -#include +#include #include #include #include #include #include +#include #include #include #include @@ -63,8 +65,6 @@ #include #include #include -#include -#include #include #include #include @@ -93,105 +93,19 @@ #include "openspaceengine_lua.inl" -using namespace openspace::scripting; -using namespace ghoul::filesystem; -using namespace ghoul::logging; -using namespace ghoul::cmdparser; - namespace { constexpr const char* _loggerCat = "OpenSpaceEngine"; - - constexpr const char* SgctConfigArgumentCommand = "-config"; - constexpr const int CacheVersion = 1; - - const glm::ivec3 FontAtlasSize{ 1536, 1536, 1 }; - - struct { - std::string configurationName; - std::string sgctConfigurationName; - std::string sceneName; - std::string cacheFolder; - std::string configurationOverwrite; - } commandlineArgumentPlaceholders; - - constexpr const openspace::properties::Property::PropertyInfo VersionInfo = { - "VersionInfo", - "Version Information", - "This value contains the full string identifying this OpenSpace Version" - }; - - constexpr const openspace::properties::Property::PropertyInfo SourceControlInfo = { - "SCMInfo", - "Source Control Management Information", - "This value contains information from the SCM, such as commit hash and branch" - }; } // namespace namespace openspace { -namespace properties { class Property; } - class Scene; -OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr; - -OpenSpaceEngine::OpenSpaceEngine(std::string programName, - std::unique_ptr windowWrapper) - : _configuration(new Configuration) - , _scene(nullptr) - , _dashboard(new Dashboard) - , _downloadManager(std::make_unique()) - , _console(new LuaConsole) - , _moduleEngine(new ModuleEngine) - , _networkEngine(new NetworkEngine) - , _parallelPeer(new ParallelPeer) - , _renderEngine(new RenderEngine) - , _syncEngine(std::make_unique(4096)) - , _timeManager(new TimeManager) - , _windowWrapper(std::move(windowWrapper)) - , _commandlineParser(new ghoul::cmdparser::CommandlineParser( - std::move(programName), - ghoul::cmdparser::CommandlineParser::AllowUnknownCommands::Yes - )) - , _navigationHandler(new interaction::NavigationHandler) - , _keyBindingManager(new interaction::KeyBindingManager) - , _scriptEngine(new scripting::ScriptEngine) - , _scriptScheduler(new scripting::ScriptScheduler) - , _virtualPropertyManager(new VirtualPropertyManager) - , _rootPropertyOwner(new properties::PropertyOwner({ "" })) +OpenSpaceEngine::OpenSpaceEngine() + : _scene(nullptr) , _loadingScreen(nullptr) - , _versionInformation{ - properties::StringProperty(VersionInfo, OPENSPACE_VERSION_STRING_FULL), - properties::StringProperty(SourceControlInfo, OPENSPACE_GIT_FULL) - } { - _rootPropertyOwner->addPropertySubOwner(_moduleEngine.get()); - - _navigationHandler->setPropertyOwner(_rootPropertyOwner.get()); - // New property subowners also have to be added to the ImGuiModule callback! - _rootPropertyOwner->addPropertySubOwner(_navigationHandler.get()); - _rootPropertyOwner->addPropertySubOwner(_timeManager.get()); - - _rootPropertyOwner->addPropertySubOwner(_renderEngine.get()); - _rootPropertyOwner->addPropertySubOwner(_renderEngine->screenSpaceOwner()); - - // The virtual property manager is not part of the rootProperty owner since it cannot - // have an identifier or the "regex as identifier" trick would not work - //_rootPropertyOwner->addPropertySubOwner(_virtualPropertyManager.get()); - - if (_windowWrapper) { - _rootPropertyOwner->addPropertySubOwner(_windowWrapper.get()); - } - _rootPropertyOwner->addPropertySubOwner(_parallelPeer.get()); - _rootPropertyOwner->addPropertySubOwner(_console.get()); - _rootPropertyOwner->addPropertySubOwner(_dashboard.get()); - - _versionInformation.versionString.setReadOnly(true); - _rootPropertyOwner->addProperty(_versionInformation.versionString); - _versionInformation.sourceControlInformation.setReadOnly(true); - _rootPropertyOwner->addProperty(_versionInformation.sourceControlInformation); - FactoryManager::initialize(); FactoryManager::ref().addFactory( std::make_unique>(), @@ -232,166 +146,46 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, SpiceManager::initialize(); TransformationManager::initialize(); - - _syncEngine->addSyncable(_scriptEngine.get()); } -OpenSpaceEngine& OpenSpaceEngine::ref() { - ghoul_assert(_engine, "OpenSpaceEngine not created"); - return *_engine; +OpenSpaceEngine::~OpenSpaceEngine() {} // NOLINT + +void deinitialize() { } -bool OpenSpaceEngine::isCreated() { - return _engine != nullptr; -} - -void OpenSpaceEngine::create(int argc, char** argv, - std::unique_ptr windowWrapper, - std::vector& sgctArguments, - bool& requestClose, bool consoleLog) -{ - ghoul_assert(!_engine, "OpenSpaceEngine was already created"); - - requestClose = false; - - LDEBUG("Initialize FileSystem"); - - ghoul::initialize(); - - // Initialize the LogManager and add the console log as this will be used every time - // and we need a fall back if something goes wrong between here and when we add the - // logs from the configuration file. If the user requested as specific loglevel in the - // configuration file, we will deinitialize this LogManager and reinitialize it later - // with the correct LogLevel - LogManager::initialize( - LogLevel::Debug, - ghoul::logging::LogManager::ImmediateFlush::Yes - ); - if (consoleLog) { - LogMgr.addLog(std::make_unique()); - } - - // Sanity check of values - if (argc < 1 || argv == nullptr) { - throw ghoul::RuntimeError( - "No arguments were passed to this function", - "OpenSpaceEngine" - ); - } - - // Create other objects - LDEBUG("Creating OpenSpaceEngine"); - _engine = new OpenSpaceEngine(std::string(argv[0]), std::move(windowWrapper)); - - // Query modules for commandline arguments - _engine->gatherCommandlineArguments(); - - // Parse commandline arguments - std::vector args(argv, argv + argc); - std::vector arguments = - _engine->_commandlineParser->setCommandLine(args); - - bool showHelp = _engine->_commandlineParser->execute(); - if (showHelp) { - _engine->_commandlineParser->displayHelp(std::cout); - requestClose = true; - return; - } - - sgctArguments = std::move(arguments); - - // Find configuration - std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName; - if (configurationFilePath.empty()) { - LDEBUG("Finding configuration"); - configurationFilePath = findConfiguration(); - } - configurationFilePath = absPath(configurationFilePath); - - if (!FileSys.fileExists(configurationFilePath)) { - throw ghoul::FileNotFoundError( - "Configuration file '" + configurationFilePath + "'" - ); - } - LINFO(fmt::format("Configuration Path: '{}'", configurationFilePath)); - - // Loading configuration from disk - LDEBUG("Loading configuration from disk"); - try { - *_engine->_configuration = loadConfigurationFromFile(configurationFilePath); - - // If the user requested a commandline-based configuation script that should - // overwrite some of the values, this is the time to do it - if (!commandlineArgumentPlaceholders.configurationOverwrite.empty()) { - LDEBUG("Executing Lua script passed through the commandline:"); - LDEBUG(commandlineArgumentPlaceholders.configurationOverwrite); - ghoul::lua::runScript( - _engine->_configuration->state, - commandlineArgumentPlaceholders.configurationOverwrite - ); - parseLuaState(*_engine->_configuration); - } - } - catch (const documentation::SpecificationError& e) { - LFATAL(fmt::format( - "Loading of configuration file '{}' failed", configurationFilePath - )); - for (const documentation::TestResult::Offense& o : e.result.offenses) { - LERRORC(o.offender, ghoul::to_string(o.reason)); - } - for (const documentation::TestResult::Warning& w : e.result.warnings) { - LWARNINGC(w.offender, ghoul::to_string(w.reason)); - } - throw; - } - catch (const ghoul::RuntimeError& e) { - LFATAL(fmt::format( - "Loading of configuration file '{}' failed", configurationFilePath - )); - LFATALC(e.component, e.message); - throw; - } - +void OpenSpaceEngine::initialize() { + LTRACE("OpenSpaceEngine::initialize(begin)"); // Registering Path tokens. If the BASE path is set, it is the only one that will // overwrite the default path of the cfg directory for (const std::pair& path : - _engine->_configuration->pathTokens) + global::configuration.pathTokens) { - std::string fullKey = - FileSystem::TokenOpeningBraces + path.first + FileSystem::TokenClosingBraces; - LDEBUGC( - "ConfigurationManager", - fmt::format("Registering path {}: {}", fullKey, path.second) - ); + std::string fullKey = ghoul::filesystem::FileSystem::TokenOpeningBraces + + path.first + + ghoul::filesystem::FileSystem::TokenClosingBraces; + LDEBUG(fmt::format("Registering path {}: {}", fullKey, path.second)); - bool override = (fullKey == "${BASE}"); + const bool override = (fullKey == "${BASE}"); if (override) { - LINFOC( - "ConfigurationManager", - fmt::format("Overriding base path with '{}'", path.second) - ); + LINFO(fmt::format("Overriding base path with '{}'", path.second)); } using Override = ghoul::filesystem::FileSystem::Override; FileSys.registerPathToken( std::move(fullKey), std::move(path.second), - override ? Override::Yes : Override::No + Override(override) ); } - const bool hasCacheCommandline = !commandlineArgumentPlaceholders.cacheFolder.empty(); - const bool hasCacheConfig = _engine->_configuration->usePerSceneCache; + global::initialize(); + + std::string cacheFolder = absPath("${CACHE}"); - if (hasCacheCommandline || hasCacheConfig) { - if (hasCacheCommandline) { - cacheFolder = commandlineArgumentPlaceholders.cacheFolder; - } - if (hasCacheConfig) { - std::string scene = _engine->_configuration->asset; - cacheFolder += "-" + ghoul::filesystem::File(scene).baseName(); - } + if (global::configuration.usePerSceneCache) { + std::string scene = global::configuration.asset; + cacheFolder += "-" + ghoul::filesystem::File(scene).baseName(); LINFO(fmt::format("Old cache: {}", absPath("${CACHE}"))); LINFO(fmt::format("New cache: {}", cacheFolder)); @@ -410,26 +204,6 @@ void OpenSpaceEngine::create(int argc, char** argv, } } - // Initialize the requested logs from the configuration file - _engine->configureLogging(consoleLog); - - LINFOC("OpenSpace Version", std::string(OPENSPACE_VERSION_STRING_FULL)); - LINFOC("Commit", std::string(OPENSPACE_GIT_FULL)); - - // Register modules - _engine->_moduleEngine->initialize(_engine->_configuration->moduleConfigurations); - - // After registering the modules, the documentations for the available classes - // can be added as well - for (OpenSpaceModule* m : _engine->_moduleEngine->modules()) { - for (const documentation::Documentation& doc : m->documentations()) { - DocEng.addDocumentation(doc); - } - } - - DocEng.addDocumentation(Configuration::Documentation); - - // Create the cachemanager try { FileSys.createCacheManager(cacheFolder, CacheVersion); } @@ -438,77 +212,127 @@ void OpenSpaceEngine::create(int argc, char** argv, LFATALC(e.component, e.message); } + + + // Initialize the requested logs from the configuration file + // We previously initialized the LogManager with a console log to provide some logging + // until we know which logs should be added + if (ghoul::logging::LogManager::isInitialized()) { + ghoul::logging::LogManager::deinitialize(); + } + + ghoul::logging::LogLevel level = ghoul::logging::levelFromString( + global::configuration.logging.level + ); + bool immediateFlush = global::configuration.logging.forceImmediateFlush; + + using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; + ghoul::logging::LogManager::initialize(level, ImmediateFlush(immediateFlush)); + LogMgr.addLog(std::make_unique()); + + for (const ghoul::Dictionary& log : global::configuration.logging.logs) { + try { + LogMgr.addLog(createLog(log)); + } + catch (const documentation::SpecificationError& e) { + LERROR("Failed loading of log"); + for (const documentation::TestResult::Offense& o : e.result.offenses) { + LERRORC(o.offender, ghoul::to_string(o.reason)); + } + for (const documentation::TestResult::Warning& w : e.result.warnings) { + LWARNINGC(w.offender, ghoul::to_string(w.reason)); + } + throw; + } + } + +#ifdef WIN32 + if (IsDebuggerPresent()) { + LogMgr.addLog(std::make_unique()); + } +#endif // WIN32 + +#ifndef GHOUL_LOGGING_ENABLE_TRACE + LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); + + if (level == ghoul::logging::LogLevel::Trace) { + LWARNING( + "Desired logging level is set to 'Trace' but application was " << + "compiled without Trace support" + ); + } +#endif // GHOUL_LOGGING_ENABLE_TRACE + + + + LINFOC("OpenSpace Version", std::string(OPENSPACE_VERSION_STRING_FULL)); + LINFOC("Commit", std::string(OPENSPACE_GIT_FULL)); + + // Register modules + global::moduleEngine.initialize(global::configuration.moduleConfigurations); + + // After registering the modules, the documentations for the available classes + // can be added as well + for (OpenSpaceModule* m : global::moduleEngine.modules()) { + for (const documentation::Documentation& doc : m->documentations()) { + DocEng.addDocumentation(doc); + } + } + DocEng.addDocumentation(configuration::Configuration::Documentation); + // Register the provided shader directories ghoul::opengl::ShaderPreprocessor::addIncludePath(absPath("${SHADERS}")); - // Determining SGCT configuration file - LDEBUG("Determining SGCT configuration file"); - std::string sgctConfigurationPath = _engine->_configuration->windowConfiguration; - LDEBUG(fmt::format("SGCT Configuration file: {}", sgctConfigurationPath)); + // Register Lua script functions + LDEBUG("Registering Lua libraries"); + registerCoreClasses(global::scriptEngine); - if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) { - LDEBUG(fmt::format( - "Overwriting SGCT configuration file with commandline argument: {}", - commandlineArgumentPlaceholders.sgctConfigurationName - )); - sgctConfigurationPath = commandlineArgumentPlaceholders.sgctConfigurationName; + global::scriptEngine.addLibrary(global::openSpaceEngine._assetManager->luaLibrary()); + + for (OpenSpaceModule* module : global::moduleEngine.modules()) { + global::scriptEngine.addLibrary(module->luaLibrary()); + + for (scripting::LuaLibrary& l : module->luaLibraries()) { + global::scriptEngine.addLibrary(l); + } } - // Prepend the outgoing sgctArguments with the program name - // as well as the configuration file that sgct is supposed to use - sgctArguments.insert(sgctArguments.begin(), argv[0]); - sgctArguments.insert(sgctArguments.begin() + 1, SgctConfigArgumentCommand); - sgctArguments.insert(sgctArguments.begin() + 2, absPath(sgctConfigurationPath)); + global::scriptEngine.initialize(); + + writeStaticDocumentation(); + + _shutdown.waitTime = global::configuration.shutdownCountdown; + + global::navigationHandler.initialize(); + + global::renderEngine.initialize(); + + for (const std::function& func : global::callback::initialize) { + func(); + } // Set up asset loader std::unique_ptr w = std::make_unique(); SynchronizationWatcher* rawWatcher = w.get(); - _engine->_assetManager = std::make_unique( + global::openSpaceEngine._assetManager = std::make_unique( std::make_unique( - *OsEng.scriptEngine().luaState(), + *global::scriptEngine.luaState(), rawWatcher, FileSys.absPath("${ASSETS}") ), std::move(w) ); + + global::openSpaceEngine._assetManager->initialize(); + scheduleLoadSingleAsset(global::configuration.asset); + + LTRACE("OpenSpaceEngine::initialize(end)"); } -void OpenSpaceEngine::destroy() { - if (_engine->parallelPeer().status() != ParallelConnection::Status::Disconnected) { - _engine->parallelPeer().disconnect(); - } - - _engine->_syncEngine->removeSyncables(_engine->timeManager().getSyncables()); - if (_engine->_scene && _engine->_scene->camera()) { - _engine->_syncEngine->removeSyncables(_engine->_scene->camera()->getSyncables()); - } - - _engine->_renderEngine->deinitializeGL(); - - _engine->_moduleEngine->deinitializeGL(); - _engine->_moduleEngine->deinitialize(); - _engine->_console->deinitialize(); - - _engine->_scriptEngine->deinitialize(); - - delete _engine; - _engine = nullptr; - FactoryManager::deinitialize(); - TransformationManager::deinitialize(); - SpiceManager::deinitialize(); - - ghoul::fontrendering::FontRenderer::deinitialize(); - - LogManager::deinitialize(); - - ghoul::deinitialize(); - LTRACE("OpenSpaceEngine::destroy(end)"); -} - -void OpenSpaceEngine::initialize() { - LTRACE("OpenSpaceEngine::initialize(begin)"); +void OpenSpaceEngine::initializeGL() { + LTRACE("OpenSpaceEngine::initializeGL(begin)"); //glbinding::Binding::useCurrentContext(); glbinding::Binding::initialize(glfwGetProcAddress); @@ -516,7 +340,7 @@ void OpenSpaceEngine::initialize() { // clear the screen so the user doesn't have to see old buffer contents left on the // graphics card LDEBUG("Clearing all Windows"); - _windowWrapper->clearAllWindows(glm::vec4(0.f, 0.f, 0.f, 1.f)); + global::windowDelegate.clearAllWindows(glm::vec4(0.f, 0.f, 0.f, 1.f)); LDEBUG("Adding system components"); // Detect and log OpenCL and OpenGL versions and available devices @@ -533,14 +357,14 @@ void OpenSpaceEngine::initialize() { using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity; Verbosity verbosity = ghoul::from_string( - _engine->_configuration->logging.capabilitiesVerbosity - ); + global::configuration.logging.capabilitiesVerbosity + ); SysCap.logCapabilities(verbosity); // Check the required OpenGL versions of the registered modules ghoul::systemcapabilities::Version version = - _engine->_moduleEngine->requiredOpenGLVersion(); + global::moduleEngine.requiredOpenGLVersion(); LINFO(fmt::format("Required OpenGL version: {}", ghoul::to_string(version))); if (OpenGLCap.openGLVersion() < version) { @@ -554,7 +378,7 @@ void OpenSpaceEngine::initialize() { { // Check the available OpenGL extensions against the required extensions using OCC = ghoul::systemcapabilities::OpenGLCapabilitiesComponent; - for (OpenSpaceModule* m : _engine->_moduleEngine->modules()) { + for (OpenSpaceModule* m : global::moduleEngine.modules()) { for (const std::string& ext : m->requiredOpenGLExtensions()) { if (!SysCap.component().isExtensionSupported(ext)) { LFATAL(fmt::format( @@ -567,54 +391,212 @@ void OpenSpaceEngine::initialize() { } } - // Register Lua script functions - LDEBUG("Registering Lua libraries"); - registerCoreClasses(*_scriptEngine); - - _scriptEngine->addLibrary(_engine->_assetManager->luaLibrary()); - - for (OpenSpaceModule* module : _moduleEngine->modules()) { - _scriptEngine->addLibrary(module->luaLibrary()); - - for (scripting::LuaLibrary& l : module->luaLibraries()) { - _scriptEngine->addLibrary(l); - } - } - - scriptEngine().initialize(); - - writeStaticDocumentation(); - - _shutdown.waitTime = _engine->_configuration->shutdownCountdown; - - if (!commandlineArgumentPlaceholders.sceneName.empty()) { - _engine->_configuration->asset = commandlineArgumentPlaceholders.sceneName; - } - - // Initialize the NavigationHandler - _navigationHandler->initialize(); - - // Load a light and a monospaced font loadFonts(); - - _renderEngine->initialize(); _loadingScreen = std::make_unique( - LoadingScreen::ShowMessage(_configuration->loadingScreen.isShowingMessages), - LoadingScreen::ShowNodeNames(_configuration->loadingScreen.isShowingNodeNames), - LoadingScreen::ShowProgressbar(_configuration->loadingScreen.isShowingProgressbar) - ); + LoadingScreen::ShowMessage(global::configuration.loadingScreen.isShowingMessages), + LoadingScreen::ShowNodeNames( + global::configuration.loadingScreen.isShowingNodeNames + ), + LoadingScreen::ShowProgressbar( + global::configuration.loadingScreen.isShowingProgressbar + ) + ); _loadingScreen->render(); - for (const std::function& func : _moduleCallbacks.initialize) { + + + + + LTRACE("OpenSpaceEngine::initializeGL::Console::initialize(begin)"); + try { + global::luaConsole.initialize(); + } + catch (ghoul::RuntimeError& e) { + LERROR("Error initializing Console with error:"); + LERRORC(e.component, e.message); + } + LTRACE("OpenSpaceEngine::initializeGL::Console::initialize(end)"); + + LTRACE("OpenSpaceEngine::initializeGL::DebugContext(begin)"); + bool debugActive = global::configuration.openGLDebugContext.isActive; + + // Debug output is not available before 4.3 + const ghoul::systemcapabilities::Version minVersion = { 4, 3, 0 }; + if (debugActive && OpenGLCap.openGLVersion() < minVersion) { + LINFO("OpenGL Debug context requested, but insufficient version available"); + debugActive = false; + } + + if (debugActive) { + using namespace ghoul::opengl::debug; + + bool synchronous = global::configuration.openGLDebugContext.isSynchronous; + setDebugOutput(DebugOutput(debugActive), SynchronousOutput(synchronous)); + + for (const configuration::Configuration::OpenGLDebugContext::IdentifierFilter&f : + global::configuration.openGLDebugContext.identifierFilters) + { + setDebugMessageControl( + ghoul::from_string(f.source), + ghoul::from_string(f.type), + { f.identifier }, + Enabled::No + ); + + } + + for (const std::string& sev : + global::configuration.openGLDebugContext.severityFilters) + { + setDebugMessageControl( + Source::DontCare, + Type::DontCare, + ghoul::from_string(sev), + Enabled::No + ); + } + + auto callback = [](Source source, Type type, Severity severity, + unsigned int id, std::string message) -> void + { + const std::string s = ghoul::to_string(source); + const std::string t = ghoul::to_string(type); + + const std::string category = + "OpenGL (" + s + ") [" + t + "] {" + std::to_string(id) + "}"; + switch (severity) { + case Severity::High: + LERRORC(category, message); + break; + case Severity::Medium: + LWARNINGC(category, message); + break; + case Severity::Low: + LINFOC(category, message); + break; + case Severity::Notification: + LDEBUGC(category, message); + break; + default: + throw ghoul::MissingCaseException(); + } + }; + ghoul::opengl::debug::setDebugCallback(callback); + } + LTRACE("OpenSpaceEngine::initializeGL::DebugContext(end)"); + + // The ordering of the KeyCheckOpenGLState and KeyLogEachOpenGLCall are important as + // the callback mask in glbinding is stateful for each context, and since + // KeyLogEachOpenGLCall is more specific, we want it to be able to overwrite the + // state from KeyCheckOpenGLState + if (global::configuration.isCheckingOpenGLState) { + using namespace glbinding; + + // Infinite loop -- welcome to the danger zone + setCallbackMaskExcept(CallbackMask::After, { "glGetError" }); + setAfterCallback([](const FunctionCall& f) { + const GLenum error = glGetError(); + switch (error) { + case GL_NO_ERROR: + break; + case GL_INVALID_ENUM: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_INVALID_ENUM", f.function->name()) + ); + break; + case GL_INVALID_VALUE: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_INVALID_VALUE", f.function->name()) + ); + break; + case GL_INVALID_OPERATION: + LERRORC( + "OpenGL Invalid State", + fmt::format( + "Function {}: GL_INVALID_OPERATION", f.function->name() + )); + break; + case GL_INVALID_FRAMEBUFFER_OPERATION: + LERRORC( + "OpenGL Invalid State", + fmt::format( + "Function {}: GL_INVALID_FRAMEBUFFER_OPERATION", + f.function->name() + ) + ); + break; + case GL_OUT_OF_MEMORY: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_OUT_OF_MEMORY", f.function->name()) + ); + break; + default: + LERRORC( + "OpenGL Invalid State", + fmt::format("Unknown error code: {0:x}", static_cast(error)) + ); + } + }); + } + + if (global::configuration.isLoggingOpenGLCalls) { + using namespace ghoul::logging; + LogLevel level = levelFromString(global::configuration.logging.level); + if (level > LogLevel::Trace) { + LWARNING( + "Logging OpenGL calls is enabled, but the selected log level does " + "not include TRACE, so no OpenGL logs will be printed"); + } + else { + using namespace glbinding; + + setCallbackMask(CallbackMask::After | CallbackMask::ParametersAndReturnValue); + glbinding::setAfterCallback([](const glbinding::FunctionCall& call) { + std::string arguments = std::accumulate( + call.parameters.begin(), + call.parameters.end(), + std::string("("), + [](std::string a, const std::unique_ptr& v) { + std::stringstream s; + s << v; + return a + s.str() + ", "; + } + ); + // Remove the final ", " + arguments = arguments.substr(0, arguments.size() - 2) + ")"; + + std::string returnValue; + std::stringstream s; + if (call.returnValue) { + s << call.returnValue; + returnValue = " -> " + s.str(); + } + + LTRACEC( + "OpenGL", + call.function->name() + std::move(arguments) + std::move(returnValue) + ); + }); + } + } + + LDEBUG("Initializing Rendering Engine"); + global::renderEngine.initializeGL(); + + global::moduleEngine.initializeGL(); + + for (const std::function& func : global::callback::initializeGL) { func(); } - _engine->_assetManager->initialize(); - scheduleLoadSingleAsset(_engine->_configuration->asset); + LINFO("Finished initializing OpenGL"); - LTRACE("OpenSpaceEngine::initialize(end)"); + LTRACE("OpenSpaceEngine::initializeGL(end)"); } void OpenSpaceEngine::scheduleLoadSingleAsset(std::string assetPath) { @@ -625,30 +607,30 @@ void OpenSpaceEngine::scheduleLoadSingleAsset(std::string assetPath) { void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { LTRACE("OpenSpaceEngine::loadSingleAsset(begin)"); - windowWrapper().setBarrier(false); - windowWrapper().setSynchronization(false); + global::windowDelegate.setBarrier(false); + global::windowDelegate.setSynchronization(false); defer { - windowWrapper().setSynchronization(true); - windowWrapper().setBarrier(true); + global::windowDelegate.setSynchronization(true); + global::windowDelegate.setBarrier(true); }; if (assetPath.empty()) { return; } if (_scene) { - _syncEngine->removeSyncables(_timeManager->getSyncables()); + global::syncEngine.removeSyncables(global::timeManager.getSyncables()); if (_scene && _scene->camera()) { - _syncEngine->removeSyncables(_scene->camera()->getSyncables()); + global::syncEngine.removeSyncables(_scene->camera()->getSyncables()); } - _renderEngine->setScene(nullptr); - _renderEngine->setCamera(nullptr); - _navigationHandler->setCamera(nullptr); + global::renderEngine.setScene(nullptr); + global::renderEngine.setCamera(nullptr); + global::navigationHandler.setCamera(nullptr); _scene->clear(); - _rootPropertyOwner->removePropertySubOwner(_scene.get()); + global::rootPropertyOwner.removePropertySubOwner(_scene.get()); } std::unique_ptr sceneInitializer; - if (_configuration->useMultithreadedInitialization) { + if (global::configuration.useMultithreadedInitialization) { unsigned int nAvailableThreads = std::thread::hardware_concurrency(); unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads - 1; sceneInitializer = std::make_unique(nThreads); @@ -657,16 +639,16 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { } _scene = std::make_unique(std::move(sceneInitializer)); - _rootPropertyOwner->addPropertySubOwner(_scene.get()); + global::rootPropertyOwner.addPropertySubOwner(_scene.get()); _scene->setCamera(std::make_unique()); Camera* camera = _scene->camera(); camera->setParent(_scene->root()); - _renderEngine->setCamera(camera); - _navigationHandler->setCamera(camera); - _navigationHandler->setFocusNode(camera->parent()); + global::renderEngine.setCamera(camera); + global::navigationHandler.setCamera(camera); + global::navigationHandler.setFocusNode(camera->parent()); - _renderEngine->setScene(_scene.get()); + global::renderEngine.setScene(_scene.get()); _assetManager->removeAll(); _assetManager->add(assetPath); @@ -754,14 +736,17 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { _loadingScreen->postMessage("Initializing OpenGL"); _loadingScreen->finalize(); - _renderEngine->updateScene(); - _renderEngine->setGlobalBlackOutFactor(0.f); - _renderEngine->startFading(1, 3.f); + _loadingScreen = nullptr; - _syncEngine->addSyncables(_timeManager->getSyncables()); + global::renderEngine.updateScene(); + + global::renderEngine.setGlobalBlackOutFactor(0.f); + global::renderEngine.startFading(1, 3.f); + + global::syncEngine.addSyncables(global::timeManager.getSyncables()); if (_scene && _scene->camera()) { - _syncEngine->addSyncables(_scene->camera()->getSyncables()); + global::syncEngine.addSyncables(_scene->camera()->getSyncables()); } #ifdef __APPLE__ @@ -779,91 +764,78 @@ void OpenSpaceEngine::deinitialize() { LTRACE("OpenSpaceEngine::deinitialize(begin)"); // We want to render an image informing the user that we are shutting down - _renderEngine->renderEndscreen(); + global::renderEngine.renderEndscreen(); + global::windowDelegate.swapBuffer(); - _engine->_windowWrapper->swapBuffer(); - - for (const std::function& func : _engine->_moduleCallbacks.deinitializeGL) { + for (const std::function& func : global::callback::deinitializeGL) { func(); } - for (const std::function& func : _engine->_moduleCallbacks.deinitialize) { + for (const std::function& func : global::callback::deinitialize) { func(); } - _engine->assetManager().deinitialize(); - _engine->_scene = nullptr; + global::openSpaceEngine.assetManager().deinitialize(); + global::openSpaceEngine._scene = nullptr; + + global::navigationHandler.deinitialize(); + + LTRACE("deinitialize(begin)"); + if (global::parallelPeer.status() != ParallelConnection::Status::Disconnected) { + global::parallelPeer.disconnect(); + } + if (global::renderEngine.scene() && global::renderEngine.scene()->camera()) { + global::syncEngine.removeSyncables( + global::renderEngine.scene()->camera()->getSyncables() + ); + } + + global::deinitializeGL(); + global::deinitialize(); + + FactoryManager::deinitialize(); + TransformationManager::deinitialize(); + SpiceManager::deinitialize(); + + ghoul::fontrendering::FontRenderer::deinitialize(); + + ghoul::logging::LogManager::deinitialize(); + + ghoul::deinitialize(); + LTRACE("deinitialize(end)"); - _navigationHandler->deinitialize(); - _renderEngine->deinitialize(); LTRACE("OpenSpaceEngine::deinitialize(end)"); } void OpenSpaceEngine::writeStaticDocumentation() { // If a LuaDocumentationFile was specified, generate it now - if (!_configuration->documentation.lua.empty()) { - _scriptEngine->writeDocumentation(absPath(_configuration->documentation.lua)); + if (!global::configuration.documentation.lua.empty()) { + global::scriptEngine.writeDocumentation( + absPath(global::configuration.documentation.lua) + ); } // If a general documentation was specified, generate it now - if (!_configuration->documentation.documentation.empty()) { - DocEng.writeDocumentation(absPath(_configuration->documentation.documentation)); - } - - if (!_configuration->documentation.factory.empty()) { - FactoryManager::ref().writeDocumentation( - absPath(_configuration->documentation.factory) + if (!global::configuration.documentation.documentation.empty()) { + DocEng.writeDocumentation( + absPath(global::configuration.documentation.documentation) ); } -} -void OpenSpaceEngine::gatherCommandlineArguments() { - commandlineArgumentPlaceholders.configurationName = ""; - _commandlineParser->addCommand(std::make_unique>( - commandlineArgumentPlaceholders.configurationName, "--config", "-c", - "Provides the path to the OpenSpace configuration file." - )); - - commandlineArgumentPlaceholders.sgctConfigurationName = ""; - _commandlineParser->addCommand(std::make_unique>( - commandlineArgumentPlaceholders.sgctConfigurationName, "--sgct", "-s", - "Provides the path to the SGCT configuration file, overriding the value set in " - "the OpenSpace configuration file." - )); - - commandlineArgumentPlaceholders.sceneName = ""; - _commandlineParser->addCommand(std::make_unique>( - commandlineArgumentPlaceholders.sceneName, "--scene", "", "Provides the path to " - "the scene file, overriding the value set in the OpenSpace configuration file." - )); - - commandlineArgumentPlaceholders.cacheFolder = ""; - _commandlineParser->addCommand(std::make_unique>( - commandlineArgumentPlaceholders.cacheFolder, "--cacheDir", "", "Provides the " - "path to a cache file, overriding the value set in the OpenSpace configuration " - "file." - )); - - commandlineArgumentPlaceholders.configurationOverwrite = ""; - _commandlineParser->addCommand(std::make_unique>( - commandlineArgumentPlaceholders.configurationOverwrite, "--lua", "-l", - "Provides the ability to pass arbitrary Lua code to the application that will be " - "evaluated after the configuration file has been loaded but before the other " - "commandline arguments are triggered. This can be used to manipulate the " - "configuration file without editing the file on disk, for example in a " - "planetarium environment. Please not that the Lua script must not contain any - " - "or they will be interpreted as a new command. Similar, in Bash, ${...} will be " - "evaluated before it is passed to OpenSpace." - )); + if (!global::configuration.documentation.factory.empty()) { + FactoryManager::ref().writeDocumentation( + absPath(global::configuration.documentation.factory) + ); + } } void OpenSpaceEngine::runGlobalCustomizationScripts() { LINFO("Running Global initialization scripts"); ghoul::lua::LuaState state; - OsEng.scriptEngine().initializeLuaState(state); + global::scriptEngine.initializeLuaState(state); - for (const std::string& script : _configuration->globalCustomizationScripts) { + for (const std::string& script : global::configuration.globalCustomizationScripts) { std::string s = absPath(script); if (FileSys.fileExists(s)) { try { @@ -880,10 +852,9 @@ void OpenSpaceEngine::runGlobalCustomizationScripts() { } void OpenSpaceEngine::loadFonts() { - _fontManager = std::make_unique(FontAtlasSize); - _fontManager->initialize(); + global::fontManager.initialize(); - for (const std::pair& font : _configuration->fonts) { + for (const std::pair& font : global::configuration.fonts) { std::string key = font.first; std::string fontName = absPath(font.second); @@ -893,7 +864,7 @@ void OpenSpaceEngine::loadFonts() { } LDEBUG(fmt::format("Registering font '{}' with key '{}'", fontName, key)); - bool success = _fontManager->registerFontPath(key, fontName); + bool success = global::fontManager.registerFontPath(key, fontName); if (!success) { LERROR(fmt::format( @@ -913,279 +884,40 @@ void OpenSpaceEngine::loadFonts() { } } -void OpenSpaceEngine::configureLogging(bool consoleLog) { - // We previously initialized the LogManager with a console log to provide some logging - // until we know which logs should be added - LogManager::deinitialize(); - - LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); - bool immediateFlush = _configuration->logging.forceImmediateFlush; - - using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; - LogManager::initialize( - level, - ImmediateFlush(immediateFlush) - ); - if (consoleLog) { - LogMgr.addLog(std::make_unique()); - } - - for (const ghoul::Dictionary& log : _configuration->logging.logs) { - try { - LogMgr.addLog(createLog(log)); - } - catch (const documentation::SpecificationError& e) { - LERROR("Failed loading of log"); - for (const documentation::TestResult::Offense& o : e.result.offenses) { - LERRORC(o.offender, ghoul::to_string(o.reason)); - } - for (const documentation::TestResult::Warning& w : e.result.warnings) { - LWARNINGC(w.offender, ghoul::to_string(w.reason)); - } - throw; - } - } - -#ifdef WIN32 - if (IsDebuggerPresent()) { - LogMgr.addLog(std::make_unique()); - } -#endif // WIN32 - -#ifndef GHOUL_LOGGING_ENABLE_TRACE - LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); - - if (level == ghoul::logging::LogLevel::Trace) { - LWARNING( - "Desired logging level is set to 'Trace' but application was " << - "compiled without Trace support" - ); - } -#endif // GHOUL_LOGGING_ENABLE_TRACE -} - void OpenSpaceEngine::writeSceneDocumentation() { // Write keyboard documentation. - if (!_configuration->documentation.keyboard.empty()) { - keyBindingManager().writeDocumentation( - absPath(_configuration->documentation.keyboard) + if (!global::configuration.documentation.keyboard.empty()) { + global::keybindingManager.writeDocumentation( + absPath(global::configuration.documentation.keyboard) ); } - if (!_configuration->documentation.license.empty()) { + if (!global::configuration.documentation.license.empty()) { _scene->writeSceneLicenseDocumentation( - absPath(_configuration->documentation.license) + absPath(global::configuration.documentation.license) ); } - if (!_configuration->documentation.sceneProperty.empty()) { - _scene->writeDocumentation(absPath(_configuration->documentation.sceneProperty)); - } - - if (!_configuration->documentation.property.empty()) { - _rootPropertyOwner->writeDocumentation( - absPath(_configuration->documentation.property) + if (!global::configuration.documentation.sceneProperty.empty()) { + _scene->writeDocumentation( + absPath(global::configuration.documentation.sceneProperty) ); } -} -void OpenSpaceEngine::initializeGL() { - LTRACE("OpenSpaceEngine::initializeGL(begin)"); - - LTRACE("OpenSpaceEngine::initializeGL::Console::initialize(begin)"); - try { - _engine->_console->initialize(); + if (!global::configuration.documentation.property.empty()) { + global::rootPropertyOwner.writeDocumentation( + absPath(global::configuration.documentation.property) + ); } - catch (ghoul::RuntimeError& e) { - LERROR("Error initializing Console with error:"); - LERRORC(e.component, e.message); - } - LTRACE("OpenSpaceEngine::initializeGL::Console::initialize(end)"); - - LTRACE("OpenSpaceEngine::initializeGL::DebugContext(begin)"); - bool debugActive = _configuration->openGLDebugContext.isActive; - - // Debug output is not available before 4.3 - const ghoul::systemcapabilities::Version minVersion = { 4, 3, 0 }; - if (debugActive && OpenGLCap.openGLVersion() < minVersion) { - LINFO("OpenGL Debug context requested, but insufficient version available"); - debugActive = false; - } - - if (debugActive) { - using namespace ghoul::opengl::debug; - - bool synchronous = _configuration->openGLDebugContext.isSynchronous; - setDebugOutput(DebugOutput(debugActive), SynchronousOutput(synchronous)); - - using IdFilter = Configuration::OpenGLDebugContext::IdentifierFilter; - for (const IdFilter&f : _configuration->openGLDebugContext.identifierFilters) { - setDebugMessageControl( - ghoul::from_string(f.source), - ghoul::from_string(f.type), - { f.identifier }, - Enabled::No - ); - - } - - for (const std::string& sev : _configuration->openGLDebugContext.severityFilters){ - setDebugMessageControl( - Source::DontCare, - Type::DontCare, - ghoul::from_string(sev), - Enabled::No - ); - } - - auto callback = [](Source source, Type type, Severity severity, - unsigned int id, std::string message) -> void - { - const std::string s = ghoul::to_string(source); - const std::string t = ghoul::to_string(type); - - const std::string category = - "OpenGL (" + s + ") [" + t + "] {" + std::to_string(id) + "}"; - switch (severity) { - case Severity::High: - LERRORC(category, message); - break; - case Severity::Medium: - LWARNINGC(category, message); - break; - case Severity::Low: - LINFOC(category, message); - break; - case Severity::Notification: - LDEBUGC(category, message); - break; - default: - throw ghoul::MissingCaseException(); - } - }; - ghoul::opengl::debug::setDebugCallback(callback); - } - LTRACE("OpenSpaceEngine::initializeGL::DebugContext(end)"); - - // The ordering of the KeyCheckOpenGLState and KeyLogEachOpenGLCall are important as - // the callback mask in glbinding is stateful for each context, and since - // KeyLogEachOpenGLCall is more specific, we want it to be able to overwrite the - // state from KeyCheckOpenGLState - if (_configuration->isCheckingOpenGLState) { - using namespace glbinding; - - // Infinite loop -- welcome to the danger zone - setCallbackMaskExcept(CallbackMask::After, { "glGetError" }); - setAfterCallback([](const FunctionCall& f) { - const GLenum error = glGetError(); - switch (error) { - case GL_NO_ERROR: - break; - case GL_INVALID_ENUM: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_ENUM", f.function->name()) - ); - break; - case GL_INVALID_VALUE: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_VALUE", f.function->name()) - ); - break; - case GL_INVALID_OPERATION: - LERRORC( - "OpenGL Invalid State", - fmt::format( - "Function {}: GL_INVALID_OPERATION", f.function->name() - )); - break; - case GL_INVALID_FRAMEBUFFER_OPERATION: - LERRORC( - "OpenGL Invalid State", - fmt::format( - "Function {}: GL_INVALID_FRAMEBUFFER_OPERATION", - f.function->name() - ) - ); - break; - case GL_OUT_OF_MEMORY: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_OUT_OF_MEMORY", f.function->name()) - ); - break; - default: - LERRORC( - "OpenGL Invalid State", - fmt::format("Unknown error code: {0:x}", static_cast(error)) - ); - } - }); - } - - if (_configuration->isLoggingOpenGLCalls) { - LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); - if (level > LogLevel::Trace) { - LWARNING( - "Logging OpenGL calls is enabled, but the selected log level does " - "not include TRACE, so no OpenGL logs will be printed"); - } - else { - using namespace glbinding; - - setCallbackMask(CallbackMask::After | CallbackMask::ParametersAndReturnValue); - glbinding::setAfterCallback([](const glbinding::FunctionCall& call) { - std::string arguments = std::accumulate( - call.parameters.begin(), - call.parameters.end(), - std::string("("), - [](std::string a, const std::unique_ptr& v) { - std::stringstream s; - s << v; - return a + s.str() + ", "; - } - ); - // Remove the final ", " - arguments = arguments.substr(0, arguments.size() - 2) + ")"; - - std::string returnValue; - std::stringstream s; - if (call.returnValue) { - s << call.returnValue; - returnValue = " -> " + s.str(); - } - - LTRACEC( - "OpenGL", - call.function->name() + std::move(arguments) + std::move(returnValue) - ); - }); - } - } - - LDEBUG("Initializing Rendering Engine"); - _renderEngine->initializeGL(); - - _moduleEngine->initializeGL(); - - for (const std::function& func : _moduleCallbacks.initializeGL) { - func(); - } - - LINFO("Finished initializing OpenGL"); - - LTRACE("OpenSpaceEngine::initializeGL(end)"); } void OpenSpaceEngine::preSynchronization() { LTRACE("OpenSpaceEngine::preSynchronization(begin)"); std::unique_ptr perf; - if (OsEng.renderEngine().performanceManager()) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "OpenSpaceEngine::preSynchronization", - OsEng.renderEngine().performanceManager() + "OpenSpaceEngine::preSynchronization" ); } @@ -1199,41 +931,41 @@ void OpenSpaceEngine::preSynchronization() { } if (_isFirstRenderingFirstFrame) { - _windowWrapper->setSynchronization(false); + global::windowDelegate.setSynchronization(false); } - bool master = _windowWrapper->isMaster(); + bool master = global::windowDelegate.isMaster(); - _syncEngine->preSynchronization(SyncEngine::IsMaster(master)); + global::syncEngine.preSynchronization(SyncEngine::IsMaster(master)); if (master) { - double dt = _windowWrapper->averageDeltaTime(); - _timeManager->preSynchronization(dt); + double dt = global::windowDelegate.averageDeltaTime(); + global::timeManager.preSynchronization(dt); using Iter = std::vector::const_iterator; - std::pair scheduledScripts = _scriptScheduler->progressTo( - timeManager().time().j2000Seconds() + std::pair scheduledScripts = global::scriptScheduler.progressTo( + global::timeManager.time().j2000Seconds() ); for (Iter it = scheduledScripts.first; it != scheduledScripts.second; ++it) { - _scriptEngine->queueScript( + global::scriptEngine.queueScript( *it, - ScriptEngine::RemoteScripting::Yes + scripting::ScriptEngine::RemoteScripting::Yes ); } - _renderEngine->updateScene(); + global::renderEngine.updateScene(); //_navigationHandler->updateCamera(dt); if (_scene) { Camera* camera = _scene->camera(); if (camera) { - _navigationHandler->updateCamera(dt); + global::navigationHandler.updateCamera(dt); camera->invalidateCache(); } } - _parallelPeer->preSynchronization(); + global::parallelPeer.preSynchronization(); } - for (const std::function& func : _moduleCallbacks.preSync) { + for (const std::function& func : global::callback::preSync) { func(); } LTRACE("OpenSpaceEngine::preSynchronization(end)"); @@ -1243,31 +975,30 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { LTRACE("OpenSpaceEngine::postSynchronizationPreDraw(begin)"); std::unique_ptr perf; - if (OsEng.renderEngine().performanceManager()) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "OpenSpaceEngine::postSynchronizationPreDraw", - OsEng.renderEngine().performanceManager() + "OpenSpaceEngine::postSynchronizationPreDraw" ); } - bool master = _windowWrapper->isMaster(); - _syncEngine->postSynchronization(SyncEngine::IsMaster(master)); + bool master = global::windowDelegate.isMaster(); + global::syncEngine.postSynchronization(SyncEngine::IsMaster(master)); // This probably doesn't have to be done here every frame, but doing it earlier gives // weird results when using side_by_side stereo --- abock using FR = ghoul::fontrendering::FontRenderer; - FR::defaultRenderer().setFramebufferSize(_renderEngine->fontResolution()); + FR::defaultRenderer().setFramebufferSize(global::renderEngine.fontResolution()); FR::defaultProjectionRenderer().setFramebufferSize( - _renderEngine->renderingResolution() + global::renderEngine.renderingResolution() ); if (_shutdown.inShutdown) { if (_shutdown.timer <= 0.f) { - _windowWrapper->terminate(); + global::windowDelegate.terminate(); return; } - _shutdown.timer -= static_cast(_windowWrapper->averageDeltaTime()); + _shutdown.timer -= static_cast(global::windowDelegate.averageDeltaTime()); } @@ -1276,26 +1007,26 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { writeSceneDocumentation(); } - _renderEngine->updateScene(); - _renderEngine->updateFade(); - _renderEngine->updateRenderer(); - _renderEngine->updateScreenSpaceRenderables(); - _renderEngine->updateShaderPrograms(); + global::renderEngine.updateScene(); + global::renderEngine.updateFade(); + global::renderEngine.updateRenderer(); + global::renderEngine.updateScreenSpaceRenderables(); + global::renderEngine.updateShaderPrograms(); if (!master) { _scene->camera()->invalidateCache(); } - for (const std::function& func : _moduleCallbacks.postSyncPreDraw) { + for (const std::function& func : global::callback::postSyncPreDraw) { func(); } // Testing this every frame has minimal impact on the performance --- abock // Debug build: 1-2 us ; Release build: <= 1 us using ghoul::logging::LogManager; - int warningCounter = LogMgr.messageCounter(LogLevel::Warning); - int errorCounter = LogMgr.messageCounter(LogLevel::Error); - int fatalCounter = LogMgr.messageCounter(LogLevel::Fatal); + int warningCounter = LogMgr.messageCounter(ghoul::logging::LogLevel::Warning); + int errorCounter = LogMgr.messageCounter(ghoul::logging::LogLevel::Error); + int fatalCounter = LogMgr.messageCounter(ghoul::logging::LogLevel::Fatal); if (warningCounter > 0) { LWARNINGC("Logging", fmt::format("Number of Warnings: {}", warningCounter)); @@ -1318,22 +1049,24 @@ void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& view LTRACE("OpenSpaceEngine::render(begin)"); std::unique_ptr perf; - if (OsEng.renderEngine().performanceManager()) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "OpenSpaceEngine::render", - OsEng.renderEngine().performanceManager() + "OpenSpaceEngine::render" ); } const bool isGuiWindow = - _windowWrapper->hasGuiWindow() ? _windowWrapper->isGuiWindow() : true; + global::windowDelegate.hasGuiWindow() ? + global::windowDelegate.isGuiWindow() : + true; + if (isGuiWindow) { - _console->update(); + global::luaConsole.update(); } - _renderEngine->render(sceneMatrix, viewMatrix, projectionMatrix); + global::renderEngine.render(sceneMatrix, viewMatrix, projectionMatrix); - for (const std::function& func : _moduleCallbacks.render) { + for (const std::function& func : global::callback::render) { func(); } @@ -1344,22 +1077,23 @@ void OpenSpaceEngine::drawOverlays() { LTRACE("OpenSpaceEngine::drawOverlays(begin)"); std::unique_ptr perf; - if (OsEng.renderEngine().performanceManager()) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "OpenSpaceEngine::drawOverlays", - OsEng.renderEngine().performanceManager() + "OpenSpaceEngine::drawOverlays" ); } const bool isGuiWindow = - _windowWrapper->hasGuiWindow() ? _windowWrapper->isGuiWindow() : true; + global::windowDelegate.hasGuiWindow() ? + global::windowDelegate.isGuiWindow() : + true; if (isGuiWindow) { - _renderEngine->renderOverlays(_shutdown); - _console->render(); + global::renderEngine.renderOverlays(_shutdown); + global::luaConsole.render(); } - for (const std::function& func : _moduleCallbacks.draw2D) { + for (const std::function& func : global::callback::draw2D) { func(); } @@ -1370,21 +1104,20 @@ void OpenSpaceEngine::postDraw() { LTRACE("OpenSpaceEngine::postDraw(begin)"); std::unique_ptr perf; - if (OsEng.renderEngine().performanceManager()) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "OpenSpaceEngine::postDraw", - OsEng.renderEngine().performanceManager() + "OpenSpaceEngine::postDraw" ); } - _renderEngine->postDraw(); + global::renderEngine.postDraw(); - for (const std::function& func : _moduleCallbacks.postDraw) { + for (const std::function& func : global::callback::postDraw) { func(); } if (_isFirstRenderingFirstFrame) { - _windowWrapper->setSynchronization(true); + global::windowDelegate.setSynchronization(true); _isFirstRenderingFirstFrame = false; } @@ -1393,39 +1126,39 @@ void OpenSpaceEngine::postDraw() { void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction action) { using F = std::function; - for (const F& func : _moduleCallbacks.keyboard) { + for (const F& func : global::callback::keyboard) { const bool isConsumed = func(key, mod, action); if (isConsumed) { return; } } - if (!_configuration->isConsoleDisabled) { - const bool isConsoleConsumed = _console->keyboardCallback(key, mod, action); + if (!global::configuration.isConsoleDisabled) { + bool isConsoleConsumed = global::luaConsole.keyboardCallback(key, mod, action); if (isConsoleConsumed) { return; } } - _navigationHandler->keyboardCallback(key, mod, action); - _keyBindingManager->keyboardCallback(key, mod, action); + global::navigationHandler.keyboardCallback(key, mod, action); + global::keybindingManager.keyboardCallback(key, mod, action); } void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier) { using F = std::function; - for (const F& func : _moduleCallbacks.character) { + for (const F& func : global::callback::character) { bool isConsumed = func(codepoint, modifier); if (isConsumed) { return; } } - _console->charCallback(codepoint, modifier); + global::luaConsole.charCallback(codepoint, modifier); } void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action) { using F = std::function; - for (const F& func : _moduleCallbacks.mouseButton) { + for (const F& func : global::callback::mouseButton) { bool isConsumed = func(button, action); if (isConsumed) { // If the mouse was released, we still want to forward it to the navigation @@ -1443,62 +1176,59 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action // Check if the user clicked on one of the 'buttons' the RenderEngine is drawing if (action == MouseAction::Press) { - bool isConsumed = _renderEngine->mouseActivationCallback(_mousePosition); + bool isConsumed = global::renderEngine.mouseActivationCallback( + global::windowDelegate.mousePosition() + ); if (isConsumed) { return; } } - _navigationHandler->mouseButtonCallback(button, action); + global::navigationHandler.mouseButtonCallback(button, action); } void OpenSpaceEngine::mousePositionCallback(double x, double y) { using F = std::function; - for (const F& func : _moduleCallbacks.mousePosition) { + for (const F& func : global::callback::mousePosition) { func(x, y); } - _mousePosition = { x, y }; - - _navigationHandler->mousePositionCallback(x, y); + global::navigationHandler.mousePositionCallback(x, y); } void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY) { using F = std::function; - for (const F& func : _moduleCallbacks.mouseScrollWheel) { + for (const F& func : global::callback::mouseScrollWheel) { bool isConsumed = func(posX, posY); if (isConsumed) { return; } } - _navigationHandler->mouseScrollWheelCallback(posY); -} - -void OpenSpaceEngine::setJoystickInputStates(interaction::JoystickInputStates& states) { - _navigationHandler->setJoystickInputStates(states); + global::navigationHandler.mouseScrollWheelCallback(posY); } void OpenSpaceEngine::encode() { - _syncEngine->encodeSyncables(); - - _networkEngine->publishStatusMessage(); - _networkEngine->sendMessages(); + global::syncEngine.encodeSyncables(); + global::networkEngine.publishStatusMessage(); + global::networkEngine.sendMessages(); } void OpenSpaceEngine::decode() { - _syncEngine->decodeSyncables(); + global::syncEngine.decodeSyncables(); } void OpenSpaceEngine::externalControlCallback(const char* receivedChars, int size, int /*clientId*/) { + // Not currently used anymore; should be replaced with a non-SGCT relient socket + if (size == 0) { return; } - _networkEngine->handleMessage(std::string(receivedChars, size)); + global::networkEngine.handleMessage(std::string(receivedChars, size)); } void OpenSpaceEngine::toggleShutdownMode() { @@ -1599,166 +1329,14 @@ scripting::LuaLibrary OpenSpaceEngine::luaLibrary() { }; } -// Registers a callback for a specific CallbackOption -void OpenSpaceEngine::registerModuleCallback(OpenSpaceEngine::CallbackOption option, - std::function function) -{ - switch (option) { - case CallbackOption::Initialize: - _moduleCallbacks.initialize.push_back(std::move(function)); - break; - case CallbackOption::Deinitialize: - _moduleCallbacks.deinitialize.push_back(std::move(function)); - break; - case CallbackOption::InitializeGL: - _moduleCallbacks.initializeGL.push_back(std::move(function)); - break; - case CallbackOption::DeinitializeGL: - _moduleCallbacks.deinitializeGL.push_back(std::move(function)); - break; - case CallbackOption::PreSync: - _moduleCallbacks.preSync.push_back(std::move(function)); - break; - case CallbackOption::PostSyncPreDraw: - _moduleCallbacks.postSyncPreDraw.push_back(std::move(function)); - break; - case CallbackOption::Render: - _moduleCallbacks.render.push_back(std::move(function)); - break; - case CallbackOption::Draw2D: - _moduleCallbacks.draw2D.push_back(std::move(function)); - break; - case CallbackOption::PostDraw: - _moduleCallbacks.postDraw.push_back(std::move(function)); - break; - default: - throw ghoul::MissingCaseException(); - } -} - -void OpenSpaceEngine::registerModuleKeyboardCallback( - std::function function) -{ - _moduleCallbacks.keyboard.push_back(std::move(function)); -} - -void OpenSpaceEngine::registerModuleCharCallback( - std::function function) -{ - _moduleCallbacks.character.push_back(std::move(function)); -} - -void OpenSpaceEngine::registerModuleMouseButtonCallback( - std::function function) -{ - _moduleCallbacks.mouseButton.push_back(std::move(function)); -} - -void OpenSpaceEngine::registerModuleMousePositionCallback( - std::function function) -{ - _moduleCallbacks.mousePosition.push_back(std::move(function)); -} - -void OpenSpaceEngine::registerModuleMouseScrollWheelCallback( - std::function function) -{ - _moduleCallbacks.mouseScrollWheel.push_back(std::move(function)); -} - -const Configuration& OpenSpaceEngine::configuration() const { - ghoul_assert(_configuration, "Configuration must not be nullptr"); - return *_configuration; -} - -LuaConsole& OpenSpaceEngine::console() { - ghoul_assert(_console, "LuaConsole must not be nullptr"); - return *_console; -} - -Dashboard& OpenSpaceEngine::dashboard() { - ghoul_assert(_dashboard, "Dashboard must not be nullptr"); - return *_dashboard; -} - -DownloadManager& OpenSpaceEngine::downloadManager() { - ghoul_assert(_downloadManager, "Download Manager must not be nullptr"); - return *_downloadManager; -} - -NetworkEngine& OpenSpaceEngine::networkEngine() { - ghoul_assert(_networkEngine, "NetworkEngine must not be nullptr"); - return *_networkEngine; -} - -ModuleEngine& OpenSpaceEngine::moduleEngine() { - ghoul_assert(_moduleEngine, "ModuleEngine must not be nullptr"); - return *_moduleEngine; -} - -ParallelPeer& OpenSpaceEngine::parallelPeer() { - ghoul_assert(_parallelPeer, "ParallelPeer must not be nullptr"); - return *_parallelPeer; -} - -RenderEngine& OpenSpaceEngine::renderEngine() { - ghoul_assert(_renderEngine, "RenderEngine must not be nullptr"); - return *_renderEngine; -} - -TimeManager& OpenSpaceEngine::timeManager() { - ghoul_assert(_timeManager, "Download Manager must not be nullptr"); - return *_timeManager; -} - LoadingScreen& OpenSpaceEngine::loadingScreen() { ghoul_assert(_loadingScreen, "Loading Screen must not be nullptr"); return *_loadingScreen; } -WindowWrapper& OpenSpaceEngine::windowWrapper() { - ghoul_assert(_windowWrapper, "Window Wrapper must not be nullptr"); - return *_windowWrapper; -} - AssetManager& OpenSpaceEngine::assetManager() { ghoul_assert(_assetManager, "Asset Manager must not be nullptr"); return *_assetManager; } -ghoul::fontrendering::FontManager& OpenSpaceEngine::fontManager() { - ghoul_assert(_fontManager, "Font Manager must not be nullptr"); - return *_fontManager; -} - -interaction::NavigationHandler& OpenSpaceEngine::navigationHandler() { - ghoul_assert(_navigationHandler, "NavigationHandler must not be nullptr"); - return *_navigationHandler; -} - -interaction::KeyBindingManager& OpenSpaceEngine::keyBindingManager() { - ghoul_assert(_keyBindingManager, "KeyBindingManager must not be nullptr"); - return *_keyBindingManager; -} - -properties::PropertyOwner& OpenSpaceEngine::rootPropertyOwner() { - ghoul_assert(_rootPropertyOwner, "Root Property Namespace must not be nullptr"); - return *_rootPropertyOwner; -} - -VirtualPropertyManager& OpenSpaceEngine::virtualPropertyManager() { - ghoul_assert(_virtualPropertyManager, "Virtual Property Manager must not be nullptr"); - return *_virtualPropertyManager; -} - -ScriptEngine& OpenSpaceEngine::scriptEngine() { - ghoul_assert(_scriptEngine, "ScriptEngine must not be nullptr"); - return *_scriptEngine; -} - -ScriptScheduler& OpenSpaceEngine::scriptScheduler() { - ghoul_assert(_scriptScheduler, "ScriptScheduler must not be nullptr"); - return *_scriptScheduler; -} - } // namespace openspace diff --git a/src/engine/openspaceengine_lua.inl b/src/engine/openspaceengine_lua.inl index 6b5561859a..cdf1d390d1 100644 --- a/src/engine/openspaceengine_lua.inl +++ b/src/engine/openspaceengine_lua.inl @@ -22,6 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include +#include +#include +#include #include namespace openspace::luascriptfunctions { @@ -35,7 +39,7 @@ namespace openspace::luascriptfunctions { int toggleShutdown(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::toggleShutdown"); - OsEng.toggleShutdownMode(); + global::openSpaceEngine.toggleShutdownMode(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -49,8 +53,8 @@ int toggleShutdown(lua_State* L) { int writeDocumentation(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::writeDocumentation"); - OsEng.writeStaticDocumentation(); - OsEng.writeSceneDocumentation(); + global::openSpaceEngine.writeStaticDocumentation(); + global::openSpaceEngine.writeSceneDocumentation(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -128,7 +132,7 @@ int addVirtualProperty(lua_State* L) { } lua_settop(L, 0); - OsEng.virtualPropertyManager().addProperty(std::move(prop)); + global::virtualPropertyManager.addProperty(std::move(prop)); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -143,9 +147,9 @@ int removeVirtualProperty(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeVirtualProperty"); const std::string& name = ghoul::lua::value(L, 1); - properties::Property* p = OsEng.virtualPropertyManager().property(name); + properties::Property* p = global::virtualPropertyManager.property(name); if (p) { - OsEng.virtualPropertyManager().removeProperty(p); + global::virtualPropertyManager.removeProperty(p); } else { LWARNINGC( @@ -168,9 +172,9 @@ int removeAllVirtualProperties(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::removeAllVirtualProperties"); const std::vector& ps = - OsEng.virtualPropertyManager().properties(); + global::virtualPropertyManager.properties(); for (properties::Property* p : ps) { - OsEng.virtualPropertyManager().removeProperty(p); + global::virtualPropertyManager.removeProperty(p); delete p; } @@ -190,7 +194,7 @@ int addTag(lua_State* L) { std::string tag = ghoul::lua::value(L, 2); lua_settop(L, 0); - SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(uri); + SceneGraphNode* node = global::renderEngine.scene()->sceneGraphNode(uri); if (!node) { return ghoul::lua::luaError( L, @@ -216,7 +220,7 @@ int removeTag(lua_State* L) { const std::string& tag = ghoul::lua::value(L, 2); lua_settop(L, 0); - SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(uri); + SceneGraphNode* node = global::renderEngine.scene()->sceneGraphNode(uri); if (!node) { return ghoul::lua::luaError( L, @@ -243,14 +247,14 @@ int downloadFile(lua_State* L) { lua_settop(L, 0); LINFOC("OpenSpaceEngine", fmt::format("Downloading file from {}", uri)); - DownloadManager dm = DownloadManager(DownloadManager::UseMultipleThreads::No); - std::shared_ptr future = dm.downloadFile( - uri, - savePath, - DownloadManager::OverrideFile::Yes, - DownloadManager::FailOnError::Yes, - 5 - ); + std::shared_ptr future = + global::downloadManager.downloadFile( + uri, + savePath, + DownloadManager::OverrideFile::Yes, + DownloadManager::FailOnError::Yes, + 5 + ); if (!future || (future && !future->isFinished)) { return ghoul::lua::luaError( L, @@ -264,13 +268,13 @@ int downloadFile(lua_State* L) { int isMaster(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::isMaster"); - ghoul::lua::push(L, OsEng.windowWrapper().isMaster()); + ghoul::lua::push(L, global::windowDelegate.isMaster()); return 1; } int clusterId(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::clusterId"); - ghoul::lua::push(L, OsEng.windowWrapper().clusterId()); + ghoul::lua::push(L, global::windowDelegate.clusterId()); return 1; } diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp deleted file mode 100644 index 7e063dfb3b..0000000000 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2018 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include - -#include "sgct.h" - -#undef near -#undef far - -namespace { - constexpr const char* GuiWindowTag = "GUI"; - - constexpr openspace::properties::Property::PropertyInfo EyeSeparationInfo = { - "EyeSeparation", - "Eye Separation", - "Sets a static eye separation for use in stereoscopic rendering. If no " - "stereoscopic rendering is performed, this value is unused." - }; - - constexpr openspace::properties::Property::PropertyInfo ShowStatsGraphInfo = { - "ShowStatsGraph", - "Show Statistics Graph", - "Toggles the rendering of the SGCT statistics graph that is rendered on top of " - "every image. The statistics show the frame time, synchronization time, and many " - "other timings as reported by SGCT." - }; -} // namespace - -namespace openspace { - -SGCTWindowWrapper::SGCTWindowWrapper() - : _eyeSeparation(EyeSeparationInfo, 0.f, 0.f, 0.2f) - , _showStatsGraph(ShowStatsGraphInfo, false) -{ - _showStatsGraph.onChange([this](){ - sgct::Engine::instance()->setStatsGraphVisibility(_showStatsGraph); - }); - addProperty(_showStatsGraph); - - addProperty(_eyeSeparation); - _eyeSeparation.onChange([this](){ - setEyeSeparationDistance(_eyeSeparation); - }); -} - -void SGCTWindowWrapper::terminate() { - sgct::Engine::instance()->terminate(); -} - -void SGCTWindowWrapper::setBarrier(bool enabled) { - sgct::SGCTWindow::setBarrier(enabled); -} - -void SGCTWindowWrapper::setSynchronization(bool enabled) { - sgct_core::ClusterManager::instance()->setUseIgnoreSync(enabled); -} - -void SGCTWindowWrapper::clearAllWindows(const glm::vec4& clearColor) { - size_t n = sgct::Engine::instance()->getNumberOfWindows(); - for (size_t i = 0; i < n; ++i) { - glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GLFWwindow* win = sgct::Engine::instance()->getWindowPtr(i)->getWindowHandle(); - glfwSwapBuffers(win); - } -} - -bool SGCTWindowWrapper::windowHasResized() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->isWindowResized(); -} - -double SGCTWindowWrapper::averageDeltaTime() const { - return sgct::Engine::instance()->getAvgDt(); -} - -double SGCTWindowWrapper::deltaTime() const { - return sgct::Engine::instance()->getDt(); -} - -double SGCTWindowWrapper::applicationTime() const { - return sgct::Engine::getTime(); -} - -glm::vec2 SGCTWindowWrapper::mousePosition() const { - int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); - double posX, posY; - sgct::Engine::instance()->getMousePos(id, &posX, &posY); - return glm::vec2(posX, posY); -} - -uint32_t SGCTWindowWrapper::mouseButtons(int maxNumber) const { - int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); - uint32_t result = 0; - for (int i = 0; i < maxNumber; ++i) { - bool button = (sgct::Engine::instance()->getMouseButton(id, i) != 0); - if (button) { - result |= (1 << i); - } - } - return result; -} - -glm::ivec2 SGCTWindowWrapper::currentWindowSize() const { - auto window = sgct::Engine::instance()->getCurrentWindowPtr(); - return glm::ivec2( - window->getXResolution(), - window->getYResolution()); -} - -glm::ivec2 SGCTWindowWrapper::currentSubwindowSize() const { - auto window = sgct::Engine::instance()->getCurrentWindowPtr(); - switch (window->getStereoMode()) { - case sgct::SGCTWindow::Side_By_Side_Stereo: - case sgct::SGCTWindow::Side_By_Side_Inverted_Stereo: - return glm::ivec2(window->getXResolution() / 2, window->getYResolution()); - case sgct::SGCTWindow::Top_Bottom_Stereo: - case sgct::SGCTWindow::Top_Bottom_Inverted_Stereo: - return glm::ivec2(window->getXResolution(), window->getYResolution() / 2); - default: - return glm::ivec2(window->getXResolution(), window->getYResolution()); - } -} - -glm::ivec2 SGCTWindowWrapper::currentWindowResolution() const { - int x, y; - auto window = sgct::Engine::instance()->getCurrentWindowPtr(); - window->getFinalFBODimensions(x, y); - return glm::ivec2(x, y); -} - -glm::ivec2 SGCTWindowWrapper::currentDrawBufferResolution() const { - sgct_core::Viewport* viewport = - sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); - if (viewport != nullptr){ - if (viewport->hasSubViewports() && viewport->getNonLinearProjectionPtr()) { - int res = viewport->getNonLinearProjectionPtr()->getCubemapResolution(); - return glm::ivec2(res, res); - } else { - return currentWindowResolution(); - } - } - throw WindowWrapperException("No viewport available"); -} - -glm::ivec2 SGCTWindowWrapper::getCurrentViewportSize() const { - sgct_core::Viewport* viewport = - sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); - if (viewport != nullptr) { - int xx = 0, yy = 0; - sgct::Engine::instance()->getCurrentViewportSize(xx, yy); - return glm::ivec2(xx, yy); - } - throw WindowWrapperException("No viewport available"); -} - -glm::vec2 SGCTWindowWrapper::dpiScaling() const { - return glm::vec2( - sgct::Engine::instance()->getCurrentWindowPtr()->getXScale(), - sgct::Engine::instance()->getCurrentWindowPtr()->getYScale() - ); -} - -int SGCTWindowWrapper::currentNumberOfAaSamples() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->getNumberOfAASamples(); -} - -bool SGCTWindowWrapper::isRegularRendering() const { - sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr(); - ghoul_assert( - w->getNumberOfViewports() > 0, - "At least one viewport must exist at this time" - ); - sgct_core::Viewport* vp = w->getViewport(0); - sgct_core::NonLinearProjection* nlp = vp->getNonLinearProjectionPtr(); - return nlp == nullptr; -} - -bool SGCTWindowWrapper::hasGuiWindow() const { - auto engine = sgct::Engine::instance(); - for (size_t i = 0; i < engine->getNumberOfWindows(); ++i) { - if (engine->getWindowPtr(i)->checkIfTagExists(GuiWindowTag)) { - return true; - } - } - return false; -} - -bool SGCTWindowWrapper::isGuiWindow() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->checkIfTagExists( - GuiWindowTag - ); -} - -bool SGCTWindowWrapper::isMaster() const { - return sgct::Engine::instance()->isMaster(); -} - -int SGCTWindowWrapper::clusterId() const { - return sgct_core::ClusterManager::instance()->getThisNodeId(); -} - -bool SGCTWindowWrapper::isSwapGroupMaster() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->isSwapGroupMaster(); -} - -bool SGCTWindowWrapper::isUsingSwapGroups() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->isUsingSwapGroups(); -} - -glm::mat4 SGCTWindowWrapper::viewProjectionMatrix() const { - return sgct::Engine::instance()->getCurrentModelViewProjectionMatrix(); -} - -glm::mat4 SGCTWindowWrapper::modelMatrix() const { - return sgct::Engine::instance()->getModelMatrix(); -} - -void SGCTWindowWrapper::setNearFarClippingPlane(float nearPlane, float farPlane) { - sgct::Engine::instance()->setNearAndFarClippingPlanes(nearPlane, farPlane); -} - -void SGCTWindowWrapper::setEyeSeparationDistance(float distance) { - sgct::Engine::instance()->setEyeSeparation(distance); -} - -glm::ivec4 SGCTWindowWrapper::viewportPixelCoordinates() const { - sgct::SGCTWindow* window = sgct::Engine::instance()->getCurrentWindowPtr(); - if (!window || !window->getCurrentViewport()) { - return glm::ivec4(0, 0, 0, 0); - } - - const int* viewportData = sgct::Engine::instance()->getCurrentViewportPixelCoords(); - return glm::ivec4(viewportData[0], viewportData[2], viewportData[1], viewportData[3]); -} - -bool SGCTWindowWrapper::isExternalControlConnected() const { - return sgct::Engine::instance()->isExternalControlConnected(); -} - -void SGCTWindowWrapper::sendMessageToExternalControl( - const std::vector& message) const -{ - sgct::Engine::instance()->sendMessageToExternalControl( - message.data(), - static_cast(message.size()) - ); -} - -bool SGCTWindowWrapper::isSimpleRendering() const { - return (sgct::Engine::instance()->getCurrentRenderTarget() != - sgct::Engine::NonLinearBuffer); -} - -bool SGCTWindowWrapper::isFisheyeRendering() const { - sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr(); - return dynamic_cast( - w->getViewport(0)->getNonLinearProjectionPtr() - ); -} - -void SGCTWindowWrapper::takeScreenshot(bool applyWarping) const { - sgct::SGCTSettings::instance()->setCaptureFromBackBuffer(applyWarping); - sgct::Engine::instance()->takeScreenshot(); -} - -void SGCTWindowWrapper::swapBuffer() const { - GLFWwindow* w = glfwGetCurrentContext(); - glfwSwapBuffers(w); - glfwPollEvents(); -} - -int SGCTWindowWrapper::nWindows() const { - return static_cast(sgct::Engine::instance()->getNumberOfWindows()); -} - -int SGCTWindowWrapper::currentWindowId() const { - return sgct::Engine::instance()->getCurrentWindowPtr()->getId(); -} - -} // namespace openspace diff --git a/src/engine/wrapper/windowwrapper.cpp b/src/engine/wrapper/windowwrapper.cpp deleted file mode 100644 index d4818913d9..0000000000 --- a/src/engine/wrapper/windowwrapper.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2018 * - * * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this * - * software and associated documentation files (the "Software"), to deal in the Software * - * without restriction, including without limitation the rights to use, copy, modify, * - * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * - * permit persons to whom the Software is furnished to do so, subject to the following * - * conditions: * - * * - * The above copyright notice and this permission notice shall be included in all copies * - * or substantial portions of the Software. * - * * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * - * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * - ****************************************************************************************/ - -#include - -#include -#include - -namespace luascriptfunctions { - -int setSynchronization(lua_State* L) { - ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::setSynchronization"); - - const bool b = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); - OsEng.windowWrapper().setSynchronization(b); - - ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); - return 0; -} - -} // namespace luascriptfunctions - -namespace openspace { - -WindowWrapper::WindowWrapperException::WindowWrapperException(const std::string& msg) - : ghoul::RuntimeError(msg, "WindowWrapper") -{} - -WindowWrapper::WindowWrapper() - : properties::PropertyOwner({ "WindowWrapper" }) -{} - -scripting::LuaLibrary WindowWrapper::luaLibrary() { - return { - "cluster", - { - { - "setSynchronization", - &luascriptfunctions::setSynchronization, - {}, - "bool", - "Enables or disables the frame synchronization of the cluster. If the " - "synchronization is enabled, the computers in the cluster will swap " - "their backbuffers at the same time, either supported by hardware or by " - "network signals." - } - } - }; -} - -void WindowWrapper::terminate() {} - -void WindowWrapper::setBarrier(bool) {} - -void WindowWrapper::setSynchronization(bool) {} - -void WindowWrapper::clearAllWindows(const glm::vec4&) {} - -bool WindowWrapper::windowHasResized() const { - return false; -} - -double WindowWrapper::averageDeltaTime() const { - return 0.0; -} - -double WindowWrapper::deltaTime() const { - return 0.0; -} - -double WindowWrapper::applicationTime() const { - return 0.0; -} - -glm::vec2 WindowWrapper::mousePosition() const { - return glm::vec2(0.f); -} - -uint32_t WindowWrapper::mouseButtons(int) const { - return uint32_t(0); -} - -glm::ivec2 WindowWrapper::currentWindowSize() const { - return glm::ivec2(0); -} - -glm::ivec2 WindowWrapper::currentSubwindowSize() const { - return currentWindowSize(); -} - -glm::ivec2 WindowWrapper::currentWindowResolution() const { - return currentWindowSize(); -} - -glm::ivec2 WindowWrapper::currentDrawBufferResolution() const { - return currentWindowSize(); -} - -glm::ivec2 WindowWrapper::getCurrentViewportSize() const { - return currentWindowSize(); -} - -glm::vec2 WindowWrapper::dpiScaling() const { - return glm::vec2(1.f); -} - -int WindowWrapper::currentNumberOfAaSamples() const { - return 1; -} - -bool WindowWrapper::isRegularRendering() const { - return true; -} - -bool WindowWrapper::hasGuiWindow() const { - return false; -} - -bool WindowWrapper::isGuiWindow() const { - return false; -} - -bool WindowWrapper::isMaster() const { - return false; -} - -int WindowWrapper::clusterId() const { - return 0; -} - -bool WindowWrapper::isSwapGroupMaster() const { - return false; -} - -bool WindowWrapper::isUsingSwapGroups() const { - return false; -} - -glm::mat4 WindowWrapper::viewProjectionMatrix() const { - return glm::mat4(1.f); -} - -glm::mat4 WindowWrapper::modelMatrix() const { - return glm::mat4(1.f); -} - -void WindowWrapper::setNearFarClippingPlane(float, float) {} - -void WindowWrapper::setEyeSeparationDistance(float) {} - -glm::ivec4 WindowWrapper::viewportPixelCoordinates() const { - return glm::ivec4( - 0, - currentWindowResolution().x, - 0, - currentWindowResolution().y - ); -} - - -bool WindowWrapper::isExternalControlConnected() const { - return false; -} - -void WindowWrapper::sendMessageToExternalControl(const std::vector&) const { -} - -bool WindowWrapper::isSimpleRendering() const { - return true; -} - -bool WindowWrapper::isFisheyeRendering() const { - return false; -} - -void WindowWrapper::takeScreenshot(bool) const {} - -void WindowWrapper::swapBuffer() const {} - -int WindowWrapper::nWindows() const { - return 0; -} - -int WindowWrapper::currentWindowId() const { - return 0; -} - - -} // namespace openspace diff --git a/src/interaction/inputstate.cpp b/src/interaction/inputstate.cpp index f0b67464fd..42d08e3896 100644 --- a/src/interaction/inputstate.cpp +++ b/src/interaction/inputstate.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -69,10 +70,6 @@ void InputState::mouseScrollWheelCallback(double mouseScrollDelta) { _mouseScrollDelta = mouseScrollDelta; } -void InputState::setJoystickInputStates(JoystickInputStates& states) { - _joystickInputStates = &states; -} - const std::vector>& InputState::pressedKeys() const { return _keysDown; } @@ -106,16 +103,12 @@ bool InputState::isMouseButtonPressed(MouseButton mouseButton) const { return it != _mouseButtonsDown.end(); } -const JoystickInputStates& InputState::joystickInputStates() const { - return *_joystickInputStates; -} - float InputState::joystickAxis(int i) const { - return _joystickInputStates->axis(i); + return global::joystickInputStates.axis(i); } bool InputState::joystickButton(int i) const { - return _joystickInputStates->button(i, JoystickAction::Press); + return global::joystickInputStates.button(i, JoystickAction::Press); } } // namespace openspace::interaction diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index c6d8eff281..e4bb651ca7 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -152,10 +152,10 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, for (int i = 0; i < JoystickInputState::MaxButtons; ++i) { auto itRange = _buttonMapping.equal_range(i); for (auto it = itRange.first; it != itRange.second; ++it) { - bool active = inputState.joystickInputStates().button(i, it->second.action); + bool active = global::joystickInputStates.button(i, it->second.action); if (active) { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( it->second.command, scripting::ScriptEngine::RemoteScripting(it->second.synchronization) ); diff --git a/src/interaction/keybindingmanager.cpp b/src/interaction/keybindingmanager.cpp index b18c0e0777..5389a8c8cf 100644 --- a/src/interaction/keybindingmanager.cpp +++ b/src/interaction/keybindingmanager.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -34,7 +34,7 @@ namespace openspace::interaction { -KeyBindingManager::KeyBindingManager() +KeybindingManager::KeybindingManager() : DocumentationGenerator( "Documentation", "keybindings", @@ -46,7 +46,7 @@ KeyBindingManager::KeyBindingManager() ) {} -void KeyBindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) +void KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { if (action == KeyAction::Press || action == KeyAction::Repeat) { // iterate over key bindings @@ -54,7 +54,7 @@ void KeyBindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyActio for (auto it = ret.first; it != ret.second; ++it) { using RS = scripting::ScriptEngine::RemoteScripting; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( it->second.command, it->second.synchronization ? RS::Yes : RS::No ); @@ -62,11 +62,11 @@ void KeyBindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyActio } } -void KeyBindingManager::resetKeyBindings() { +void KeybindingManager::resetKeyBindings() { _keyLua.clear(); } -void KeyBindingManager::bindKeyLocal(Key key, KeyModifier modifier, +void KeybindingManager::bindKeyLocal(Key key, KeyModifier modifier, std::string luaCommand, std::string documentation) { _keyLua.insert({ @@ -79,7 +79,7 @@ void KeyBindingManager::bindKeyLocal(Key key, KeyModifier modifier, }); } -void KeyBindingManager::bindKey(Key key, KeyModifier modifier, +void KeybindingManager::bindKey(Key key, KeyModifier modifier, std::string luaCommand, std::string documentation) { _keyLua.insert({ @@ -92,7 +92,7 @@ void KeyBindingManager::bindKey(Key key, KeyModifier modifier, }); } -void KeyBindingManager::removeKeyBinding(const std::string& key) { +void KeybindingManager::removeKeyBinding(const std::string& key) { // Erase-remove idiom does not work for std::multimap so we have to do this on foot KeyWithModifier k = stringToKey(key); @@ -110,8 +110,8 @@ void KeyBindingManager::removeKeyBinding(const std::string& key) { } } -std::vector> -KeyBindingManager::keyBinding(const std::string& key) const +std::vector> +KeybindingManager::keyBinding(const std::string& key) const { std::vector> result; @@ -123,7 +123,7 @@ KeyBindingManager::keyBinding(const std::string& key) const return result; } -std::string KeyBindingManager::generateJson() const { +std::string KeybindingManager::generateJson() const { std::stringstream json; json << "["; bool first = true; @@ -145,7 +145,7 @@ std::string KeyBindingManager::generateJson() const { return json.str(); } -scripting::LuaLibrary KeyBindingManager::luaLibrary() { +scripting::LuaLibrary KeybindingManager::luaLibrary() { return { "", { diff --git a/src/interaction/keybindingmanager_lua.inl b/src/interaction/keybindingmanager_lua.inl index 2e01d9c7ec..ce0a08dcfa 100644 --- a/src/interaction/keybindingmanager_lua.inl +++ b/src/interaction/keybindingmanager_lua.inl @@ -22,6 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include #include namespace openspace::luascriptfunctions { @@ -57,7 +58,7 @@ int bindKey(lua_State* L) { std::string doc = (nArguments == 3) ? ghoul::lua::value(L, 3) : ""; - OsEng.keyBindingManager().bindKey( + global::keybindingManager.bindKey( iKey.key, iKey.modifier, std::move(command), @@ -96,7 +97,7 @@ int bindKeyLocal(lua_State* L) { std::string doc = nArguments == 3 ? ghoul::lua::value(L, 3) : ""; - OsEng.keyBindingManager().bindKeyLocal( + global::keybindingManager.bindKeyLocal( iKey.key, iKey.modifier, std::move(command), @@ -124,9 +125,9 @@ int getKeyBindings(lua_State* L) { ); using K = KeyWithModifier; - using V = interaction::KeyBindingManager::KeyInformation; + using V = interaction::KeybindingManager::KeyInformation; - const std::vector>& info = OsEng.keyBindingManager().keyBinding(key); + const std::vector>& info = global::keybindingManager.keyBinding(key); lua_createtable(L, static_cast(info.size()), 0); int i = 1; @@ -161,7 +162,7 @@ int clearKey(lua_State* L) { if (t == LUA_TSTRING) { // The user provided a single key const std::string& key = ghoul::lua::value(L, 1); - OsEng.keyBindingManager().removeKeyBinding(key); + global::keybindingManager.removeKeyBinding(key); } else { // The user provided a list of keys @@ -169,7 +170,7 @@ int clearKey(lua_State* L) { ghoul::lua::luaDictionaryFromState(L, d); for (size_t i = 1; i <= d.size(); ++i) { const std::string& k = d.value(std::to_string(i)); - OsEng.keyBindingManager().removeKeyBinding(k); + global::keybindingManager.removeKeyBinding(k); } lua_pop(L, 1); } @@ -187,7 +188,7 @@ int clearKey(lua_State* L) { int clearKeys(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::clearKeys"); - OsEng.keyBindingManager().resetKeyBindings(); + global::keybindingManager.resetKeyBindings(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; diff --git a/src/interaction/keyframenavigator.cpp b/src/interaction/keyframenavigator.cpp index 1670100f64..a2d43d909e 100644 --- a/src/interaction/keyframenavigator.cpp +++ b/src/interaction/keyframenavigator.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -35,7 +35,7 @@ namespace openspace::interaction { void KeyframeNavigator::updateCamera(Camera& camera) { - double now = OsEng.windowWrapper().applicationTime(); + double now = global::windowDelegate.applicationTime(); if (_cameraPoseTimeline.nKeyframes() == 0) { return; diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 4d5ab68172..6ec75b9532 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -99,18 +99,18 @@ NavigationHandler::NavigationHandler() NavigationHandler::~NavigationHandler() {} // NOLINT void NavigationHandler::initialize() { - OsEng.parallelPeer().connectionEvent().subscribe( + global::parallelPeer.connectionEvent().subscribe( "NavigationHandler", "statusChanged", [this]() { - _useKeyFrameInteraction = (OsEng.parallelPeer().status() == + _useKeyFrameInteraction = (global::parallelPeer.status() == ParallelConnection::Status::ClientWithHost); } ); } void NavigationHandler::deinitialize() { - OsEng.parallelPeer().connectionEvent().unsubscribe("NavigationHandler"); + global::parallelPeer.connectionEvent().unsubscribe("NavigationHandler"); } void NavigationHandler::setFocusNode(SceneGraphNode* node) { @@ -196,10 +196,6 @@ void NavigationHandler::keyboardCallback(Key key, KeyModifier modifier, KeyActio _inputState->keyboardCallback(key, modifier, action); } -void NavigationHandler::setJoystickInputStates(JoystickInputStates& states) { - _inputState->setJoystickInputStates(states); -} - void NavigationHandler::setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict) { bool readSuccessful = true; diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index fce7d9335b..74ea2c4681 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -39,7 +39,7 @@ int restoreCameraStateFromFile(lua_State* L) { return ghoul::lua::luaError(L, "filepath string is empty"); } - OsEng.navigationHandler().restoreCameraStateFromFile(cameraStateFilePath); + global::navigationHandler.restoreCameraStateFromFile(cameraStateFilePath); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -51,7 +51,7 @@ int setCameraState(lua_State* L) { try { ghoul::Dictionary dictionary; ghoul::lua::luaDictionaryFromState(L, dictionary); - OsEng.navigationHandler().setCameraStateFromDictionary(dictionary); + global::navigationHandler.setCameraStateFromDictionary(dictionary); } catch (const ghoul::RuntimeError& e) { lua_settop(L, 0); return ghoul::lua::luaError( @@ -80,7 +80,7 @@ int saveCameraStateToFile(lua_State* L) { return ghoul::lua::luaError(L, "filepath string is empty"); } - OsEng.navigationHandler().saveCameraStateToFile(cameraStateFilePath); + global::navigationHandler.saveCameraStateToFile(cameraStateFilePath); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -89,7 +89,7 @@ int saveCameraStateToFile(lua_State* L) { int resetCameraDirection(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::resetCameraDirection"); - OsEng.navigationHandler().resetCameraDirection(); + global::navigationHandler.resetCameraDirection(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -108,7 +108,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; - OsEng.navigationHandler().setJoystickAxisMapping( + global::navigationHandler.setJoystickAxisMapping( axis, ghoul::from_string(axisType), interaction::JoystickCameraStates::AxisInvert(shouldInvert), @@ -126,7 +126,7 @@ int joystickAxis(lua_State* L) { const int axis = ghoul::lua::value(L, 1); using AI = interaction::JoystickCameraStates::AxisInformation; - AI info = OsEng.navigationHandler().joystickAxisMapping(axis); + AI info = global::navigationHandler.joystickAxisMapping(axis); lua_settop(L, 0); const bool invert = info.invert; @@ -144,7 +144,7 @@ int setJoystickAxisDeadzone(lua_State* L) { const float deadzone = ghoul::lua::value(L, 2); lua_settop(L, 0); - OsEng.navigationHandler().setJoystickAxisDeadzone(axis, deadzone); + global::navigationHandler.setJoystickAxisDeadzone(axis, deadzone); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -155,7 +155,7 @@ int joystickAxisDeadzone(lua_State* L) { const int axis = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); - const float deadzone = OsEng.navigationHandler().joystickAxisDeadzone(axis); + const float deadzone = global::navigationHandler.joystickAxisDeadzone(axis); ghoul::lua::push(L, deadzone); ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); @@ -182,7 +182,7 @@ int bindJoystickButton(lua_State* L) { const bool isRemote = n == 5 ? ghoul::lua::value(L, 5) : true; lua_settop(L, 0); - OsEng.navigationHandler().bindJoystickButtonCommand( + global::navigationHandler.bindJoystickButtonCommand( button, std::move(command), action, @@ -199,7 +199,7 @@ int clearJoystickButton(lua_State* L) { const int button = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); - OsEng.navigationHandler().clearJoystickButtonCommand(button); + global::navigationHandler.clearJoystickButtonCommand(button); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -211,7 +211,7 @@ int joystickButton(lua_State* L) { const int button = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); const std::vector& cmds = - OsEng.navigationHandler().joystickButtonCommand(button); + global::navigationHandler.joystickButtonCommand(button); std::string cmd = std::accumulate( cmds.begin(), diff --git a/src/interaction/touchbar.mm b/src/interaction/touchbar.mm index 866586cce2..ba7234df89 100644 --- a/src/interaction/touchbar.mm +++ b/src/interaction/touchbar.mm @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -31,6 +32,8 @@ #include #include +using namespace openspace; + // Apple uses 'defer' as named arguments in some functions, so unfortunately, we have to // undef our defer macro from ghoul/misc/defer.h #undef defer @@ -90,7 +93,7 @@ NSArray* focusIdentifiers; if ([identifier isEqualToString:pauseResultId]) { NSButton* button = [NSButton buttonWithTitle:NSLocalizedString( - (OsEng.timeManager().isPaused() ? @"Resume" : @"Pause"), + (global::timeManager.isPaused() ? @"Resume" : @"Pause"), @"" ) target:self action:@selector(pauseResumeButtonAction:) @@ -170,14 +173,14 @@ NSArray* focusIdentifiers; } - (void)pauseResumeButtonAction:(id)sender { - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.time.togglePause();", - openspace::scripting::ScriptEngine::RemoteScripting::Yes + scripting::ScriptEngine::RemoteScripting::Yes ); NSButton* button = static_cast(sender); // This check is inverted since the togglePause script has not run yet - [button setTitle: OsEng.timeManager().isPaused() ? @"Pause" : @"Resume"]; + [button setTitle: global::timeManager.isPaused() ? @"Pause" : @"Resume"]; } - (void)focusObjectAction:(id)sender { @@ -185,17 +188,17 @@ NSArray* focusIdentifiers; NSString* title = [button title]; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "openspace.setPropertyValue('NavigationHandler.Origin', '" + std::string([title UTF8String]) + "');", - openspace::scripting::ScriptEngine::RemoteScripting::Yes + scripting::ScriptEngine::RemoteScripting::Yes ); } - (void)fullGuiButtonAction:(id)sender { // Remove unused variable warning (void)sender; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "local b = openspace.getPropertyValue(\ 'Modules.ImGUI.Main.Enabled'\ );\ @@ -207,14 +210,14 @@ NSArray* focusIdentifiers; 'Modules.ImGUI.Main.IsHidden',\ b\ );", - openspace::scripting::ScriptEngine::RemoteScripting::No + scripting::ScriptEngine::RemoteScripting::No ); } - (void)simpleGuiButtonAction:(id)sender { // Remove unused variable warning (void)sender; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( "local b = openspace.getPropertyValue('Modules.ImGUI.Main.FeaturedProperties.Enabled');\n\ local c = openspace.getPropertyValue('Modules.ImGUI.Main.IsHidden');\n\ openspace.setPropertyValue('Modules.ImGUI.*.Enabled', false);\n\ @@ -242,7 +245,7 @@ else\n\ );\n\ openspace.setPropertyValueSingle('Modules.ImGUI.Main.IsHidden', b);\n\ end", - openspace::scripting::ScriptEngine::RemoteScripting::No + scripting::ScriptEngine::RemoteScripting::No ); } @end @@ -264,7 +267,7 @@ void showTouchbar() { } std::vector nodes = - OsEng.renderEngine().scene()->allSceneGraphNodes(); + global::renderEngine.scene()->allSceneGraphNodes(); std::sort( nodes.begin(), diff --git a/src/mission/missionmanager.cpp b/src/mission/missionmanager.cpp index fa1f62c3b9..2f94ac202d 100644 --- a/src/mission/missionmanager.cpp +++ b/src/mission/missionmanager.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include diff --git a/src/mission/missionmanager_lua.inl b/src/mission/missionmanager_lua.inl index 0ce5bb8d82..650383270e 100644 --- a/src/mission/missionmanager_lua.inl +++ b/src/mission/missionmanager_lua.inl @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include + namespace openspace::luascriptfunctions { int loadMission(lua_State* L) { @@ -36,7 +38,7 @@ int loadMission(lua_State* L) { return ghoul::lua::luaError(L, "Filepath is empty"); } - std::string name = MissionManager::ref().loadMission(absPath(missionFileName)); + std::string name = global::missionManager.loadMission(absPath(missionFileName)); ghoul::lua::push(L, name); ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); @@ -55,11 +57,11 @@ int unloadMission(lua_State* L) { return ghoul::lua::luaError(L, "Mission name is empty"); } - if (!MissionManager::ref().hasMission(missionName)) { + if (!global::missionManager.hasMission(missionName)) { return ghoul::lua::luaError(L, "Mission was not previously loaded"); } - MissionManager::ref().unloadMission(missionName); + global::missionManager.unloadMission(missionName); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -77,7 +79,7 @@ int hasMission(lua_State* L) { return ghoul::lua::luaError(L, "Missing name is empty"); } - const bool hasMission = MissionManager::ref().hasMission(missionName); + const bool hasMission = global::missionManager.hasMission(missionName); ghoul::lua::push(L, hasMission); @@ -97,7 +99,7 @@ int setCurrentMission(lua_State* L) { return ghoul::lua::luaError(L, "Mission name is empty"); } - MissionManager::ref().setCurrentMission(missionName); + global::missionManager.setCurrentMission(missionName); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; diff --git a/src/network/networkengine.cpp b/src/network/networkengine.cpp index 71bb9e90ad..3f2f73cb8e 100644 --- a/src/network/networkengine.cpp +++ b/src/network/networkengine.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -61,7 +61,7 @@ bool NetworkEngine::handleMessage(const std::string& message) { const char type = message[0]; switch (type) { case MessageTypeLuaScript: // LuaScript - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( message.substr(1), scripting::ScriptEngine::RemoteScripting::No ); @@ -79,7 +79,7 @@ bool NetworkEngine::handleMessage(const std::string& message) { void NetworkEngine::publishStatusMessage() { if (!_shouldPublishStatusMessage || - !OsEng.windowWrapper().isExternalControlConnected()) + !global::windowDelegate.isExternalControlConnected()) { return; } @@ -89,13 +89,13 @@ void NetworkEngine::publishStatusMessage() { // 8 bytes: delta time as double // Total: 40 - const Time& currentTime = OsEng.timeManager().time(); + const Time& currentTime = global::timeManager.time(); uint16_t messageSize = 0; const double time = currentTime.j2000Seconds(); const std::string timeString = currentTime.UTC(); - double delta = OsEng.timeManager().deltaTime(); + double delta = global::timeManager.deltaTime(); messageSize += sizeof(time); @@ -169,7 +169,7 @@ void NetworkEngine::publishMessage(MessageIdentifier identifier, } void NetworkEngine::sendMessages() { - if (!OsEng.windowWrapper().isExternalControlConnected()) { + if (!global::windowDelegate.isExternalControlConnected()) { return; } @@ -186,7 +186,7 @@ void NetworkEngine::sendMessages() { // Prepending the message identifier to the front m.body.insert(m.body.begin(), identifier.data.begin(), identifier.data.end()); - OsEng.windowWrapper().sendMessageToExternalControl(m.body); + global::windowDelegate.sendMessageToExternalControl(m.body); } _messagesToSend.clear(); @@ -204,7 +204,7 @@ void NetworkEngine::sendInitialInformation() { std::vector payload = m.body; payload.insert(payload.begin(), identifier.data.begin(), identifier.data.end()); - OsEng.windowWrapper().sendMessageToExternalControl(payload); + global::windowDelegate.sendMessageToExternalControl(payload); LINFO(fmt::format( "Sent initial message: (s={}) [i={}]", m.body.size(), identifier.value )); @@ -224,7 +224,7 @@ void NetworkEngine::sendInitialInformation() { std::vector d; d.insert(d.begin(), identifier.data.begin(), identifier.data.end()); - OsEng.windowWrapper().sendMessageToExternalControl(d); + global::windowDelegate.sendMessageToExternalControl(d); _shouldPublishStatusMessage = true; } diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index 1e2cc4f25d..47fafecdf9 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include diff --git a/src/network/parallelpeer.cpp b/src/network/parallelpeer.cpp index c5af3a8543..0311a9640d 100644 --- a/src/network/parallelpeer.cpp +++ b/src/network/parallelpeer.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -127,10 +127,10 @@ ParallelPeer::ParallelPeer() ParallelPeer::~ParallelPeer() { disconnect(); if (_timeJumpCallback != -1) { - OsEng.timeManager().removeTimeJumpCallback(_timeJumpCallback); + global::timeManager.removeTimeJumpCallback(_timeJumpCallback); } if (_timeJumpCallback != -1) { - OsEng.timeManager().removeTimeJumpCallback(_timeJumpCallback); + global::timeManager.removeTimeJumpCallback(_timeJumpCallback); } } @@ -227,7 +227,7 @@ void ParallelPeer::handleMessage(const ParallelConnection::Message& message) { void ParallelPeer::analyzeTimeDifference(double messageTimestamp) { std::lock_guard latencyLock(_latencyMutex); - const double timeDiff = OsEng.windowWrapper().applicationTime() - messageTimestamp; + const double timeDiff = global::windowDelegate.applicationTime() - messageTimestamp; if (_latencyDiffs.empty()) { _initialTimeDiff = timeDiff; } @@ -282,7 +282,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) datamessagestructures::CameraKeyframe kf(buffer); const double convertedTimestamp = convertTimestamp(kf._timestamp); - OsEng.navigationHandler().keyframeNavigator().removeKeyframesAfter( + global::navigationHandler.keyframeNavigator().removeKeyframesAfter( convertedTimestamp ); @@ -293,16 +293,16 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) pose.scale = kf._scale; pose.followFocusNodeRotation = kf._followNodeRotation; - OsEng.navigationHandler().keyframeNavigator().addKeyframe(convertedTimestamp, + global::navigationHandler.keyframeNavigator().addKeyframe(convertedTimestamp, pose); break; } case datamessagestructures::Type::TimelineData: { - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); datamessagestructures::TimeTimeline timelineMessage(buffer); if (timelineMessage._clear) { - OsEng.timeManager().removeKeyframesAfter( + global::timeManager.removeKeyframesAfter( convertTimestamp(timestamp), true ); @@ -317,7 +317,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) const double convertedTimestamp = convertTimestamp(keyframesMessage[0]._timestamp); - OsEng.timeManager().removeKeyframesAfter(convertedTimestamp, true); + global::timeManager.removeKeyframesAfter(convertedTimestamp, true); } for (const datamessagestructures::TimeKeyframe& kfMessage : keyframesMessage) @@ -333,9 +333,9 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) // We only need at least one keyframe before the current timestamp, // so we can remove any other previous ones if (kfTimestamp < now) { - OsEng.timeManager().removeKeyframesBefore(kfTimestamp, true); + global::timeManager.removeKeyframesBefore(kfTimestamp, true); } - OsEng.timeManager().addKeyframe( + global::timeManager.addKeyframe( kfTimestamp, timeKeyframeData ); @@ -346,7 +346,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) datamessagestructures::ScriptMessage sm; sm.deserialize(buffer); - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( sm._script, scripting::ScriptEngine::RemoteScripting::No ); @@ -406,8 +406,8 @@ void ParallelPeer::connectionStatusMessageReceived(const std::vector& mess setStatus(status); - OsEng.navigationHandler().keyframeNavigator().clearKeyframes(); - OsEng.timeManager().clearKeyframes(); + global::navigationHandler.keyframeNavigator().clearKeyframes(); + global::timeManager.clearKeyframes(); } void ParallelPeer::nConnectionsMessageReceived(const std::vector& message) @@ -453,7 +453,7 @@ void ParallelPeer::requestHostship() { reinterpret_cast(&passwordHash) + sizeof(uint64_t) ); - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); _connection.sendMessage(ParallelConnection::Message( ParallelConnection::MessageType::HostshipRequest, buffer @@ -461,7 +461,7 @@ void ParallelPeer::requestHostship() { } void ParallelPeer::resignHostship() { - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); std::vector buffer; _connection.sendMessage(ParallelConnection::Message( @@ -489,7 +489,7 @@ void ParallelPeer::sendScript(std::string script) { std::vector buffer; sm.serialize(buffer); - double timestamp = OsEng.windowWrapper().applicationTime(); + double timestamp = global::windowDelegate.applicationTime(); ParallelConnection::DataMessage message( datamessagestructures::Type::ScriptData, timestamp, @@ -499,8 +499,8 @@ void ParallelPeer::sendScript(std::string script) { } void ParallelPeer::resetTimeOffset() { - OsEng.navigationHandler().keyframeNavigator().clearKeyframes(); - OsEng.timeManager().clearKeyframes(); + global::navigationHandler.keyframeNavigator().clearKeyframes(); + global::timeManager.clearKeyframes(); std::lock_guard latencyLock(_latencyMutex); _latencyDiffs.clear(); } @@ -514,7 +514,7 @@ void ParallelPeer::preSynchronization() { } if (isHost()) { - double now = OsEng.windowWrapper().applicationTime(); + double now = global::windowDelegate.applicationTime(); if (_lastCameraKeyframeTimestamp + _cameraKeyframeInterval < now) { sendCameraKeyframe(); @@ -541,18 +541,18 @@ void ParallelPeer::setStatus(ParallelConnection::Status status) { _connectionEvent->publish("statusChanged"); } if (isHost()) { - OsEng.timeManager().addTimeJumpCallback([this]() { + global::timeManager.addTimeJumpCallback([this]() { _timeJumped = true; }); - OsEng.timeManager().addTimelineChangeCallback([this]() { + global::timeManager.addTimelineChangeCallback([this]() { _timeTimelineChanged = true; }); } else { if (_timeJumpCallback != -1) { - OsEng.timeManager().removeTimeJumpCallback(_timeJumpCallback); + global::timeManager.removeTimeJumpCallback(_timeJumpCallback); } if (_timeTimelineChangeCallback != -1) { - OsEng.timeManager().removeTimelineChangeCallback(_timeTimelineChangeCallback); + global::timeManager.removeTimelineChangeCallback(_timeTimelineChangeCallback); } } } @@ -588,30 +588,30 @@ const std::string& ParallelPeer::hostName() { } void ParallelPeer::sendCameraKeyframe() { - SceneGraphNode* focusNode = OsEng.navigationHandler().focusNode(); + SceneGraphNode* focusNode = global::navigationHandler.focusNode(); if (!focusNode) { return; } // Create a keyframe with current position and orientation of camera datamessagestructures::CameraKeyframe kf; - kf._position = OsEng.navigationHandler().focusNodeToCameraVector(); + kf._position = global::navigationHandler.focusNodeToCameraVector(); kf._followNodeRotation = - OsEng.navigationHandler().orbitalNavigator().followingNodeRotation(); + global::navigationHandler.orbitalNavigator().followingNodeRotation(); if (kf._followNodeRotation) { kf._position = glm::inverse(focusNode->worldRotationMatrix()) * kf._position; - kf._rotation = OsEng.navigationHandler().focusNodeToCameraRotation(); + kf._rotation = global::navigationHandler.focusNodeToCameraRotation(); } else { - kf._rotation = OsEng.navigationHandler().camera()->rotationQuaternion(); + kf._rotation = global::navigationHandler.camera()->rotationQuaternion(); } kf._focusNode = focusNode->identifier(); - kf._scale = OsEng.navigationHandler().camera()->scaling(); + kf._scale = global::navigationHandler.camera()->scaling(); // Timestamp as current runtime of OpenSpace instance - kf._timestamp = OsEng.windowWrapper().applicationTime(); + kf._timestamp = global::windowDelegate.applicationTime(); // Create a buffer for the keyframe std::vector buffer; @@ -619,7 +619,7 @@ void ParallelPeer::sendCameraKeyframe() { // Fill the keyframe buffer kf.serialize(buffer); - const double timestamp = OsEng.windowWrapper().applicationTime(); + const double timestamp = global::windowDelegate.applicationTime(); // Send message _connection.sendDataMessage(ParallelConnection::DataMessage( datamessagestructures::Type::CameraData, @@ -630,7 +630,7 @@ void ParallelPeer::sendCameraKeyframe() { void ParallelPeer::sendTimeTimeline() { // Create a keyframe with current position and orientation of camera - const Timeline timeline = OsEng.timeManager().timeline(); + const Timeline timeline = global::timeManager.timeline(); std::deque> keyframes = timeline.keyframes(); datamessagestructures::TimeTimeline timelineMessage; @@ -655,10 +655,10 @@ void ParallelPeer::sendTimeTimeline() { // If time jumped this frame, this is represented in the keyframe. if (timeline.nKeyframes() == 0) { datamessagestructures::TimeKeyframe kfMessage; - kfMessage._time = OsEng.timeManager().time().j2000Seconds(); - kfMessage._dt = OsEng.timeManager().targetDeltaTime(); - kfMessage._paused = OsEng.timeManager().isPaused(); - kfMessage._timestamp = OsEng.windowWrapper().applicationTime(); + kfMessage._time = global::timeManager.time().j2000Seconds(); + kfMessage._dt = global::timeManager.targetDeltaTime(); + kfMessage._paused = global::timeManager.isPaused(); + kfMessage._timestamp = global::windowDelegate.applicationTime(); kfMessage._requiresTimeJump = _timeJumped; timelineMessage._keyframes.push_back(kfMessage); } @@ -668,7 +668,7 @@ void ParallelPeer::sendTimeTimeline() { // Fill the timeline buffer timelineMessage.serialize(buffer); - double timestamp = OsEng.windowWrapper().applicationTime(); + double timestamp = global::windowDelegate.applicationTime(); // Send message _connection.sendDataMessage(ParallelConnection::DataMessage( datamessagestructures::Type::TimelineData, diff --git a/src/network/parallelpeer_lua.inl b/src/network/parallelpeer_lua.inl index dfa5dc636c..2ecc52f4f0 100644 --- a/src/network/parallelpeer_lua.inl +++ b/src/network/parallelpeer_lua.inl @@ -27,8 +27,8 @@ namespace openspace::luascriptfunctions { int connect(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::connect"); - if (OsEng.windowWrapper().isMaster()) { - OsEng.parallelPeer().connect(); + if (global::windowDelegate.isMaster()) { + global::parallelPeer.connect(); } ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -38,8 +38,8 @@ int connect(lua_State* L) { int disconnect(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::disconnect"); - if (OsEng.windowWrapper().isMaster()) { - OsEng.parallelPeer().connect(); + if (global::windowDelegate.isMaster()) { + global::parallelPeer.connect(); } ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -49,8 +49,8 @@ int disconnect(lua_State* L) { int requestHostship(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::requestHostship"); - if (OsEng.windowWrapper().isMaster()) { - OsEng.parallelPeer().requestHostship(); + if (global::windowDelegate.isMaster()) { + global::parallelPeer.requestHostship(); } ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -60,8 +60,8 @@ int requestHostship(lua_State* L) { int resignHostship(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::resignHostship"); - if (OsEng.windowWrapper().isMaster()) { - OsEng.parallelPeer().resignHostship(); + if (global::windowDelegate.isMaster()) { + global::parallelPeer.resignHostship(); } ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index a0cdac3651..bdf45cde33 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -130,62 +130,72 @@ void PerformanceManager::DestroyGlobalSharedMemory() { sharedMemory.releaseLock(); } -PerformanceManager::PerformanceManager(std::string loggingDirectory, std::string prefix) - : _logDir(absPath(std::move(loggingDirectory))) - , _prefix(std::move(prefix)) -{ - PerformanceManager::CreateGlobalSharedMemory(); +PerformanceManager::~PerformanceManager() {} - ghoul::SharedMemory sharedMemory(GlobalSharedMemoryName); - sharedMemory.acquireLock(); - defer { - sharedMemory.releaseLock(); - }; +void PerformanceManager::setEnabled(bool enabled) { + _logDir = absPath("${BASE}"); + _prefix = "PM-"; - GlobalMemory* m = reinterpret_cast(sharedMemory.memory()); + _performanceMeasurementEnabled = enabled; - // The the first free block (which also coincides with the number of blocks - uint8_t blockIndex = m->number; - ++(m->number); + if (enabled) { + PerformanceManager::CreateGlobalSharedMemory(); - const std::string& localName = LocalSharedMemoryNameBase + std::to_string(blockIndex); - - // Compute the total size - const int totalSize = sizeof(PerformanceLayout); - LINFO(fmt::format("Create shared memory '{}' of {} bytes", localName, totalSize)); - - if (ghoul::SharedMemory::exists(localName)) { - throw ghoul::RuntimeError( - "Shared Memory '" + localName + "' block already existed" - ); - } - - ghoul::SharedMemory::create(localName, totalSize); - - _performanceMemory = std::make_unique(localName); - // Using the placement-new to create a PerformanceLayout in the shared memory - new (_performanceMemory->memory()) PerformanceLayout; -} - -PerformanceManager::~PerformanceManager() { - if (loggingEnabled()) { - outputLogs(); - } - - if (_performanceMemory) { ghoul::SharedMemory sharedMemory(GlobalSharedMemoryName); sharedMemory.acquireLock(); + defer { + sharedMemory.releaseLock(); + }; + GlobalMemory* m = reinterpret_cast(sharedMemory.memory()); - --(m->number); - sharedMemory.releaseLock(); - LINFO(fmt::format("Remove shared memory '{}'", _performanceMemory->name())); - ghoul::SharedMemory::remove(_performanceMemory->name()); + // The the first free block (which also coincides with the number of blocks + uint8_t blockIndex = m->number; + ++(m->number); - _performanceMemory = nullptr; + const std::string& localName = LocalSharedMemoryNameBase + + std::to_string(blockIndex); + + // Compute the total size + const int totalSize = sizeof(PerformanceLayout); + LINFO(fmt::format("Create shared memory '{}' of {} bytes", localName, totalSize)); + + if (ghoul::SharedMemory::exists(localName)) { + throw ghoul::RuntimeError( + "Shared Memory '" + localName + "' block already existed" + ); + } + + ghoul::SharedMemory::create(localName, totalSize); + + _performanceMemory = std::make_unique(localName); + // Using the placement-new to create a PerformanceLayout in the shared memory + new (_performanceMemory->memory()) PerformanceLayout; } + else { + if (loggingEnabled()) { + outputLogs(); + } - PerformanceManager::DestroyGlobalSharedMemory(); + if (_performanceMemory) { + ghoul::SharedMemory sharedMemory(GlobalSharedMemoryName); + sharedMemory.acquireLock(); + GlobalMemory* m = reinterpret_cast(sharedMemory.memory()); + --(m->number); + sharedMemory.releaseLock(); + + LINFO(fmt::format("Remove shared memory '{}'", _performanceMemory->name())); + ghoul::SharedMemory::remove(_performanceMemory->name()); + + _performanceMemory = nullptr; + } + + PerformanceManager::DestroyGlobalSharedMemory(); + } +} + +bool PerformanceManager::isEnabled() const { + return _performanceMeasurementEnabled; } void PerformanceManager::resetPerformanceMeasurements() { diff --git a/src/performance/performancemeasurement.cpp b/src/performance/performancemeasurement.cpp index 3a7b47a0b4..73e9d93710 100644 --- a/src/performance/performancemeasurement.cpp +++ b/src/performance/performancemeasurement.cpp @@ -24,22 +24,17 @@ #include +#include #include #include -#include namespace openspace::performance { -PerformanceMeasurement::PerformanceMeasurement(std::string identifier, - std::shared_ptr manager) +PerformanceMeasurement::PerformanceMeasurement(std::string identifier) : _identifier(std::move(identifier)) - , _manager(std::move(manager)) { - if (_manager.lock()) { - glFinish(); - - _startTime = std::chrono::high_resolution_clock::now(); - } + glFinish(); + _startTime = std::chrono::high_resolution_clock::now(); } PerformanceMeasurement::~PerformanceMeasurement() { @@ -49,9 +44,10 @@ PerformanceMeasurement::~PerformanceMeasurement() { endTime - _startTime ).count(); - if (std::shared_ptr m = _manager.lock()) { - m->storeIndividualPerformanceMeasurement(std::move(_identifier), duration); - } + global::performanceManager.storeIndividualPerformanceMeasurement( + std::move(_identifier), + duration + ); } } // namespace openspace::performance diff --git a/src/query/query.cpp b/src/query/query.cpp index 6bee5a8c9b..6bddf41612 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -32,7 +32,7 @@ namespace openspace { Scene* sceneGraph() { - return OsEng.renderEngine().scene(); + return global::renderEngine.scene(); } SceneGraphNode* sceneGraphNode(const std::string& name) { @@ -46,7 +46,7 @@ const Renderable* renderable(const std::string& name) { } properties::Property* property(const std::string& uri) { - properties::Property* property = OsEng.rootPropertyOwner().property(uri); + properties::Property* property = global::rootPropertyOwner.property(uri); return property; } @@ -54,14 +54,14 @@ std::vector allProperties() { std::vector properties; std::vector p = - OsEng.rootPropertyOwner().propertiesRecursive(); + global::rootPropertyOwner.propertiesRecursive(); properties.insert(properties.end(), p.begin(), p.end()); // The virtual property manager is not part of the rootProperty owner since it cannot // have an identifier or the "regex as identifier" trick would not work std::vector p2 = - OsEng.virtualPropertyManager().propertiesRecursive(); + global::virtualPropertyManager.propertiesRecursive(); properties.insert(properties.end(), p2.begin(), p2.end()); diff --git a/src/rendering/abufferrenderer.cpp b/src/rendering/abufferrenderer.cpp index 65d6ba0958..b9d0b65012 100644 --- a/src/rendering/abufferrenderer.cpp +++ b/src/rendering/abufferrenderer.cpp @@ -26,8 +26,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -138,7 +138,7 @@ void ABufferRenderer::initialize() { LERRORC(e.component, e.message); } - OsEng.renderEngine().raycasterManager().addListener(*this); + global::raycasterManager.addListener(*this); } void ABufferRenderer::deinitialize() { @@ -153,7 +153,7 @@ void ABufferRenderer::deinitialize() { glDeleteBuffers(1, &_vertexPositionBuffer); glDeleteVertexArrays(1, &_screenQuad); - OsEng.renderEngine().raycasterManager().removeListener(*this); + global::raycasterManager.removeListener(*this); } void ABufferRenderer::raycastersChanged(VolumeRaycaster&, IsAttached) { @@ -542,9 +542,7 @@ void ABufferRenderer::updateMSAASamplingPattern() { glDeleteVertexArrays(1, &nOneStripVAO); } -void ABufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, - bool doPerformanceMeasurements) -{ +void ABufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor) { PerfMeasure("ABufferRenderer::render"); if (!scene || !camera) { @@ -584,7 +582,7 @@ void ABufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, static_cast(Renderable::RenderBin::Transparent) | static_cast(Renderable::RenderBin::Overlay); - Time time = OsEng.timeManager().time(); + Time time = global::timeManager.time(); RenderData data{ *camera, psc(), time, doPerformanceMeasurements, renderBinMask, {} }; RendererTasks tasks; scene->render(data, tasks); @@ -866,7 +864,7 @@ void ABufferRenderer::updateResolveDictionary() { _resolveDictionary = dict; - OsEng.renderEngine().setResolveData(dict); + global::renderEngine.setResolveData(dict); _dirtyResolveDictionary = false; } @@ -879,7 +877,7 @@ void ABufferRenderer::updateRaycastData() { _helperPaths.clear(); const std::vector& raycasters = - OsEng.renderEngine().raycasterManager().raycasters(); + global::renderEngine.raycasterManager().raycasters(); std::map namespaceIndices; // raycaster ids are positive integers starting at 0. (for raycasters, @@ -960,7 +958,7 @@ void ABufferRenderer::updateRendererData() { _rendererData = dict; - OsEng.renderEngine().setRendererData(dict); + global::renderEngine.setRendererData(dict); _dirtyRendererData = false; } diff --git a/src/rendering/dashboard.cpp b/src/rendering/dashboard.cpp index ba2c9bb4aa..3e0fe9daf2 100644 --- a/src/rendering/dashboard.cpp +++ b/src/rendering/dashboard.cpp @@ -48,6 +48,8 @@ Dashboard::Dashboard() addProperty(_isEnabled); } +Dashboard::~Dashboard() {} + void Dashboard::addDashboardItem(std::unique_ptr item) { const std::string& originalIdentifier = item->identifier(); int suffix = 1; diff --git a/src/rendering/dashboard_lua.inl b/src/rendering/dashboard_lua.inl index 1419805801..7b2500d6b6 100644 --- a/src/rendering/dashboard_lua.inl +++ b/src/rendering/dashboard_lua.inl @@ -22,9 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include -#include #include +#include #include namespace openspace::luascriptfunctions { @@ -49,7 +48,7 @@ int addDashboardItem(lua_State* L) { } lua_settop(L, 0); - OsEng.dashboard().addDashboardItem(DashboardItem::createFromDictionary(d)); + global::dashboard.addDashboardItem(DashboardItem::createFromDictionary(d)); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -70,7 +69,7 @@ int removeDashboardItem(lua_State* L) { std::string identifier = luaL_checkstring(L, -1); - OsEng.dashboard().removeDashboardItem(identifier); + global::dashboard.removeDashboardItem(identifier); lua_settop(L, 0); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -85,7 +84,7 @@ int removeDashboardItem(lua_State* L) { int clearDashboardItems(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::clearDashboardItems"); - OsEng.dashboard().clearDashboardItems(); + global::dashboard.clearDashboardItems(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 065460ddf8..7b5502cc3b 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -24,8 +24,9 @@ #include -#include -#include +#include +#include +#include #include #include #include @@ -229,8 +230,8 @@ void FramebufferRenderer::initialize() { ghoul::opengl::updateUniformLocations(*_resolveProgram, _uniformCache, UniformNames); - OsEng.renderEngine().raycasterManager().addListener(*this); - OsEng.renderEngine().deferredcasterManager().addListener(*this); + global::raycasterManager.addListener(*this); + global::deferredcasterManager.addListener(*this); } void FramebufferRenderer::deinitialize() { @@ -254,8 +255,8 @@ void FramebufferRenderer::deinitialize() { glDeleteBuffers(1, &_vertexPositionBuffer); glDeleteVertexArrays(1, &_screenQuad); - OsEng.renderEngine().raycasterManager().removeListener(*this); - OsEng.renderEngine().deferredcasterManager().removeListener(*this); + global::raycasterManager.removeListener(*this); + global::deferredcasterManager.removeListener(*this); } void FramebufferRenderer::raycastersChanged(VolumeRaycaster&, @@ -460,7 +461,8 @@ void FramebufferRenderer::updateRaycastData() { _insideRaycastPrograms.clear(); const std::vector& raycasters = - OsEng.renderEngine().raycasterManager().raycasters(); + global::raycasterManager.raycasters(); + int nextId = 0; for (VolumeRaycaster* raycaster : raycasters) { RaycastData data = { nextId++, "Helper" }; @@ -529,7 +531,7 @@ void FramebufferRenderer::updateDeferredcastData() { _deferredcastPrograms.clear(); const std::vector& deferredcasters = - OsEng.renderEngine().deferredcasterManager().deferredcasters(); + global::deferredcasterManager.deferredcasters(); int nextId = 0; for (Deferredcaster* caster : deferredcasters) { DeferredcastData data = { nextId++, "HELPER" }; @@ -907,14 +909,13 @@ void FramebufferRenderer::updateMSAASamplingPattern() { _dirtyMsaaSamplingPattern = false; } -void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, - bool doPerformanceMeasurements) -{ +void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor) { + const bool doPerformanceMeasurements = global::performanceManager.isEnabled(); + std::unique_ptr perf; if (doPerformanceMeasurements) { perf = std::make_unique( - "FramebufferRenderer::render", - OsEng.renderEngine().performanceManager() + "FramebufferRenderer::render" ); } @@ -945,7 +946,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac glDisablei(GL_BLEND, 2); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Time time = OsEng.timeManager().time(); + Time time = global::timeManager.time(); RenderData data = { *camera, @@ -970,8 +971,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac std::unique_ptr perfInternal; if (doPerformanceMeasurements) { perfInternal = std::make_unique( - "FramebufferRenderer::render::raycasterTasks", - OsEng.renderEngine().performanceManager() + "FramebufferRenderer::render::raycasterTasks" ); } performRaycasterTasks(tasks.raycasterTasks); @@ -985,8 +985,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac std::unique_ptr perfInternal; if (doPerformanceMeasurements) { perfInternal = std::make_unique( - "FramebufferRenderer::render::deferredTasks", - OsEng.renderEngine().performanceManager() + "FramebufferRenderer::render::deferredTasks" ); } performDeferredTasks(tasks.deferredcasterTasks); @@ -1239,7 +1238,7 @@ void FramebufferRenderer::updateRendererData() { ghoul::Dictionary dict; dict.setValue("fragmentRendererPath", std::string(RenderFragmentShaderPath)); _rendererData = dict; - OsEng.renderEngine().setRendererData(dict); + global::renderEngine.setRendererData(dict); } } // namespace openspace diff --git a/src/rendering/loadingscreen.cpp b/src/rendering/loadingscreen.cpp index 64b2df98d5..52a14abe24 100644 --- a/src/rendering/loadingscreen.cpp +++ b/src/rendering/loadingscreen.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -116,7 +116,7 @@ LoadingScreen::LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeName { "logoTexture", "useTexture", "color" } ); - _loadingFont = OsEng.fontManager().font( + _loadingFont = global::fontManager.font( "Loading", LoadingFontSize, ghoul::fontrendering::FontManager::Outline::No, @@ -124,7 +124,7 @@ LoadingScreen::LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeName ); if (_showMessage) { - _messageFont = OsEng.fontManager().font( + _messageFont = global::fontManager.font( "Loading", MessageFontSize, ghoul::fontrendering::FontManager::Outline::No, @@ -133,7 +133,7 @@ LoadingScreen::LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeName } if (_showNodeNames) { - _itemFont = OsEng.fontManager().font( + _itemFont = global::fontManager.font( "Loading", ItemFontSize, ghoul::fontrendering::FontManager::Outline::No, @@ -212,9 +212,9 @@ void LoadingScreen::render() { // We have to recalculate the positions here because we will not be informed about a // window size change - const glm::vec2 dpiScaling = OsEng.windowWrapper().dpiScaling(); + const glm::vec2 dpiScaling = global::windowDelegate.dpiScaling(); const glm::ivec2 res = - glm::vec2(OsEng.windowWrapper().currentDrawBufferResolution()) / dpiScaling; + glm::vec2(global::windowDelegate.currentDrawBufferResolution()) / dpiScaling; float screenAspectRatio = static_cast(res.x) / static_cast(res.y); @@ -611,7 +611,7 @@ void LoadingScreen::render() { glEnable(GL_DEPTH_TEST); std::this_thread::sleep_for(RefreshRate); - OsEng.windowWrapper().swapBuffer(); + global::windowDelegate.swapBuffer(); } void LoadingScreen::postMessage(std::string message) { diff --git a/src/rendering/luaconsole.cpp b/src/rendering/luaconsole.cpp index ad5fb4ba16..1e4f787ee9 100644 --- a/src/rendering/luaconsole.cpp +++ b/src/rendering/luaconsole.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -269,23 +269,23 @@ void LuaConsole::initialize() { glBindVertexArray(0); - _font = OsEng.fontManager().font( + _font = global::fontManager.font( FontName, EntryFontSize, ghoul::fontrendering::FontManager::Outline::No ); - _historyFont = OsEng.fontManager().font( + _historyFont = global::fontManager.font( FontName, HistoryFontSize, ghoul::fontrendering::FontManager::Outline::No ); - OsEng.parallelPeer().connectionEvent().subscribe( + global::parallelPeer.connectionEvent().subscribe( "luaConsole", "statusChanged", [this]() { - ParallelConnection::Status status = OsEng.parallelPeer().status(); + ParallelConnection::Status status = global::parallelPeer.status(); parallelConnectionChanged(status); } ); @@ -325,7 +325,7 @@ void LuaConsole::deinitialize() { _program = nullptr; - OsEng.parallelPeer().connectionEvent().unsubscribe("luaConsole"); + global::parallelPeer.connectionEvent().unsubscribe("luaConsole"); } bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { @@ -348,7 +348,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio } else { _isVisible = true; - if (OsEng.parallelPeer().status() == ParallelConnection::Status::Host) { + if (global::parallelPeer.status() == ParallelConnection::Status::Host) { _remoteScripting = true; } } @@ -488,7 +488,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio std::string cmd = _commands.at(_activeCommand); if (!cmd.empty()) { using RemoteScripting = scripting::ScriptEngine::RemoteScripting; - OsEng.scriptEngine().queueScript(cmd, RemoteScripting(_remoteScripting)); + global::scriptEngine.queueScript(cmd, RemoteScripting(_remoteScripting)); // Only add the current command to the history if it hasn't been // executed before. We don't want two of the same commands in a row @@ -517,7 +517,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio if (_autoCompleteInfo.lastIndex != NoAutoComplete && modifierShift) { _autoCompleteInfo.lastIndex -= 2; } - std::vector allCommands = OsEng.scriptEngine().allLuaFunctions(); + std::vector allCommands = global::scriptEngine.allLuaFunctions(); std::sort(allCommands.begin(), allCommands.end()); std::string currentCommand = _commands.at(_activeCommand); @@ -675,13 +675,13 @@ void LuaConsole::update() { // The first frame is going to be finished in approx 10 us, which causes a floating // point overflow when computing dHeight constexpr double Epsilon = 1e-4; - const double frametime = std::max(OsEng.windowWrapper().deltaTime(), Epsilon); + const double frametime = std::max(global::windowDelegate.deltaTime(), Epsilon); // Update the current height. // The current height is the offset that is used to slide // the console in from the top. - const glm::ivec2 res = OsEng.windowWrapper().currentWindowResolution(); - const glm::vec2 dpiScaling = OsEng.windowWrapper().dpiScaling(); + const glm::ivec2 res = global::windowDelegate.currentWindowResolution(); + const glm::vec2 dpiScaling = global::windowDelegate.dpiScaling(); const double dHeight = (_targetHeight - _currentHeight) * std::pow(0.98, 1.0 / (ConsoleOpenSpeed / dpiScaling.y * frametime)); @@ -705,9 +705,9 @@ void LuaConsole::render() { ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); } - const glm::vec2 dpiScaling = OsEng.windowWrapper().dpiScaling(); + const glm::vec2 dpiScaling = global::windowDelegate.dpiScaling(); const glm::ivec2 res = - glm::vec2(OsEng.windowWrapper().currentWindowResolution()) / dpiScaling; + glm::vec2(global::windowDelegate.currentWindowResolution()) / dpiScaling; // Render background @@ -888,10 +888,10 @@ void LuaConsole::render() { if (_remoteScripting) { const glm::vec4 Red(1, 0, 0, 1); - ParallelConnection::Status status = OsEng.parallelPeer().status(); + ParallelConnection::Status status = global::parallelPeer.status(); const int nClients = status != ParallelConnection::Status::Disconnected ? - OsEng.parallelPeer().nConnections() - 1 : + global::parallelPeer.nConnections() - 1 : 0; const std::string nClientsText = @@ -901,7 +901,7 @@ void LuaConsole::render() { const glm::vec2 loc = locationForRightJustifiedText(nClientsText); RenderFont(*_font, loc, nClientsText, Red); - } else if (OsEng.parallelPeer().isHost()) { + } else if (global::parallelPeer.isHost()) { const glm::vec4 LightBlue(0.4, 0.4, 1, 1); const std::string localExecutionText = "Local script execution"; diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 0f34eb873f..65790f4487 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -26,7 +26,9 @@ #include #include -#include +#include +#include +#include #include #include #include @@ -229,21 +231,9 @@ RenderEngine::RenderEngine() , _hdrExposure(HDRExposureInfo, 0.4f, 0.01f, 10.0f) , _hdrBackground(BackgroundExposureInfo, 2.8f, 0.01f, 10.0f) , _gamma(GammaInfo, 2.2f, 0.01f, 10.0f) - , _screenSpaceOwner({ "ScreenSpace" }) { _doPerformanceMeasurements.onChange([this](){ - if (_doPerformanceMeasurements) { - if (!_performanceManager) { - _performanceManager = std::make_shared( - OsEng.configuration().logging.directory, - OsEng.configuration().logging.performancePrefix - ); - } - } - else { - _performanceManager = nullptr; - } - + global::performanceManager.setEnabled(_doPerformanceMeasurements); }); addProperty(_doPerformanceMeasurements); @@ -317,30 +307,13 @@ void RenderEngine::setRendererFromString(const std::string& renderingMethod) { } void RenderEngine::initialize() { - std::string renderingMethod = OsEng.configuration().renderingMethod; - if (renderingMethod == "ABuffer") { - using Version = ghoul::systemcapabilities::Version; - - // The default rendering method has a requirement of OpenGL 4.3, so if we are - // below that, we will fall back to frame buffer operation - if (OpenGLCap.openGLVersion() < Version{ 4,3,0 }) { - LINFO("Falling back to framebuffer implementation due to OpenGL limitations"); - renderingMethod = "Framebuffer"; - } - } - // We have to perform these initializations here as the OsEng has not been initialized // in our constructor _disableSceneTranslationOnMaster = - OsEng.configuration().isSceneTranslationOnMasterDisabled; - _disableMasterRendering = OsEng.configuration().isRenderingOnMasterDisabled; + global::configuration.isSceneTranslationOnMasterDisabled; + _disableMasterRendering = global::configuration.isRenderingOnMasterDisabled; - _raycasterManager = std::make_unique(); - _deferredcasterManager = std::make_unique(); - _nAaSamples = OsEng.windowWrapper().currentNumberOfAaSamples(); - - LINFO(fmt::format("Setting renderer from string: {}", renderingMethod)); - setRendererFromString(renderingMethod); + _nAaSamples = global::windowDelegate.currentNumberOfAaSamples(); #ifdef GHOUL_USE_DEVIL ghoul::io::TextureReader::ref().addReader( @@ -369,53 +342,55 @@ void RenderEngine::initialize() { ghoul::io::TextureReader::ref().addReader( std::make_unique() ); - - MissionManager::initialize(); } void RenderEngine::initializeGL() { LTRACE("RenderEngine::initializeGL(begin)"); + + std::string renderingMethod = global::configuration.renderingMethod; + if (renderingMethod == "ABuffer") { + using Version = ghoul::systemcapabilities::Version; + + // The default rendering method has a requirement of OpenGL 4.3, so if we are + // below that, we will fall back to frame buffer operation + if (OpenGLCap.openGLVersion() < Version{ 4,3,0 }) { + LINFO("Falling back to framebuffer implementation due to OpenGL limitations"); + renderingMethod = "Framebuffer"; + } + } + + LINFO(fmt::format("Setting renderer from string: {}", renderingMethod)); + setRendererFromString(renderingMethod); + + + // TODO: Fix the power scaled coordinates in such a way that these // values can be set to more realistic values // set the close clip plane and the far clip plane to extreme values while in // development - OsEng.windowWrapper().setNearFarClippingPlane(0.001f, 1000.f); + global::windowDelegate.setNearFarClippingPlane(0.001f, 1000.f); constexpr const float FontSizeBig = 50.f; - _fontBig = OsEng.fontManager().font(KeyFontMono, FontSizeBig); + _fontBig = global::fontManager.font(KeyFontMono, FontSizeBig); constexpr const float FontSizeTime = 15.f; - _fontDate = OsEng.fontManager().font(KeyFontMono, FontSizeTime); + _fontDate = global::fontManager.font(KeyFontMono, FontSizeTime); constexpr const float FontSizeMono = 10.f; - _fontInfo = OsEng.fontManager().font(KeyFontMono, FontSizeMono); + _fontInfo = global::fontManager.font(KeyFontMono, FontSizeMono); constexpr const float FontSizeLight = 8.f; - _fontLog = OsEng.fontManager().font(KeyFontLight, FontSizeLight); + _fontLog = global::fontManager.font(KeyFontLight, FontSizeLight); LINFO("Initializing Log"); std::unique_ptr log = std::make_unique(ScreenLogTimeToLive); _log = log.get(); ghoul::logging::LogManager::ref().addLog(std::move(log)); - for (std::unique_ptr& ssr : _screenSpaceRenderables) { - ssr->initializeGL(); - } - LINFO("Finished initializing GL"); LTRACE("RenderEngine::initializeGL(end)"); } -void RenderEngine::deinitialize() { - for (std::unique_ptr& ssr : _screenSpaceRenderables) { - ssr->deinitialize(); - } - - MissionManager::deinitialize(); -} - void RenderEngine::deinitializeGL() { - for (std::unique_ptr& ssr : _screenSpaceRenderables) { - ssr->deinitializeGL(); - } + _renderer = nullptr; } void RenderEngine::updateScene() { @@ -425,14 +400,13 @@ void RenderEngine::updateScene() { _scene->updateInterpolations(); - const Time& currentTime = OsEng.timeManager().time(); - const Time& integrateFromTime = OsEng.timeManager().integrateFromTime(); + const Time& currentTime = global::timeManager.time(); + const Time& integrateFromTime = global::timeManager.integrateFromTime(); _scene->update({ { glm::dvec3(0.0), glm::dmat3(11.), 1.0 }, currentTime, - integrateFromTime, - _performanceManager != nullptr + integrateFromTime }); LTRACE("RenderEngine::updateSceneGraph(end)"); @@ -452,7 +426,7 @@ void RenderEngine::updateShaderPrograms() { } void RenderEngine::updateRenderer() { - const bool windowResized = OsEng.windowWrapper().windowHasResized(); + const bool windowResized = global::windowDelegate.windowHasResized(); if (windowResized) { _renderer->setResolution(renderingResolution()); @@ -466,28 +440,27 @@ void RenderEngine::updateRenderer() { } void RenderEngine::updateScreenSpaceRenderables() { - for (std::unique_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : global::screenSpaceRenderables) { ssr->update(); } } glm::ivec2 RenderEngine::renderingResolution() const { - if (OsEng.windowWrapper().isRegularRendering()) { - return OsEng.windowWrapper().currentWindowResolution(); + if (global::windowDelegate.isRegularRendering()) { + return global::windowDelegate.currentWindowResolution(); } else { - return OsEng.windowWrapper().currentDrawBufferResolution(); + return global::windowDelegate.currentDrawBufferResolution(); } } glm::ivec2 RenderEngine::fontResolution() const { - const std::string& value = OsEng.configuration().onScreenTextScaling; + const std::string& value = global::configuration.onScreenTextScaling; if (value == "framebuffer") { - return OsEng.windowWrapper().getCurrentViewportSize(); - //return OsEng.windowWrapper().currentWindowResolution(); + return global::windowDelegate.currentViewportSize(); } else { - return OsEng.windowWrapper().currentWindowSize(); + return global::windowDelegate.currentWindowSize(); } } @@ -523,7 +496,7 @@ void RenderEngine::updateFade() { ); } _currentFadeTime += static_cast( - OsEng.windowWrapper().averageDeltaTime() + global::windowDelegate.averageDeltaTime() ); } } @@ -533,9 +506,9 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat const glm::mat4& projectionMatrix) { LTRACE("RenderEngine::render(begin)"); - const WindowWrapper& wrapper = OsEng.windowWrapper(); + const WindowDelegate& delegate = global::windowDelegate; if (_camera) { - if (_disableSceneTranslationOnMaster && wrapper.isMaster()) { + if (_disableSceneTranslationOnMaster && delegate.isMaster()) { _camera->sgctInternal.setViewMatrix(viewMatrix); } else { @@ -545,13 +518,12 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat _camera->sgctInternal.setProjectionMatrix(projectionMatrix); } - const bool masterEnabled = wrapper.isMaster() ? !_disableMasterRendering : true; - if (masterEnabled && !wrapper.isGuiWindow() && _globalBlackOutFactor > 0.f) { + const bool masterEnabled = delegate.isMaster() ? !_disableMasterRendering : true; + if (masterEnabled && !delegate.isGuiWindow() && _globalBlackOutFactor > 0.f) { _renderer->render( _scene, _camera, - _globalBlackOutFactor, - _performanceManager != nullptr + _globalBlackOutFactor ); } @@ -566,7 +538,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat ++_frameNumber; - for (std::unique_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : global::screenSpaceRenderables) { if (ssr->isEnabled() && ssr->isReady()) { ssr->render(); } @@ -586,7 +558,7 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons local f = 'NavigationHandler.OrbitalNavigator.Friction.RotationalFriction'; openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( ToggleRotationFrictionScript, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -598,7 +570,7 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons local f = 'NavigationHandler.OrbitalNavigator.Friction.ZoomFriction'; openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( ToggleZoomFrictionScript, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -610,7 +582,7 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons local f = 'NavigationHandler.OrbitalNavigator.Friction.RollFriction'; openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( ToggleRollFrictionScript, scripting::ScriptEngine::RemoteScripting::Yes ); @@ -621,7 +593,7 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons } void RenderEngine::renderOverlays(const ShutdownInformation& shutdownInfo) { - const bool isMaster = OsEng.windowWrapper().isMaster(); + const bool isMaster = global::windowDelegate.isMaster(); if (isMaster || _showOverlayOnSlaves) { renderScreenLog(); renderVersionInformation(); @@ -689,40 +661,37 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) { void RenderEngine::renderDashboard() { std::unique_ptr perf; - if (_performanceManager) { + if (global::performanceManager.isEnabled()) { perf = std::make_unique( - "Main Dashboard::render", - OsEng.renderEngine().performanceManager() + "Main Dashboard::render" ); } glm::vec2 penPosition = glm::vec2( 10.f, - fontResolution().y - OsEng.console().currentHeight() + fontResolution().y - global::luaConsole.currentHeight() ); - OsEng.dashboard().render(penPosition); + global::dashboard.render(penPosition); } void RenderEngine::postDraw() { - const Time& currentTime = OsEng.timeManager().time(); - if (_shouldTakeScreenshot) { // We only create the directory here, as we don't want to spam the users // screenshot folder everytime we start OpenSpace even when we are not taking any // screenshots. So the first time we actually take one, we create the folder: - if (!FileSys.directoryExists(absPath("${THIS_SCREENSHOT_PATH}"))) { + if (!FileSys.directoryExists(absPath("${SCREENSHOTS}"))) { FileSys.createDirectory( - absPath("${THIS_SCREENSHOT_PATH}"), + absPath("${SCREENSHOTS}"), ghoul::filesystem::FileSystem::Recursive::Yes ); } - OsEng.windowWrapper().takeScreenshot(_applyWarping); + global::windowDelegate.takeScreenshot(_applyWarping); _shouldTakeScreenshot = false; } - if (_performanceManager) { - _performanceManager->storeScenePerformanceMeasurements( + if (global::performanceManager.isEnabled()) { + global::performanceManager.storeScenePerformanceMeasurements( scene()->allSceneGraphNodes() ); } @@ -732,14 +701,6 @@ Scene* RenderEngine::scene() { return _scene; } -RaycasterManager& RenderEngine::raycasterManager() { - return *_raycasterManager; -} - -DeferredcasterManager& RenderEngine::deferredcasterManager() { - return *_deferredcasterManager; -} - void RenderEngine::setScene(Scene* scene) { _scene = scene; } @@ -960,35 +921,27 @@ scripting::LuaLibrary RenderEngine::luaLibrary() { }; } -bool RenderEngine::doesPerformanceMeasurements() const { - return _performanceManager != nullptr; -} - -std::shared_ptr RenderEngine::performanceManager() { - return _performanceManager; -} - void RenderEngine::addScreenSpaceRenderable(std::unique_ptr s) { s->initialize(); s->initializeGL(); - _screenSpaceOwner.addPropertySubOwner(s.get()); + global::screenSpaceRootPropertyOwner.addPropertySubOwner(s.get()); - _screenSpaceRenderables.push_back(std::move(s)); + global::screenSpaceRenderables.push_back(std::move(s)); } void RenderEngine::removeScreenSpaceRenderable(ScreenSpaceRenderable* s) { const auto it = std::find_if( - _screenSpaceRenderables.begin(), - _screenSpaceRenderables.end(), + global::screenSpaceRenderables.begin(), + global::screenSpaceRenderables.end(), [s](const std::unique_ptr& r) { return r.get() == s; } ); - if (it != _screenSpaceRenderables.end()) { + if (it != global::screenSpaceRenderables.end()) { s->deinitialize(); - _screenSpaceOwner.removePropertySubOwner(s); + global::screenSpaceRootPropertyOwner.removePropertySubOwner(s); - _screenSpaceRenderables.erase(it); + global::screenSpaceRenderables.erase(it); } } @@ -1003,14 +956,14 @@ ScreenSpaceRenderable* RenderEngine::screenSpaceRenderable( const std::string& identifier) { const auto it = std::find_if( - _screenSpaceRenderables.begin(), - _screenSpaceRenderables.end(), + global::screenSpaceRenderables.begin(), + global::screenSpaceRenderables.end(), [&identifier](const std::unique_ptr& s) { return s->identifier() == identifier; } ); - if (it != _screenSpaceRenderables.end()) { + if (it != global::screenSpaceRenderables.end()) { return it->get(); } else { @@ -1019,10 +972,10 @@ ScreenSpaceRenderable* RenderEngine::screenSpaceRenderable( } std::vector RenderEngine::screenSpaceRenderables() const { - std::vector res(_screenSpaceRenderables.size()); + std::vector res(global::screenSpaceRenderables.size()); std::transform( - _screenSpaceRenderables.begin(), - _screenSpaceRenderables.end(), + global::screenSpaceRenderables.begin(), + global::screenSpaceRenderables.end(), res.begin(), [](const std::unique_ptr& p) { return p.get(); } ); @@ -1066,7 +1019,7 @@ void RenderEngine::renderCameraInformation() { constexpr const float YSeparation = 5.f; constexpr const float XSeparation = 5.f; - interaction::OrbitalNavigator nav = OsEng.navigationHandler().orbitalNavigator(); + interaction::OrbitalNavigator nav = global::navigationHandler.orbitalNavigator(); _cameraButtonLocations.rotation = { fontResolution().x - rotationBox.boundingBox.x - XSeparation, @@ -1257,8 +1210,4 @@ void RenderEngine::renderScreenLog() { } } -properties::PropertyOwner& RenderEngine::screenSpaceOwner() { - return _screenSpaceOwner; -} - } // namespace openspace diff --git a/src/rendering/renderengine_lua.inl b/src/rendering/renderengine_lua.inl index 97ad393cdb..63af288d65 100644 --- a/src/rendering/renderengine_lua.inl +++ b/src/rendering/renderengine_lua.inl @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include + namespace openspace::luascriptfunctions { /** @@ -42,7 +44,7 @@ int setRenderer(lua_State* L) { 1, ghoul::lua::PopValue::Yes ); - OsEng.renderEngine().setRendererFromString(renderer); + global::renderEngine.setRendererFromString(renderer); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -59,9 +61,9 @@ int toggleFade(lua_State* L) { const float t = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); constexpr const float fadedIn = 1.f; - const int direction = OsEng.renderEngine().globalBlackOutFactor() == fadedIn ? -1 : 1; + const int direction = global::renderEngine.globalBlackOutFactor() == fadedIn ? -1 : 1; - OsEng.renderEngine().startFading(direction, static_cast(t)); + global::renderEngine.startFading(direction, static_cast(t)); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -77,7 +79,7 @@ int fadeIn(lua_State* L) { const float t = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); - OsEng.renderEngine().startFading(1, t); + global::renderEngine.startFading(1, t); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -92,7 +94,7 @@ int fadeOut(lua_State* L) { float t = ghoul::lua::value(L, 1, ghoul::lua::PopValue::Yes); - OsEng.renderEngine().startFading(-1, t); + global::renderEngine.startFading(-1, t); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -117,7 +119,7 @@ int addScreenSpaceRenderable(lua_State* L) { std::unique_ptr s = ScreenSpaceRenderable::createFromDictionary(d); - OsEng.renderEngine().addScreenSpaceRenderable(std::move(s)); + global::renderEngine.addScreenSpaceRenderable(std::move(s)); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -131,7 +133,7 @@ int removeScreenSpaceRenderable(lua_State* L) { 1, ghoul::lua::PopValue::Yes ); - OsEng.renderEngine().removeScreenSpaceRenderable(name); + global::renderEngine.removeScreenSpaceRenderable(name); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index 60f079132b..05715fa5ab 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -26,8 +26,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -338,7 +338,7 @@ ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary _delete.onChange([this](){ std::string script = "openspace.removeScreenSpaceRenderable('" + identifier() + "');"; - OsEng.scriptEngine().queueScript( + global::scriptEngine.queueScript( script, scripting::ScriptEngine::RemoteScripting::No ); @@ -353,7 +353,7 @@ bool ScreenSpaceRenderable::initialize() { } bool ScreenSpaceRenderable::initializeGL() { - _originalViewportSize = OsEng.windowWrapper().currentWindowResolution(); + _originalViewportSize = global::windowDelegate.currentWindowResolution(); createPlane(); createShaders(); @@ -372,9 +372,8 @@ bool ScreenSpaceRenderable::deinitializeGL() { glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; - RenderEngine& renderEngine = OsEng.renderEngine(); if (_shader) { - renderEngine.removeRenderProgram(_shader.get()); + global::renderEngine.removeRenderProgram(_shader.get()); _shader = nullptr; } @@ -459,7 +458,7 @@ void ScreenSpaceRenderable::useEuclideanCoordinates(bool b) { void ScreenSpaceRenderable::createShaders() { ghoul::Dictionary dict = ghoul::Dictionary(); - auto res = OsEng.windowWrapper().currentWindowResolution(); + auto res = global::windowDelegate.currentWindowResolution(); ghoul::Dictionary rendererData = { { "fragmentRendererPath", "${SHADERS}/framebuffer/renderframebuffer.frag" }, { "windowWidth" , res.x }, @@ -479,7 +478,7 @@ void ScreenSpaceRenderable::createShaders() { } glm::mat4 ScreenSpaceRenderable::scaleMatrix() { - glm::vec2 resolution = OsEng.windowWrapper().currentWindowResolution(); + glm::vec2 resolution = global::windowDelegate.currentWindowResolution(); //to scale the plane float textureRatio = @@ -499,7 +498,7 @@ glm::mat4 ScreenSpaceRenderable::scaleMatrix() { glm::mat4 ScreenSpaceRenderable::rotationMatrix() { // Get the scene transform - glm::mat4 rotation = glm::inverse(OsEng.windowWrapper().modelMatrix()); + glm::mat4 rotation = glm::inverse(global::windowDelegate.modelMatrix()); if (!_useEuclideanCoordinates) { glm::vec2 position = _sphericalPosition.value(); @@ -539,7 +538,7 @@ void ScreenSpaceRenderable::draw(glm::mat4 modelTransform) { _shader->setUniform( _uniformCache.viewProj, - OsEng.renderEngine().scene()->camera()->viewProjectionMatrix() + global::renderEngine.scene()->camera()->viewProjectionMatrix() ); ghoul::opengl::TextureUnit unit; diff --git a/src/scene/assetmanager_lua.inl b/src/scene/assetmanager_lua.inl index 25f0ef35b9..4397d560b5 100644 --- a/src/scene/assetmanager_lua.inl +++ b/src/scene/assetmanager_lua.inl @@ -24,6 +24,7 @@ #include #include +#include namespace openspace::luascriptfunctions::asset { @@ -39,13 +40,13 @@ int add(lua_State* state) { ghoul::lua::PopValue::Yes ); - if (OsEng.renderEngine().scene()) { + if (global::renderEngine.scene()) { assetManager->add(assetName); } else { // The scene might not exist yet if OpenSpace was started without specifying an // initial asset - OsEng.scheduleLoadSingleAsset(assetName); + global::openSpaceEngine.scheduleLoadSingleAsset(assetName); } diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index 15a74e52d2..b02c372536 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index d9f723c4a3..5d9fe4f176 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -23,6 +23,8 @@ ****************************************************************************************/ #include +#include +#include #include #include #include @@ -107,12 +109,12 @@ void applyRegularExpression(lua_State* L, const std::string& regex, foundMatching = true; if (interpolationDuration == 0.0) { - OsEng.renderEngine().scene()->removePropertyInterpolation(prop); + global::renderEngine.scene()->removePropertyInterpolation(prop); prop->setLuaValue(L); } else { prop->setLuaInterpolationTarget(L); - OsEng.renderEngine().scene()->addPropertyInterpolation( + global::renderEngine.scene()->addPropertyInterpolation( prop, static_cast(interpolationDuration), easingFunction @@ -184,12 +186,12 @@ int setPropertyCall_single(properties::Property& prop, const std::string& uri, } else { if (duration == 0.0) { - OsEng.renderEngine().scene()->removePropertyInterpolation(&prop); + global::renderEngine.scene()->removePropertyInterpolation(&prop); prop.setLuaValue(L); } else { prop.setLuaInterpolationTarget(L); - OsEng.renderEngine().scene()->addPropertyInterpolation( + global::renderEngine.scene()->addPropertyInterpolation( &prop, static_cast(duration), eastingFunction @@ -409,7 +411,7 @@ int loadScene(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::loadScene"); const std::string& sceneFile = ghoul::lua::value(L, 1); - OsEng.scheduleLoadSingleAsset(sceneFile); + global::openSpaceEngine.scheduleLoadSingleAsset(sceneFile); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -428,13 +430,13 @@ int addSceneGraphNode(lua_State* L) { } try { - SceneGraphNode* node = OsEng.renderEngine().scene()->loadNode(d); + SceneGraphNode* node = global::renderEngine.scene()->loadNode(d); if (!node) { LERRORC("Scene", "Could not load scene graph node"); return ghoul::lua::luaError(L, "Error loading scene graph node"); } - OsEng.renderEngine().scene()->initializeNode(node); + global::renderEngine.scene()->initializeNode(node); } catch (const documentation::SpecificationError& e) { return ghoul::lua::luaError( @@ -462,7 +464,7 @@ int removeSceneGraphNode(lua_State* L) { 1, ghoul::lua::PopValue::Yes ); - SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(nodeName); + SceneGraphNode* node = global::renderEngine.scene()->sceneGraphNode(nodeName); if (!node) { LERRORC( "removeSceneGraphNode", @@ -512,7 +514,7 @@ int hasSceneGraphNode(lua_State* L) { 1, ghoul::lua::PopValue::Yes ); - SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(nodeName); + SceneGraphNode* node = global::renderEngine.scene()->sceneGraphNode(nodeName); ghoul::lua::push(L, node != nullptr); diff --git a/src/scene/sceneinitializer.cpp b/src/scene/sceneinitializer.cpp index f9aef56002..9a220bf2c4 100644 --- a/src/scene/sceneinitializer.cpp +++ b/src/scene/sceneinitializer.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -51,7 +52,7 @@ MultiThreadedSceneInitializer::MultiThreadedSceneInitializer(unsigned int nThrea void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) { auto initFunction = [this, node]() { - LoadingScreen& loadingScreen = OsEng.loadingScreen(); + LoadingScreen& loadingScreen = global::openSpaceEngine.loadingScreen(); LoadingScreen::ProgressInfo progressInfo; progressInfo.progress = 1.f; @@ -77,7 +78,8 @@ void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) { LoadingScreen::ProgressInfo progressInfo; progressInfo.progress = 0.f; - LoadingScreen& loadingScreen = OsEng.loadingScreen(); + + LoadingScreen& loadingScreen = global::openSpaceEngine.loadingScreen(); loadingScreen.setItemNumber(loadingScreen.itemNumber() + 1); loadingScreen.updateItem( node->identifier(), diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index 4aa1455f5d..39a206687e 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -582,8 +582,8 @@ bool ScriptEngine::writeLog(const std::string& script) { // Check that logging is enabled and initialize if necessary if (!_logFileExists) { // If a ScriptLogFile was specified, generate it now - if (!OsEng.configuration().scriptLog.empty()) { - _logFilename = absPath(OsEng.configuration().scriptLog); + if (!global::configuration.scriptLog.empty()) { + _logFilename = absPath(global::configuration.scriptLog); _logFileExists = true; LDEBUG(fmt::format( @@ -633,8 +633,8 @@ void ScriptEngine::preSync(bool isMaster) { _receivedScripts.push_back(_currentSyncedScript); _queuedScripts.pop_back(); - if (OsEng.parallelPeer().isHost() && remoteScripting) { - OsEng.parallelPeer().sendScript(_currentSyncedScript); + if (global::parallelPeer.isHost() && remoteScripting) { + global::parallelPeer.sendScript(_currentSyncedScript); } } _mutex.unlock(); diff --git a/src/scripting/scriptscheduler.cpp b/src/scripting/scriptscheduler.cpp index 0f8bc1b586..f398c0f593 100644 --- a/src/scripting/scriptscheduler.cpp +++ b/src/scripting/scriptscheduler.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include #include diff --git a/src/scripting/scriptscheduler_lua.inl b/src/scripting/scriptscheduler_lua.inl index 42c74ad719..14afad852e 100644 --- a/src/scripting/scriptscheduler_lua.inl +++ b/src/scripting/scriptscheduler_lua.inl @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include + namespace openspace::luascriptfunctions { int loadFile(lua_State* L) { @@ -36,7 +38,7 @@ int loadFile(lua_State* L) { return ghoul::lua::luaError(L, "filepath string is empty"); } - OsEng.scriptScheduler().loadScripts( + global::scriptScheduler.loadScripts( ghoul::lua::loadDictionaryFromFile(missionFileName, L) ); @@ -55,7 +57,7 @@ int loadScheduledScript(lua_State* L) { std::string forwardScript = ghoul::lua::value(L, 2); if (nArguments == 2) { - OsEng.scriptScheduler().loadScripts({ + global::scriptScheduler.loadScripts({ { "1", ghoul::Dictionary { @@ -67,7 +69,7 @@ int loadScheduledScript(lua_State* L) { } else if (nArguments == 3) { std::string backwardScript = ghoul::lua::value(L, 3); - OsEng.scriptScheduler().loadScripts({ + global::scriptScheduler.loadScripts({ { "1", ghoul::Dictionary { @@ -82,7 +84,7 @@ int loadScheduledScript(lua_State* L) { std::string backwardScript = ghoul::lua::value(L, 3); std::string universalScript = ghoul::lua::value(L, 4); - OsEng.scriptScheduler().loadScripts({ + global::scriptScheduler.loadScripts({ { "1", ghoul::Dictionary { @@ -104,7 +106,7 @@ int loadScheduledScript(lua_State* L) { int clear(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::clear"); - OsEng.scriptScheduler().clearSchedule(); + global::scriptScheduler.clearSchedule(); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; diff --git a/src/util/time.cpp b/src/util/time.cpp index 9a28faae64..b5303f80fa 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include diff --git a/src/util/time_lua.inl b/src/util/time_lua.inl index 2da3e33bf6..4ddfff668d 100644 --- a/src/util/time_lua.inl +++ b/src/util/time_lua.inl @@ -22,8 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - - +#include #include #include #include @@ -56,7 +55,7 @@ int time_setDeltaTime(lua_State* L) { return luaL_error(L, "bad argument #%d (%s)", 2, msg); } const double newDeltaTime = lua_tonumber(L, 1); - OsEng.timeManager().setDeltaTime(newDeltaTime); + global::timeManager.setDeltaTime(newDeltaTime); } else { lua_settop(L, 0); const char* msg = lua_pushfstring(L, @@ -106,7 +105,7 @@ int time_interpolateDeltaTime(lua_State* L) { const double interpolationDuration = lua_tonumber(L, 2); const double newDeltaTime = lua_tonumber(L, 1); - OsEng.timeManager().interpolateDeltaTime(newDeltaTime, interpolationDuration); + global::timeManager.interpolateDeltaTime(newDeltaTime, interpolationDuration); } else if (nArguments == 1) { const bool isNumber = (lua_isnumber(L, 1) != 0); @@ -121,8 +120,10 @@ int time_interpolateDeltaTime(lua_State* L) { return luaL_error(L, "bad argument #%d (%s)", 2, msg); } const double newDeltaTime = lua_tonumber(L, 1); - OsEng.timeManager().interpolateDeltaTime(newDeltaTime, - OsEng.timeManager().defaultDeltaTimeInterpolationDuration()); + global::timeManager.interpolateDeltaTime( + newDeltaTime, + global::timeManager.defaultDeltaTimeInterpolationDuration() + ); } else { lua_settop(L, 0); @@ -143,7 +144,7 @@ int time_interpolateDeltaTime(lua_State* L) { * Returns the delta time by calling the Time::deltaTime method */ int time_deltaTime(lua_State* L) { - lua_pushnumber(L, OsEng.timeManager().deltaTime()); + lua_pushnumber(L, global::timeManager.deltaTime()); ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); return 1; } @@ -157,7 +158,7 @@ int time_togglePause(lua_State* L) { const int nArguments = lua_gettop(L); if (nArguments == 0) { - OsEng.timeManager().setPause(!OsEng.timeManager().isPaused()); + global::timeManager.setPause(!global::timeManager.isPaused()); } else { lua_settop(L, 0); return luaL_error( @@ -197,17 +198,17 @@ int time_interpolateTogglePause(lua_State* L) { const double interpolationDuration = lua_tonumber(L, 1); - OsEng.timeManager().interpolatePause( - !OsEng.timeManager().isPaused(), + global::timeManager.interpolatePause( + !global::timeManager.isPaused(), interpolationDuration ); } else if (nArguments == 0) { - const bool pause = !OsEng.timeManager().isPaused(); - OsEng.timeManager().interpolatePause(pause, + const bool pause = !global::timeManager.isPaused(); + global::timeManager.interpolatePause(pause, pause ? - OsEng.timeManager().defaultPauseInterpolationDuration() : - OsEng.timeManager().defaultUnpauseInterpolationDuration() + global::timeManager.defaultPauseInterpolationDuration() : + global::timeManager.defaultUnpauseInterpolationDuration() ); } else { lua_settop(L, 0); @@ -234,7 +235,7 @@ int time_setPause(lua_State* L) { if (nArguments == 1) { const bool pause = lua_toboolean(L, 1) == 1; - OsEng.timeManager().setPause(pause); + global::timeManager.setPause(pause); } else { lua_settop(L, 0); return luaL_error( @@ -274,14 +275,14 @@ int time_interpolatePause(lua_State* L) { } const double interpolationDuration = lua_tonumber(L, 2); const bool pause = lua_toboolean(L, 1) == 1; - OsEng.timeManager().interpolatePause(pause, interpolationDuration); + global::timeManager.interpolatePause(pause, interpolationDuration); } else if (nArguments == 1) { const bool pause = lua_toboolean(L, 1) == 1; - OsEng.timeManager().interpolatePause(pause, + global::timeManager.interpolatePause(pause, pause ? - OsEng.timeManager().defaultPauseInterpolationDuration() : - OsEng.timeManager().defaultUnpauseInterpolationDuration() + global::timeManager.defaultPauseInterpolationDuration() : + global::timeManager.defaultUnpauseInterpolationDuration() ); } else { lua_settop(L, 0); @@ -332,12 +333,12 @@ int time_setTime(lua_State* L) { if (nArguments == 1) { if (isNumber) { double value = lua_tonumber(L, 1); - OsEng.timeManager().setTimeNextFrame(value); + global::timeManager.setTimeNextFrame(value); return 0; } if (isString) { const char* time = lua_tostring(L, 1); - OsEng.timeManager().setTimeNextFrame(Time::convertTime(time)); + global::timeManager.setTimeNextFrame(Time::convertTime(time)); return 0; } ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); @@ -384,17 +385,17 @@ int time_interpolateTime(lua_State* L) { if (lua_gettop(L) == 1) { if (isNumber) { double value = lua_tonumber(L, 1); - OsEng.timeManager().interpolateTime( + global::timeManager.interpolateTime( value, - OsEng.timeManager().defaultTimeInterpolationDuration() + global::timeManager.defaultTimeInterpolationDuration() ); return 0; } if (isString) { const char* time = lua_tostring(L, 1); - OsEng.timeManager().interpolateTime( + global::timeManager.interpolateTime( Time::convertTime(time), - OsEng.timeManager().defaultTimeInterpolationDuration() + global::timeManager.defaultTimeInterpolationDuration() ); return 0; } @@ -420,10 +421,10 @@ int time_interpolateTime(lua_State* L) { const double duration = lua_tonumber(L, 2); if (duration > 0) { - OsEng.timeManager().interpolateTime(targetTime, duration); + global::timeManager.interpolateTime(targetTime, duration); } else { - OsEng.timeManager().setTimeNextFrame(targetTime); + global::timeManager.setTimeNextFrame(targetTime); } } return 0; @@ -436,7 +437,7 @@ int time_interpolateTime(lua_State* L) { * It is returned by calling the Time::currentTime method. */ int time_currentTime(lua_State* L) { - lua_pushnumber(L, OsEng.timeManager().time().j2000Seconds()); + lua_pushnumber(L, global::timeManager.time().j2000Seconds()); ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); return 1; } @@ -448,7 +449,7 @@ int time_currentTime(lua_State* L) { * timezone by calling the Time::UTC method */ int time_currentTimeUTC(lua_State* L) { - lua_pushstring(L, OsEng.timeManager().time().UTC().c_str()); + lua_pushstring(L, global::timeManager.time().UTC().c_str()); ghoul_assert(lua_gettop(L) == 1, "Incorrect number of items left on stack"); return 1; } diff --git a/src/util/timemanager.cpp b/src/util/timemanager.cpp index d96bfe216e..bbd4d6b7f5 100644 --- a/src/util/timemanager.cpp +++ b/src/util/timemanager.cpp @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include #include #include @@ -107,8 +107,8 @@ TimeManager::TimeManager() void TimeManager::interpolateTime(double targetTime, double durationSeconds) { ghoul_precondition(durationSeconds > 0.f, "durationSeconds must be positive"); - const double now = OsEng.windowWrapper().applicationTime(); - const bool pause = OsEng.timeManager().isPaused(); + const double now = global::windowDelegate.applicationTime(); + const bool pause = isPaused(); const TimeKeyframeData current = { time(), deltaTime(), false, false }; const TimeKeyframeData next = { targetTime, targetDeltaTime(), pause, false }; @@ -221,7 +221,7 @@ void TimeManager::progressTime(double dt) { return; } - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); const std::deque>& keyframes = _timeline.keyframes(); auto firstFutureKeyframe = std::lower_bound( @@ -511,7 +511,7 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation return; } - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); Time newTime = time().j2000Seconds() + (_deltaTime + newDeltaTime) * 0.5 * interpolationDuration; @@ -534,7 +534,7 @@ void TimeManager::interpolatePause(bool pause, double interpolationDuration) { return; } - const double now = OsEng.windowWrapper().applicationTime(); + const double now = global::windowDelegate.applicationTime(); double targetDelta = pause ? 0.0 : _targetDeltaTime; Time newTime = time().j2000Seconds() + (_deltaTime + targetDelta) * 0.5 * interpolationDuration; diff --git a/tests/main.cpp b/tests/main.cpp index c3104da314..1e1ac69a52 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -49,17 +49,16 @@ #define GHL_THROW_ON_ASSERT #endif // GHL_THROW_ON_ASSERTGHL_THROW_ON_ASSERT +#include #include -#include +#include #include #include #include -//#include -//#include -//#include #include #include #include +#include #include #include @@ -95,7 +94,6 @@ -using namespace ghoul::cmdparser; using namespace ghoul::filesystem; using namespace ghoul::logging; @@ -112,22 +110,16 @@ int main(int argc, char** argv) { // Workaround for Visual Studio Google Test Adapter: // Do not try to initialize osengine if gtest is just listing tests - bool skipOsEng = false; std::vector gtestArgs(argv, argv + argc); if (std::find(gtestArgs.begin(), gtestArgs.end(), "--gtest_list_tests") != gtestArgs.end()) { - skipOsEng = true; - } + using namespace openspace; + ghoul::initialize(); - if (!skipOsEng) { - openspace::OpenSpaceEngine::create( - argc, - argv, - std::make_unique(), - args, - close, - consoleLog - ); - FileSys.registerPathToken("${TESTDIR}" , "${BASE}/tests"); + std::string configFile = configuration::findConfiguration(); + global::configuration = configuration::loadConfigurationFromFile(configFile); + global::openSpaceEngine.initialize(); + + FileSys.registerPathToken("${TESTDIR}", "${BASE}/tests"); // All of the relevant tests initialize the SpiceManager openspace::SpiceManager::deinitialize(); diff --git a/tests/test_assetloader.inl b/tests/test_assetloader.inl index 0e63ef3d91..6daa6ff887 100644 --- a/tests/test_assetloader.inl +++ b/tests/test_assetloader.inl @@ -44,8 +44,9 @@ #include #include -#include -#include +#include +//#include +#include class AssetLoaderTest; @@ -68,8 +69,8 @@ protected: _scene = std::make_unique( std::make_unique() ); - ghoul::lua::LuaState* state = OsEng.scriptEngine().luaState(); - OsEng.scriptEngine().initialize(); + ghoul::lua::LuaState* state = openspace::global::scriptEngine.luaState(); + openspace::global::scriptEngine.initialize(); _syncWatcher = std::make_unique(); _assetLoader = std::make_unique( *state, @@ -84,7 +85,7 @@ protected: } virtual void TearDown() { - OsEng.scriptEngine().deinitialize(); + openspace::global::scriptEngine.deinitialize(); } std::unique_ptr _scene;