From 99b26040c23474b8faa6f7c22e95866d6e9c173a Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 11 Jan 2018 09:44:46 +0100 Subject: [PATCH 01/79] Update sgct --- ext/sgct | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/sgct b/ext/sgct index 7f56f724c1..0a72a676bd 160000 --- a/ext/sgct +++ b/ext/sgct @@ -1 +1 @@ -Subproject commit 7f56f724c1103effcec217dd66513c42eb1545e1 +Subproject commit 0a72a676bdf5e73c86d11abb3e0dc4846ea65cc1 From 521cb0f5ae32de9183c3565efcada1531da7e341 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 11 Jan 2018 14:40:16 +0100 Subject: [PATCH 02/79] Use framebuffer size to determine gui size --- modules/imgui/imguimodule.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index 2bebd14f48..9cefc7e437 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -169,8 +169,10 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { WindowWrapper& wrapper = OsEng.windowWrapper(); 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(); - glm::ivec2 windowSize = wrapper.currentWindowSize(); uint32_t mouseButtons = wrapper.mouseButtons(2); double dt = std::max(wrapper.averageDeltaTime(), 0.0); @@ -183,7 +185,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { gui.startFrame( static_cast(dt), glm::vec2(windowSize), - wrapper.dpiScaling(), + resolution / windowSize, mousePosition, mouseButtons ); From 499879c84e1a593c2c8ac6650d14692ebc65eb02 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 14 Feb 2018 15:05:52 +0100 Subject: [PATCH 03/79] Start to implement stereo support with adaptive stereoscopic depth --- .../openspace/interaction/orbitalnavigator.h | 12 ++ .../openspace/rendering/framebufferrenderer.h | 2 + include/openspace/util/camera.h | 9 +- .../rendering/atmospheredeferredcaster.cpp | 4 +- modules/base/rendering/renderablemodel.cpp | 2 +- .../globebrowsing/rendering/chunkrenderer.cpp | 4 +- .../rendering/renderableplanetprojection.cpp | 2 +- src/engine/wrapper/sgctwindowwrapper.cpp | 2 +- src/interaction/orbitalnavigator.cpp | 62 +++++++++++ src/rendering/framebufferrenderer.cpp | 104 +++++++++--------- src/rendering/renderable.cpp | 2 +- src/util/camera.cpp | 26 +++-- 12 files changed, 160 insertions(+), 71 deletions(-) diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index 38c569b34b..47f0614412 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -84,6 +84,10 @@ private: properties::FloatProperty _minimumAllowedDistance; properties::FloatProperty _sensitivity; + properties::BoolProperty _useAdaptiveStereoscopicDepth; + properties::FloatProperty _stereoscopicDepthOfFocusSurface; + properties::FloatProperty _staticViewScaleExponent; + MouseStates _mouseStates; SceneGraphNode* _focusNode = nullptr; @@ -193,6 +197,14 @@ private: const glm::dvec3& cameraPosition, const SurfacePositionHandle& positionHandle); + /** + * Get the vector from the camera to the surface of the focus object in world space. + */ + glm::dvec3 cameraToSurfaceVector( + const glm::dvec3& cameraPos, + const glm::dvec3& centerPos, + const SurfacePositionHandle& posHandle); + /** * Calculates a SurfacePositionHandle given a camera position in world space. */ diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 6f61cd2238..f8f43ae9e2 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -82,6 +82,8 @@ public: void update() override; void render(float blackoutFactor, bool doPerformanceMeasurements) override; + void performRaycasterTasks(const std::vector& tasks); + void performDeferredTasks(const std::vector& tasks); /** * Update render data diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index 71dd85a0bc..70e7ea88f8 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -91,7 +91,7 @@ public: void setPositionVec3(Vec3 pos); void setFocusPositionVec3(Vec3 pos); void setRotation(Quat rotation); - void setScaling(glm::vec2 scaling); + void setScaling(float scaling); void setMaxFov(float fov); void setParent(SceneGraphNode* parent); @@ -106,12 +106,13 @@ public: const Vec3& viewDirectionWorldSpace() const; const Vec3& lookUpVectorCameraSpace() const; const Vec3& lookUpVectorWorldSpace() const; - const glm::vec2& scaling() const; const Mat4& viewRotationMatrix() const; + const Mat4& viewScaleMatrix() const; const Quat& rotationQuaternion() const; float maxFov() const; float sinMaxFov() const; SceneGraphNode* parent() const; + float scaling() const; // @TODO this should simply be called viewMatrix! // Or it needs to be changed so that it actually is combined. Right now it is @@ -186,10 +187,9 @@ private: SyncData _position; SyncData _rotation; - SyncData _scaling; + SyncData _scaling; SceneGraphNode* _parent; - // _focusPosition to be removed Vec3 _focusPosition; float _maxFov; @@ -198,6 +198,7 @@ private: mutable Cached _cachedViewDirection; mutable Cached _cachedLookupVector; mutable Cached _cachedViewRotationMatrix; + mutable Cached _cachedViewScaleMatrix; mutable Cached _cachedCombinedViewMatrix; mutable Cached _cachedSinMaxFov; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index c2842a3a33..52a7594e9c 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -248,9 +248,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("dModelTransformMatrix", _modelTransform); // The following scale comes from PSC transformations. - float fScaleFactor = renderData.camera.scaling().x * - pow(10.0, renderData.camera.scaling().y); - glm::dmat4 dfScaleCamTransf = glm::scale(glm::dvec3(fScaleFactor)); + glm::dmat4 dfScaleCamTransf = glm::scale(glm::dvec3(1.0)); program.setUniform( "dInverseScaleTransformMatrix", glm::inverse(dfScaleCamTransf) diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index 9f94d6a74f..6ddf023ca9 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -208,7 +208,7 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { glm::vec3 directionToSun = glm::normalize(_sunPos - data.modelTransform.translation); glm::vec3 directionToSunViewSpace = - glm::mat3(data.camera.combinedViewMatrix()) * directionToSun; + glm::normalize(glm::mat3(data.camera.combinedViewMatrix()) * directionToSun); _programObject->setUniform( _uniformCache.directionToSunViewSpace, diff --git a/modules/globebrowsing/rendering/chunkrenderer.cpp b/modules/globebrowsing/rendering/chunkrenderer.cpp index 20c0e3d376..e3b370fc3d 100644 --- a/modules/globebrowsing/rendering/chunkrenderer.cpp +++ b/modules/globebrowsing/rendering/chunkrenderer.cpp @@ -263,7 +263,7 @@ void ChunkRenderer::setCommonUniforms(ghoul::opengl::ProgramObject& programObjec glm::vec3 directionToSunCameraSpace = glm::vec3(viewTransform * glm::dvec4(directionToSunWorldSpace, 0)); programObject.setUniform( - "lightDirectionCameraSpace", -directionToSunCameraSpace); + "lightDirectionCameraSpace", -glm::normalize(directionToSunCameraSpace)); } if (chunk.owner().generalProperties().performShading) { @@ -469,7 +469,7 @@ void ChunkRenderer::renderChunkLocally(const Chunk& chunk, const RenderData& dat if (_layerManager->layerGroup(layergroupid::HeightLayers).activeLayers().size() > 0) { // Apply an extra scaling to the height if the object is scaled programObject->setUniform( - "heightScale", static_cast(data.modelTransform.scale)); + "heightScale", static_cast(data.modelTransform.scale * data.camera.scaling())); } setCommonUniforms(*programObject, chunk, data); diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index 3430224be6..715c87c709 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -537,7 +537,7 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _projectionComponent.generateMipMap(); } - _camScaling = data.camera.scaling(); + _camScaling = glm::vec2(1, 0); // Unit scaling _up = data.camera.lookUpVectorCameraSpace(); if (_capture && _projectionComponent.doesPerformProjection()) { diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index fef3b7b9ff..d9f2801978 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -51,7 +51,7 @@ namespace { namespace openspace { SGCTWindowWrapper::SGCTWindowWrapper() - : _eyeSeparation(EyeSeparationInfo, 0.f, 0.f, 10.f) + : _eyeSeparation(EyeSeparationInfo, 0.f, 0.f, 0.2f) , _showStatsGraph(ShowStatsGraphInfo, false) { _showStatsGraph.onChange([this](){ diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index 06ed097435..b5fbecd444 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -84,6 +84,33 @@ namespace { "Minimum allowed distance", "" // @TODO Missing documentation }; + + static const openspace::properties::Property::PropertyInfo + UseAdaptiveStereoscopicDepthInfo = { + "UseAdaptiveStereoscopicDepth", + "Adaptive Steroscopic Depth", + "Dynamically adjust the view scaling based on the distance to the surface of " + "the focus node. If enabled, view scale will be set to " + "StereoscopicDepthOfFocusSurface / distance. " + "If disabled, view scale will be set to 10^StaticViewScaleExponent." + }; + + static const openspace::properties::Property::PropertyInfo + StaticViewScaleExponentInfo = { + "StaticViewScaleExponent", + "Static View Scale Exponent", + "Statically scale the world by 10^StaticViewScaleExponent. " + "Only used if UseAdaptiveStereoscopicDepthInfo is set to false." + }; + + static const openspace::properties::Property::PropertyInfo + StereoscopicDepthOfFocusSurfaceInfo = { + "StereoscopicDepthOfFocusSurface", + "Stereoscopic depth of the surface in focus", + "Set the stereoscopically perceived distance (in meters) to the surface of " + "the focus node. " + "Only used if UseAdaptiveStereoscopicDepthInfo is set to true." + }; } // namespace namespace openspace::interaction { @@ -107,6 +134,9 @@ OrbitalNavigator::OrbitalNavigator() , _minimumAllowedDistance(MinimumDistanceInfo, 10.0f, 0.0f, 10000.f) , _sensitivity(SensitivityInfo, 20.0f, 1.0f, 50.f) , _mouseStates(_sensitivity * pow(10.0, -4), 1 / (_friction.friction + 0.0000001)) + , _useAdaptiveStereoscopicDepth(UseAdaptiveStereoscopicDepthInfo, true) + , _staticViewScaleExponent(StaticViewScaleExponentInfo, 0.f, -30, 10) + , _stereoscopicDepthOfFocusSurface(StereoscopicDepthOfFocusSurfaceInfo, 8, 0.25, 100) { auto smoothStep = [](double t) { @@ -158,6 +188,10 @@ OrbitalNavigator::OrbitalNavigator() addProperty(_followFocusNodeRotationDistance); addProperty(_minimumAllowedDistance); addProperty(_sensitivity); + + addProperty(_useAdaptiveStereoscopicDepth); + addProperty(_staticViewScaleExponent); + addProperty(_stereoscopicDepthOfFocusSurface); } OrbitalNavigator::~OrbitalNavigator() {} @@ -263,9 +297,37 @@ void OrbitalNavigator::updateCameraStateFromMouseStates(Camera& camera, double d // Update the camera state camera.setPositionVec3(camPos); camera.setRotation(camRot.globalRotation * camRot.localRotation); + + if (_useAdaptiveStereoscopicDepth) { + glm::vec3 surfaceToCamera = static_cast( + cameraToSurfaceVector(camPos, centerPos, posHandle) + ); + camera.setScaling( + _stereoscopicDepthOfFocusSurface / glm::length(surfaceToCamera) + ); + } else { + camera.setScaling(glm::pow(10.f, _staticViewScaleExponent)); + } } } +glm::dvec3 OrbitalNavigator::cameraToSurfaceVector( + const glm::dvec3& camPos, + const glm::dvec3& centerPos, + const SurfacePositionHandle& posHandle) +{ + glm::dmat4 modelTransform = _focusNode->modelTransform(); + glm::dvec3 posDiff = camPos - centerPos; + glm::dvec3 centerToActualSurfaceModelSpace = + posHandle.centerToReferenceSurface + + posHandle.referenceSurfaceOutDirection * posHandle.heightToSurface; + + glm::dvec3 centerToActualSurface = + glm::dmat3(modelTransform) * centerToActualSurfaceModelSpace; + + return centerToActualSurface - posDiff; +} + void OrbitalNavigator::setFocusNode(SceneGraphNode* focusNode) { _focusNode = focusNode; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 7b304eaabc..87ff1be165 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -925,19 +925,13 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure return; } - glEnable(GL_DEPTH_TEST); - - - Time time = OsEng.timeManager().time(); - - RenderData data = { *_camera, psc(), time, doPerformanceMeasurements, 0, {} }; - RendererTasks tasks; - // Capture standard fbo GLint defaultFbo; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFbo); glBindFramebuffer(GL_FRAMEBUFFER, _mainFramebuffer); + glEnable(GL_DEPTH_TEST); + // deferred g-buffer GLenum textureBuffers[3] = { GL_COLOR_ATTACHMENT0, @@ -952,6 +946,11 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure glDisablei(GL_BLEND, 2); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + Time time = OsEng.timeManager().time(); + RenderData data = { *_camera, psc(), time, doPerformanceMeasurements, 0,{} }; + RendererTasks tasks; + data.renderBinMask = static_cast(Renderable::RenderBin::Background); _scene->render(data, tasks); data.renderBinMask = static_cast(Renderable::RenderBin::Opaque); @@ -961,7 +960,49 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure data.renderBinMask = static_cast(Renderable::RenderBin::Overlay); _scene->render(data, tasks); - for (const RaycasterTask& raycasterTask : tasks.raycasterTasks) { + + performRaycasterTasks(tasks.raycasterTasks); + + glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); + GLenum dBuffer[1] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, dBuffer); + glClear(GL_COLOR_BUFFER_BIT); + + performDeferredTasks(tasks.deferredcasterTasks); + + if (!tasks.deferredcasterTasks.empty()) { + // JCC: Temporarily disabled. Need to test it on mac and linux before final + // merging. + /*glBindFramebuffer(GL_READ_FRAMEBUFFER, _deferredFramebuffer); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, defaultFbo); + GLenum dBuffer[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, dBuffer); + glReadBuffer(GL_COLOR_ATTACHMENT0); + glBlitFramebuffer(0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), + 0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), + GL_COLOR_BUFFER_BIT, GL_NEAREST); + */ + //glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); + } else { + _resolveProgram->activate(); + + ghoul::opengl::TextureUnit mainColorTextureUnit; + mainColorTextureUnit.activate(); + + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainColorTexture); + _resolveProgram->setUniform(_uniformCache.mainColorTexture, mainColorTextureUnit); + _resolveProgram->setUniform(_uniformCache.blackoutFactor, blackoutFactor); + _resolveProgram->setUniform(_uniformCache.nAaSamples, _nAaSamples); + glBindVertexArray(_screenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + glBindVertexArray(0); + + _resolveProgram->deactivate(); + } +} + +void FramebufferRenderer::performRaycasterTasks(const std::vector& tasks) { + for (const RaycasterTask& raycasterTask : tasks) { VolumeRaycaster* raycaster = raycasterTask.raycaster; glBindFramebuffer(GL_FRAMEBUFFER, _exitFramebuffer); @@ -1041,18 +1082,15 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure LWARNING("Raycaster is not attached when trying to perform raycaster task"); } } +} +void FramebufferRenderer::performDeferredTasks(const std::vector& tasks) { // g-buffer - if (!tasks.deferredcasterTasks.empty()) { + if (!tasks.empty()) { //glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _deferredFramebuffer); - glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - GLenum dBuffer[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, dBuffer); - glClear(GL_COLOR_BUFFER_BIT); - bool firstPaint = true; - for (const DeferredcasterTask& deferredcasterTask : tasks.deferredcasterTasks) { + for (const DeferredcasterTask& deferredcasterTask : tasks) { Deferredcaster* deferredcaster = deferredcasterTask.deferredcaster; @@ -1125,45 +1163,13 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure if (firstPaint) { firstPaint = false; } - } - else { + } else { LWARNING( "Deferredcaster is not attached when trying to perform deferred task" ); } } } - - if (!tasks.deferredcasterTasks.empty()) { - // JCC: Temporarily disabled. Need to test it on mac and linux before final - // merging. - /*glBindFramebuffer(GL_READ_FRAMEBUFFER, _deferredFramebuffer); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, defaultFbo); - GLenum dBuffer[] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, dBuffer); - glReadBuffer(GL_COLOR_ATTACHMENT0); - glBlitFramebuffer(0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), - 0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), - GL_COLOR_BUFFER_BIT, GL_NEAREST); - */ - //glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - } else { - glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - _resolveProgram->activate(); - - ghoul::opengl::TextureUnit mainColorTextureUnit; - mainColorTextureUnit.activate(); - - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainColorTexture); - _resolveProgram->setUniform(_uniformCache.mainColorTexture, mainColorTextureUnit); - _resolveProgram->setUniform(_uniformCache.blackoutFactor, blackoutFactor); - _resolveProgram->setUniform(_uniformCache.nAaSamples, _nAaSamples); - glBindVertexArray(_screenQuad); - glDrawArrays(GL_TRIANGLES, 0, 6); - glBindVertexArray(0); - - _resolveProgram->deactivate(); - } } void FramebufferRenderer::setScene(Scene* scene) { diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index 6ab6e314c4..7b12f3552d 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -187,7 +187,7 @@ void Renderable::setPscUniforms(ghoul::opengl::ProgramObject& program, program.setUniform("campos", camera.position().vec4()); program.setUniform("objpos", position.vec4()); program.setUniform("camrot", glm::mat4(camera.viewRotationMatrix())); - program.setUniform("scaling", camera.scaling()); + program.setUniform("scaling", glm::vec2(1, 0)); } Renderable::RenderBin Renderable::renderBin() const { diff --git a/src/util/camera.cpp b/src/util/camera.cpp index b6483cc7cd..f8c5454c2a 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -49,8 +49,6 @@ namespace openspace { : _focusPosition() , _maxFov(0.f) { - - _scaling = glm::vec2(1.f, 0.f); _position = Vec3(1.0, 1.0, 1.0); Vec3 eulerAngles(1.0, 1.0, 1.0); _rotation = Quat(eulerAngles); @@ -60,7 +58,6 @@ namespace openspace { : sgctInternal(o.sgctInternal) , _position(o._position) , _rotation(o._rotation) - , _scaling(o._scaling) , _focusPosition(o._focusPosition) , _maxFov(o._maxFov) , _cachedViewDirection(o._cachedViewDirection) @@ -91,9 +88,11 @@ namespace openspace { _cachedCombinedViewMatrix.isDirty = true; } - void Camera::setScaling(glm::vec2 scaling) { + void Camera::setScaling(float scaling) { std::lock_guard _lock(_mutex); - _scaling = std::move(scaling); + _scaling = scaling; + _cachedViewScaleMatrix.isDirty = true; + _cachedCombinedViewMatrix.isDirty = true; } void Camera::setMaxFov(float fov) { @@ -154,10 +153,6 @@ namespace openspace { return _cachedLookupVector.datum; } - const glm::vec2& Camera::scaling() const { - return _scaling; - } - float Camera::maxFov() const { return _maxFov; } @@ -174,6 +169,10 @@ namespace openspace { return _parent; } + float Camera::scaling() const { + return _scaling; + } + const Camera::Mat4& Camera::viewRotationMatrix() const { if (_cachedViewRotationMatrix.isDirty) { _cachedViewRotationMatrix.datum = glm::mat4_cast( @@ -183,6 +182,14 @@ namespace openspace { return _cachedViewRotationMatrix.datum; } + const Camera::Mat4& Camera::viewScaleMatrix() const + { + if (_cachedViewScaleMatrix.isDirty) { + _cachedViewScaleMatrix.datum = glm::scale(glm::vec3(_scaling)); + } + return _cachedViewScaleMatrix.datum; + } + const Camera::Quat& Camera::rotationQuaternion() const { return _rotation; } @@ -193,6 +200,7 @@ namespace openspace { glm::inverse(glm::translate(Mat4(1.0), static_cast(_position))); _cachedCombinedViewMatrix.datum = Mat4(sgctInternal.viewMatrix()) * + Mat4(viewScaleMatrix()) * Mat4(viewRotationMatrix()) * cameraTranslation; _cachedCombinedViewMatrix.isDirty = true; From 4b3a11c4aa0cae6897c945b43e9cd8b1d43fa4d6 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 14 Feb 2018 11:35:58 -0500 Subject: [PATCH 04/79] Initial fixes in ATM for stereo rendering. --- include/openspace/util/camera.h | 1 + .../rendering/atmospheredeferredcaster.cpp | 5 +++++ .../atmosphere/shaders/atmosphere_deferred_fs.glsl | 13 ++++++++----- src/util/camera.cpp | 4 ++++ 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index 70e7ea88f8..b3b2e28d03 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -171,6 +171,7 @@ public: psc unsynchedPosition() const; // [[deprecated("Replaced by Camera::focusPositionVec3()")]] psc focusPosition() const; + const glm::mat4& sceneMatrix() const; // @TODO use Camera::SgctInternal interface instead // [[deprecated("Replaced by Camera::SgctInternal::viewMatrix()")]] const glm::mat4& viewMatrix() const; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 52a7594e9c..23bec4878f 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -255,6 +255,11 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); // World to Eye Space in OS + program.setUniform( + "dInverseCamScaleTransform", + glm::inverse(renderData.camera.viewScaleMatrix()) + ); + program.setUniform( "dInverseCamRotTransform", glm::mat4_cast( diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index e924730ecd..a4c434f2b4 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -88,6 +88,7 @@ uniform sampler2DMS mainColorTexture; uniform dmat4 dInverseSgctEyeToWorldTranform; // SGCT Eye to OS World uniform dmat4 dSgctEyeToOSEyeTranform; // SGCT Eye to OS Eye * uniform dmat4 dInverseSgctProjectionMatrix; // Clip to SGCT Eye * +uniform dmat4 dInverseCamScaleTransform; uniform dmat4 dInverseCamRotTransform; uniform dmat4 dInverseModelTransformMatrix; uniform dmat4 dModelTransformMatrix; @@ -260,13 +261,14 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // Clip to SGCT Eye dvec4 sgctEyeCoords = dInverseSgctProjectionMatrix * clipCoords; - sgctEyeCoords.w = 1.0; + sgctEyeCoords.w = clipCoords.z;//1.0; // SGCT Eye to OS Eye dvec4 tOSEyeCoordsInv = dSgctEyeToOSEyeTranform * sgctEyeCoords; // OS Eye to World coords - dvec4 tmpRInv = dInverseCamRotTransform * tOSEyeCoordsInv; + dvec4 tmpSInv = dInverseCamScaleTransform * tOSEyeCoordsInv; + dvec4 tmpRInv = dInverseCamRotTransform * tmpSInv;//tOSEyeCoordsInv; dvec4 worldCoords = dvec4(dvec3(tmpRInv) + dCampos, 1.0); // World to Object @@ -634,8 +636,9 @@ void main() { // Fragments positions into G-Buffer are written in OS Eye Space (Camera Rig Coords) // when using their positions later, one must convert them to the planet's coords - // OS Eye to World coords - dvec4 tmpRInvPos = dInverseCamRotTransform * dSgctEyeToOSEyeTranform * position; + // OS Eye to World coords + dvec4 tmpSInvPos = dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; + dvec4 tmpRInvPos = dInverseCamRotTransform * tmpSInvPos;//dSgctEyeToOSEyeTranform * position; dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCampos, 1.0); // World to Object (Normal and Position in meters) @@ -652,7 +655,7 @@ void main() { float dC = float(length(cameraPositionInObject.xyz)); float x1 = 1e8; if (dC > x1) { - pixelDepth += 1000.0; + pixelDepth += 1000.0; float alpha = 1000.0; float beta = 1000000.0; float x2 = 1e9; diff --git a/src/util/camera.cpp b/src/util/camera.cpp index f8c5454c2a..3da20a3f69 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -306,6 +306,10 @@ namespace openspace { return psc(_focusPosition); } + const glm::mat4& Camera::sceneMatrix() const { + return sgctInternal.sceneMatrix(); + } + const glm::mat4& Camera::viewMatrix() const { return sgctInternal.viewMatrix(); } From cb77e2839cd68d3367ec8263cd481c2104f55c13 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 14 Feb 2018 18:17:59 +0100 Subject: [PATCH 05/79] Fix bug with accurate normal rendering in stereo --- modules/globebrowsing/rendering/chunkrenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/globebrowsing/rendering/chunkrenderer.cpp b/modules/globebrowsing/rendering/chunkrenderer.cpp index e3b370fc3d..6f5c977397 100644 --- a/modules/globebrowsing/rendering/chunkrenderer.cpp +++ b/modules/globebrowsing/rendering/chunkrenderer.cpp @@ -374,7 +374,7 @@ void ChunkRenderer::renderChunkGlobally(const Chunk& chunk, const RenderData& da { // Apply an extra scaling to the height if the object is scaled programObject->setUniform( - "heightScale", static_cast(data.modelTransform.scale)); + "heightScale", static_cast(data.modelTransform.scale * data.camera.scaling())); } setCommonUniforms(*programObject, chunk, data); From 656bd0e89e5d896bbcd857774ba6f238bc908145 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 15 Feb 2018 19:04:50 +0100 Subject: [PATCH 06/79] Star rendering: stereo support + remove psc --- modules/space/rendering/renderablestars.cpp | 163 +++++++++----------- modules/space/rendering/renderablestars.h | 10 +- modules/space/shaders/star_fs.glsl | 28 ++-- modules/space/shaders/star_ge.glsl | 49 ++---- modules/space/shaders/star_vs.glsl | 20 +-- 5 files changed, 102 insertions(+), 168 deletions(-) diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 5823510146..edbeaf29bd 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -99,25 +100,24 @@ namespace { "stars." }; - static const openspace::properties::Property::PropertyInfo TransparencyInfo = { - "Transparency", - "Transparency", - "This value is a multiplicative factor that is applied to the transparency of " - "all stars." + static const openspace::properties::Property::PropertyInfo MagnitudeExponentInfo = { + "MagnitudeExponent", + "MagnitudeExponent", + "Adjust star magnitude by 10^MagnitudeExponent. " + "Stars closer than this distance are given full opacity. " + "Farther away, stars dim proportionally to the logarithm of their distance." }; - static const openspace::properties::Property::PropertyInfo ScaleFactorInfo = { - "ScaleFactor", - "Scale Factor", - "This value is used as a multiplicative factor that is applied to the apparent " - "size of each star." + static const openspace::properties::Property::PropertyInfo SharpnessInfo = { + "Sharpness", + "Sharpness", + "Adjust star sharpness" }; - static const openspace::properties::Property::PropertyInfo MinBillboardSizeInfo = { - "MinBillboardSize", - "Min Billboard Size", - "This value is used as a lower limit on the size of stars that are rendered. Any " - "stars that have a smaller apparent size will be discarded entirely." + static const openspace::properties::Property::PropertyInfo BillboardSizeInfo = { + "BillboardSize", + "Billboard Size", + "Set the billboard size of all stars" }; } // namespace @@ -162,22 +162,22 @@ documentation::Documentation RenderableStars::Documentation() { ColorOptionInfo.description }, { - TransparencyInfo.identifier, + MagnitudeExponentInfo.identifier, new DoubleVerifier, Optional::Yes, - TransparencyInfo.description + MagnitudeExponentInfo.description }, { - ScaleFactorInfo.identifier, + SharpnessInfo.identifier, new DoubleVerifier, Optional::Yes, - ScaleFactorInfo.description + SharpnessInfo.description }, { - MinBillboardSizeInfo.identifier, + BillboardSizeInfo.identifier, new DoubleVerifier, Optional::Yes, - MinBillboardSizeInfo.description + BillboardSizeInfo.description } } }; @@ -193,9 +193,9 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) , _colorTextureIsDirty(true) , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _dataIsDirty(true) - , _alphaValue(TransparencyInfo, 1.f, 0.f, 1.f) - , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 10.f) - , _minBillboardSize(MinBillboardSizeInfo, 1.f, 1.f, 100.f) + , _magnitudeExponent(MagnitudeExponentInfo, 19.f, 0.f, 30.f) + , _sharpness(SharpnessInfo, 1.f, 0.f, 5.f) + , _billboardSize(BillboardSizeInfo, 30.f, 1.f, 100.f) , _program(nullptr) , _speckFile("") , _nValuesPerStar(0) @@ -258,26 +258,26 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) ); addProperty(_colorTexturePath); - if (dictionary.hasKey(TransparencyInfo.identifier)) { - _alphaValue = static_cast( - dictionary.value(TransparencyInfo.identifier) + if (dictionary.hasKey(MagnitudeExponentInfo.identifier)) { + _magnitudeExponent = static_cast( + dictionary.value(MagnitudeExponentInfo.identifier) ); } - addProperty(_alphaValue); + addProperty(_magnitudeExponent); - if (dictionary.hasKey(ScaleFactorInfo.identifier)) { - _scaleFactor = static_cast( - dictionary.value(ScaleFactorInfo.identifier) - ); + if (dictionary.hasKey(SharpnessInfo.identifier)) { + _sharpness = static_cast( + dictionary.value(SharpnessInfo.identifier) + ); } - addProperty(_scaleFactor); + addProperty(_sharpness); - if (dictionary.hasKey(MinBillboardSizeInfo.identifier)) { - _minBillboardSize = static_cast( - dictionary.value(MinBillboardSizeInfo.identifier) + if (dictionary.hasKey(BillboardSizeInfo.identifier)) { + _billboardSize = static_cast( + dictionary.value(BillboardSizeInfo.identifier) ); } - addProperty(_minBillboardSize); + addProperty(_billboardSize); } RenderableStars::~RenderableStars() {} @@ -294,14 +294,15 @@ void RenderableStars::initializeGL() { absPath("${MODULE_SPACE}/shaders/star_ge.glsl") ); + _uniformCache.model = _program->uniformLocation("model"); _uniformCache.view = _program->uniformLocation("view"); + _uniformCache.viewScaling = _program->uniformLocation("viewScaling"); _uniformCache.projection = _program->uniformLocation("projection"); _uniformCache.colorOption = _program->uniformLocation("colorOption"); - _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); - _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); - _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.magnitudeExponent = _program->uniformLocation("magnitudeExponent"); + _uniformCache.sharpness = _program->uniformLocation("sharpness"); + _uniformCache.billboardSize = _program->uniformLocation("billboardSize"); _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.scaling = _program->uniformLocation("scaling"); _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); @@ -331,25 +332,29 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { glDepthMask(false); _program->activate(); - // @Check overwriting the scaling from the camera; error as parsec->meter conversion - // is done twice? ---abock - glm::vec2 scaling = glm::vec2(1, -19); + glm::mat4 model = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * + glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - _program->setUniform(_uniformCache.view, data.camera.viewMatrix()); - _program->setUniform(_uniformCache.projection, data.camera.projectionMatrix()); + glm::mat4 view = data.camera.combinedViewMatrix(); + glm::mat4 projection = data.camera.projectionMatrix(); + float viewScaling = data.camera.scaling(); + + _program->setUniform(_uniformCache.model, model); + _program->setUniform(_uniformCache.view, view); + _program->setUniform(_uniformCache.projection, projection); + _program->setUniform(_uniformCache.viewScaling, viewScaling); _program->setUniform(_uniformCache.colorOption, _colorOption); - _program->setUniform(_uniformCache.alphaValue, _alphaValue); - _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); - _program->setUniform(_uniformCache.minBillboardSize, _minBillboardSize); + _program->setUniform(_uniformCache.magnitudeExponent, _magnitudeExponent); + _program->setUniform(_uniformCache.sharpness, _sharpness); + _program->setUniform(_uniformCache.billboardSize, _billboardSize); _program->setUniform( _uniformCache.screenSize, glm::vec2(OsEng.renderEngine().renderingResolution()) ); - setPscUniforms(*_program.get(), data.camera, data.position); - _program->setUniform(_uniformCache.scaling, scaling); - ghoul::opengl::TextureUnit psfUnit; psfUnit.activate(); _pointSpreadFunctionTexture->bind(); @@ -552,14 +557,15 @@ void RenderableStars::update(const UpdateData&) { if (_program->isDirty()) { _program->rebuildFromFile(); + _uniformCache.model = _program->uniformLocation("model"); _uniformCache.view = _program->uniformLocation("view"); + _uniformCache.viewScaling = _program->uniformLocation("viewScaling"); _uniformCache.projection = _program->uniformLocation("projection"); _uniformCache.colorOption = _program->uniformLocation("colorOption"); - _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); - _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); - _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.magnitudeExponent = _program->uniformLocation("magnitudeExponent"); + _uniformCache.sharpness = _program->uniformLocation("sharpness"); + _uniformCache.billboardSize = _program->uniformLocation("billboardSize"); _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.scaling = _program->uniformLocation("scaling"); _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); } @@ -735,51 +741,20 @@ bool RenderableStars::saveCachedFile(const std::string& file) const { void RenderableStars::createDataSlice(ColorOption option) { _slicedData.clear(); - // This is only temporary until the scalegraph is in place ---abock - float minDistance = std::numeric_limits::max(); - float maxDistance = -std::numeric_limits::max(); - - for (size_t i = 0; i < _fullData.size(); i+=_nValuesPerStar) { - float distLy = _fullData[i + 6]; - //if (distLy < 20.f) { - minDistance = std::min(minDistance, distLy); - maxDistance = std::max(maxDistance, distLy); - //} - } - for (size_t i = 0; i < _fullData.size(); i+=_nValuesPerStar) { glm::vec3 p = glm::vec3(_fullData[i + 0], _fullData[i + 1], _fullData[i + 2]); - - // This is only temporary until the scalegraph is in place. It places all stars - // on a sphere with a small variation in the distance to account for blending - // issues ---abock - //if (p != glm::vec3(0.f)) - // p = glm::normalize(p); - - //float distLy = _fullData[i + 6]; - //float normalizedDist = (distLy - minDistance) / (maxDistance - minDistance); - //float distance = 18.f - normalizedDist / 1.f ; - - - //psc position = psc(glm::vec4(p, distance)); - - // Convert parsecs -> meter - psc position = psc(glm::vec4(p * 0.308567756f, 17)); - - //position[1] *= parsecsToMetersFactor[0]; - //position[2] *= parsecsToMetersFactor[0]; - //position[3] += parsecsToMetersFactor[1]; + p *= openspace::distanceconstants::Parsec; switch (option) { case ColorOption::Color: { union { ColorVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - position[0], position[1], position[2], position[3] + p[0], p[1], p[2], 1.0 } }; #ifdef USING_STELLAR_TEST_GRID @@ -802,11 +777,11 @@ void RenderableStars::createDataSlice(ColorOption option) { { union { VelocityVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - position[0], position[1], position[2], position[3] + p[0], p[1], p[2], 1.0 } }; layout.value.bvColor = _fullData[i + 3]; @@ -826,11 +801,11 @@ void RenderableStars::createDataSlice(ColorOption option) { { union { SpeedVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - position[0], position[1], position[2], position[3] + p[0], p[1], p[2], 1.0 } }; layout.value.bvColor = _fullData[i + 3]; diff --git a/modules/space/rendering/renderablestars.h b/modules/space/rendering/renderablestars.h index fd2cd92e5a..3e8ced2282 100644 --- a/modules/space/rendering/renderablestars.h +++ b/modules/space/rendering/renderablestars.h @@ -86,13 +86,13 @@ private: properties::OptionProperty _colorOption; bool _dataIsDirty; - properties::FloatProperty _alphaValue; - properties::FloatProperty _scaleFactor; - properties::FloatProperty _minBillboardSize; + properties::FloatProperty _magnitudeExponent; + properties::FloatProperty _sharpness; + properties::FloatProperty _billboardSize; std::unique_ptr _program; - UniformCache(view, projection, colorOption, alphaValue, scaleFactor, - minBillboardSize, screenSize, scaling, psfTexture, colorTexture) _uniformCache; + UniformCache(model, view, viewScaling, projection, colorOption, magnitudeExponent, sharpness, + billboardSize, screenSize, scaling, psfTexture, colorTexture) _uniformCache; std::string _speckFile; diff --git a/modules/space/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl index 9ee5b90c4f..0c53b621b2 100644 --- a/modules/space/shaders/star_fs.glsl +++ b/modules/space/shaders/star_fs.glsl @@ -23,7 +23,7 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "PowerScaling/powerScaling_fs.hglsl" +#include "floatoperations.glsl" // keep in sync with renderablestars.h:ColorOption enum const int COLOROPTION_COLOR = 0; @@ -32,9 +32,9 @@ const int COLOROPTION_SPEED = 2; uniform sampler2D psfTexture; uniform sampler1D colorTexture; -uniform float minBillboardSize; -uniform float alphaValue; +uniform float magnitudeExponent; +uniform float sharpness; uniform int colorOption; in vec4 vs_position; @@ -43,13 +43,7 @@ in vec3 ge_brightness; in vec3 ge_velocity; in float ge_speed; in vec2 texCoord; -in float billboardSize; - -#include "fragment.glsl" -//#include "PowerScaling/powerScaling_fs.hglsl" - -uniform vec2 magnitudeClamp; - +in float ge_observationDistance; vec4 bv2rgb(float bv) { // BV is [-0.4,2.0] @@ -60,7 +54,7 @@ vec4 bv2rgb(float bv) { Fragment getFragment() { // Something in the color calculations need to be changed because before it was dependent // on the gl blend functions since the abuffer was not involved - + vec4 color = vec4(0.0); switch (colorOption) { case COLOROPTION_COLOR: @@ -77,19 +71,15 @@ Fragment getFragment() { vec4 textureColor = texture(psfTexture, texCoord); vec4 fullColor = vec4(color.rgb, textureColor.a); - fullColor.a *= alphaValue; + fullColor.a = pow(fullColor.a, sharpness); - vec4 position = vs_position; - // This has to be fixed when the scale graph is in place ---emiax - position.w = 15; + float d = magnitudeExponent - log(ge_observationDistance) / log(10.0); + fullColor.a *= clamp(d, 0.0, 1.0); Fragment frag; frag.color = fullColor; - frag.depth = pscDepth(position); - - // G-Buffer + frag.depth = safeLength(vs_position); frag.gPosition = ge_gPosition; - // There is no normal here frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); if (fullColor.a == 0) { diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index b6fc81b941..3b2b95573c 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -24,15 +24,14 @@ #version __CONTEXT__ -#include "PowerScaling/powerScalingMath.hglsl" +#include "floatoperations.glsl" layout(points) in; -in vec4 psc_position[]; + in vec3 vs_brightness[]; in vec3 vs_velocity[]; in vec4 vs_gPosition[]; in float vs_speed[]; -in vec4 cam_position[]; layout(triangle_strip, max_vertices = 4) out; @@ -42,12 +41,11 @@ out vec3 ge_brightness; out vec3 ge_velocity; out float ge_speed; out vec2 texCoord; -out float billboardSize; - -uniform mat4 projection; +out float ge_observationDistance; +uniform float viewScaling; uniform float scaleFactor; -uniform float minBillboardSize; +uniform float billboardSize; uniform vec2 screenSize; const vec2 corners[4] = vec2[4]( @@ -57,50 +55,27 @@ const vec2 corners[4] = vec2[4]( vec2(1.0, 0.0) ); - void main() { - // JCC: We want to display the Sun. - // if ((psc_position[0].x == 0.0) && - // (psc_position[0].y == 0.0) && - // (psc_position[0].z == 0.0)) - // { - // return; - // } - ge_brightness = vs_brightness[0]; ge_velocity = vs_velocity[0]; ge_speed = vs_speed[0]; float absoluteMagnitude = vs_brightness[0].z; - float modifiedSpriteSize = - exp((-30.623 - absoluteMagnitude) * 0.462) * scaleFactor * 2000; - vec4 projPos[4]; - for (int i = 0; i < 4; ++i) { - vec4 p1 = gl_in[0].gl_Position; - p1.xy += vec2(modifiedSpriteSize * (corners[i] - vec2(0.5))); - projPos[i] = projection * p1; - } - - // Calculate the positions of the lower left and upper right corners of the - // billboard in screen-space - vec2 ll = (((projPos[1].xy / projPos[1].w) + 1.0) / 2.0) * screenSize; - vec2 ur = (((projPos[2].xy / projPos[2].w) + 1.0) / 2.0) * screenSize; - - // The billboard is smaller than one pixel, we can discard it - float sizeInPixels = length(ll - ur); - if (sizeInPixels < minBillboardSize) { - return; - } + vec4 projectedPoint = gl_in[0].gl_Position; + vec2 starSize = vec2(billboardSize) / screenSize * projectedPoint.w; for (int i = 0; i < 4; i++) { vs_position = gl_in[0].gl_Position; - gl_Position = projPos[i]; + gl_Position = projectedPoint + vec4(starSize * (corners[i] - 0.5), 0.0, 0.0); + gl_Position.z = 0.0; + texCoord = corners[i]; // G-Buffer ge_gPosition = vs_gPosition[0]; - billboardSize = sizeInPixels; + ge_observationDistance = safeLength(vs_gPosition[0] / viewScaling); + EmitVertex(); } diff --git a/modules/space/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl index 7ff61c0f5e..594bcfbc5a 100644 --- a/modules/space/shaders/star_vs.glsl +++ b/modules/space/shaders/star_vs.glsl @@ -31,30 +31,24 @@ in vec3 in_brightness; in vec3 in_velocity; in float in_speed; -out vec4 psc_position; out vec3 vs_brightness; out vec3 vs_velocity; out float vs_speed; out vec4 vs_gPosition; +uniform mat4 model; uniform mat4 view; uniform mat4 projection; - void main() { - vec4 p = in_position; - psc_position = p; vs_brightness = in_brightness; vs_velocity = in_velocity; vs_speed = in_speed; - vec4 tmp = p; - vec4 position = pscTransform(tmp, mat4(1.0)); - - // G-Buffer - vs_gPosition = view * (vec4(1E19, 1E19, 1E19, 1.0) * position); - - position = view * position; - - gl_Position = position; + vec3 modelPosition = in_position.xyz; + + vec4 viewPosition = view * model * vec4(modelPosition, 1.0); + + vs_gPosition = viewPosition; + gl_Position = projection * vs_gPosition; } From 954e3a888d061b850979d5c70e185f8118dfb603 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Fri, 16 Feb 2018 13:52:42 +0100 Subject: [PATCH 07/79] Interpolate stereoscopic depth when changing focus node --- .../openspace/interaction/orbitalnavigator.h | 10 ++ src/interaction/orbitalnavigator.cpp | 91 +++++++++++++++---- 2 files changed, 83 insertions(+), 18 deletions(-) diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index 47f0614412..b6ace82be8 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -88,13 +88,18 @@ private: properties::FloatProperty _stereoscopicDepthOfFocusSurface; properties::FloatProperty _staticViewScaleExponent; + properties::FloatProperty _rotateToFocusInterpolationTime; + properties::FloatProperty _stereoInterpolationTime; + MouseStates _mouseStates; SceneGraphNode* _focusNode = nullptr; glm::dvec3 _previousFocusNodePosition; glm::dquat _previousFocusNodeRotation; + double _currentCameraToSurfaceDistance; Interpolator _rotateToFocusNodeInterpolator; + Interpolator _cameraToSurfaceDistanceInterpolator; Interpolator _followRotationInterpolator; /** @@ -129,6 +134,11 @@ private: glm::dquat interpolateLocalRotation(double deltaTime, const glm::dquat& localCameraRotation); + + double interpolateCameraToSurfaceDistance(double deltaTime, + double currentDistance, + double targetDistance); + /** * Translates the horizontal direction. If far from the focus object, this will * result in an orbital rotation around the object. This function does not affect the diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index b5fbecd444..3f68f1b411 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -85,6 +85,22 @@ namespace { "" // @TODO Missing documentation }; + static const openspace::properties::Property::PropertyInfo + StereoInterpolationTimeInfo = { + "StereoInterpolationTime", + "Stereo interpolation time", + "The time to interpolate to a new stereoscopic depth " + "when the focus node is changed" + }; + + static const openspace::properties::Property::PropertyInfo + RotateToFocusInterpolationTimeInfo = { + "RotateToFocusInterpolationTime", + "Rotate to focus interpolation time", + "The time to interpolate the camera rotation " + "when the focus node is changed" + }; + static const openspace::properties::Property::PropertyInfo UseAdaptiveStereoscopicDepthInfo = { "UseAdaptiveStereoscopicDepth", @@ -137,6 +153,8 @@ OrbitalNavigator::OrbitalNavigator() , _useAdaptiveStereoscopicDepth(UseAdaptiveStereoscopicDepthInfo, true) , _staticViewScaleExponent(StaticViewScaleExponentInfo, 0.f, -30, 10) , _stereoscopicDepthOfFocusSurface(StereoscopicDepthOfFocusSurfaceInfo, 8, 0.25, 100) + , _rotateToFocusInterpolationTime(RotateToFocusInterpolationTimeInfo, 2.0, 0.0, 10.0) + , _stereoInterpolationTime(StereoInterpolationTimeInfo, 8.0, 0.0, 10.0) { auto smoothStep = [](double t) { @@ -164,6 +182,7 @@ OrbitalNavigator::OrbitalNavigator() return (6 * (t + t*t) / (1 - 3 * t*t + 2 * t*t*t)); }; _rotateToFocusNodeInterpolator.setTransferFunction(smoothStepDerivedTranferFunction); + _cameraToSurfaceDistanceInterpolator.setTransferFunction(smoothStepDerivedTranferFunction); // Define callback functions for changed properties _friction.roll.onChange([&]() { @@ -192,6 +211,9 @@ OrbitalNavigator::OrbitalNavigator() addProperty(_useAdaptiveStereoscopicDepth); addProperty(_staticViewScaleExponent); addProperty(_stereoscopicDepthOfFocusSurface); + + addProperty(_rotateToFocusInterpolationTime); + addProperty(_stereoInterpolationTime); } OrbitalNavigator::~OrbitalNavigator() {} @@ -299,11 +321,17 @@ void OrbitalNavigator::updateCameraStateFromMouseStates(Camera& camera, double d camera.setRotation(camRot.globalRotation * camRot.localRotation); if (_useAdaptiveStereoscopicDepth) { - glm::vec3 surfaceToCamera = static_cast( + double targetCameraToSurfaceDistance = glm::length( cameraToSurfaceVector(camPos, centerPos, posHandle) ); + _currentCameraToSurfaceDistance = interpolateCameraToSurfaceDistance( + deltaTime, + _currentCameraToSurfaceDistance, + targetCameraToSurfaceDistance); + camera.setScaling( - _stereoscopicDepthOfFocusSurface / glm::length(surfaceToCamera) + _stereoscopicDepthOfFocusSurface / + static_cast(_currentCameraToSurfaceDistance) ); } else { camera.setScaling(glm::pow(10.f, _staticViewScaleExponent)); @@ -349,9 +377,12 @@ void OrbitalNavigator::startInterpolateCameraDirection(const Camera& camera) { // Minimum is two second. Otherwise proportional to angle _rotateToFocusNodeInterpolator.setInterpolationTime(static_cast( - glm::max(angle * 2.0, 2.0) + glm::max(angle, 1.0) * _rotateToFocusInterpolationTime )); _rotateToFocusNodeInterpolator.start(); + + _cameraToSurfaceDistanceInterpolator.setInterpolationTime(_stereoInterpolationTime); + _cameraToSurfaceDistanceInterpolator.start(); } bool OrbitalNavigator::followingNodeRotation() const { @@ -429,24 +460,48 @@ glm::dquat OrbitalNavigator::rotateLocally(double deltaTime, } glm::dquat OrbitalNavigator::interpolateLocalRotation(double deltaTime, - const glm::dquat& localCameraRotation) + const glm::dquat& localCameraRotation) { - if (_rotateToFocusNodeInterpolator.isInterpolating()) { - double t = _rotateToFocusNodeInterpolator.value(); - _rotateToFocusNodeInterpolator.setDeltaTime(static_cast(deltaTime)); - _rotateToFocusNodeInterpolator.step(); - glm::dquat result = glm::slerp( - localCameraRotation, - glm::dquat(glm::dvec3(0.0)), - glm::min(t * _rotateToFocusNodeInterpolator.deltaTimeScaled(), 1.0)); - if (angle(result) < 0.01) { - _rotateToFocusNodeInterpolator.end(); - } - return result; - } - else { + if (!_rotateToFocusNodeInterpolator.isInterpolating()) { return localCameraRotation; } + double t = _rotateToFocusNodeInterpolator.value(); + _rotateToFocusNodeInterpolator.setDeltaTime(static_cast(deltaTime)); + _rotateToFocusNodeInterpolator.step(); + glm::dquat result = glm::slerp( + localCameraRotation, + glm::dquat(glm::dvec3(0.0)), + glm::min(t * _rotateToFocusNodeInterpolator.deltaTimeScaled(), 1.0)); + if (angle(result) < 0.01) { + _rotateToFocusNodeInterpolator.end(); + } + return result; +} + +double OrbitalNavigator::interpolateCameraToSurfaceDistance(double deltaTime, + double currentDistance, + double targetDistance +) { + if (!_cameraToSurfaceDistanceInterpolator.isInterpolating()) { + return targetDistance; + } + + double t = _cameraToSurfaceDistanceInterpolator.value(); + _cameraToSurfaceDistanceInterpolator.setDeltaTime(static_cast(deltaTime)); + _cameraToSurfaceDistanceInterpolator.step(); + + // Interpolate distance logarithmically. + double result = glm::exp(glm::mix( + glm::log(currentDistance), + glm::log(targetDistance), + glm::min(t * _cameraToSurfaceDistanceInterpolator.deltaTimeScaled(), 1.0))); + + double ratio = currentDistance / targetDistance; + if (glm::abs(ratio - 1.0) < 0.000001) { + _cameraToSurfaceDistanceInterpolator.end(); + } + + return result; } glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, From f129da56483335b57cb80817e85fd81aaaf5e8f9 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Fri, 16 Feb 2018 14:18:16 +0100 Subject: [PATCH 08/79] Additive blending for stars + add star parameters --- data/assets/scene/digitaluniverse/stars.asset | 5 ++++- modules/space/rendering/renderablestars.cpp | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/data/assets/scene/digitaluniverse/stars.asset b/data/assets/scene/digitaluniverse/stars.asset index 939667f169..72c4c14bb9 100644 --- a/data/assets/scene/digitaluniverse/stars.asset +++ b/data/assets/scene/digitaluniverse/stars.asset @@ -29,7 +29,10 @@ local object = { Type = "RenderableStars", File = speck .. "/stars.speck", Texture = textures .. "/halo.png", - ColorMap = colorLUT .. "/colorbv.cmap" + ColorMap = colorLUT .. "/colorbv.cmap", + MagnitudeExponent = 19, + BillboardSize = 30, + Sharpness = 1.3 }, GuiPath = "/Milky Way/Stars" } diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index edbeaf29bd..eb1919b995 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -329,7 +329,9 @@ void RenderableStars::deinitializeGL() { } void RenderableStars::render(const RenderData& data, RendererTasks&) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDepthMask(false); + _program->activate(); glm::mat4 model = @@ -373,6 +375,7 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { _program->deactivate(); glDepthMask(true); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void RenderableStars::update(const UpdateData&) { From 0f7ca1790fd1861cb27ca44bc1d50aae76b687b0 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 19 Feb 2018 14:22:57 +0100 Subject: [PATCH 09/79] Do not clear the default fbo in framebuffer renderer. Already handled by SGCT. --- src/rendering/framebufferrenderer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 87ff1be165..58c827d893 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -966,7 +966,6 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); GLenum dBuffer[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, dBuffer); - glClear(GL_COLOR_BUFFER_BIT); performDeferredTasks(tasks.deferredcasterTasks); From 5a23a3e93f2588346da4efe25131e1b391dac850 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 19 Feb 2018 22:11:12 +0100 Subject: [PATCH 10/79] Fix atmosphere stereo bugs --- include/openspace/util/camera.h | 1 + .../rendering/atmospheredeferredcaster.cpp | 15 ++++++++++---- .../shaders/atmosphere_deferred_fs.glsl | 3 ++- src/rendering/framebufferrenderer.cpp | 7 ++++++- src/util/camera.cpp | 20 +++++++++++++++++++ 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index b3b2e28d03..d691f1181f 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -101,6 +101,7 @@ public: // Accessors // Remove Vec3 from the name when psc is gone const Vec3& positionVec3() const; + const Vec3 eyePositionVec3() const; const Vec3& unsynchedPositionVec3() const; const Vec3& focusPositionVec3() const; const Vec3& viewDirectionWorldSpace() const; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 23bec4878f..5821803910 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -192,7 +192,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, _modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); - double distance = glm::distance(tPlanetPosWorld, renderData.camera.positionVec3()); + double distance = glm::distance(tPlanetPosWorld, renderData.camera.eyePositionVec3()); if (distance > DISTANCE_CULLING) { program.setUniform("cullAtmosphere", 1); } @@ -254,11 +254,16 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::inverse(dfScaleCamTransf) ); + program.setUniform( + "dCamScaleTransform", + renderData.camera.viewScaleMatrix() + ); + // World to Eye Space in OS program.setUniform( "dInverseCamScaleTransform", glm::inverse(renderData.camera.viewScaleMatrix()) - ); + ); program.setUniform( "dInverseCamRotTransform", @@ -284,7 +289,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("dInverseSgctProjectionMatrix", dInverseProjection); program.setUniform("dObjpos", glm::dvec4(renderData.position.dvec3(), 1.0)); - program.setUniform("dCampos", renderData.camera.positionVec3()); + + glm::dvec3 campos = renderData.camera.eyePositionVec3(); + program.setUniform("dCampos", campos); double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( @@ -300,7 +307,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // Sun following camera position if (_sunFollowingCameraEnabled) { sunPosObj = inverseModelMatrix * glm::dvec4( - renderData.camera.positionVec3(), + renderData.camera.eyePositionVec3(), 1.0 ); } diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index a4c434f2b4..21a73bfc69 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -88,6 +88,7 @@ uniform sampler2DMS mainColorTexture; uniform dmat4 dInverseSgctEyeToWorldTranform; // SGCT Eye to OS World uniform dmat4 dSgctEyeToOSEyeTranform; // SGCT Eye to OS Eye * uniform dmat4 dInverseSgctProjectionMatrix; // Clip to SGCT Eye * +uniform dmat4 dCamScaleTransform; uniform dmat4 dInverseCamScaleTransform; uniform dmat4 dInverseCamRotTransform; uniform dmat4 dInverseModelTransformMatrix; @@ -639,7 +640,7 @@ void main() { // OS Eye to World coords dvec4 tmpSInvPos = dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; dvec4 tmpRInvPos = dInverseCamRotTransform * tmpSInvPos;//dSgctEyeToOSEyeTranform * position; - dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCampos, 1.0); + dvec4 fragWorldCoords = dCamScaleTransform * dvec4(dvec3(tmpRInvPos) + dCampos, 1.0); // World to Object (Normal and Position in meters) dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 58c827d893..5c142dd588 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -331,7 +331,12 @@ void FramebufferRenderer::update() { for (auto &program : _deferredcastPrograms) { if (program.second && program.second->isDirty()) { - program.second->rebuildFromFile(); + try { + program.second->rebuildFromFile(); + } + catch (const ghoul::RuntimeError& e) { + LERRORC(e.component, e.message); + } } } } diff --git a/src/util/camera.cpp b/src/util/camera.cpp index 3da20a3f69..bc59e4dc66 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -121,6 +121,26 @@ namespace openspace { return _position; } + const Camera::Vec3 Camera::eyePositionVec3() const { + glm::dvec4 eyeInEyeSpace(0.0, 0.0, 0.0, 1.0); + + glm::dmat4 invViewMatrix = glm::inverse(sgctInternal.viewMatrix()); + glm::dmat4 invRotationMatrix = glm::inverse(viewRotationMatrix()); + glm::dmat4 invTranslationMatrix = + glm::translate(Mat4(1.0), static_cast(_position)); + + glm::dmat4 invViewScale = glm::inverse(viewScaleMatrix()); + + glm::dvec4 eyeInWorldSpace = + invTranslationMatrix * + invRotationMatrix * + invViewScale * + invViewMatrix * + eyeInEyeSpace; + + return glm::dvec3(eyeInWorldSpace.x, eyeInWorldSpace.y, eyeInWorldSpace.z); + } + const Camera::Vec3& Camera::unsynchedPositionVec3() const { return _position; } From ab1543841ab6dbedf5c707ac4bd71e5e1b2910d9 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 21 Feb 2018 14:02:54 +0100 Subject: [PATCH 11/79] Fix atmosphere stereo bug: positions are stored in camera rig space --- .../atmosphere/shaders/atmosphere_deferred_fs.glsl | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 21a73bfc69..b48a085d31 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -265,12 +265,11 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, sgctEyeCoords.w = clipCoords.z;//1.0; // SGCT Eye to OS Eye - dvec4 tOSEyeCoordsInv = dSgctEyeToOSEyeTranform * sgctEyeCoords; + dvec4 tOSEyeCoords = dSgctEyeToOSEyeTranform * sgctEyeCoords; // OS Eye to World coords - dvec4 tmpSInv = dInverseCamScaleTransform * tOSEyeCoordsInv; - dvec4 tmpRInv = dInverseCamRotTransform * tmpSInv;//tOSEyeCoordsInv; - dvec4 worldCoords = dvec4(dvec3(tmpRInv) + dCampos, 1.0); + dvec4 cameraOffsetWorldCoords = dInverseCamRotTransform * dInverseCamScaleTransform * tOSEyeCoords; + dvec4 worldCoords = dvec4(dvec3(cameraOffsetWorldCoords) + dCampos, 1.0); // World to Object dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; @@ -638,9 +637,8 @@ void main() { // when using their positions later, one must convert them to the planet's coords // OS Eye to World coords - dvec4 tmpSInvPos = dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; - dvec4 tmpRInvPos = dInverseCamRotTransform * tmpSInvPos;//dSgctEyeToOSEyeTranform * position; - dvec4 fragWorldCoords = dCamScaleTransform * dvec4(dvec3(tmpRInvPos) + dCampos, 1.0); + dvec4 fragWorldCoordsOffset = dInverseCamRotTransform * dInverseCamScaleTransform * position; + dvec4 fragWorldCoords = dvec4(dvec3(fragWorldCoordsOffset) + dCampos, 1.0); // World to Object (Normal and Position in meters) dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; From 7e5db07bd525fa9420f7e3e566306472581d7aa5 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 21 Feb 2018 21:40:21 +0100 Subject: [PATCH 12/79] Fix more atmosphere stereo bugs --- .../rendering/atmospheredeferredcaster.cpp | 8 +++--- .../shaders/atmosphere_deferred_fs.glsl | 25 +++++++++---------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 5821803910..eb6e7632b6 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -272,11 +272,6 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ) ); - program.setUniform( - "dInverseSgctEyeToWorldTranform", - glm::inverse(renderData.camera.combinedViewMatrix()) - ); - // Eye Space in OS to Eye Space in SGCT glm::dmat4 dOsEye2SGCTEye = glm::dmat4(renderData.camera.viewMatrix()); glm::dmat4 dSgctEye2OSEye = glm::inverse(dOsEye2SGCTEye); @@ -293,6 +288,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dvec3 campos = renderData.camera.eyePositionVec3(); program.setUniform("dCampos", campos); + glm::dvec3 camRigPos = renderData.camera.positionVec3(); + program.setUniform("dCamRigPos", camRigPos); + double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( "SUN", diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index b48a085d31..553051baf3 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -85,7 +85,6 @@ uniform sampler2DMS mainNormalTexture; uniform sampler2DMS mainColorTexture; // Model Transform Matrix Used for Globe Rendering -uniform dmat4 dInverseSgctEyeToWorldTranform; // SGCT Eye to OS World uniform dmat4 dSgctEyeToOSEyeTranform; // SGCT Eye to OS Eye * uniform dmat4 dInverseSgctProjectionMatrix; // Clip to SGCT Eye * uniform dmat4 dCamScaleTransform; @@ -96,6 +95,7 @@ uniform dmat4 dModelTransformMatrix; //uniform dmat4 dSGCTEyeToOSWorldTransformMatrix; uniform dvec4 dObjpos; +uniform dvec3 dCamRigPos; uniform dvec3 dCampos; uniform dvec3 sunDirectionObj; uniform dvec3 ellipsoidRadii; @@ -253,23 +253,20 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // ====================================== // ======= Avoiding Some Matrices ======= - // NDC to clip coordinates (gl_FragCoord.w = 1.0/w_clip) - // Using the interpolated coords: - // Assuming Red Book is right: z_ndc e [0, 1] and not [-1, 1] + // Compute positions and directions in world space. dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], msaaSamplePatter[mssaSample+1]); - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, interpolatedNDCPos.z, 1.0) / gl_FragCoord.w; + dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 1.0, 1.0); // Clip to SGCT Eye dvec4 sgctEyeCoords = dInverseSgctProjectionMatrix * clipCoords; - sgctEyeCoords.w = clipCoords.z;//1.0; // SGCT Eye to OS Eye dvec4 tOSEyeCoords = dSgctEyeToOSEyeTranform * sgctEyeCoords; - + // OS Eye to World coords - dvec4 cameraOffsetWorldCoords = dInverseCamRotTransform * dInverseCamScaleTransform * tOSEyeCoords; - dvec4 worldCoords = dvec4(dvec3(cameraOffsetWorldCoords) + dCampos, 1.0); + dvec4 offsetWorldCoords = dInverseCamRotTransform * dInverseCamScaleTransform * tOSEyeCoords; + dvec4 worldCoords = dvec4(dvec3(offsetWorldCoords) + dCampos, 1.0); // World to Object dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; @@ -313,6 +310,9 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor out vec3 attenuation, const vec3 fragPosObj, const double maxLength, const double pixelDepth, const vec4 spaceColor, const float sunIntensity) { + + const float INTERPOLATION_EPS = 0.004f; // precision const from Brunetton + vec3 radiance; r = length(x); @@ -344,7 +344,7 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor float mu0 = dot(x0, v) * invr0; bool groundHit = false; - if ((pixelDepth > 0.0) && (pixelDepth < maxLength)) { + if ((pixelDepth > INTERPOLATION_EPS) && (pixelDepth < maxLength)) { t = float(pixelDepth); groundHit = true; @@ -377,7 +377,6 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor // In order to avoid imprecision problems near horizon, // we interpolate between two points: above and below horizon - const float INTERPOLATION_EPS = 0.004f; // precision const from Brunetton if (abs(mu - muHorizon) < INTERPOLATION_EPS) { // We want an interpolation value close to 1/2, so the // contribution of each radiance value is almost the same @@ -637,8 +636,8 @@ void main() { // when using their positions later, one must convert them to the planet's coords // OS Eye to World coords - dvec4 fragWorldCoordsOffset = dInverseCamRotTransform * dInverseCamScaleTransform * position; - dvec4 fragWorldCoords = dvec4(dvec3(fragWorldCoordsOffset) + dCampos, 1.0); + dvec4 fragWorldCoordsOffset = dInverseCamRotTransform * dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; + dvec4 fragWorldCoords = dvec4(dvec3(fragWorldCoordsOffset) + dCamRigPos, 1.0); // World to Object (Normal and Position in meters) dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; From 9558d58ceeedfeabb9a0a919f09b09ecc1c31230 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 14 Mar 2018 14:20:12 -0400 Subject: [PATCH 13/79] Preparing branch for merging with stereo --- modules/atmosphere/rendering/atmospheredeferredcaster.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index d72c55729e..741477e8a0 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -192,7 +192,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, _modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); - double distance = glm::distance(tPlanetPosWorld, renderData.camera.positionVec3()); + double distance = glm::distance(tPlanetPosWorld, renderData.camera.eyePositionVec3()); if (distance > DISTANCE_CULLING) { program.setUniform("cullAtmosphere", 1); } @@ -268,7 +268,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dmat4 dInverseCameraRotationToSgctEyeTransform = glm::mat4_cast( static_cast(renderData.camera.rotationQuaternion()) - ) * dSgctEye2OSEye; + ) * glm::inverse(renderData.camera.viewScaleMatrix()) * dSgctEye2OSEye; glm::dmat4 dInverseSGCTEyeToTmpRotTransformMatrix = @@ -289,7 +289,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, dInverseCameraRotationToSgctEyeTransform); program.setUniform(_uniformCache2.dObjpos, glm::dvec4(renderData.position.dvec3(), 1.0)); - program.setUniform(_uniformCache2.dCampos, renderData.camera.positionVec3()); + program.setUniform(_uniformCache2.dCampos, renderData.camera.eyePositionVec3()); glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); @@ -308,7 +308,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // Sun following camera position if (_sunFollowingCameraEnabled) { sunPosObj = inverseModelMatrix * glm::dvec4( - renderData.camera.positionVec3(), + renderData.camera.eyePositionVec3(), 1.0 ); } From d34244ddcac1b33fae535dbd731cfc620ade5f54 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 14 Mar 2018 14:56:51 -0400 Subject: [PATCH 14/79] Fixed merging between PerformanceATM and Stereo. --- src/rendering/framebufferrenderer.cpp | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 3d953ae03e..d8aaac64fa 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -333,7 +333,12 @@ namespace openspace { for (auto &program : _deferredcastPrograms) { if (program.second && program.second->isDirty()) { - program.second->rebuildFromFile(); + try { + program.second->rebuildFromFile(); + } + catch (const ghoul::RuntimeError& e) { + LERRORC(e.component, e.message); + } } } } @@ -543,6 +548,7 @@ namespace openspace { absPath(vsPath), absPath(deferredShaderPath), deferredDict); + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; _deferredcastPrograms[caster]->setIgnoreSubroutineUniformLocationError( IgnoreError::Yes @@ -550,6 +556,8 @@ namespace openspace { _deferredcastPrograms[caster]->setIgnoreUniformLocationError( IgnoreError::Yes ); + + caster->initializeCachedVariables(*_deferredcastPrograms[caster]); } catch (ghoul::RuntimeError& e) { LERRORC(e.component, e.message); @@ -1207,21 +1215,7 @@ namespace openspace { } } - if (!tasks.deferredcasterTasks.empty()) { - // JCC: Temporarily disabled. Need to test it on mac and linux before final - // merging. - /*glBindFramebuffer(GL_READ_FRAMEBUFFER, _deferredFramebuffer); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, defaultFbo); - GLenum dBuffer[] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, dBuffer); - glReadBuffer(GL_COLOR_ATTACHMENT0); - glBlitFramebuffer(0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), - 0, 0, GLsizei(_resolution.x), GLsizei(_resolution.y), - GL_COLOR_BUFFER_BIT, GL_NEAREST); - */ - //glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - } - else { + if (tasks.deferredcasterTasks.empty()) { glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); _resolveProgram->activate(); From 39855e15127c522fcdf50ce553dbb4bddd363fba Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 16 Mar 2018 15:01:34 -0400 Subject: [PATCH 15/79] Updated names in atmosphere code. --- .../rendering/atmospheredeferredcaster.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index e36fdb5511..ae2d1fb0c1 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -255,27 +255,27 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dmat4 dInverseProjection = glm::inverse( glm::dmat4(renderData.camera.projectionMatrix())); - glm::dmat4 dInverseCameraRotationToSgctEyeTransform = glm::mat4_cast( + glm::dmat4 dInverseSGCTEyeToTmpRotTransformMatrix = glm::mat4_cast( static_cast(renderData.camera.rotationQuaternion()) ) * glm::inverse(renderData.camera.viewScaleMatrix()) * dSgctEye2OSEye; - glm::dmat4 dInverseSGCTEyeToTmpRotTransformMatrix = - dInverseCameraRotationToSgctEyeTransform * dInverseProjection; + glm::dmat4 dInverseProjectionToTmpRotTransformMatrix = + dInverseSGCTEyeToTmpRotTransformMatrix * dInverseProjection; - double *mSource = (double*)glm::value_ptr(dInverseSGCTEyeToTmpRotTransformMatrix); + double *mSource = (double*)glm::value_ptr(dInverseProjectionToTmpRotTransformMatrix); mSource[12] += renderData.camera.positionVec3().x; mSource[13] += renderData.camera.positionVec3().y; mSource[14] += renderData.camera.positionVec3().z; mSource[15] = 1.0; glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * - dInverseSGCTEyeToTmpRotTransformMatrix; + dInverseProjectionToTmpRotTransformMatrix; program.setUniform(_uniformCache2.dInverseSgctProjectionToModelTransformMatrix, inverseWholeMatrixPipeline); program.setUniform(_uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix, - dInverseCameraRotationToSgctEyeTransform); + dInverseSGCTEyeToTmpRotTransformMatrix); program.setUniform(_uniformCache2.dObjpos, glm::dvec4(renderData.position.dvec3(), 1.0)); program.setUniform(_uniformCache2.dCampos, renderData.camera.eyePositionVec3()); From 785d0ad29498d6925d755a6328ddaa40c4df0915 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 19 Mar 2018 12:29:05 -0400 Subject: [PATCH 16/79] Changes in framebuffer and atm code fixing wrong merge (still need clean up). --- .../rendering/atmospheredeferredcaster.cpp | 46 +- .../rendering/atmospheredeferredcaster.h | 2 +- .../shaders/atmosphere_deferred_fs.glsl | 26 +- .../shaders/localchunkedlodpatch_vs.glsl | 4 +- openspace.cfg | 1 + src/rendering/framebufferrenderer.cpp | 445 ++++++++---------- src/util/camera.cpp | 3 +- 7 files changed, 248 insertions(+), 279 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index b325ac3cb6..d424d386e5 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -233,38 +233,48 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform(_uniformCache2.dInverseModelTransformMatrix, inverseModelMatrix); program.setUniform(_uniformCache2.dModelTransformMatrix, _modelTransform); - // Eye Space in OS to Eye Space in SGCT + // Eye Space in SGCT to Eye Space in OS glm::dmat4 dSgctEye2OSEye = glm::inverse( - glm::dmat4(renderData.camera.viewMatrix())); - - // Eye Space in SGCT to Projection (Clip) Space in SGCT - glm::dmat4 dInverseProjection = glm::inverse( - glm::dmat4(renderData.camera.projectionMatrix())); + glm::dmat4(renderData.camera.viewMatrix())); glm::dmat4 dInverseSGCTEyeToTmpRotTransformMatrix = glm::mat4_cast( static_cast(renderData.camera.rotationQuaternion()) ) * glm::inverse(renderData.camera.viewScaleMatrix()) * dSgctEye2OSEye; + + // Eye Space in SGCT to OS Camera Before Rotation + program.setUniform(_uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix, + dInverseSGCTEyeToTmpRotTransformMatrix); - + // SGCT Projection to SGCT Eye Space + glm::dmat4 dInverseProjection = glm::inverse( + glm::dmat4(renderData.camera.projectionMatrix())); + + // SGCT Projection to OS Camera Before Rotation glm::dmat4 dInverseProjectionToTmpRotTransformMatrix = dInverseSGCTEyeToTmpRotTransformMatrix * dInverseProjection; - double *mSource = (double*)glm::value_ptr(dInverseProjectionToTmpRotTransformMatrix); - mSource[12] += renderData.camera.positionVec3().x; + // SGCT Projection to World Space + glm::dmat4 dInverseSgctProjectionToWorldTransformMatrix(dInverseProjectionToTmpRotTransformMatrix); + double *mSource = (double*)glm::value_ptr(dInverseSgctProjectionToWorldTransformMatrix); + mSource[12] += renderData.camera.eyePositionVec3().x; + mSource[13] += renderData.camera.eyePositionVec3().y; + mSource[14] += renderData.camera.eyePositionVec3().z; + /*mSource[12] += renderData.camera.positionVec3().x; mSource[13] += renderData.camera.positionVec3().y; - mSource[14] += renderData.camera.positionVec3().z; + mSource[14] += renderData.camera.positionVec3().z;*/ mSource[15] = 1.0; - + + // SGCT Projection to Object Space glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * - dInverseProjectionToTmpRotTransformMatrix; + dInverseSgctProjectionToWorldTransformMatrix; program.setUniform(_uniformCache2.dInverseSgctProjectionToModelTransformMatrix, inverseWholeMatrixPipeline); - program.setUniform(_uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix, - dInverseSGCTEyeToTmpRotTransformMatrix); - - program.setUniform(_uniformCache2.dCampos, renderData.camera.eyePositionVec3()); - + program.setUniform(_uniformCache2.dCamRigPos, renderData.camera.positionVec3()); + program.setUniform("dSGCTEyePosWorld", renderData.camera.eyePositionVec3()); + program.setUniform("dSGCTEyePosObj", inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0)); + + //glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); @@ -451,7 +461,7 @@ void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramO _uniformCache2.dModelTransformMatrix = program.uniformLocation("dModelTransformMatrix"); _uniformCache2.dInverseSgctProjectionToModelTransformMatrix = program.uniformLocation("dInverseSgctProjectionToModelTransformMatrix"); _uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix = program.uniformLocation("dInverseSGCTEyeToTmpRotTransformMatrix"); - _uniformCache2.dCampos = program.uniformLocation("dCampos"); + _uniformCache2.dCamRigPos = program.uniformLocation("dCamRigPos"); _uniformCache2.dCamPosObj = program.uniformLocation("dCamPosObj"); _uniformCache2.sunDirectionObj = program.uniformLocation("sunDirectionObj"); _uniformCache2.hardShadows = program.uniformLocation("hardShadows"); diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index 2fa9dd6d96..aec647cef5 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -137,7 +137,7 @@ private: UniformCache(dInverseModelTransformMatrix, dModelTransformMatrix, dInverseSgctProjectionToModelTransformMatrix, dInverseSGCTEyeToTmpRotTransformMatrix, - dCampos, dCamPosObj, sunDirectionObj, + dCamRigPos, dCamPosObj, sunDirectionObj, hardShadows, transmittanceTexture, irradianceTexture, inscatterTexture) _uniformCache2; diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 46cb2bd321..7a2f74a7d0 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -89,7 +89,9 @@ uniform dmat4 dModelTransformMatrix; uniform dmat4 dInverseSGCTEyeToTmpRotTransformMatrix; uniform dmat4 dInverseSgctProjectionToModelTransformMatrix; -uniform dvec3 dCampos; +uniform dvec3 dSGCTEyePosWorld; +uniform dvec4 dSGCTEyePosObj; +uniform dvec3 dCamRigPos; uniform dvec4 dCamPosObj; uniform dvec3 sunDirectionObj; @@ -186,12 +188,12 @@ struct dRay { * intersection of the ray with atmosphere when the eye position * is inside atmosphere. */ -bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const float atmRadius, - out bool inside, out float offset, out float maxLength ) { - vec3 l = vec3(planetPosition) - vec3(ray.origin.xyz); - float s = dot(l, vec3(ray.direction.xyz)); - float l2 = dot(l, l); - float r2 = atmRadius * atmRadius; // avoiding surface acne +bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const double atmRadius, + out bool inside, out double offset, out double maxLength ) { + dvec3 l = planetPosition - ray.origin.xyz; + double s = dot(l, ray.direction.xyz); + double l2 = dot(l, l); + double r2 = atmRadius * atmRadius; // avoiding surface acne // Ray origin (eye position) is behind sphere if ((s < 0.0) && (l2 > r2)) { @@ -201,7 +203,7 @@ bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const f return false; } - float m2 = l2 - s*s; + double m2 = l2 - s*s; // Ray misses atmospere if (m2 > r2) { @@ -214,7 +216,7 @@ bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const f // We already now the ray hits the atmosphere // If q = 0.0f, there is only one intersection - float q = sqrt(r2 - m2); + double q = sqrt(r2 - m2); // If l2 < r2, the ray origin is inside the sphere if (l2 > r2) { @@ -249,7 +251,7 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // Compute positions and directions in world space. dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], msaaSamplePatter[mssaSample+1]); - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, interpolatedNDCPos.z, 1.0) / gl_FragCoord.w; + dvec4 clipCoords = dvec4((interpolatedNDCPos.xy + samplePos)/ gl_FragCoord.w, 0.0, 1.0); // Clip to Object Coords dvec4 objectCoords = dInverseSgctProjectionToModelTransformMatrix * clipCoords; @@ -260,7 +262,7 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); // Camera Position in Object Space - cameraPositionInObject = dCamPosObj; + cameraPositionInObject = dSGCTEyePosObj;//dCamPosObj; // ============================ // ====== Building Ray ======== @@ -608,7 +610,7 @@ void main() { // OS Eye to World coords dvec4 tmpRInvPos = dInverseSGCTEyeToTmpRotTransformMatrix * position; - dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCampos, 1.0); + dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCamRigPos, 1.0); // World to Object (Normal and Position in meters) dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; diff --git a/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl b/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl index de8651e9b6..188618e760 100644 --- a/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl +++ b/modules/globebrowsing/shaders/localchunkedlodpatch_vs.glsl @@ -110,7 +110,7 @@ void main() { fs_normal = patchNormalModelSpace; positionCameraSpace = p; -#if USE_ECLIPSE_SHADOWS + #if USE_ECLIPSE_SHADOWS positionWorldSpace = vec3(inverseViewTransform * dvec4(p, 1.0)); -#endif + #endif } diff --git a/openspace.cfg b/openspace.cfg index f71fa86c58..17f49c373f 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -25,6 +25,7 @@ return { -- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"}, -- SGCTConfig = "${CONFIG}/spout_output.xml", + -- SGCTConfig = "${CONFIG}/stereo.xml", --SGCTConfig = "${CONFIG}/openvr_oculusRiftCv1.xml", --SGCTConfig = "${CONFIG}/openvr_htcVive.xml", diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index d8aaac64fa..6db7c4bc26 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -302,7 +302,7 @@ namespace openspace { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); - } + } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } @@ -313,7 +313,7 @@ namespace openspace { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); - } + } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } @@ -324,7 +324,7 @@ namespace openspace { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); - } + } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } @@ -335,7 +335,7 @@ namespace openspace { if (program.second && program.second->isDirty()) { try { program.second->rebuildFromFile(); - } + } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } @@ -476,7 +476,7 @@ namespace openspace { ExitFragmentShaderPath, dict ); - } + } catch (ghoul::RuntimeError e) { LERROR(e.message); } @@ -489,7 +489,7 @@ namespace openspace { absPath(RaycastFragmentShaderPath), outsideDict ); - } + } catch (ghoul::RuntimeError e) { LERROR(e.message); } @@ -548,7 +548,6 @@ namespace openspace { absPath(vsPath), absPath(deferredShaderPath), deferredDict); - using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; _deferredcastPrograms[caster]->setIgnoreSubroutineUniformLocationError( IgnoreError::Yes @@ -937,19 +936,13 @@ namespace openspace { return; } - glEnable(GL_DEPTH_TEST); - - - Time time = OsEng.timeManager().time(); - - RenderData data = { *_camera, psc(), time, doPerformanceMeasurements, 0,{} }; - RendererTasks tasks; - // Capture standard fbo GLint defaultFbo; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFbo); glBindFramebuffer(GL_FRAMEBUFFER, _mainFramebuffer); + glEnable(GL_DEPTH_TEST); + // deferred g-buffer GLenum textureBuffers[3] = { GL_COLOR_ATTACHMENT0, @@ -964,54 +957,19 @@ namespace openspace { glDisablei(GL_BLEND, 2); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - { - std::unique_ptr perfInternal; - if (doPerformanceMeasurements) { - perfInternal = std::make_unique( - "FramebufferRenderer::render::background", - OsEng.renderEngine().performanceManager() - ); - } + Time time = OsEng.timeManager().time(); - data.renderBinMask = static_cast(Renderable::RenderBin::Background); - _scene->render(data, tasks); - } - { - std::unique_ptr perfInternal; - if (doPerformanceMeasurements) { - perfInternal = std::make_unique( - "FramebufferRenderer::render::opaque", - OsEng.renderEngine().performanceManager() - ); - } + RenderData data = { *_camera, psc(), time, doPerformanceMeasurements, 0,{} }; + RendererTasks tasks; - data.renderBinMask = static_cast(Renderable::RenderBin::Opaque); - _scene->render(data, tasks); - } - { - std::unique_ptr perfInternal; - if (doPerformanceMeasurements) { - perfInternal = std::make_unique( - "FramebufferRenderer::render::transparent", - OsEng.renderEngine().performanceManager() - ); - } - - data.renderBinMask = static_cast(Renderable::RenderBin::Transparent); - _scene->render(data, tasks); - } - { - std::unique_ptr perfInternal; - if (doPerformanceMeasurements) { - perfInternal = std::make_unique( - "FramebufferRenderer::render::overlay", - OsEng.renderEngine().performanceManager() - ); - } - - data.renderBinMask = static_cast(Renderable::RenderBin::Overlay); - _scene->render(data, tasks); - } + data.renderBinMask = static_cast(Renderable::RenderBin::Background); + _scene->render(data, tasks); + data.renderBinMask = static_cast(Renderable::RenderBin::Opaque); + _scene->render(data, tasks); + data.renderBinMask = static_cast(Renderable::RenderBin::Transparent); + _scene->render(data, tasks); + data.renderBinMask = static_cast(Renderable::RenderBin::Overlay); + _scene->render(data, tasks); { std::unique_ptr perfInternal; @@ -1021,102 +979,14 @@ namespace openspace { OsEng.renderEngine().performanceManager() ); } - - - for (const RaycasterTask& raycasterTask : tasks.raycasterTasks) { - VolumeRaycaster* raycaster = raycasterTask.raycaster; - - glBindFramebuffer(GL_FRAMEBUFFER, _exitFramebuffer); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - ghoul::opengl::ProgramObject* exitProgram = _exitPrograms[raycaster].get(); - if (exitProgram) { - exitProgram->activate(); - raycaster->renderExitPoints(raycasterTask.renderData, *exitProgram); - exitProgram->deactivate(); - } - - glBindFramebuffer(GL_FRAMEBUFFER, _mainFramebuffer); - glm::vec3 cameraPosition; - bool cameraIsInside = raycaster->cameraIsInside( - raycasterTask.renderData, - cameraPosition - ); - ghoul::opengl::ProgramObject* raycastProgram = nullptr; - - if (cameraIsInside) { - raycastProgram = _insideRaycastPrograms[raycaster].get(); - if (raycastProgram) { - raycastProgram->activate(); - raycastProgram->setUniform("cameraPosInRaycaster", cameraPosition); - } - else { - raycastProgram = _insideRaycastPrograms[raycaster].get(); - raycastProgram->activate(); - raycastProgram->setUniform("cameraPosInRaycaster", cameraPosition); - } - } - else { - raycastProgram = _raycastPrograms[raycaster].get(); - if (raycastProgram) { - raycastProgram->activate(); - } - else { - raycastProgram = _raycastPrograms[raycaster].get(); - raycastProgram->activate(); - } - } - - if (raycastProgram) { - raycaster->preRaycast(_raycastData[raycaster], *raycastProgram); - - ghoul::opengl::TextureUnit exitColorTextureUnit; - exitColorTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _exitColorTexture); - raycastProgram->setUniform("exitColorTexture", exitColorTextureUnit); - - ghoul::opengl::TextureUnit exitDepthTextureUnit; - exitDepthTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _exitDepthTexture); - raycastProgram->setUniform("exitDepthTexture", exitDepthTextureUnit); - - ghoul::opengl::TextureUnit mainDepthTextureUnit; - mainDepthTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainDepthTexture); - raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); - - raycastProgram->setUniform("nAaSamples", _nAaSamples); - raycastProgram->setUniform("windowSize", _resolution); - - glDisable(GL_DEPTH_TEST); - glDepthMask(false); - if (cameraIsInside) { - glBindVertexArray(_screenQuad); - glDrawArrays(GL_TRIANGLES, 0, 6); - glBindVertexArray(0); - } - else { - raycaster->renderEntryPoints( - raycasterTask.renderData, - *raycastProgram - ); - } - glDepthMask(true); - glEnable(GL_DEPTH_TEST); - - raycaster->postRaycast(_raycastData[raycaster], *raycastProgram); - raycastProgram->deactivate(); - } - else { - LWARNING( - "Raycaster is not attached when trying to perform raycaster task" - ); - } - } + performRaycasterTasks(tasks.raycasterTasks); } - // g-buffer - if (!tasks.deferredcasterTasks.empty()) { + glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); + GLenum dBuffer[1] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, dBuffer); + + { std::unique_ptr perfInternal; if (doPerformanceMeasurements) { perfInternal = std::make_unique( @@ -1124,97 +994,9 @@ namespace openspace { OsEng.renderEngine().performanceManager() ); } - - //glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _deferredFramebuffer); - glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - GLenum dBuffer[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, dBuffer); - glClear(GL_COLOR_BUFFER_BIT); - - bool firstPaint = true; - - for (const DeferredcasterTask& deferredcasterTask : tasks.deferredcasterTasks) { - - Deferredcaster* deferredcaster = deferredcasterTask.deferredcaster; - - ghoul::opengl::ProgramObject* deferredcastProgram = nullptr; - - if (deferredcastProgram != _deferredcastPrograms[deferredcaster].get() - || deferredcastProgram == nullptr) { - deferredcastProgram = _deferredcastPrograms[deferredcaster].get(); - } - - if (deferredcastProgram) { - - deferredcastProgram->activate(); - - // adding G-Buffer - ghoul::opengl::TextureUnit mainDColorTextureUnit; - mainDColorTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainColorTexture); - deferredcastProgram->setUniform( - "mainColorTexture", - mainDColorTextureUnit - ); - - ghoul::opengl::TextureUnit mainPositionTextureUnit; - mainPositionTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainPositionTexture); - deferredcastProgram->setUniform( - "mainPositionTexture", - mainPositionTextureUnit - ); - - ghoul::opengl::TextureUnit mainNormalTextureUnit; - mainNormalTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainNormalTexture); - deferredcastProgram->setUniform( - "mainNormalTexture", - mainNormalTextureUnit - ); - - deferredcastProgram->setUniform("nAaSamples", _nAaSamples); - // 48 = 16 samples * 3 coords - deferredcastProgram->setUniform("msaaSamplePatter", &_mSAAPattern[0], 48); - - deferredcastProgram->setUniform("firstPaint", firstPaint); - deferredcastProgram->setUniform("atmExposure", _hdrExposure); - deferredcastProgram->setUniform("backgroundConstant", _hdrBackground); - - deferredcaster->preRaycast( - deferredcasterTask.renderData, - _deferredcastData[deferredcaster], - *deferredcastProgram - ); - - glDisable(GL_DEPTH_TEST); - glDepthMask(false); - - glBindVertexArray(_screenQuad); - glDrawArrays(GL_TRIANGLES, 0, 6); - glBindVertexArray(0); - - glDepthMask(true); - glEnable(GL_DEPTH_TEST); - - deferredcaster->postRaycast(deferredcasterTask.renderData, - _deferredcastData[deferredcaster], - *deferredcastProgram); - - deferredcastProgram->deactivate(); - - if (firstPaint) { - firstPaint = false; - } - } - else { - LWARNING( - "Deferredcaster is not attached when trying to perform deferred task" - ); - } - } + performDeferredTasks(tasks.deferredcasterTasks); } - + if (tasks.deferredcasterTasks.empty()) { glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); _resolveProgram->activate(); @@ -1234,6 +1016,179 @@ namespace openspace { } } + void FramebufferRenderer::performRaycasterTasks(const std::vector& tasks) { + for (const RaycasterTask& raycasterTask : tasks) { + VolumeRaycaster* raycaster = raycasterTask.raycaster; + + glBindFramebuffer(GL_FRAMEBUFFER, _exitFramebuffer); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + ghoul::opengl::ProgramObject* exitProgram = _exitPrograms[raycaster].get(); + if (exitProgram) { + exitProgram->activate(); + raycaster->renderExitPoints(raycasterTask.renderData, *exitProgram); + exitProgram->deactivate(); + } + + glBindFramebuffer(GL_FRAMEBUFFER, _mainFramebuffer); + glm::vec3 cameraPosition; + bool cameraIsInside = raycaster->cameraIsInside( + raycasterTask.renderData, + cameraPosition + ); + ghoul::opengl::ProgramObject* raycastProgram = nullptr; + + if (cameraIsInside) { + raycastProgram = _insideRaycastPrograms[raycaster].get(); + if (raycastProgram) { + raycastProgram->activate(); + raycastProgram->setUniform("cameraPosInRaycaster", cameraPosition); + } + else { + raycastProgram = _insideRaycastPrograms[raycaster].get(); + raycastProgram->activate(); + raycastProgram->setUniform("cameraPosInRaycaster", cameraPosition); + } + } + else { + raycastProgram = _raycastPrograms[raycaster].get(); + if (raycastProgram) { + raycastProgram->activate(); + } + else { + raycastProgram = _raycastPrograms[raycaster].get(); + raycastProgram->activate(); + } + } + + if (raycastProgram) { + raycaster->preRaycast(_raycastData[raycaster], *raycastProgram); + + ghoul::opengl::TextureUnit exitColorTextureUnit; + exitColorTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _exitColorTexture); + raycastProgram->setUniform("exitColorTexture", exitColorTextureUnit); + + ghoul::opengl::TextureUnit exitDepthTextureUnit; + exitDepthTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _exitDepthTexture); + raycastProgram->setUniform("exitDepthTexture", exitDepthTextureUnit); + + ghoul::opengl::TextureUnit mainDepthTextureUnit; + mainDepthTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainDepthTexture); + raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); + + raycastProgram->setUniform("nAaSamples", _nAaSamples); + raycastProgram->setUniform("windowSize", _resolution); + + glDisable(GL_DEPTH_TEST); + glDepthMask(false); + if (cameraIsInside) { + glBindVertexArray(_screenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + glBindVertexArray(0); + } + else { + raycaster->renderEntryPoints(raycasterTask.renderData, *raycastProgram); + } + glDepthMask(true); + glEnable(GL_DEPTH_TEST); + + raycaster->postRaycast(_raycastData[raycaster], *raycastProgram); + raycastProgram->deactivate(); + } + else { + LWARNING("Raycaster is not attached when trying to perform raycaster task"); + } + } + } + + void FramebufferRenderer::performDeferredTasks(const std::vector& tasks) { + bool firstPaint = true; + + for (const DeferredcasterTask& deferredcasterTask : tasks) { + + Deferredcaster* deferredcaster = deferredcasterTask.deferredcaster; + + ghoul::opengl::ProgramObject* deferredcastProgram = nullptr; + + if (deferredcastProgram != _deferredcastPrograms[deferredcaster].get() + || deferredcastProgram == nullptr) { + deferredcastProgram = _deferredcastPrograms[deferredcaster].get(); + } + + if (deferredcastProgram) { + + deferredcastProgram->activate(); + + // adding G-Buffer + ghoul::opengl::TextureUnit mainDColorTextureUnit; + mainDColorTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainColorTexture); + deferredcastProgram->setUniform( + "mainColorTexture", + mainDColorTextureUnit + ); + + ghoul::opengl::TextureUnit mainPositionTextureUnit; + mainPositionTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainPositionTexture); + deferredcastProgram->setUniform( + "mainPositionTexture", + mainPositionTextureUnit + ); + + ghoul::opengl::TextureUnit mainNormalTextureUnit; + mainNormalTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, _mainNormalTexture); + deferredcastProgram->setUniform( + "mainNormalTexture", + mainNormalTextureUnit + ); + + deferredcastProgram->setUniform("nAaSamples", _nAaSamples); + // 48 = 16 samples * 3 coords + deferredcastProgram->setUniform("msaaSamplePatter", &_mSAAPattern[0], 48); + + deferredcastProgram->setUniform("firstPaint", firstPaint); + deferredcastProgram->setUniform("atmExposure", _hdrExposure); + deferredcastProgram->setUniform("backgroundConstant", _hdrBackground); + + deferredcaster->preRaycast( + deferredcasterTask.renderData, + _deferredcastData[deferredcaster], + *deferredcastProgram + ); + + glDisable(GL_DEPTH_TEST); + glDepthMask(false); + + glBindVertexArray(_screenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + glBindVertexArray(0); + + glDepthMask(true); + glEnable(GL_DEPTH_TEST); + + deferredcaster->postRaycast(deferredcasterTask.renderData, + _deferredcastData[deferredcaster], + *deferredcastProgram); + + deferredcastProgram->deactivate(); + + if (firstPaint) { + firstPaint = false; + } + } + else { + LWARNING( + "Deferredcaster is not attached when trying to perform deferred task" + ); + } + } + } + void FramebufferRenderer::setScene(Scene* scene) { _scene = scene; } diff --git a/src/util/camera.cpp b/src/util/camera.cpp index bc59e4dc66..5318e67e47 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -125,7 +125,8 @@ namespace openspace { glm::dvec4 eyeInEyeSpace(0.0, 0.0, 0.0, 1.0); glm::dmat4 invViewMatrix = glm::inverse(sgctInternal.viewMatrix()); - glm::dmat4 invRotationMatrix = glm::inverse(viewRotationMatrix()); + glm::dmat4 invRotationMatrix = + glm::mat4_cast(static_cast(_rotation)); glm::dmat4 invTranslationMatrix = glm::translate(Mat4(1.0), static_cast(_position)); From ce392b53e640ec7ee0b3ea0faae11b62003ca84a Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 19 Mar 2018 15:17:15 -0400 Subject: [PATCH 17/79] Same changes in stereo. --- .../rendering/atmospheredeferredcaster.cpp | 14 ++++++++------ .../shaders/atmosphere_deferred_fs.glsl | 17 ++++++++--------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index d424d386e5..87eb0ee20d 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -256,14 +256,18 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // SGCT Projection to World Space glm::dmat4 dInverseSgctProjectionToWorldTransformMatrix(dInverseProjectionToTmpRotTransformMatrix); double *mSource = (double*)glm::value_ptr(dInverseSgctProjectionToWorldTransformMatrix); + mSource[12] += renderData.camera.eyePositionVec3().x; mSource[13] += renderData.camera.eyePositionVec3().y; mSource[14] += renderData.camera.eyePositionVec3().z; - /*mSource[12] += renderData.camera.positionVec3().x; + /* + mSource[12] += renderData.camera.positionVec3().x; mSource[13] += renderData.camera.positionVec3().y; - mSource[14] += renderData.camera.positionVec3().z;*/ + mSource[14] += renderData.camera.positionVec3().z; + */ mSource[15] = 1.0; + // SGCT Projection to Object Space glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * dInverseSgctProjectionToWorldTransformMatrix; @@ -271,11 +275,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, inverseWholeMatrixPipeline); program.setUniform(_uniformCache2.dCamRigPos, renderData.camera.positionVec3()); - program.setUniform("dSGCTEyePosWorld", renderData.camera.eyePositionVec3()); - program.setUniform("dSGCTEyePosObj", inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0)); - //glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); - glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); + glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); + //glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); double lt; diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 7a2f74a7d0..18c59d8b99 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -89,8 +89,6 @@ uniform dmat4 dModelTransformMatrix; uniform dmat4 dInverseSGCTEyeToTmpRotTransformMatrix; uniform dmat4 dInverseSgctProjectionToModelTransformMatrix; -uniform dvec3 dSGCTEyePosWorld; -uniform dvec4 dSGCTEyePosObj; uniform dvec3 dCamRigPos; uniform dvec4 dCamPosObj; uniform dvec3 sunDirectionObj; @@ -248,7 +246,7 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // ====================================== // ======= Avoiding Some Matrices ======= - // Compute positions and directions in world space. + // Compute positions and directions in object space. dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], msaaSamplePatter[mssaSample+1]); dvec4 clipCoords = dvec4((interpolatedNDCPos.xy + samplePos)/ gl_FragCoord.w, 0.0, 1.0); @@ -261,14 +259,15 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // space results in imprecision. planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); - // Camera Position in Object Space - cameraPositionInObject = dSGCTEyePosObj;//dCamPosObj; + // Camera Position in Object Space (in meters) + cameraPositionInObject = dCamPosObj; // ============================ // ====== Building Ray ======== // Ray in object space (in KM) ray.origin = cameraPositionInObject * dvec4(0.001, 0.001, 0.001, 1.0); - ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); + //ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); + ray.direction = dvec4(normalize((objectCoords.xyz * dvec3(0.001))- ray.origin.xyz), 0.0); } /* @@ -588,8 +587,8 @@ void main() { cameraPositionInObject); bool insideATM = false; - double offset = 0.0; - double maxLength = 0.0; + double offset = 0.0; // in Km + double maxLength = 0.0; // in Km bool intersectATM = false; @@ -607,7 +606,7 @@ void main() { vec4 normal = texelFetch(mainNormalTexture, fragCoords, i); // Data in the mainPositionTexture are written in view space (view plus camera rig) vec4 position = texelFetch(mainPositionTexture, fragCoords, i); - + // OS Eye to World coords dvec4 tmpRInvPos = dInverseSGCTEyeToTmpRotTransformMatrix * position; dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCamRigPos, 1.0); From 0fcd3d9fabd020639b50810aeda7a7a654f5064b Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Tue, 20 Mar 2018 14:23:46 +0100 Subject: [PATCH 18/79] Send view scaling over parallel connection --- include/openspace/interaction/keyframenavigator.h | 1 + include/openspace/network/messagestructures.h | 12 ++++++++++++ src/interaction/keyframenavigator.cpp | 8 ++++++++ src/network/parallelconnection.cpp | 2 +- src/network/parallelpeer.cpp | 2 ++ 5 files changed, 24 insertions(+), 1 deletion(-) diff --git a/include/openspace/interaction/keyframenavigator.h b/include/openspace/interaction/keyframenavigator.h index 1d7f5164b5..0346e894b4 100644 --- a/include/openspace/interaction/keyframenavigator.h +++ b/include/openspace/interaction/keyframenavigator.h @@ -41,6 +41,7 @@ public: glm::dvec3 position; glm::quat rotation; std::string focusNode; + float scale; bool followFocusNodeRotation; }; diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index e677f1f306..b98d00976e 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -49,6 +49,7 @@ struct CameraKeyframe { glm::dquat _rotation; bool _followNodeRotation; std::string _focusNode; + float _scale; double _timestamp; @@ -88,6 +89,12 @@ struct CameraKeyframe { _focusNode.data() + nodeNameLength ); + buffer.insert( + buffer.end(), + reinterpret_cast(&_scale), + reinterpret_cast(&_scale) + sizeof(_scale) + ); + // Add timestamp buffer.insert( buffer.end(), @@ -124,6 +131,11 @@ struct CameraKeyframe { _focusNode = std::string(buffer.data() + offset, buffer.data() + offset + size); offset += size; + // Scale + size = sizeof(_scale); + memcpy(&_scale, buffer.data() + offset, size); + offset += size; + // Timestamp size = sizeof(_timestamp); memcpy(&_timestamp, buffer.data() + offset, size); diff --git a/src/interaction/keyframenavigator.cpp b/src/interaction/keyframenavigator.cpp index bb7a95392e..f609dcf167 100644 --- a/src/interaction/keyframenavigator.cpp +++ b/src/interaction/keyframenavigator.cpp @@ -116,6 +116,14 @@ void KeyframeNavigator::updateCamera(Camera& camera) { camera.setRotation( glm::slerp(prevKeyframeCameraRotation, nextKeyframeCameraRotation, t) ); + + // We want to affect view scaling, such that we achieve + // logarithmic interpolation of distance to an imagined focus node. + // To do this, we interpolate the scale reciprocal logarithmically. + const float prevInvScaleExp = glm::log(1.0 / prevPose.scale); + const float nextInvScaleExp = glm::log(1.0 / nextPose.scale); + const float interpolatedInvScaleExp = prevInvScaleExp * (1 - t) + nextInvScaleExp * t; + camera.setScaling(1.0 / glm::exp(interpolatedInvScaleExp)); } Timeline& KeyframeNavigator::timeline() { diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index fb5694f308..493f174319 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -27,7 +27,7 @@ #include namespace { -const uint32_t ProtocolVersion = 3; +const uint32_t ProtocolVersion = 4; const char* _loggerCat = "ParallelConnection"; } // namespace diff --git a/src/network/parallelpeer.cpp b/src/network/parallelpeer.cpp index e388914926..fb62de1f2a 100644 --- a/src/network/parallelpeer.cpp +++ b/src/network/parallelpeer.cpp @@ -287,6 +287,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& messageContent) pose.focusNode = kf._focusNode; pose.position = kf._position; pose.rotation = kf._rotation; + pose.scale = kf._scale; pose.followFocusNodeRotation = kf._followNodeRotation; OsEng.navigationHandler().keyframeNavigator().addKeyframe(kf._timestamp, pose); @@ -539,6 +540,7 @@ void ParallelPeer::sendCameraKeyframe() { } kf._focusNode = focusNode->identifier(); + kf._scale = OsEng.navigationHandler().camera()->scaling(); // Timestamp as current runtime of OpenSpace instance kf._timestamp = OsEng.windowWrapper().applicationTime(); From 1ef8e208218ac4a01caf374c29e5f6c1ce432aa3 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Tue, 20 Mar 2018 21:32:49 +0100 Subject: [PATCH 19/79] Start fixing atmosphere stereo rendering --- .../rendering/atmospheredeferredcaster.cpp | 33 +++++++++++-------- .../rendering/atmospheredeferredcaster.h | 4 +-- .../shaders/atmosphere_deferred_fs.glsl | 18 +++++----- 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 87eb0ee20d..c40b48a667 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -237,25 +237,32 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dmat4 dSgctEye2OSEye = glm::inverse( glm::dmat4(renderData.camera.viewMatrix())); - glm::dmat4 dInverseSGCTEyeToTmpRotTransformMatrix = glm::mat4_cast( - static_cast(renderData.camera.rotationQuaternion()) - ) * glm::inverse(renderData.camera.viewScaleMatrix()) * dSgctEye2OSEye; + glm::dmat4 dFragmentToWorldMatrix = + glm::mat4_cast( + static_cast(renderData.camera.rotationQuaternion()) + ) * glm::inverse(renderData.camera.viewScaleMatrix()); + // Eye Space in SGCT to OS Camera Before Rotation - program.setUniform(_uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix, - dInverseSGCTEyeToTmpRotTransformMatrix); + program.setUniform(_uniformCache2.dFragmentToWorldMatrix, + dFragmentToWorldMatrix); // SGCT Projection to SGCT Eye Space glm::dmat4 dInverseProjection = glm::inverse( glm::dmat4(renderData.camera.projectionMatrix())); // SGCT Projection to OS Camera Before Rotation - glm::dmat4 dInverseProjectionToTmpRotTransformMatrix = - dInverseSGCTEyeToTmpRotTransformMatrix * dInverseProjection; + glm::dmat4 dProjectionToTmpRotTransformMatrix = + glm::mat4_cast( + static_cast(renderData.camera.rotationQuaternion()) + ) * + dSgctEye2OSEye * + glm::inverse(renderData.camera.viewScaleMatrix()) * + dInverseProjection; // SGCT Projection to World Space - glm::dmat4 dInverseSgctProjectionToWorldTransformMatrix(dInverseProjectionToTmpRotTransformMatrix); - double *mSource = (double*)glm::value_ptr(dInverseSgctProjectionToWorldTransformMatrix); + glm::dmat4 dSgctProjectionToWorldTransformMatrix(dProjectionToTmpRotTransformMatrix); + double *mSource = (double*)glm::value_ptr(dSgctProjectionToWorldTransformMatrix); mSource[12] += renderData.camera.eyePositionVec3().x; mSource[13] += renderData.camera.eyePositionVec3().y; @@ -270,8 +277,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, // SGCT Projection to Object Space glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * - dInverseSgctProjectionToWorldTransformMatrix; - program.setUniform(_uniformCache2.dInverseSgctProjectionToModelTransformMatrix, + dSgctProjectionToWorldTransformMatrix; + program.setUniform(_uniformCache2.dSgctProjectionToModelTransformMatrix, inverseWholeMatrixPipeline); program.setUniform(_uniformCache2.dCamRigPos, renderData.camera.positionVec3()); @@ -461,8 +468,8 @@ void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramO _uniformCache.SAMPLES_NU = program.uniformLocation("SAMPLES_NU"); _uniformCache2.dInverseModelTransformMatrix = program.uniformLocation("dInverseModelTransformMatrix"); _uniformCache2.dModelTransformMatrix = program.uniformLocation("dModelTransformMatrix"); - _uniformCache2.dInverseSgctProjectionToModelTransformMatrix = program.uniformLocation("dInverseSgctProjectionToModelTransformMatrix"); - _uniformCache2.dInverseSGCTEyeToTmpRotTransformMatrix = program.uniformLocation("dInverseSGCTEyeToTmpRotTransformMatrix"); + _uniformCache2.dSgctProjectionToModelTransformMatrix = program.uniformLocation("dSgctProjectionToModelTransformMatrix"); + _uniformCache2.dFragmentToWorldMatrix = program.uniformLocation("dFragmentToWorldMatrix"); _uniformCache2.dCamRigPos = program.uniformLocation("dCamRigPos"); _uniformCache2.dCamPosObj = program.uniformLocation("dCamPosObj"); _uniformCache2.sunDirectionObj = program.uniformLocation("sunDirectionObj"); diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index aec647cef5..f371174516 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -135,8 +135,8 @@ private: HO, betaOzoneExtinction, SAMPLES_R, SAMPLES_MU, SAMPLES_MU_S, SAMPLES_NU) _uniformCache; UniformCache(dInverseModelTransformMatrix, dModelTransformMatrix, - dInverseSgctProjectionToModelTransformMatrix, - dInverseSGCTEyeToTmpRotTransformMatrix, + dSgctProjectionToModelTransformMatrix, + dFragmentToWorldMatrix, dCamRigPos, dCamPosObj, sunDirectionObj, hardShadows, transmittanceTexture, irradianceTexture, inscatterTexture) _uniformCache2; diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 18c59d8b99..02f88e0c37 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -86,8 +86,8 @@ uniform sampler2DMS mainColorTexture; uniform dmat4 dInverseModelTransformMatrix; uniform dmat4 dModelTransformMatrix; -uniform dmat4 dInverseSGCTEyeToTmpRotTransformMatrix; -uniform dmat4 dInverseSgctProjectionToModelTransformMatrix; +uniform dmat4 dFragmentToWorldMatrix; +uniform dmat4 dSgctProjectionToModelTransformMatrix; uniform dvec3 dCamRigPos; uniform dvec4 dCamPosObj; @@ -249,10 +249,10 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // Compute positions and directions in object space. dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], msaaSamplePatter[mssaSample+1]); - dvec4 clipCoords = dvec4((interpolatedNDCPos.xy + samplePos)/ gl_FragCoord.w, 0.0, 1.0); + dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 0.0, 1.0); // Clip to Object Coords - dvec4 objectCoords = dInverseSgctProjectionToModelTransformMatrix * clipCoords; + dvec4 objectCoords = dSgctProjectionToModelTransformMatrix * clipCoords; // Planet Position in Object Space // JCC: Applying the inverse of the model transformation on the object postion in World @@ -533,8 +533,10 @@ vec3 sunColor(const vec3 x, const float t, const vec3 v, const vec3 s, const flo } void main() { - ivec2 fragCoords = ivec2(gl_FragCoord); + ivec2 fragCoords = ivec2(gl_FragCoord); + if (cullAtmosphere == 0) { + vec4 atmosphereFinalColor = vec4(0.0f); int nSamples = 1; // First we determine if the pixel is complex (different fragments on it) @@ -608,11 +610,11 @@ void main() { vec4 position = texelFetch(mainPositionTexture, fragCoords, i); // OS Eye to World coords - dvec4 tmpRInvPos = dInverseSGCTEyeToTmpRotTransformMatrix * position; - dvec4 fragWorldCoords = dvec4(dvec3(tmpRInvPos) + dCamRigPos, 1.0); - + dvec4 fragWorldCoords = dFragmentToWorldMatrix * position; + // World to Object (Normal and Position in meters) dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; + // Distance of the pixel in the gBuffer to the observer // JCC (12/12/2017): AMD distance function is buggy. From 4e58c338746ed426796571c66a0af60ac87ca752 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 21 Mar 2018 17:44:50 +0100 Subject: [PATCH 20/79] Revert to working atm code, before optimization. Stereo now working. --- .../rendering/atmospheredeferredcaster.cpp | 477 +++++++++--------- .../shaders/atmosphere_deferred_fs.glsl | 139 ++--- 2 files changed, 308 insertions(+), 308 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index c40b48a667..04f32d1640 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -1,62 +1,62 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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. * +****************************************************************************************/ - /*************************************************************************************** - * Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the - * following code. - ****************************************************************************************/ +/*************************************************************************************** +* Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the +* following code. +****************************************************************************************/ - /** - * Precomputed Atmospheric Scattering - * Copyright (c) 2008 INRIA - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. +/** +* Precomputed Atmospheric Scattering +* Copyright (c) 2008 INRIA +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holders nor the names of its +* contributors may be used to endorse or promote products derived from +* this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +* THE POSSIBILITY OF SUCH DAMAGE. - */ +*/ #include #include @@ -90,16 +90,16 @@ namespace { - const char* _loggerCat = "AtmosphereDeferredcaster"; - const char* GlslDeferredcastPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - const char* GlslDeferredcastFSPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - const char* GlslDeferredcastVsPath = - "${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; +const char* _loggerCat = "AtmosphereDeferredcaster"; +const char* GlslDeferredcastPath = +"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; +const char* GlslDeferredcastFSPath = +"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; +const char* GlslDeferredcastVsPath = +"${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; - const float ATM_EPS = 2.0; - const double KM_TO_M = 1000.0; +const float ATM_EPS = 2.0; +const double KM_TO_M = 1000.0; } // namespace namespace openspace { @@ -162,16 +162,20 @@ void AtmosphereDeferredcaster::initialize() { } } +void AtmosphereDeferredcaster::update(const UpdateData&) {}; + +void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramObject&) {} + void AtmosphereDeferredcaster::deinitialize() { - _transmittanceProgramObject = nullptr; - _irradianceProgramObject = nullptr; - _irradianceSupTermsProgramObject = nullptr; - _inScatteringProgramObject = nullptr; + _transmittanceProgramObject = nullptr; + _irradianceProgramObject = nullptr; + _irradianceSupTermsProgramObject = nullptr; + _inScatteringProgramObject = nullptr; _inScatteringSupTermsProgramObject = nullptr; - _deltaEProgramObject = nullptr; - _deltaSProgramObject = nullptr; - _deltaSSupTermsProgramObject = nullptr; - _deltaJProgramObject = nullptr; + _deltaEProgramObject = nullptr; + _deltaSProgramObject = nullptr; + _deltaSSupTermsProgramObject = nullptr; + _deltaJProgramObject = nullptr; glDeleteTextures(1, &_transmittanceTableTexture); glDeleteTextures(1, &_irradianceTableTexture); @@ -184,8 +188,8 @@ void AtmosphereDeferredcaster::deinitialize() { } void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, - const DeferredcastData&, - ghoul::opengl::ProgramObject& program) + const DeferredcastData&, + ghoul::opengl::ProgramObject& program) { // Atmosphere Frustum Culling glm::dvec3 tPlanetPosWorld = glm::dvec3( @@ -207,85 +211,89 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, (_atmosphereRadius + ATM_EPS)*KM_TO_M) ) { - program.setUniform(_uniformCache.cullAtmosphere, 1); + program.setUniform("cullAtmosphere", 1); } else { - program.setUniform(_uniformCache.cullAtmosphere, 0); - program.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); - program.setUniform(_uniformCache.Rt, _atmosphereRadius); - program.setUniform(_uniformCache.groundRadianceEmittion, _planetGroundRadianceEmittion); - program.setUniform(_uniformCache.HR, _rayleighHeightScale); - program.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); - program.setUniform(_uniformCache.HM, _mieHeightScale); - program.setUniform(_uniformCache.betaMieExtinction, _mieExtinctionCoeff); - program.setUniform(_uniformCache.mieG, _miePhaseConstant); - program.setUniform(_uniformCache.sunRadiance, _sunRadianceIntensity); - program.setUniform(_uniformCache.ozoneLayerEnabled, _ozoneEnabled); - program.setUniform(_uniformCache.HO, _ozoneHeightScale); - program.setUniform(_uniformCache.betaOzoneExtinction, _ozoneExtinctionCoeff); - program.setUniform(_uniformCache.SAMPLES_R, _r_samples); - program.setUniform(_uniformCache.SAMPLES_MU, _mu_samples); - program.setUniform(_uniformCache.SAMPLES_MU_S, _mu_s_samples); - program.setUniform(_uniformCache.SAMPLES_NU, _nu_samples); + program.setUniform("cullAtmosphere", 0); + program.setUniform("Rg", _atmospherePlanetRadius); + program.setUniform("Rt", _atmosphereRadius); + program.setUniform( + "AverageGroundReflectance", + _planetAverageGroundReflectance + ); + program.setUniform("groundRadianceEmittion", _planetGroundRadianceEmittion); + program.setUniform("HR", _rayleighHeightScale); + program.setUniform("betaRayleigh", _rayleighScatteringCoeff); + program.setUniform("HM", _mieHeightScale); + program.setUniform("betaMieScattering", _mieScatteringCoeff); + program.setUniform("betaMieExtinction", _mieExtinctionCoeff); + program.setUniform("mieG", _miePhaseConstant); + program.setUniform("sunRadiance", _sunRadianceIntensity); + program.setUniform("ozoneLayerEnabled", _ozoneEnabled); + program.setUniform("HO", _ozoneHeightScale); + program.setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); + + program.setUniform("TRANSMITTANCE_W", _transmittance_table_width); + program.setUniform("TRANSMITTANCE_H", _transmittance_table_height); + program.setUniform("SKY_W", _irradiance_table_width); + program.setUniform("SKY_H", _irradiance_table_height); + program.setUniform("OTHER_TEXTURES_W", _delta_e_table_width); + program.setUniform("OTHER_TEXTURES_H", _delta_e_table_height); + program.setUniform("SAMPLES_R", _r_samples); + program.setUniform("SAMPLES_MU", _mu_samples); + program.setUniform("SAMPLES_MU_S", _mu_s_samples); + program.setUniform("SAMPLES_NU", _nu_samples); + + program.setUniform("ModelTransformMatrix", _modelTransform); // Object Space glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); - program.setUniform(_uniformCache2.dInverseModelTransformMatrix, inverseModelMatrix); - program.setUniform(_uniformCache2.dModelTransformMatrix, _modelTransform); + program.setUniform("dInverseModelTransformMatrix", inverseModelMatrix); + program.setUniform("dModelTransformMatrix", _modelTransform); - // Eye Space in SGCT to Eye Space in OS - glm::dmat4 dSgctEye2OSEye = glm::inverse( - glm::dmat4(renderData.camera.viewMatrix())); + // The following scale comes from PSC transformations. + glm::dmat4 dfScaleCamTransf = glm::scale(glm::dvec3(1.0)); + program.setUniform( + "dInverseScaleTransformMatrix", + glm::inverse(dfScaleCamTransf) + ); - glm::dmat4 dFragmentToWorldMatrix = + program.setUniform( + "dCamScaleTransform", + renderData.camera.viewScaleMatrix() + ); + + // World to Eye Space in OS + program.setUniform( + "dInverseCamScaleTransform", + glm::inverse(renderData.camera.viewScaleMatrix()) + ); + + program.setUniform( + "dInverseCamRotTransform", glm::mat4_cast( static_cast(renderData.camera.rotationQuaternion()) - ) * glm::inverse(renderData.camera.viewScaleMatrix()); + ) + ); + // Eye Space in OS to Eye Space in SGCT + glm::dmat4 dOsEye2SGCTEye = glm::dmat4(renderData.camera.viewMatrix()); + glm::dmat4 dSgctEye2OSEye = glm::inverse(dOsEye2SGCTEye); + program.setUniform("dSgctEyeToOSEyeTranform", dSgctEye2OSEye); - // Eye Space in SGCT to OS Camera Before Rotation - program.setUniform(_uniformCache2.dFragmentToWorldMatrix, - dFragmentToWorldMatrix); - - // SGCT Projection to SGCT Eye Space - glm::dmat4 dInverseProjection = glm::inverse( - glm::dmat4(renderData.camera.projectionMatrix())); + // Eye Space in SGCT to Projection (Clip) Space in SGCT + glm::dmat4 dSgctEye2Clip = glm::dmat4(renderData.camera.projectionMatrix()); + glm::dmat4 dInverseProjection = glm::inverse(dSgctEye2Clip); - // SGCT Projection to OS Camera Before Rotation - glm::dmat4 dProjectionToTmpRotTransformMatrix = - glm::mat4_cast( - static_cast(renderData.camera.rotationQuaternion()) - ) * - dSgctEye2OSEye * - glm::inverse(renderData.camera.viewScaleMatrix()) * - dInverseProjection; - - // SGCT Projection to World Space - glm::dmat4 dSgctProjectionToWorldTransformMatrix(dProjectionToTmpRotTransformMatrix); - double *mSource = (double*)glm::value_ptr(dSgctProjectionToWorldTransformMatrix); - - mSource[12] += renderData.camera.eyePositionVec3().x; - mSource[13] += renderData.camera.eyePositionVec3().y; - mSource[14] += renderData.camera.eyePositionVec3().z; - /* - mSource[12] += renderData.camera.positionVec3().x; - mSource[13] += renderData.camera.positionVec3().y; - mSource[14] += renderData.camera.positionVec3().z; - */ - mSource[15] = 1.0; - + program.setUniform("dInverseSgctProjectionMatrix", dInverseProjection); - // SGCT Projection to Object Space - glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * - dSgctProjectionToWorldTransformMatrix; - program.setUniform(_uniformCache2.dSgctProjectionToModelTransformMatrix, - inverseWholeMatrixPipeline); + program.setUniform("dObjpos", glm::dvec4(renderData.position.dvec3(), 1.0)); - program.setUniform(_uniformCache2.dCamRigPos, renderData.camera.positionVec3()); - - glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); - //glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); - program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); + glm::dvec3 campos = renderData.camera.eyePositionVec3(); + program.setUniform("dCampos", campos); + + glm::dvec3 camRigPos = renderData.camera.positionVec3(); + program.setUniform("dCamRigPos", camRigPos); double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( @@ -311,7 +319,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, } // Sun Position in Object Space - program.setUniform(_uniformCache2.sunDirectionObj, glm::normalize(glm::dvec3(sunPosObj))); + program.setUniform("sunDirectionObj", glm::normalize(glm::dvec3(sunPosObj))); + + program.setUniform("ellipsoidRadii", _ellipsoidRadii); // Shadow calculations.. if (!_shadowConfArray.empty()) { @@ -339,8 +349,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); casterPos *= KM_TO_M; // converting to meters - // First we determine if the caster is shadowing the current planet - // (all calculations in World Coordinates): + // First we determine if the caster is shadowing the current planet + // (all calculations in World Coordinates): glm::dvec3 planetCasterVec = casterPos - renderData.position.dvec3(); glm::dvec3 sourceCasterVec = casterPos - sourcePos; double sc_length = glm::length(sourceCasterVec); @@ -362,7 +372,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, shadowData.isShadowing = false; if (((d_test - rp_test) < (_atmospherePlanetRadius * KM_TO_M)) && - //if (((d_test - rp_test) < (_atmosphereRadius * KM_TO_M)) && + //if (((d_test - rp_test) < (_atmosphereRadius * KM_TO_M)) && (casterDistSun < planetDistSun)) { // The current caster is shadowing the current planet shadowData.isShadowing = true; @@ -371,7 +381,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); shadowData.xp = xp_test; shadowData.xu = shadowData.rc * sc_length / - (shadowData.rs - shadowData.rc); + (shadowData.rs - shadowData.rc); shadowData.casterPositionVec = casterPos; } shadowDataArray.push_back(shadowData); @@ -405,26 +415,26 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, } counter++; } - program.setUniform(_uniformCache2.hardShadows, _hardShadowsEnabled); + program.setUniform("hardShadows", _hardShadowsEnabled); } } } _transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - program.setUniform(_uniformCache2.transmittanceTexture, _transmittanceTableTextureUnit); + program.setUniform("transmittanceTexture", _transmittanceTableTextureUnit); _irradianceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); - program.setUniform(_uniformCache2.irradianceTexture, _irradianceTableTextureUnit); + program.setUniform("irradianceTexture", _irradianceTableTextureUnit); _inScatteringTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); - program.setUniform(_uniformCache2.inscatterTexture, _inScatteringTableTextureUnit); + program.setUniform("inscatterTexture", _inScatteringTableTextureUnit); } void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, - ghoul::opengl::ProgramObject&) + const DeferredcastData&, + ghoul::opengl::ProgramObject&) { // Deactivate the texture units _transmittanceTableTextureUnit.deactivate(); @@ -448,41 +458,6 @@ std::string AtmosphereDeferredcaster::helperPath() const { return ""; // no helper file } -void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramObject& program) { - _uniformCache.cullAtmosphere = program.uniformLocation("cullAtmosphere"); - _uniformCache.Rg = program.uniformLocation("Rg"); - _uniformCache.Rt = program.uniformLocation("Rt"); - _uniformCache.groundRadianceEmittion = program.uniformLocation("groundRadianceEmittion"); - _uniformCache.HR = program.uniformLocation("HR"); - _uniformCache.betaRayleigh = program.uniformLocation("betaRayleigh"); - _uniformCache.HM = program.uniformLocation("HM"); - _uniformCache.betaMieExtinction = program.uniformLocation("betaMieExtinction"); - _uniformCache.mieG = program.uniformLocation("mieG"); - _uniformCache.sunRadiance = program.uniformLocation("sunRadiance"); - _uniformCache.ozoneLayerEnabled = program.uniformLocation("ozoneLayerEnabled"); - _uniformCache.HO = program.uniformLocation("HO"); - _uniformCache.betaOzoneExtinction = program.uniformLocation("betaOzoneExtinction"); - _uniformCache.SAMPLES_R = program.uniformLocation("SAMPLES_R"); - _uniformCache.SAMPLES_MU = program.uniformLocation("SAMPLES_MU"); - _uniformCache.SAMPLES_MU_S = program.uniformLocation("SAMPLES_MU_S"); - _uniformCache.SAMPLES_NU = program.uniformLocation("SAMPLES_NU"); - _uniformCache2.dInverseModelTransformMatrix = program.uniformLocation("dInverseModelTransformMatrix"); - _uniformCache2.dModelTransformMatrix = program.uniformLocation("dModelTransformMatrix"); - _uniformCache2.dSgctProjectionToModelTransformMatrix = program.uniformLocation("dSgctProjectionToModelTransformMatrix"); - _uniformCache2.dFragmentToWorldMatrix = program.uniformLocation("dFragmentToWorldMatrix"); - _uniformCache2.dCamRigPos = program.uniformLocation("dCamRigPos"); - _uniformCache2.dCamPosObj = program.uniformLocation("dCamPosObj"); - _uniformCache2.sunDirectionObj = program.uniformLocation("sunDirectionObj"); - _uniformCache2.hardShadows = program.uniformLocation("hardShadows"); - _uniformCache2.transmittanceTexture = program.uniformLocation("transmittanceTexture"); - _uniformCache2.irradianceTexture = program.uniformLocation("irradianceTexture"); - _uniformCache2.inscatterTexture = program.uniformLocation("inscatterTexture"); -} - -void AtmosphereDeferredcaster::update(const UpdateData&) { - -} - void AtmosphereDeferredcaster::setModelTransform(const glm::dmat4& transform) { _modelTransform = transform; } @@ -500,13 +475,13 @@ void AtmosphereDeferredcaster::setPlanetRadius(float planetRadius) { } void AtmosphereDeferredcaster::setPlanetAverageGroundReflectance( - float averageGReflectance) + float averageGReflectance) { _planetAverageGroundReflectance = averageGReflectance; } void AtmosphereDeferredcaster::setPlanetGroundRadianceEmittion( - float groundRadianceEmittion) + float groundRadianceEmittion) { _planetGroundRadianceEmittion = groundRadianceEmittion; } @@ -537,19 +512,19 @@ void AtmosphereDeferredcaster::setSunRadianceIntensity(float sunRadiance) { } void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( - const glm::vec3& rayScattCoeff) + const glm::vec3& rayScattCoeff) { _rayleighScatteringCoeff = rayScattCoeff; } void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( - const glm::vec3& ozoneExtCoeff) + const glm::vec3& ozoneExtCoeff) { _ozoneExtinctionCoeff = ozoneExtCoeff; } void AtmosphereDeferredcaster::setMieScatteringCoefficients( - const glm::vec3& mieScattCoeff) + const glm::vec3& mieScattCoeff) { _mieScatteringCoeff = mieScattCoeff; } @@ -568,7 +543,7 @@ void AtmosphereDeferredcaster::setHardShadows(bool enabled) { } void AtmosphereDeferredcaster::setShadowConfigArray( - const std::vector& shadowConfigArray) + const std::vector& shadowConfigArray) { _shadowConfArray = shadowConfigArray; } @@ -578,7 +553,7 @@ void AtmosphereDeferredcaster::enableSunFollowing(bool enable) { } void AtmosphereDeferredcaster::setPrecalculationTextureScale( - float preCalculatedTexturesScale) + float preCalculatedTexturesScale) { _calculationTextureScale = preCalculatedTexturesScale; _transmittance_table_width *= static_cast(_calculationTextureScale); @@ -844,8 +819,8 @@ void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { } void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, - GLenum drawBuffers[1], - GLsizei vertexSize) + GLenum drawBuffers[1], + GLsizei vertexSize) { ghoul::opengl::TextureUnit transmittanceTableTextureUnit; ghoul::opengl::TextureUnit irradianceTableTextureUnit; @@ -1070,9 +1045,9 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, } std::stringstream sst; if (_saveCalculationTextures) { - sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _mu_s_samples * _nu_samples, _mu_samples); + sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _mu_s_samples * _nu_samples, _mu_samples); } _deltaJProgramObject->deactivate(); @@ -1119,10 +1094,10 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _delta_e_table_width, _delta_e_table_height); + sst.str(std::string()); + sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _delta_e_table_width, _delta_e_table_height); } _irradianceSupTermsProgramObject->deactivate(); @@ -1154,14 +1129,14 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT0, - sst.str(), - _mu_s_samples * _nu_samples, - _mu_samples - ); + sst.str(std::string()); + sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile( + GL_COLOR_ATTACHMENT0, + sst.str(), + _mu_s_samples * _nu_samples, + _mu_samples + ); } _inScatteringSupTermsProgramObject->deactivate(); @@ -1188,10 +1163,10 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, loadAtmosphereDataIntoShaderProgram(_irradianceFinalProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _delta_e_table_width, _delta_e_table_height); + sst.str(std::string()); + sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _delta_e_table_width, _delta_e_table_height); } _irradianceFinalProgramObject->deactivate(); @@ -1217,10 +1192,10 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _mu_s_samples * _nu_samples, _mu_samples); + sst.str(std::string()); + sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _mu_s_samples * _nu_samples, _mu_samples); } _deltaSSupTermsProgramObject->deactivate(); @@ -1323,7 +1298,7 @@ void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloa } void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( - std::unique_ptr& shaderProg) + std::unique_ptr& shaderProg) { shaderProg->setUniform("Rg", _atmospherePlanetRadius); shaderProg->setUniform("Rt", _atmosphereRadius); @@ -1358,7 +1333,7 @@ void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( } void AtmosphereDeferredcaster::checkFrameBufferState( - const std::string& codePosition) const + const std::string& codePosition) const { if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framework not built. " + codePosition); @@ -1379,8 +1354,8 @@ void AtmosphereDeferredcaster::checkFrameBufferState( break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: LERROR("Returned if GL_READ_BUFFER is not GL_NONE and the value of " - "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color attachment " - "point named by GL_READ_BUFFER."); + "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color attachment " + "point named by GL_READ_BUFFER."); break; case GL_FRAMEBUFFER_UNSUPPORTED: LERROR("Returned if the combination of internal formats of the attached " @@ -1418,25 +1393,25 @@ void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVer } void AtmosphereDeferredcaster::step3DTexture( - std::unique_ptr& shaderProg, - int layer, bool doCalc) + std::unique_ptr& shaderProg, + int layer, bool doCalc) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering if (doCalc) { - float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; - float atm2 = _atmosphereRadius * _atmosphereRadius; - float diff = atm2 - earth2; - float ri = static_cast(layer) / static_cast(_r_samples - 1); - float ri_2 = ri * ri; + float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; + float atm2 = _atmosphereRadius * _atmosphereRadius; + float diff = atm2 - earth2; + float ri = static_cast(layer) / static_cast(_r_samples - 1); + float ri_2 = ri * ri; float epsilon = (layer == 0) ? 0.01f : (layer == (static_cast(_r_samples) - 1)) ? -0.001f : 0.0f; - float r = sqrtf(earth2 + ri_2 * diff) + epsilon; - float dminG = r - _atmospherePlanetRadius; - float dminT = _atmosphereRadius - r; - float dh = sqrtf(r * r - earth2); - float dH = dh + sqrtf(diff); + float r = sqrtf(earth2 + ri_2 * diff) + epsilon; + float dminG = r - _atmospherePlanetRadius; + float dminT = _atmosphereRadius - r; + float dh = sqrtf(r * r - earth2); + float dH = dh + sqrtf(diff); shaderProg->setUniform("r", r); shaderProg->setUniform("dhdH", dminT, dH, dminG, dh); @@ -1446,8 +1421,8 @@ void AtmosphereDeferredcaster::step3DTexture( } void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, - const std::string& fileName, - int width, int height) const + const std::string& fileName, + int width, int height) const { std::fstream ppmFile; @@ -1483,8 +1458,8 @@ void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachme for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { ppmFile << static_cast(pixels[k]) << " " - << static_cast(pixels[k + 1]) << " " - << static_cast(pixels[k + 2]) << " "; + << static_cast(pixels[k + 1]) << " " + << static_cast(pixels[k + 2]) << " "; k += 3; } ppmFile << std::endl; @@ -1496,8 +1471,8 @@ void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachme } bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, - const glm::dvec3& position, - double radius) const + const glm::dvec3& position, + double radius) const { // Frustum Planes @@ -1514,36 +1489,36 @@ bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, glm::dvec3 farNormal = col4 - col3; // Plane Distances - double leftDistance = MVMatrix[15] + MVMatrix[12]; - double rightDistance = MVMatrix[15] - MVMatrix[12]; + double leftDistance = MVMatrix[15] + MVMatrix[12]; + double rightDistance = MVMatrix[15] - MVMatrix[12]; double bottomDistance = MVMatrix[15] + MVMatrix[13]; - double topDistance = MVMatrix[15] - MVMatrix[13]; - double nearDistance = MVMatrix[15] + MVMatrix[14]; - double farDistance = MVMatrix[15] - MVMatrix[14]; + double topDistance = MVMatrix[15] - MVMatrix[13]; + double nearDistance = MVMatrix[15] + MVMatrix[14]; + double farDistance = MVMatrix[15] - MVMatrix[14]; // Normalize Planes double invMag = 1.0 / glm::length(leftNormal); - leftNormal *= invMag; + leftNormal *= invMag; leftDistance *= invMag; invMag = 1.0 / glm::length(rightNormal); - rightNormal *= invMag; + rightNormal *= invMag; rightDistance *= invMag; invMag = 1.0 / glm::length(bottomNormal); - bottomNormal *= invMag; + bottomNormal *= invMag; bottomDistance *= invMag; invMag = 1.0 / glm::length(topNormal); - topNormal *= invMag; + topNormal *= invMag; topDistance *= invMag; invMag = 1.0 / glm::length(nearNormal); - nearNormal *= invMag; + nearNormal *= invMag; nearDistance *= invMag; invMag = 1.0 / glm::length(farNormal); - farNormal *= invMag; + farNormal *= invMag; farDistance *= invMag; if ((glm::dot(leftNormal, position) + leftDistance) < -radius) { @@ -1563,7 +1538,7 @@ bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, } // The far plane testing is disabled because the atm has no depth. /*else if ((glm::dot(farNormal, position) + farDistance) < -radius) { - return false; + return false; }*/ return true; diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 02f88e0c37..8be6dfebc0 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -84,14 +84,21 @@ uniform sampler2DMS mainPositionTexture; uniform sampler2DMS mainNormalTexture; uniform sampler2DMS mainColorTexture; +// Model Transform Matrix Used for Globe Rendering +uniform dmat4 dSgctEyeToOSEyeTranform; // SGCT Eye to OS Eye * +uniform dmat4 dInverseSgctProjectionMatrix; // Clip to SGCT Eye * +uniform dmat4 dCamScaleTransform; +uniform dmat4 dInverseCamScaleTransform; +uniform dmat4 dInverseCamRotTransform; uniform dmat4 dInverseModelTransformMatrix; uniform dmat4 dModelTransformMatrix; -uniform dmat4 dFragmentToWorldMatrix; -uniform dmat4 dSgctProjectionToModelTransformMatrix; +//uniform dmat4 dSGCTEyeToOSWorldTransformMatrix; +uniform dvec4 dObjpos; uniform dvec3 dCamRigPos; -uniform dvec4 dCamPosObj; +uniform dvec3 dCampos; uniform dvec3 sunDirectionObj; +uniform dvec3 ellipsoidRadii; /******************************************************************************* ***** ALL CALCULATIONS FOR ECLIPSE ARE IN METERS AND IN WORLD SPACE SYSTEM **** @@ -246,28 +253,38 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, // ====================================== // ======= Avoiding Some Matrices ======= - // Compute positions and directions in object space. + // Compute positions and directions in world space. dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], - msaaSamplePatter[mssaSample+1]); - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 0.0, 1.0); + msaaSamplePatter[mssaSample+1]); + dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 1.0, 1.0); - // Clip to Object Coords - dvec4 objectCoords = dSgctProjectionToModelTransformMatrix * clipCoords; + // Clip to SGCT Eye + dvec4 sgctEyeCoords = dInverseSgctProjectionMatrix * clipCoords; + // SGCT Eye to OS Eye + dvec4 tOSEyeCoords = dSgctEyeToOSEyeTranform * sgctEyeCoords; + + // OS Eye to World coords + dvec4 offsetWorldCoords = dInverseCamRotTransform * dInverseCamScaleTransform * tOSEyeCoords; + dvec4 worldCoords = dvec4(dvec3(offsetWorldCoords) + dCampos, 1.0); + + // World to Object + dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; + // Planet Position in Object Space // JCC: Applying the inverse of the model transformation on the object postion in World // space results in imprecision. planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); + //planetPositionObjectCoords = dInverseModelTransformMatrix * dvec4(dObjpos.xyz, 1.0); - // Camera Position in Object Space (in meters) - cameraPositionInObject = dCamPosObj; - + // Camera Position in Object Space + cameraPositionInObject = dInverseModelTransformMatrix * dvec4(dCampos, 1.0); + // ============================ // ====== Building Ray ======== // Ray in object space (in KM) ray.origin = cameraPositionInObject * dvec4(0.001, 0.001, 0.001, 1.0); - //ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); - ray.direction = dvec4(normalize((objectCoords.xyz * dvec3(0.001))- ray.origin.xyz), 0.0); + ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); } /* @@ -374,12 +391,11 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor // From cosine law where t = distance between x and x0 // r0^2 = r^2 + t^2 - 2 * r * t * cos(PI-theta) r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); - float invr0 = 1.0/r0; // From the dot product: cos(theta0) = (x0 dot v)/(||ro||*||v||) // mu0 = ((x + t) dot v) / r0 // mu0 = (x dot v + t dot v) / r0 // mu0 = (r*mu + t) / r0 - mu0 = (r * mu + t) * invr0; + mu0 = (r * mu + t) / r0; vec4 inScatterAboveX = texture4D(inscatterTexture, r, mu, muSun, nu); vec4 inScatterAboveXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); // Attention for the attenuation.r value applied to the S_Mie @@ -388,7 +404,7 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor // Below Horizon mu = muHorizon + INTERPOLATION_EPS; r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); - mu0 = (r * mu + t) * invr0; + mu0 = (r * mu + t) / r0; vec4 inScatterBelowX = texture4D(inscatterTexture, r, mu, muSun, nu); vec4 inScatterBelowXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); // Attention for the attenuation.r value applied to the S_Mie @@ -453,8 +469,7 @@ vec3 groundColor(const vec3 x, const float t, const vec3 v, const vec3 s, const vec3 x0 = x + t * v; float r0 = length(x0); // Normal of intersection point. - // Normal must be normalized. - vec3 n = normal; + vec3 n = normalize(normal); //vec4 groundReflectance = groundColor * vec4(.37); vec4 groundReflectance = groundColor * vec4(groundRadianceEmittion, groundRadianceEmittion, groundRadianceEmittion, 1.0f); @@ -532,30 +547,25 @@ vec3 sunColor(const vec3 x, const float t, const vec3 v, const vec3 s, const flo return transmittance * sunFinalColor; } -void main() { - ivec2 fragCoords = ivec2(gl_FragCoord); - +void main() { if (cullAtmosphere == 0) { - vec4 atmosphereFinalColor = vec4(0.0f); - int nSamples = 1; + // First we determine if the pixel is complex (different fragments on it) bool complex = false; vec4 oldColor, currentColor; //vec4 colorArray[16]; //int colorIndexArray[16]; - oldColor = texelFetch(mainColorTexture, fragCoords, 0); + oldColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), 0); //colorArray[0] = oldColor; //colorIndexArray[0] = 0; for (int i = 1; i < nAaSamples; i++) { - //vec4 normal = texelFetch(mainNormalTexture, fragCoords, i); - vec4 currentColor = texelFetch(mainColorTexture, fragCoords, i); + //vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); + vec4 currentColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); //colorArray[i] = currentColor; if (currentColor != oldColor) { complex = true; - //nSamples = nAaSamples; - nSamples = nAaSamples > 1 ? nAaSamples / 2 : nAaSamples; break; // for (int c = 0; c < nAaSamples; c++) { // if (currentColor == colorArray[c]) { @@ -574,10 +584,18 @@ void main() { // } oldColor = currentColor; } + + int nSamples = 1; + if (complex) { + //nSamples = nAaSamples; + nSamples = nAaSamples > 1 ? nAaSamples/2 : nAaSamples; + } for (int i = 0; i < nSamples; i++) { - // Color from G-Buffer - vec4 color = texelFetch(mainColorTexture, fragCoords, i); + vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); + vec4 color = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); + // Data in the mainPositionTexture are written in view space (view plus camera rig) + vec4 position = texelFetch(mainPositionTexture, ivec2(gl_FragCoord), i); // Ray in object space dRay ray; @@ -589,39 +607,47 @@ void main() { cameraPositionInObject); bool insideATM = false; - double offset = 0.0; // in Km - double maxLength = 0.0; // in Km + double offset = 0.0; + double maxLength = 0.0; bool intersectATM = false; - intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, ray, - Rt - (ATM_EPSILON * 0.001), insideATM, offset, maxLength ); - + // Instead of ray-ellipsoid intersection lets transform the ray to a sphere: + dRay transfRay; + transfRay.origin = ray.origin; + transfRay.direction = ray.direction; + + // transfRay.origin.z *= 1000.0/ellipsoidRadii.x; + // transfRay.direction.z *= 1000.0/ellipsoidRadii.x; + // transfRay.origin.x *= 1000.0/ellipsoidRadii.y; + // transfRay.direction.x *= 1000.0/ellipsoidRadii.y; + // transfRay.origin.y *= 1000.0/ellipsoidRadii.z; + // transfRay.direction.y *= 1000.0/ellipsoidRadii.z; + // transfRay.direction.xyz = normalize(transfRay.direction.xyz); + + intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, transfRay, + Rt - ATM_EPSILON/100.0, insideATM, offset, maxLength ); + if ( intersectATM ) { // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel // in the depth buffer is less than the distance to the atmosphere then the atmosphere // is occluded - // Fragments positions into G-Buffer are written in SGCT Eye Space (View plus Camera Rig Coords) + // Fragments positions into G-Buffer are written in OS Eye Space (Camera Rig Coords) // when using their positions later, one must convert them to the planet's coords - // Get data from G-Buffer - vec4 normal = texelFetch(mainNormalTexture, fragCoords, i); - // Data in the mainPositionTexture are written in view space (view plus camera rig) - vec4 position = texelFetch(mainPositionTexture, fragCoords, i); - - // OS Eye to World coords - dvec4 fragWorldCoords = dFragmentToWorldMatrix * position; - + // OS Eye to World coords + dvec4 fragWorldCoordsOffset = dInverseCamRotTransform * dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; + dvec4 fragWorldCoords = dvec4(dvec3(fragWorldCoordsOffset) + dCamRigPos, 1.0); + // World to Object (Normal and Position in meters) - dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; - + dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; // Distance of the pixel in the gBuffer to the observer // JCC (12/12/2017): AMD distance function is buggy. //double pixelDepth = distance(cameraPositionInObject.xyz, fragObjectCoords.xyz); double pixelDepth = length(cameraPositionInObject.xyz - fragObjectCoords.xyz); - // JCC (12/13/2017): Trick to remove floating error in texture. + // JCC (12/13/2017): TRick to remove floating error in texture. // We see a squared noise on planet's surface when seeing the planet // from far away. float dC = float(length(cameraPositionInObject.xyz)); @@ -633,13 +659,13 @@ void main() { float x2 = 1e9; float diffGreek = beta - alpha; float diffDist = x2 - x1; - float varA = diffGreek/diffDist; - float varB = (alpha - varA * x1); - pixelDepth += double(varA * dC + varB); + float varA = diffGreek/diffDist; + float varB = (alpha - varA * x1); + pixelDepth += double(varA * dC + varB); } // All calculations are done in Km: - pixelDepth *= 0.001; + pixelDepth *= 0.001; fragObjectCoords.xyz *= 0.001; if (position.xyz != vec3(0.0) && (pixelDepth < offset)) { @@ -654,9 +680,9 @@ void main() { // If the observer is already inside the atm, offset = 0.0 // and no changes at all. vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); - float r = 0.0f;//length(x); + float r = 0.0;//length(x); vec3 v = vec3(ray.direction.xyz); - float mu = 0.0f;//dot(x, v) / r; + float mu = 0.0;//dot(x, v) / r; vec3 s = vec3(sunDirectionObj); float tF = float(maxLength - t); @@ -665,7 +691,7 @@ void main() { // next comparison with the planet's ground make sense: pixelDepth -= offset; - dvec4 onATMPos = dModelTransformMatrix * dvec4(x * 1000.0, 1.0); + dvec4 onATMPos = dModelTransformMatrix * dvec4(x*1000.0, 1.0); vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, fragWorldCoords.xyz, true); @@ -693,7 +719,7 @@ void main() { else { // no intersection //discard; atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); - } + } } renderTarget = atmosphereFinalColor / float(nSamples); @@ -702,7 +728,7 @@ void main() { if (firstPaint) { vec4 bColor = vec4(0.0f); for (int f = 0; f < nAaSamples; f++) { - bColor += texelFetch(mainColorTexture, fragCoords, f); + bColor += texelFetch(mainColorTexture, ivec2(gl_FragCoord), f); } bColor /= float(nAaSamples); renderTarget = vec4(HDR(bColor.xyz * backgroundConstant, atmExposure), bColor.a); @@ -714,4 +740,3 @@ void main() { } } - From c50c5637873916c093083905d09c9beb5da198c1 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 21 Mar 2018 18:38:28 -0400 Subject: [PATCH 21/79] New stars for stereo rendering. --- modules/space/rendering/renderablestars.cpp | 21 ++++++-- modules/space/shaders/star_fs.glsl | 2 + modules/space/shaders/star_ge.glsl | 57 +++++++++++++++++++-- modules/space/shaders/star_vs.glsl | 5 +- 4 files changed, 77 insertions(+), 8 deletions(-) diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index e7f04183e3..9d2e90ab4a 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -42,6 +42,9 @@ #include #include #include +#include + +//#define USING_STELLAR_TEST_GRID namespace { constexpr const char* _loggerCat = "RenderableStars"; @@ -358,6 +361,8 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { glm::vec2(OsEng.renderEngine().renderingResolution()) ); + _program->setUniform("eyePosition", glm::vec3(data.camera.eyePositionVec3())); + ghoul::opengl::TextureUnit psfUnit; psfUnit.activate(); _pointSpreadFunctionTexture->bind(); @@ -649,7 +654,7 @@ bool RenderableStars::readSpeckFile() { file.seekg(position); break; } - + if (line.substr(0, 7) == "datavar") { // datavar lines are structured as follows: // datavar # description @@ -667,6 +672,9 @@ bool RenderableStars::readSpeckFile() { _nValuesPerStar += 3; // X Y Z are not counted in the Speck file indices + float minLumValue = std::numeric_limits::max(); + float maxLumValue = std::numeric_limits::min(); + do { std::vector values(_nValuesPerStar); @@ -683,11 +691,18 @@ bool RenderableStars::readSpeckFile() { break; } } + minLumValue = values[4] < minLumValue ? values[4] : minLumValue; + maxLumValue = values[4] > maxLumValue ? values[4] : maxLumValue; if (!nullArray) { _fullData.insert(_fullData.end(), values.begin(), values.end()); } } while (!file.eof()); + // Normalize Luminosity: + for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { + _fullData[i + 4] = (_fullData[i + 4] - minLumValue) / (maxLumValue - minLumValue); + } + return true; } @@ -768,8 +783,8 @@ void RenderableStars::createDataSlice(ColorOption option) { } }; #ifdef USING_STELLAR_TEST_GRID - layout.value.bvColor = _fullData[i + 3]; - layout.value.luminance = _fullData[i + 3]; + layout.value.bvColor = 0.650;// _fullData[i + 3]; + layout.value.luminance = _fullData[i + 4]; layout.value.absoluteMagnitude = _fullData[i + 3]; #else layout.value.bvColor = _fullData[i + 3]; diff --git a/modules/space/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl index 0c53b621b2..a128debca7 100644 --- a/modules/space/shaders/star_fs.glsl +++ b/modules/space/shaders/star_fs.glsl @@ -36,6 +36,7 @@ uniform sampler1D colorTexture; uniform float magnitudeExponent; uniform float sharpness; uniform int colorOption; +uniform vec3 eyePosition; in vec4 vs_position; in vec4 ge_gPosition; @@ -44,6 +45,7 @@ in vec3 ge_velocity; in float ge_speed; in vec2 texCoord; in float ge_observationDistance; +in vec4 ge_worldPosition; vec4 bv2rgb(float bv) { // BV is [-0.4,2.0] diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index 3b2b95573c..64389c6e5d 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -32,6 +32,7 @@ in vec3 vs_brightness[]; in vec3 vs_velocity[]; in vec4 vs_gPosition[]; in float vs_speed[]; +in vec4 vs_worldPosition[]; layout(triangle_strip, max_vertices = 4) out; @@ -42,11 +43,13 @@ out vec3 ge_velocity; out float ge_speed; out vec2 texCoord; out float ge_observationDistance; +out vec4 ge_worldPosition; uniform float viewScaling; uniform float scaleFactor; uniform float billboardSize; uniform vec2 screenSize; +uniform vec3 eyePosition; const vec2 corners[4] = vec2[4]( vec2(0.0, 1.0), @@ -56,15 +59,63 @@ const vec2 corners[4] = vec2[4]( ); void main() { + + if ((vs_worldPosition[0].x == 0.0) && + (vs_worldPosition[0].y == 0.0) && + (vs_worldPosition[0].z == 0.0)) + { + return; + } + ge_brightness = vs_brightness[0]; ge_velocity = vs_velocity[0]; ge_speed = vs_speed[0]; - - float absoluteMagnitude = vs_brightness[0].z; + ge_worldPosition = vs_worldPosition[0]; vec4 projectedPoint = gl_in[0].gl_Position; - vec2 starSize = vec2(billboardSize) / screenSize * projectedPoint.w; + + float distanceToStarInParsecs = length(ge_worldPosition.xyz / 3.0856776E16 - eyePosition / 3.0856776E16); + float luminosity = ge_brightness.y; + + // Working like Partiview + float pSize = 3.0E5; + float slum = 1.0; + float samplingFactor = 1.0; + float apparentBrightness = (pSize * slum * samplingFactor * luminosity) / (distanceToStarInParsecs * distanceToStarInParsecs); + + vec2 multiplier = vec2(apparentBrightness * projectedPoint.w); + + // Max Star Sizes: + // Fragment Coords: + vec2 bottomLeft = screenSize * ((projectedPoint.xy + vec2(multiplier) * corners[1])/projectedPoint.w + vec2(1.0)) - vec2(0.5); + vec2 topRight = screenSize * ((projectedPoint.xy + vec2(multiplier) * corners[2])/projectedPoint.w + vec2(1.0)) - vec2(0.5); + + float height = abs(topRight.y - bottomLeft.y); + float width = abs(topRight.x - bottomLeft.x); + float var = (height + width); + + float maxBillboardSize = billboardSize; + float minBillboardSize = 1.0; + + if ((height > maxBillboardSize) || + (width > maxBillboardSize)) { + //if (height > maxBillboardSize) { + float correctionScale = height > maxBillboardSize ? maxBillboardSize / (topRight.y - bottomLeft.y) : + maxBillboardSize / (topRight.x - bottomLeft.x); + multiplier *= correctionScale; + } else { + if (width < 2.0f * minBillboardSize) { + float maxVar = 2.0f * minBillboardSize; + float minVar = minBillboardSize; + float ta = ( (var - minVar)/(maxVar - minVar) ); + if (ta == 0.0f) + return; + } + } + + vec2 starSize = multiplier; + for (int i = 0; i < 4; i++) { vs_position = gl_in[0].gl_Position; gl_Position = projectedPoint + vec4(starSize * (corners[i] - 0.5), 0.0, 0.0); diff --git a/modules/space/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl index 594bcfbc5a..f204842af3 100644 --- a/modules/space/shaders/star_vs.glsl +++ b/modules/space/shaders/star_vs.glsl @@ -35,6 +35,7 @@ out vec3 vs_brightness; out vec3 vs_velocity; out float vs_speed; out vec4 vs_gPosition; +out vec4 vs_worldPosition; uniform mat4 model; uniform mat4 view; @@ -46,8 +47,8 @@ void main() { vs_speed = in_speed; vec3 modelPosition = in_position.xyz; - - vec4 viewPosition = view * model * vec4(modelPosition, 1.0); + vs_worldPosition = model * vec4(modelPosition, 1.0); + vec4 viewPosition = view * vs_worldPosition; vs_gPosition = viewPosition; gl_Position = projection * vs_gPosition; From e660699ca577a339d448e12ef8da4752f318a536 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 22 Mar 2018 17:14:04 +0100 Subject: [PATCH 22/79] Do not interpolate stereo distance if there is no previous focus node --- .../openspace/interaction/orbitalnavigator.h | 1 + src/interaction/orbitalnavigator.cpp | 23 +++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index b6ace82be8..1329158e79 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -97,6 +97,7 @@ private: glm::dvec3 _previousFocusNodePosition; glm::dquat _previousFocusNodeRotation; double _currentCameraToSurfaceDistance; + bool _directlySetStereoDistance = false; Interpolator _rotateToFocusNodeInterpolator; Interpolator _cameraToSurfaceDistanceInterpolator; diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index f95c9fb7b7..607d51980d 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -324,10 +324,15 @@ void OrbitalNavigator::updateCameraStateFromMouseStates(Camera& camera, double d double targetCameraToSurfaceDistance = glm::length( cameraToSurfaceVector(camPos, centerPos, posHandle) ); - _currentCameraToSurfaceDistance = interpolateCameraToSurfaceDistance( - deltaTime, - _currentCameraToSurfaceDistance, - targetCameraToSurfaceDistance); + if (_directlySetStereoDistance) { + _currentCameraToSurfaceDistance = targetCameraToSurfaceDistance; + _directlySetStereoDistance = false; + } else { + _currentCameraToSurfaceDistance = interpolateCameraToSurfaceDistance( + deltaTime, + _currentCameraToSurfaceDistance, + targetCameraToSurfaceDistance); + } camera.setScaling( _stereoscopicDepthOfFocusSurface / @@ -357,11 +362,15 @@ glm::dvec3 OrbitalNavigator::cameraToSurfaceVector( } void OrbitalNavigator::setFocusNode(SceneGraphNode* focusNode) { + if (!_focusNode) { + _directlySetStereoDistance = true; + } + _focusNode = focusNode; - if (_focusNode != nullptr) { - _previousFocusNodePosition = _focusNode->worldPosition(); - _previousFocusNodeRotation = glm::quat_cast(_focusNode->worldRotationMatrix()); + if (focusNode != nullptr) { + _previousFocusNodePosition = focusNode->worldPosition(); + _previousFocusNodeRotation = glm::quat_cast(focusNode->worldRotationMatrix()); } } From e8b260915ef3237855a9d8435f0c4aeba62d5e26 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 22 Mar 2018 18:15:56 +0100 Subject: [PATCH 23/79] Render GUI on whole screen when rendering side-by-side and top-bottom stereo --- .../engine/wrapper/sgctwindowwrapper.h | 1 + .../openspace/engine/wrapper/windowwrapper.h | 9 +++++ modules/imgui/imguimodule.cpp | 3 ++ modules/webbrowser/src/screenspacebrowser.cpp | 4 +-- src/engine/wrapper/sgctwindowwrapper.cpp | 35 +++++++++++-------- src/engine/wrapper/windowwrapper.cpp | 4 +++ 6 files changed, 40 insertions(+), 16 deletions(-) diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h index 14da478f65..4bb68cf43f 100644 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ b/include/openspace/engine/wrapper/sgctwindowwrapper.h @@ -53,6 +53,7 @@ public: 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::vec2 dpiScaling() const override; diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index 259faca1e6..f1b583be41 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -137,6 +137,15 @@ public: */ 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 in stereoscopic side-by-side/top-bottom rendeirng when rendering + * one of the eyes. + * \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. diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index e8b8d0b3ff..86642533ba 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -171,6 +171,9 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { 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(); bool showGui = wrapper.hasGuiWindow() ? wrapper.isGuiWindow() : true; if (wrapper.isMaster() && showGui) { diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index 7ae604f5e3..aa2e2129fc 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -57,7 +57,7 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) _url = dictionary.value(KeyUrl); } - glm::vec2 windowDimensions = OsEng.windowWrapper().currentWindowSize(); + glm::vec2 windowDimensions = OsEng.windowWrapper().currentSubwindowSize(); _dimensions = windowDimensions; _texture = std::make_unique(glm::uvec3(windowDimensions, 1.0f)); @@ -77,7 +77,7 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) } bool ScreenSpaceBrowser::initialize() { - _originalViewportSize = OsEng.windowWrapper().currentWindowSize(); + _originalViewportSize = OsEng.windowWrapper().currentSubwindowSize(); _renderHandler->setTexture((GLuint) *_texture); createPlane(); diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index d9f2801978..6dbcb38cb6 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -123,22 +123,29 @@ uint32_t SGCTWindowWrapper::mouseButtons(int maxNumber) const { } 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()); + 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()); } } diff --git a/src/engine/wrapper/windowwrapper.cpp b/src/engine/wrapper/windowwrapper.cpp index 3cc0d7fcad..718747e09f 100644 --- a/src/engine/wrapper/windowwrapper.cpp +++ b/src/engine/wrapper/windowwrapper.cpp @@ -109,6 +109,10 @@ glm::ivec2 WindowWrapper::currentWindowSize() const { return glm::ivec2(0); } +glm::ivec2 WindowWrapper::currentSubwindowSize() const { + return currentWindowSize(); +} + glm::ivec2 WindowWrapper::currentWindowResolution() const { return currentWindowSize(); } From 6b1044122259c2aea1fd9f160a2c2f134c8dc115 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 22 Mar 2018 18:18:37 +0100 Subject: [PATCH 24/79] Fix comment --- include/openspace/engine/wrapper/windowwrapper.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index f1b583be41..34c4832f21 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -140,8 +140,8 @@ public: /** * 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 in stereoscopic side-by-side/top-bottom rendeirng when rendering - * one of the eyes. + * 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; From ecfc5fd2686071a53aa5f79bb9d0da3dab06eec5 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Fri, 23 Mar 2018 10:17:30 +0100 Subject: [PATCH 25/79] Resore indentation in AtmospherDdeferredCaster --- .../rendering/atmospheredeferredcaster.cpp | 165 +++++++++--------- 1 file changed, 82 insertions(+), 83 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 04f32d1640..236334c9ff 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -1,62 +1,61 @@ /***************************************************************************************** -* * -* 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. * -****************************************************************************************/ + * * + * 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. * + ****************************************************************************************/ -/*************************************************************************************** -* Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the -* following code. -****************************************************************************************/ + /*************************************************************************************** + * Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the + * following code. + ****************************************************************************************/ -/** -* Precomputed Atmospheric Scattering -* Copyright (c) 2008 INRIA -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* 3. Neither the name of the copyright holders nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -* THE POSSIBILITY OF SUCH DAMAGE. - -*/ + /** + * Precomputed Atmospheric Scattering + * Copyright (c) 2008 INRIA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ #include #include @@ -90,16 +89,16 @@ namespace { -const char* _loggerCat = "AtmosphereDeferredcaster"; -const char* GlslDeferredcastPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; -const char* GlslDeferredcastFSPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; -const char* GlslDeferredcastVsPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; + const char* _loggerCat = "AtmosphereDeferredcaster"; + const char* GlslDeferredcastPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; + const char* GlslDeferredcastFSPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; + const char* GlslDeferredcastVsPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; -const float ATM_EPS = 2.0; -const double KM_TO_M = 1000.0; + const float ATM_EPS = 2.0; + const double KM_TO_M = 1000.0; } // namespace namespace openspace { @@ -349,8 +348,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); casterPos *= KM_TO_M; // converting to meters - // First we determine if the caster is shadowing the current planet - // (all calculations in World Coordinates): + // First we determine if the caster is shadowing the current planet + // (all calculations in World Coordinates): glm::dvec3 planetCasterVec = casterPos - renderData.position.dvec3(); glm::dvec3 sourceCasterVec = casterPos - sourcePos; double sc_length = glm::length(sourceCasterVec); @@ -372,7 +371,6 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, shadowData.isShadowing = false; if (((d_test - rp_test) < (_atmospherePlanetRadius * KM_TO_M)) && - //if (((d_test - rp_test) < (_atmosphereRadius * KM_TO_M)) && (casterDistSun < planetDistSun)) { // The current caster is shadowing the current planet shadowData.isShadowing = true; @@ -433,8 +431,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, } void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, - ghoul::opengl::ProgramObject&) + const DeferredcastData&, + ghoul::opengl::ProgramObject&) { // Deactivate the texture units _transmittanceTableTextureUnit.deactivate(); @@ -512,7 +510,7 @@ void AtmosphereDeferredcaster::setSunRadianceIntensity(float sunRadiance) { } void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( - const glm::vec3& rayScattCoeff) + const glm::vec3& rayScattCoeff) { _rayleighScatteringCoeff = rayScattCoeff; } @@ -524,7 +522,7 @@ void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( } void AtmosphereDeferredcaster::setMieScatteringCoefficients( - const glm::vec3& mieScattCoeff) + const glm::vec3& mieScattCoeff) { _mieScatteringCoeff = mieScattCoeff; } @@ -543,7 +541,7 @@ void AtmosphereDeferredcaster::setHardShadows(bool enabled) { } void AtmosphereDeferredcaster::setShadowConfigArray( - const std::vector& shadowConfigArray) + const std::vector& shadowConfigArray) { _shadowConfArray = shadowConfigArray; } @@ -819,8 +817,8 @@ void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { } void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, - GLenum drawBuffers[1], - GLsizei vertexSize) + GLenum drawBuffers[1], + GLsizei vertexSize) { ghoul::opengl::TextureUnit transmittanceTableTextureUnit; ghoul::opengl::TextureUnit irradianceTableTextureUnit; @@ -1298,7 +1296,7 @@ void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloa } void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( - std::unique_ptr& shaderProg) + std::unique_ptr& shaderProg) { shaderProg->setUniform("Rg", _atmospherePlanetRadius); shaderProg->setUniform("Rt", _atmosphereRadius); @@ -1333,7 +1331,7 @@ void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( } void AtmosphereDeferredcaster::checkFrameBufferState( - const std::string& codePosition) const + const std::string& codePosition) const { if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framework not built. " + codePosition); @@ -1393,8 +1391,8 @@ void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVer } void AtmosphereDeferredcaster::step3DTexture( - std::unique_ptr& shaderProg, - int layer, bool doCalc) + std::unique_ptr& shaderProg, + int layer, bool doCalc) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering if (doCalc) { @@ -1421,8 +1419,9 @@ void AtmosphereDeferredcaster::step3DTexture( } void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, - const std::string& fileName, - int width, int height) const + const std::string& fileName, + int width, + int height) const { std::fstream ppmFile; @@ -1471,8 +1470,8 @@ void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachme } bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, - const glm::dvec3& position, - double radius) const + const glm::dvec3& position, + double radius) const { // Frustum Planes From d3f42edbc81660ff43e6faf9325fb4a7b8bc71e4 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Fri, 23 Mar 2018 10:17:30 +0100 Subject: [PATCH 26/79] Restore indentation in AtmosphereDeferredCaster --- .../rendering/atmospheredeferredcaster.cpp | 165 +++++++++--------- 1 file changed, 82 insertions(+), 83 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 04f32d1640..236334c9ff 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -1,62 +1,61 @@ /***************************************************************************************** -* * -* 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. * -****************************************************************************************/ + * * + * 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. * + ****************************************************************************************/ -/*************************************************************************************** -* Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the -* following code. -****************************************************************************************/ + /*************************************************************************************** + * Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the + * following code. + ****************************************************************************************/ -/** -* Precomputed Atmospheric Scattering -* Copyright (c) 2008 INRIA -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* 3. Neither the name of the copyright holders nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -* THE POSSIBILITY OF SUCH DAMAGE. - -*/ + /** + * Precomputed Atmospheric Scattering + * Copyright (c) 2008 INRIA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ #include #include @@ -90,16 +89,16 @@ namespace { -const char* _loggerCat = "AtmosphereDeferredcaster"; -const char* GlslDeferredcastPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; -const char* GlslDeferredcastFSPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; -const char* GlslDeferredcastVsPath = -"${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; + const char* _loggerCat = "AtmosphereDeferredcaster"; + const char* GlslDeferredcastPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; + const char* GlslDeferredcastFSPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; + const char* GlslDeferredcastVsPath = + "${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; -const float ATM_EPS = 2.0; -const double KM_TO_M = 1000.0; + const float ATM_EPS = 2.0; + const double KM_TO_M = 1000.0; } // namespace namespace openspace { @@ -349,8 +348,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, ); casterPos *= KM_TO_M; // converting to meters - // First we determine if the caster is shadowing the current planet - // (all calculations in World Coordinates): + // First we determine if the caster is shadowing the current planet + // (all calculations in World Coordinates): glm::dvec3 planetCasterVec = casterPos - renderData.position.dvec3(); glm::dvec3 sourceCasterVec = casterPos - sourcePos; double sc_length = glm::length(sourceCasterVec); @@ -372,7 +371,6 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, shadowData.isShadowing = false; if (((d_test - rp_test) < (_atmospherePlanetRadius * KM_TO_M)) && - //if (((d_test - rp_test) < (_atmosphereRadius * KM_TO_M)) && (casterDistSun < planetDistSun)) { // The current caster is shadowing the current planet shadowData.isShadowing = true; @@ -433,8 +431,8 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, } void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, - ghoul::opengl::ProgramObject&) + const DeferredcastData&, + ghoul::opengl::ProgramObject&) { // Deactivate the texture units _transmittanceTableTextureUnit.deactivate(); @@ -512,7 +510,7 @@ void AtmosphereDeferredcaster::setSunRadianceIntensity(float sunRadiance) { } void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( - const glm::vec3& rayScattCoeff) + const glm::vec3& rayScattCoeff) { _rayleighScatteringCoeff = rayScattCoeff; } @@ -524,7 +522,7 @@ void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( } void AtmosphereDeferredcaster::setMieScatteringCoefficients( - const glm::vec3& mieScattCoeff) + const glm::vec3& mieScattCoeff) { _mieScatteringCoeff = mieScattCoeff; } @@ -543,7 +541,7 @@ void AtmosphereDeferredcaster::setHardShadows(bool enabled) { } void AtmosphereDeferredcaster::setShadowConfigArray( - const std::vector& shadowConfigArray) + const std::vector& shadowConfigArray) { _shadowConfArray = shadowConfigArray; } @@ -819,8 +817,8 @@ void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { } void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, - GLenum drawBuffers[1], - GLsizei vertexSize) + GLenum drawBuffers[1], + GLsizei vertexSize) { ghoul::opengl::TextureUnit transmittanceTableTextureUnit; ghoul::opengl::TextureUnit irradianceTableTextureUnit; @@ -1298,7 +1296,7 @@ void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloa } void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( - std::unique_ptr& shaderProg) + std::unique_ptr& shaderProg) { shaderProg->setUniform("Rg", _atmospherePlanetRadius); shaderProg->setUniform("Rt", _atmosphereRadius); @@ -1333,7 +1331,7 @@ void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( } void AtmosphereDeferredcaster::checkFrameBufferState( - const std::string& codePosition) const + const std::string& codePosition) const { if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framework not built. " + codePosition); @@ -1393,8 +1391,8 @@ void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVer } void AtmosphereDeferredcaster::step3DTexture( - std::unique_ptr& shaderProg, - int layer, bool doCalc) + std::unique_ptr& shaderProg, + int layer, bool doCalc) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering if (doCalc) { @@ -1421,8 +1419,9 @@ void AtmosphereDeferredcaster::step3DTexture( } void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, - const std::string& fileName, - int width, int height) const + const std::string& fileName, + int width, + int height) const { std::fstream ppmFile; @@ -1471,8 +1470,8 @@ void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachme } bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, - const glm::dvec3& position, - double radius) const + const glm::dvec3& position, + double radius) const { // Frustum Planes From 5da36f290b81b90abd32f27af627064ad1027f1d Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 26 Mar 2018 13:40:32 +0200 Subject: [PATCH 27/79] Start to optimize atmosphere rendering --- .../rendering/atmospheredeferredcaster.cpp | 35 +- .../shaders/atmosphere_deferred_fs.glsl | 359 ++++++++---------- 2 files changed, 189 insertions(+), 205 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 236334c9ff..234fceedfe 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -187,8 +187,8 @@ void AtmosphereDeferredcaster::deinitialize() { } void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, - const DeferredcastData&, - ghoul::opengl::ProgramObject& program) + const DeferredcastData&, + ghoul::opengl::ProgramObject& program) { // Atmosphere Frustum Culling glm::dvec3 tPlanetPosWorld = glm::dvec3( @@ -250,6 +250,22 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("dInverseModelTransformMatrix", inverseModelMatrix); program.setUniform("dModelTransformMatrix", _modelTransform); + + glm::dmat4 eyeToModel = + inverseModelMatrix * + glm::inverse(renderData.camera.combinedViewMatrix()); + + program.setUniform("eyeToModel", + glm::mat4(eyeToModel)); + + glm::dmat4 clipToModel = + eyeToModel * + glm::inverse(glm::dmat4(renderData.camera.projectionMatrix())); + + program.setUniform("clipToModel", + glm::mat4(clipToModel)); + + // The following scale comes from PSC transformations. glm::dmat4 dfScaleCamTransf = glm::scale(glm::dvec3(1.0)); program.setUniform( @@ -294,6 +310,21 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dvec3 camRigPos = renderData.camera.positionVec3(); program.setUniform("dCamRigPos", camRigPos); + + glm::dmat4 tempTransform = + glm::mat4_cast( + static_cast(renderData.camera.rotationQuaternion()) + ) * + glm::inverse(renderData.camera.viewScaleMatrix()) * + dSgctEye2OSEye * + dInverseProjection; + + program.setUniform("tempTransform", glm::mat4(tempTransform)); + + glm::dmat4 eyeToWorldTransform = + glm::inverse(renderData.camera.combinedViewMatrix()); + program.setUniform("eyeToWorld", glm::mat4(eyeToWorldTransform)); + double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( "SUN", diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 8be6dfebc0..0c0412dd3d 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -85,16 +85,15 @@ uniform sampler2DMS mainNormalTexture; uniform sampler2DMS mainColorTexture; // Model Transform Matrix Used for Globe Rendering -uniform dmat4 dSgctEyeToOSEyeTranform; // SGCT Eye to OS Eye * -uniform dmat4 dInverseSgctProjectionMatrix; // Clip to SGCT Eye * -uniform dmat4 dCamScaleTransform; -uniform dmat4 dInverseCamScaleTransform; -uniform dmat4 dInverseCamRotTransform; uniform dmat4 dInverseModelTransformMatrix; uniform dmat4 dModelTransformMatrix; //uniform dmat4 dSGCTEyeToOSWorldTransformMatrix; -uniform dvec4 dObjpos; +uniform mat4 eyeToModel; +uniform mat4 eyeToWorld; +uniform mat4 clipToModel; +uniform mat4 tempTransform; + uniform dvec3 dCamRigPos; uniform dvec3 dCampos; uniform dvec3 sunDirectionObj; @@ -258,18 +257,13 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, msaaSamplePatter[mssaSample+1]); dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 1.0, 1.0); - // Clip to SGCT Eye - dvec4 sgctEyeCoords = dInverseSgctProjectionMatrix * clipCoords; - - // SGCT Eye to OS Eye - dvec4 tOSEyeCoords = dSgctEyeToOSEyeTranform * sgctEyeCoords; - - // OS Eye to World coords - dvec4 offsetWorldCoords = dInverseCamRotTransform * dInverseCamScaleTransform * tOSEyeCoords; + dvec4 offsetWorldCoords = tempTransform * clipCoords; dvec4 worldCoords = dvec4(dvec3(offsetWorldCoords) + dCampos, 1.0); // World to Object dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; + //objectCoords = dmat4(eyeToModel) * sgctEyeCoords; + //objectCoords = dmat4(clipToModel) * clipCoords; // Planet Position in Object Space // JCC: Applying the inverse of the model transformation on the object postion in World @@ -547,196 +541,155 @@ vec3 sunColor(const vec3 x, const float t, const vec3 v, const vec3 s, const flo return transmittance * sunFinalColor; } -void main() { - if (cullAtmosphere == 0) { - vec4 atmosphereFinalColor = vec4(0.0f); - - // First we determine if the pixel is complex (different fragments on it) - bool complex = false; - vec4 oldColor, currentColor; - //vec4 colorArray[16]; - //int colorIndexArray[16]; - - oldColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), 0); - //colorArray[0] = oldColor; - //colorIndexArray[0] = 0; - for (int i = 1; i < nAaSamples; i++) { - //vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); - vec4 currentColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); - //colorArray[i] = currentColor; - if (currentColor != oldColor) { - complex = true; - break; - // for (int c = 0; c < nAaSamples; c++) { - // if (currentColor == colorArray[c]) { - // colorIndexArray[i] = c; - // break; - // } - // } - } - //else { - // for (int c = 0; c < nAaSamples; c++) { - // if (currentColor == colorArray[c]) { - // colorIndexArray[i] = c; - // break; - // } - // } - // } - oldColor = currentColor; - } - - int nSamples = 1; - if (complex) { - //nSamples = nAaSamples; - nSamples = nAaSamples > 1 ? nAaSamples/2 : nAaSamples; - } - - for (int i = 0; i < nSamples; i++) { - vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); - vec4 color = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); - // Data in the mainPositionTexture are written in view space (view plus camera rig) - vec4 position = texelFetch(mainPositionTexture, ivec2(gl_FragCoord), i); - - // Ray in object space - dRay ray; - dvec4 planetPositionObjectCoords = dvec4(0.0); - dvec4 cameraPositionInObject = dvec4(0.0); - - // Get the ray from camera to atm in object space - dCalculateRayRenderableGlobe(i * 3, ray, planetPositionObjectCoords, - cameraPositionInObject); - - bool insideATM = false; - double offset = 0.0; - double maxLength = 0.0; - - bool intersectATM = false; - - // Instead of ray-ellipsoid intersection lets transform the ray to a sphere: - dRay transfRay; - transfRay.origin = ray.origin; - transfRay.direction = ray.direction; - - // transfRay.origin.z *= 1000.0/ellipsoidRadii.x; - // transfRay.direction.z *= 1000.0/ellipsoidRadii.x; - // transfRay.origin.x *= 1000.0/ellipsoidRadii.y; - // transfRay.direction.x *= 1000.0/ellipsoidRadii.y; - // transfRay.origin.y *= 1000.0/ellipsoidRadii.z; - // transfRay.direction.y *= 1000.0/ellipsoidRadii.z; - // transfRay.direction.xyz = normalize(transfRay.direction.xyz); - - intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, transfRay, - Rt - ATM_EPSILON/100.0, insideATM, offset, maxLength ); - - if ( intersectATM ) { - // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel - // in the depth buffer is less than the distance to the atmosphere then the atmosphere - // is occluded - // Fragments positions into G-Buffer are written in OS Eye Space (Camera Rig Coords) - // when using their positions later, one must convert them to the planet's coords - - // OS Eye to World coords - dvec4 fragWorldCoordsOffset = dInverseCamRotTransform * dInverseCamScaleTransform * dSgctEyeToOSEyeTranform * position; - dvec4 fragWorldCoords = dvec4(dvec3(fragWorldCoordsOffset) + dCamRigPos, 1.0); - - // World to Object (Normal and Position in meters) - dvec4 fragObjectCoords = dInverseModelTransformMatrix * fragWorldCoords; - - // Distance of the pixel in the gBuffer to the observer - // JCC (12/12/2017): AMD distance function is buggy. - //double pixelDepth = distance(cameraPositionInObject.xyz, fragObjectCoords.xyz); - double pixelDepth = length(cameraPositionInObject.xyz - fragObjectCoords.xyz); - - // JCC (12/13/2017): TRick to remove floating error in texture. - // We see a squared noise on planet's surface when seeing the planet - // from far away. - float dC = float(length(cameraPositionInObject.xyz)); - float x1 = 1e8; - if (dC > x1) { - pixelDepth += 1000.0; - float alpha = 1000.0; - float beta = 1000000.0; - float x2 = 1e9; - float diffGreek = beta - alpha; - float diffDist = x2 - x1; - float varA = diffGreek/diffDist; - float varB = (alpha - varA * x1); - pixelDepth += double(varA * dC + varB); - } - - // All calculations are done in Km: - pixelDepth *= 0.001; - fragObjectCoords.xyz *= 0.001; - - if (position.xyz != vec3(0.0) && (pixelDepth < offset)) { - atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); - //discard; - } else { - // Following paper nomenclature - double t = offset; - vec3 attenuation; - - // Moving observer from camera location to top atmosphere - // If the observer is already inside the atm, offset = 0.0 - // and no changes at all. - vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); - float r = 0.0;//length(x); - vec3 v = vec3(ray.direction.xyz); - float mu = 0.0;//dot(x, v) / r; - vec3 s = vec3(sunDirectionObj); - float tF = float(maxLength - t); - - // Because we may move the camera origin to the top of atmosphere - // we also need to adjust the pixelDepth for tdCalculateRayRenderableGlobehis offset so the - // next comparison with the planet's ground make sense: - pixelDepth -= offset; - - dvec4 onATMPos = dModelTransformMatrix * dvec4(x*1000.0, 1.0); - vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); - vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, fragWorldCoords.xyz, true); - - float sunIntensityInscatter = sunRadiance * eclipseShadowATM.x; - float sunIntensityGround = sunRadiance * eclipseShadowPlanet.x; - - float irradianceFactor = 0.0; - - vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, - s, r, mu, attenuation, - vec3(fragObjectCoords.xyz), - maxLength, pixelDepth, - color, sunIntensityInscatter); - vec3 groundColor = groundColor(x, tF, v, s, r, mu, attenuation, - color, normal.xyz, irradianceFactor, - normal.a, sunIntensityGround); - vec3 sunColor = sunColor(x, tF, v, s, r, mu, irradianceFactor); - - // Final Color of ATM plus terrain: - vec4 finalRadiance = vec4(HDR(inscatterColor + groundColor + sunColor, atmExposure), 1.0); - - atmosphereFinalColor += finalRadiance; - } - } - else { // no intersection - //discard; - atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); - } - } - - renderTarget = atmosphereFinalColor / float(nSamples); - } - else { // culling - if (firstPaint) { - vec4 bColor = vec4(0.0f); - for (int f = 0; f < nAaSamples; f++) { - bColor += texelFetch(mainColorTexture, ivec2(gl_FragCoord), f); - } - bColor /= float(nAaSamples); - renderTarget = vec4(HDR(bColor.xyz * backgroundConstant, atmExposure), bColor.a); +int chooseNumberOfSamples() { + vec4 firstColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), 0); + for (int i = 1; i < nAaSamples; i++) { + vec4 currentColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); + if (currentColor != firstColor) { + return nAaSamples > 1 ? nAaSamples/2 : nAaSamples; } - else { - discard; + } + return 1; +} + +vec4 getColorWithoutAtmosphere() { + if (firstPaint) { + vec4 bColor = vec4(0.0f); + for (int f = 0; f < nAaSamples; f++) { + bColor += texelFetch(mainColorTexture, ivec2(gl_FragCoord), f); } - //renderTarget = vec4(1.0, 0.0, 0.0, 1.0); - + bColor /= float(nAaSamples); + return vec4(HDR(bColor.xyz * backgroundConstant, atmExposure), bColor.a); + } + else { + discard; } } + +void main() { + if (cullAtmosphere == 1) { + renderTarget = getColorWithoutAtmosphere(); + return; + } + + vec4 atmosphereFinalColor = vec4(0.0f); + int nSamples = chooseNumberOfSamples(); + + for (int i = 0; i < nSamples; i++) { + vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); + vec4 color = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); + // Data in the mainPositionTexture are written in camera rig space + // (identical positions for all projectors and eyes) + vec4 position = texelFetch(mainPositionTexture, ivec2(gl_FragCoord), i); + + // Ray in object space + dRay ray; + dvec4 planetPositionObjectCoords = dvec4(0.0); + dvec4 cameraPositionInObject = dvec4(0.0); + + // Get the ray from camera to atm in object space + dCalculateRayRenderableGlobe(i, ray, planetPositionObjectCoords, + cameraPositionInObject); + + bool insideATM = false; + double offset = 0.0; + double maxLength = 0.0; + + bool intersectATM = false; + + // Instead of ray-ellipsoid intersection let's transform the ray to a sphere: + intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, ray, + Rt - ATM_EPSILON/100.0, insideATM, offset, maxLength ); + + if ( intersectATM ) { + // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel + // in the depth buffer is less than the distance to the atmosphere then the atmosphere + // is occluded + // Fragments positions into G-Buffer are written in OS Eye Space (Camera Rig Coords) + // when using their positions later, one must convert them to the planet's coords + + dvec4 fragObjectCoords = dvec4(eyeToModel * position); + dvec4 fragWorldCoords = dvec4(eyeToWorld * position); + + // Distance of the pixel in the gBuffer to the observer + // JCC (12/12/2017): AMD distance function is buggy. + //double pixelDepth = distance(cameraPositionInObject.xyz, fragObjectCoords.xyz); + double pixelDepth = length(cameraPositionInObject.xyz - fragObjectCoords.xyz); + + // JCC (12/13/2017): TRick to remove floating error in texture. + // We see a squared noise on planet's surface when seeing the planet + // from far away. + float dC = float(length(cameraPositionInObject.xyz)); + float x1 = 1e8; + if (dC > x1) { + pixelDepth += 1000.0; + float alpha = 1000.0; + float beta = 1000000.0; + float x2 = 1e9; + float diffGreek = beta - alpha; + float diffDist = x2 - x1; + float varA = diffGreek/diffDist; + float varB = (alpha - varA * x1); + pixelDepth += double(varA * dC + varB); + } + + // All calculations are done in Km: + pixelDepth *= 0.001; + fragObjectCoords.xyz *= 0.001; + + if (position.xyz != vec3(0.0) && (pixelDepth < offset)) { + atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); + //discard; + } else { + // Following paper nomenclature + double t = offset; + vec3 attenuation; + + // Moving observer from camera location to top atmosphere + // If the observer is already inside the atm, offset = 0.0 + // and no changes at all. + vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); + float r = 0.0;//length(x); + vec3 v = vec3(ray.direction.xyz); + float mu = 0.0;//dot(x, v) / r; + vec3 s = vec3(sunDirectionObj); + float tF = float(maxLength - t); + + // Because we may move the camera origin to the top of atmosphere + // we also need to adjust the pixelDepth for tdCalculateRayRenderableGlobehis offset so the + // next comparison with the planet's ground make sense: + pixelDepth -= offset; + + dvec4 onATMPos = dModelTransformMatrix * dvec4(x*1000.0, 1.0); + vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); + vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, fragWorldCoords.xyz, true); + + float sunIntensityInscatter = sunRadiance * eclipseShadowATM.x; + float sunIntensityGround = sunRadiance * eclipseShadowPlanet.x; + + float irradianceFactor = 0.0; + + vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, + s, r, mu, attenuation, + vec3(fragObjectCoords.xyz), + maxLength, pixelDepth, + color, sunIntensityInscatter); + vec3 groundColor = groundColor(x, tF, v, s, r, mu, attenuation, + color, normal.xyz, irradianceFactor, + normal.a, sunIntensityGround); + vec3 sunColor = sunColor(x, tF, v, s, r, mu, irradianceFactor); + + // Final Color of ATM plus terrain: + vec4 finalRadiance = vec4(HDR(inscatterColor + groundColor + sunColor, atmExposure), 1.0); + + atmosphereFinalColor += finalRadiance; + } + } + else { // no intersection + //discard; + atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); + } + } + + renderTarget = atmosphereFinalColor / float(nSamples); +} From 0899c499f0553aec39fbefeb074e8a7da5885475 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 26 Mar 2018 14:02:36 +0200 Subject: [PATCH 28/79] Cleanup --- .../rendering/atmospheredeferredcaster.cpp | 6 +++- .../shaders/atmosphere_deferred_fs.glsl | 31 ++++++------------- 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 234fceedfe..7121472581 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -250,6 +250,10 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("dInverseModelTransformMatrix", inverseModelMatrix); program.setUniform("dModelTransformMatrix", _modelTransform); + glm::vec3 camPosModelCoords = inverseModelMatrix * + glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); + + program.setUniform("camPosModelCoords", camPosModelCoords); glm::dmat4 eyeToModel = inverseModelMatrix * @@ -323,7 +327,7 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, glm::dmat4 eyeToWorldTransform = glm::inverse(renderData.camera.combinedViewMatrix()); - program.setUniform("eyeToWorld", glm::mat4(eyeToWorldTransform)); + program.setUniform("eyeToWorld", eyeToWorldTransform); double lt; glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 0c0412dd3d..05b0559dfb 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -90,10 +90,12 @@ uniform dmat4 dModelTransformMatrix; //uniform dmat4 dSGCTEyeToOSWorldTransformMatrix; uniform mat4 eyeToModel; -uniform mat4 eyeToWorld; +uniform dmat4 eyeToWorld; uniform mat4 clipToModel; uniform mat4 tempTransform; +uniform vec3 camPosModelCoords; + uniform dvec3 dCamRigPos; uniform dvec3 dCampos; uniform dvec3 sunDirectionObj; @@ -246,9 +248,7 @@ bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const d * This method avoids matrices multiplications * wherever is possible. */ -void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, - out dvec4 planetPositionObjectCoords, - out dvec4 cameraPositionInObject) { +void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray) { // ====================================== // ======= Avoiding Some Matrices ======= @@ -257,28 +257,18 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, msaaSamplePatter[mssaSample+1]); dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 1.0, 1.0); + // Clip to World dvec4 offsetWorldCoords = tempTransform * clipCoords; dvec4 worldCoords = dvec4(dvec3(offsetWorldCoords) + dCampos, 1.0); // World to Object dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; - //objectCoords = dmat4(eyeToModel) * sgctEyeCoords; - //objectCoords = dmat4(clipToModel) * clipCoords; - // Planet Position in Object Space - // JCC: Applying the inverse of the model transformation on the object postion in World - // space results in imprecision. - planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); - //planetPositionObjectCoords = dInverseModelTransformMatrix * dvec4(dObjpos.xyz, 1.0); - - // Camera Position in Object Space - cameraPositionInObject = dInverseModelTransformMatrix * dvec4(dCampos, 1.0); - // ============================ // ====== Building Ray ======== // Ray in object space (in KM) - ray.origin = cameraPositionInObject * dvec4(0.001, 0.001, 0.001, 1.0); - ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); + ray.origin = vec4(camPosModelCoords, 1.0) * dvec4(0.001, 0.001, 0.001, 1.0); + ray.direction = dvec4(normalize(objectCoords.xyz - camPosModelCoords.xyz), 0.0); } /* @@ -584,12 +574,11 @@ void main() { // Ray in object space dRay ray; - dvec4 planetPositionObjectCoords = dvec4(0.0); - dvec4 cameraPositionInObject = dvec4(0.0); + dvec4 planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); + dvec4 cameraPositionInObject = dvec4(camPosModelCoords, 1.0); // Get the ray from camera to atm in object space - dCalculateRayRenderableGlobe(i, ray, planetPositionObjectCoords, - cameraPositionInObject); + dCalculateRayRenderableGlobe(i, ray); bool insideATM = false; double offset = 0.0; From 40dfbc5db53df2451952e02b6c94e895f966a4af Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 26 Mar 2018 18:05:41 +0200 Subject: [PATCH 29/79] Atmosphere optimizations --- .../rendering/atmospheredeferredcaster.cpp | 75 ++----------------- .../shaders/atmosphere_deferred_fs.glsl | 37 ++++----- 2 files changed, 20 insertions(+), 92 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 7121472581..46f7dd4cf6 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -243,17 +243,13 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("SAMPLES_MU_S", _mu_s_samples); program.setUniform("SAMPLES_NU", _nu_samples); - program.setUniform("ModelTransformMatrix", _modelTransform); - // Object Space - glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); - program.setUniform("dInverseModelTransformMatrix", inverseModelMatrix); program.setUniform("dModelTransformMatrix", _modelTransform); - glm::vec3 camPosModelCoords = inverseModelMatrix * + glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); + glm::vec3 eyePosModelCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); - - program.setUniform("camPosModelCoords", camPosModelCoords); + program.setUniform("eyePosModelCoords", eyePosModelCoords); glm::dmat4 eyeToModel = inverseModelMatrix * @@ -262,68 +258,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("eyeToModel", glm::mat4(eyeToModel)); - glm::dmat4 clipToModel = - eyeToModel * - glm::inverse(glm::dmat4(renderData.camera.projectionMatrix())); - - program.setUniform("clipToModel", - glm::mat4(clipToModel)); - - - // The following scale comes from PSC transformations. - glm::dmat4 dfScaleCamTransf = glm::scale(glm::dvec3(1.0)); - program.setUniform( - "dInverseScaleTransformMatrix", - glm::inverse(dfScaleCamTransf) - ); - - program.setUniform( - "dCamScaleTransform", - renderData.camera.viewScaleMatrix() - ); - - // World to Eye Space in OS - program.setUniform( - "dInverseCamScaleTransform", - glm::inverse(renderData.camera.viewScaleMatrix()) - ); - - program.setUniform( - "dInverseCamRotTransform", - glm::mat4_cast( - static_cast(renderData.camera.rotationQuaternion()) - ) - ); - - // Eye Space in OS to Eye Space in SGCT - glm::dmat4 dOsEye2SGCTEye = glm::dmat4(renderData.camera.viewMatrix()); - glm::dmat4 dSgctEye2OSEye = glm::inverse(dOsEye2SGCTEye); - program.setUniform("dSgctEyeToOSEyeTranform", dSgctEye2OSEye); - - // Eye Space in SGCT to Projection (Clip) Space in SGCT - glm::dmat4 dSgctEye2Clip = glm::dmat4(renderData.camera.projectionMatrix()); - glm::dmat4 dInverseProjection = glm::inverse(dSgctEye2Clip); - - program.setUniform("dInverseSgctProjectionMatrix", dInverseProjection); - - program.setUniform("dObjpos", glm::dvec4(renderData.position.dvec3(), 1.0)); - - glm::dvec3 campos = renderData.camera.eyePositionVec3(); - program.setUniform("dCampos", campos); - - glm::dvec3 camRigPos = renderData.camera.positionVec3(); - program.setUniform("dCamRigPos", camRigPos); - - - glm::dmat4 tempTransform = - glm::mat4_cast( - static_cast(renderData.camera.rotationQuaternion()) - ) * - glm::inverse(renderData.camera.viewScaleMatrix()) * - dSgctEye2OSEye * - dInverseProjection; - - program.setUniform("tempTransform", glm::mat4(tempTransform)); + glm::mat4 invProjection = + glm::inverse(renderData.camera.projectionMatrix()); + program.setUniform("inverseProjection", invProjection); glm::dmat4 eyeToWorldTransform = glm::inverse(renderData.camera.combinedViewMatrix()); diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 05b0559dfb..31f8eb6fc7 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -85,19 +85,15 @@ uniform sampler2DMS mainNormalTexture; uniform sampler2DMS mainColorTexture; // Model Transform Matrix Used for Globe Rendering -uniform dmat4 dInverseModelTransformMatrix; + uniform dmat4 dModelTransformMatrix; -//uniform dmat4 dSGCTEyeToOSWorldTransformMatrix; +uniform dmat4 eyeToWorld; uniform mat4 eyeToModel; -uniform dmat4 eyeToWorld; -uniform mat4 clipToModel; -uniform mat4 tempTransform; +uniform mat4 inverseProjection; -uniform vec3 camPosModelCoords; +uniform vec3 eyePosModelCoords; -uniform dvec3 dCamRigPos; -uniform dvec3 dCampos; uniform dvec3 sunDirectionObj; uniform dvec3 ellipsoidRadii; @@ -249,26 +245,21 @@ bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const d * wherever is possible. */ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray) { - // ====================================== - // ======= Avoiding Some Matrices ======= - // Compute positions and directions in world space. - dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], - msaaSamplePatter[mssaSample+1]); - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 1.0, 1.0); + vec2 samplePos = vec2(msaaSamplePatter[mssaSample], + msaaSamplePatter[mssaSample+1]); - // Clip to World - dvec4 offsetWorldCoords = tempTransform * clipCoords; - dvec4 worldCoords = dvec4(dvec3(offsetWorldCoords) + dCampos, 1.0); - - // World to Object - dvec4 objectCoords = dInverseModelTransformMatrix * worldCoords; + dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 0.0, 1.0); + vec4 eyeSpaceCoords = inverseProjection * vec4(clipCoords); + eyeSpaceCoords.w = 1.0; + + dvec4 objectCoords = eyeToModel * eyeSpaceCoords; // ============================ // ====== Building Ray ======== // Ray in object space (in KM) - ray.origin = vec4(camPosModelCoords, 1.0) * dvec4(0.001, 0.001, 0.001, 1.0); - ray.direction = dvec4(normalize(objectCoords.xyz - camPosModelCoords.xyz), 0.0); + ray.origin = dvec4(vec4(eyePosModelCoords, 1.0) * dvec4(0.001, 0.001, 0.001, 1.0)); + ray.direction = dvec4(normalize(objectCoords.xyz - eyePosModelCoords.xyz), 0.0); } /* @@ -575,7 +566,7 @@ void main() { // Ray in object space dRay ray; dvec4 planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); - dvec4 cameraPositionInObject = dvec4(camPosModelCoords, 1.0); + dvec4 cameraPositionInObject = dvec4(eyePosModelCoords, 1.0); // Get the ray from camera to atm in object space dCalculateRayRenderableGlobe(i, ray); From 0f70218977539c989f399f0e19225991c74a8ba9 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Mon, 26 Mar 2018 18:38:45 +0200 Subject: [PATCH 30/79] Fix comment --- modules/atmosphere/shaders/atmosphere_deferred_fs.glsl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 31f8eb6fc7..aa1e30618e 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -585,8 +585,8 @@ void main() { // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel // in the depth buffer is less than the distance to the atmosphere then the atmosphere // is occluded - // Fragments positions into G-Buffer are written in OS Eye Space (Camera Rig Coords) - // when using their positions later, one must convert them to the planet's coords + // Fragments positions into G-Buffer are written in eye space. + // When using their positions later, one must convert them to the planet's coords dvec4 fragObjectCoords = dvec4(eyeToModel * position); dvec4 fragWorldCoords = dvec4(eyeToWorld * position); From 402cd19fb84ec8b264294b04bf607679993d6bbc Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Thu, 29 Mar 2018 17:19:24 +0200 Subject: [PATCH 31/79] Fix bug with atmosphere rendering offset after minimizing window --- .../openspace/rendering/framebufferrenderer.h | 1 + src/engine/wrapper/sgctwindowwrapper.cpp | 15 +++---- src/rendering/framebufferrenderer.cpp | 43 +++++++++++-------- 3 files changed, 32 insertions(+), 27 deletions(-) diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 506c2b1e25..56fe78ef15 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -133,6 +133,7 @@ private: bool _dirtyDeferredcastData; bool _dirtyRaycastData; bool _dirtyResolution; + bool _dirtyMsaaSamplingPattern; Camera* _camera; Scene* _scene; diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index 6dbcb38cb6..a7a4811411 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -236,14 +236,13 @@ void SGCTWindowWrapper::setEyeSeparationDistance(float distance) { } glm::ivec4 SGCTWindowWrapper::viewportPixelCoordinates() const { - int x1, xSize, y1, ySize; - sgct::Engine::instance()->getCurrentWindowPtr()->getCurrentViewportPixelCoords( - x1, - y1, - xSize, - ySize - ); - return glm::ivec4(x1, xSize, y1, ySize); + 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 { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index d36e049473..165ce9f912 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -213,7 +213,7 @@ namespace openspace { // JCC: Moved to here to avoid NVidia: "Program/shader state performance warning" updateHDRData(); updateDeferredcastData(); - updateMSAASamplingPattern(); + _dirtyMsaaSamplingPattern = true; glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); @@ -269,19 +269,6 @@ namespace openspace { } void FramebufferRenderer::update() { - if (_dirtyResolution) { - updateResolution(); - updateMSAASamplingPattern(); - } - - if (_dirtyRaycastData) { - updateRaycastData(); - } - - if (_dirtyDeferredcastData) { - updateDeferredcastData(); - } - // If the resolve dictionary changed (or a file changed on disk) // then rebuild the resolve program. if (_hdrBackGroundProgram && _hdrBackGroundProgram->isDirty()) { @@ -661,8 +648,8 @@ namespace openspace { // Saves current state GLint defaultFbo; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFbo); - GLint viewport[4]; - glGetIntegerv(GL_VIEWPORT, viewport); + + glm::ivec4 viewport = OsEng.windowWrapper().viewportPixelCoordinates(); // Main framebuffer GLuint pixelSizeTexture = 0; @@ -899,7 +886,7 @@ namespace openspace { // Convert back to [-1, 1] range and then scale for the current viewport size: for (int d = 0; d < _nAaSamples; ++d) { _mSAAPattern[d * 3] = (2.0 * _mSAAPattern[d * 3] - 1.0) / - static_cast(viewport[2]); + static_cast(viewport[1]); _mSAAPattern[(d * 3) + 1] = (2.0 * _mSAAPattern[(d * 3) + 1] - 1.0) / static_cast(viewport[3]); _mSAAPattern[(d * 3) + 2] = 0.0; @@ -909,7 +896,7 @@ namespace openspace { // Restores default state glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); - glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + glViewport(viewport[0], viewport[2], viewport[1], viewport[3]); // Deletes unused buffers glDeleteFramebuffers(1, &pixelSizeFramebuffer); @@ -921,9 +908,27 @@ namespace openspace { glDeleteTextures(1, &nOneStripTexture); glDeleteBuffers(1, &nOneStripVBO); glDeleteVertexArrays(1, &nOneStripVAO); + + _dirtyMsaaSamplingPattern = false; } void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurements) { + if (_dirtyResolution) { + updateResolution(); + } + + if (_dirtyMsaaSamplingPattern) { + updateMSAASamplingPattern(); + } + + if (_dirtyRaycastData) { + updateRaycastData(); + } + + if (_dirtyDeferredcastData) { + updateDeferredcastData(); + } + std::unique_ptr perf; if (doPerformanceMeasurements) { perf = std::make_unique( @@ -1211,7 +1216,7 @@ namespace openspace { LERROR("Framebuffer renderer does not support more than 8 MSAA samples."); _nAaSamples = 8; } - _dirtyResolution = true; + _dirtyMsaaSamplingPattern = true; } void FramebufferRenderer::setHDRExposure(float hdrExposure) { From ab93e2ca4d1b2e698a260aedba8a5552eda2a417 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Wed, 4 Apr 2018 16:58:24 +0200 Subject: [PATCH 32/79] =?UTF-8?q?Fix=20atmosphere=20floating=20point=20iss?= =?UTF-8?q?ue=C2=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/atmosphere/rendering/atmospheredeferredcaster.cpp | 3 +++ modules/atmosphere/shaders/atmosphere_deferred_fs.glsl | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 46f7dd4cf6..088181189d 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -258,6 +258,9 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, program.setUniform("eyeToModel", glm::mat4(eyeToModel)); + float viewScaling = renderData.camera.scaling(); + program.setUniform("viewScaling", viewScaling); + glm::mat4 invProjection = glm::inverse(renderData.camera.projectionMatrix()); program.setUniform("inverseProjection", invProjection); diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index aa1e30618e..50578be199 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -77,6 +77,7 @@ uniform int cullAtmosphere; uniform float backgroundConstant; uniform bool firstPaint; uniform float atmExposure; +uniform float viewScaling; uniform sampler2D irradianceTexture; uniform sampler3D inscatterTexture; @@ -253,6 +254,9 @@ void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray) { vec4 eyeSpaceCoords = inverseProjection * vec4(clipCoords); eyeSpaceCoords.w = 1.0; + // Scale the vector to avoid floating point inaccuracy. + eyeSpaceCoords.xyz *= viewScaling * 1000000.0; + dvec4 objectCoords = eyeToModel * eyeSpaceCoords; // ============================ From 0b332a586a944b970fc17664655bbaaa7b29fa97 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 12 Apr 2018 09:50:21 -0400 Subject: [PATCH 33/79] Render Saturn's rings without warnings (closes #584) --- data/assets/scene/solarsystem/planets/saturn/saturn.asset | 2 +- modules/space/rendering/renderablerings.cpp | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index 5eba3cd243..0a60fdeb1b 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -55,7 +55,7 @@ local SaturnRings = { Name = "Saturn Rings", Path = "/Solar System/Planets/Saturn" } -}, +} diff --git a/modules/space/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp index 1fb453f690..d70df74c65 100644 --- a/modules/space/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -243,8 +243,6 @@ void RenderableRings::render(const RenderData& data, RendererTasks&) { _sunPosition ); - setPscUniforms(*_shader, data.camera, data.position); - ghoul::opengl::TextureUnit unit; unit.activate(); _texture->bind(); From 20b83191617617e7d73ebf8848b33b648c5bf456 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 12 Apr 2018 10:02:04 -0400 Subject: [PATCH 34/79] Forward mouse-released events to the navigation handler regardless of whether a callback has consumed them --- src/engine/openspaceengine.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 99d2caf3c4..b9e1d2946c 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -1474,7 +1474,16 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action for (const auto& func : _moduleCallbacks.mouseButton) { bool consumed = func(button, action); if (consumed) { - return; + // If the mouse was released, we still want to forward it to the navigation + // handler in order to reliably terminate a rotation or zoom. Accidentally + // moving the cursor over a UI window is easy to miss and leads to weird + // continuing movement + if (action == MouseAction::Release) { + break; + } + else { + return; + } } } From 12db1dd0c2c7c771dcea05ab44d220f07c548b7c Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 17 Apr 2018 18:44:02 -0400 Subject: [PATCH 35/79] =?UTF-8?q?Fix=20Norrk=C3=B6ping=20WMS=20servers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mars/map_service_configs/LiU/CTX.wms | 20 ++++++---- .../LiU/Mola_Elevation.wms | 39 +++++++++++++++++-- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/CTX.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/CTX.wms index 7c0effdee4..4bebebede3 100644 --- a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/CTX.wms +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/CTX.wms @@ -1,18 +1,22 @@ - - http://wms.itn.liu.se/OnMars/wms.cgi? - CTX Mosaic - TRUE + + http://wms.itn.liu.se/Mars/CTX/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 - 256 - 256 + 4194304 + 2097152 + 13 + top - 400,204,404 - true + GEOGCS["Mars 2000", DATUM["D_Mars_2000", SPHEROID["MARS_2000_IAU_IAG",3396190.0,169.894447222361179]],PRIMEM["Greenwich"0], UNIT["Decimal_Degree",0.0174532925199433]] + 256 + 256 + 2 + false + ./gdal-cache/ctx 5 diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms index de304c2a37..52c6b9c84b 100644 --- a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms @@ -1,15 +1,48 @@ - - http://wms.itn.liu.se/OnMars/wms.cgi? - Mola Elevation + + http://wms.itn.liu.se/Mars/Mola_Elevation/tile/${z}/${y}/${x} -180.0 90.0 180.0 -90.0 + 46080 + 23040 + 6 bottom + Int16 + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 false + ./gdal-cache/mola_elevation 5 + + + \ No newline at end of file From 4041bbb93555f3a7de1157075a1863ae306578b5 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 19 Apr 2018 13:27:15 -0400 Subject: [PATCH 36/79] Cleanup (#600) * General Code Cleanup * Add check for TABs to check_style_guide.py * Removing warnings --- apps/Wormhole/main.cpp | 2 +- ext/ghoul | 2 +- ext/sgct | 2 +- .../openspace/engine/configurationmanager.h | 7 +- include/openspace/network/messagestructures.h | 2 +- include/openspace/properties/binaryproperty.h | 44 +-- .../openspace/properties/numericalproperty.h | 2 +- .../properties/numericalproperty.inl | 12 +- include/openspace/properties/property.h | 6 +- include/openspace/properties/propertyowner.h | 6 +- include/openspace/rendering/renderable.h | 2 +- include/openspace/scene/scene.h | 4 +- modules/atmosphere/atmospheremodule.cpp | 9 +- modules/atmosphere/atmospheremodule.h | 3 +- .../rendering/atmospheredeferredcaster.cpp | 27 +- .../shaders/atmosphere_deferred_vs.glsl | 2 +- .../atmosphere/shaders/deltaE_calc_fs.glsl | 2 +- .../atmosphere/shaders/deltaE_calc_vs.glsl | 2 +- .../atmosphere/shaders/deltaJ_calc_fs.glsl | 2 +- .../atmosphere/shaders/deltaJ_calc_gs.glsl | 2 +- .../atmosphere/shaders/deltaJ_calc_vs.glsl | 2 +- .../atmosphere/shaders/deltaS_calc_fs.glsl | 4 +- .../atmosphere/shaders/deltaS_calc_gs.glsl | 2 +- .../atmosphere/shaders/deltaS_calc_vs.glsl | 2 +- .../shaders/deltaS_sup_calc_fs.glsl | 2 +- .../shaders/deltaS_sup_calc_gs.glsl | 2 +- .../shaders/deltaS_sup_calc_vs.glsl | 2 +- .../shaders/inScattering_calc_fs.glsl | 2 +- .../shaders/inScattering_calc_gs.glsl | 2 +- .../shaders/inScattering_calc_vs.glsl | 2 +- .../shaders/inScattering_sup_calc_fs.glsl | 2 +- .../shaders/inScattering_sup_calc_gs.glsl | 2 +- .../shaders/inScattering_sup_calc_vs.glsl | 2 +- .../shaders/irradiance_calc_fs.glsl | 2 +- .../shaders/irradiance_calc_vs.glsl | 2 +- .../shaders/irradiance_final_fs.glsl | 3 +- .../shaders/irradiance_final_vs.glsl | 2 +- .../shaders/irradiance_sup_calc_fs.glsl | 2 +- .../shaders/irradiance_sup_calc_vs.glsl | 2 +- .../shaders/transmittance_calc_fs.glsl | 2 +- .../shaders/transmittance_calc_vs.glsl | 2 +- modules/base/dashboard/dashboarditemangle.cpp | 6 +- modules/base/dashboard/dashboarditemangle.h | 1 - modules/base/dashboard/dashboarditemdate.h | 4 +- modules/base/rendering/renderableplane.cpp | 2 +- .../base/rendering/screenspacedashboard.cpp | 2 - .../base/rendering/screenspaceimagelocal.cpp | 2 - .../base/rendering/screenspaceimageonline.cpp | 2 - modules/base/rotation/fixedrotation.cpp | 2 +- modules/cefwebgui/CMakeLists.txt | 2 +- modules/cefwebgui/cefwebguimodule.cpp | 2 +- modules/cefwebgui/cefwebguimodule.h | 8 +- modules/cefwebgui/include/guirenderhandler.h | 14 +- modules/cefwebgui/src/guirenderhandler.cpp | 2 +- .../renderablefieldlinessequence.cpp | 4 +- .../rendering/layershadermanager.cpp | 5 +- .../imgui/src/guiglobebrowsingcomponent.cpp | 2 +- modules/kameleon/src/kameleonwrapper.cpp | 16 +- .../kameleonvolume/kameleonvolumereader.cpp | 2 +- modules/kameleonvolume/kameleonvolumereader.h | 2 +- .../rendering/renderablekameleonvolume.cpp | 10 +- .../tasks/kameleonvolumetorawtask.cpp | 2 - modules/server/CMakeLists.txt | 2 +- modules/server/include/authorizationtopic.h | 15 +- modules/server/include/connection.h | 13 +- modules/server/include/connectionpool.h | 13 +- modules/server/include/getpropertytopic.h | 10 +- modules/server/include/jsonconverters.h | 10 +- modules/server/include/luascripttopic.h | 52 +-- modules/server/include/setpropertytopic.h | 10 +- modules/server/include/subscriptiontopic.h | 10 +- modules/server/include/timetopic.h | 13 +- modules/server/include/topic.h | 16 +- modules/server/include/triggerpropertytopic.h | 52 +-- modules/server/servermodule.cpp | 8 +- modules/server/servermodule.h | 2 +- modules/server/src/connection.cpp | 37 +- modules/server/src/connectionpool.cpp | 15 +- modules/server/src/jsonconverters.cpp | 2 +- .../server/src/topics/authorizationtopic.cpp | 24 +- .../server/src/topics/getpropertytopic.cpp | 6 +- modules/server/src/topics/luascripttopic.cpp | 11 +- .../server/src/topics/setpropertytopic.cpp | 2 +- .../server/src/topics/subscriptiontopic.cpp | 2 +- modules/server/src/topics/timetopic.cpp | 2 +- modules/server/src/topics/topic.cpp | 2 +- .../src/topics/triggerpropertytopic.cpp | 8 +- .../rendering/renderableshadowcylinder.cpp | 2 +- modules/sync/syncs/urlsynchronization.cpp | 2 +- modules/touch/ext/levmarq.cpp | 29 +- modules/touch/include/touchmarker.h | 1 - modules/touch/src/touchinteraction.cpp | 19 +- modules/touch/src/touchmarker.cpp | 10 +- modules/volume/envelope.cpp | 357 ++++++++++-------- modules/volume/envelope.h | 114 +++--- .../volume/rendering/basicvolumeraycaster.h | 3 +- modules/volume/transferfunction.cpp | 47 +-- modules/volume/transferfunction.h | 105 +++--- modules/volume/transferfunctionhandler.cpp | 44 +-- modules/volume/transferfunctionhandler.h | 59 ++- modules/volume/transferfunctionproperty.cpp | 44 +-- modules/volume/transferfunctionproperty.h | 52 +-- modules/volume/volumegridtype.cpp | 6 +- modules/volume/volumegridtype.h | 16 +- modules/webbrowser/CMakeLists.txt | 4 +- modules/webbrowser/include/browserclient.h | 4 +- modules/webbrowser/include/browserinstance.h | 11 +- modules/webbrowser/include/cefhost.h | 8 +- .../include/defaultbrowserlauncher.h | 22 +- modules/webbrowser/include/eventhandler.h | 20 +- .../webbrowser/include/screenspacebrowser.h | 23 +- .../include/screenspacerenderhandler.h | 14 +- modules/webbrowser/include/webbrowserapp.h | 14 +- modules/webbrowser/include/webrenderhandler.h | 8 +- modules/webbrowser/src/browserclient.cpp | 2 +- modules/webbrowser/src/browserinstance.cpp | 22 +- modules/webbrowser/src/cefhost.cpp | 12 +- .../webbrowser/src/defaultbrowserlauncher.cpp | 2 +- modules/webbrowser/src/eventhandler.cpp | 25 +- modules/webbrowser/src/processhelpermac.cpp | 2 +- .../webbrowser/src/processhelperwindows.cpp | 17 +- modules/webbrowser/src/screenspacebrowser.cpp | 18 +- .../src/screenspacerenderhandler.cpp | 2 +- modules/webbrowser/src/webbrowserapp.cpp | 2 +- modules/webbrowser/src/webrenderhandler.cpp | 27 +- modules/webbrowser/webbrowsermodule.cpp | 34 +- modules/webbrowser/webbrowsermodule.h | 2 +- modules/webgui/CMakeLists.txt | 2 +- modules/webgui/webguimodule.cpp | 2 +- modules/webgui/webguimodule.h | 11 +- src/engine/configurationmanager.cpp | 75 ---- src/engine/configurationmanager_doc.inl | 23 +- src/engine/downloadmanager.cpp | 4 +- src/engine/openspaceengine.cpp | 7 +- src/engine/virtualpropertymanager.cpp | 4 +- src/engine/wrapper/sgctwindowwrapper.cpp | 7 +- src/interaction/keybindingmanager_lua.inl | 2 +- src/interaction/touchbar.mm | 2 + src/network/parallelconnection.cpp | 15 +- src/network/parallelpeer.cpp | 30 +- src/network/parallelserver.cpp | 12 +- src/properties/binaryproperty.cpp | 46 +-- src/properties/property.cpp | 29 +- src/properties/scalar/ucharproperty.cpp | 2 +- src/rendering/framebufferrenderer.cpp | 4 +- src/rendering/renderengine.cpp | 4 +- src/scene/scene.cpp | 1 - src/scene/scenegraphnode.cpp | 2 +- src/util/httprequest.cpp | 4 +- support/coding/check_style_guide.py | 153 ++++++-- tests/test_rawvolumeio.inl | 2 +- 151 files changed, 1229 insertions(+), 1033 deletions(-) diff --git a/apps/Wormhole/main.cpp b/apps/Wormhole/main.cpp index a688f80a13..92ab97ea96 100644 --- a/apps/Wormhole/main.cpp +++ b/apps/Wormhole/main.cpp @@ -62,7 +62,7 @@ int main(int argc, char** argv) { ); std::stringstream defaultPassword; - defaultPassword << std::hex << std::setfill('0') << std::setw(6) << + defaultPassword << std::hex << std::setfill('0') << std::setw(6) << (std::hash{}( std::chrono::system_clock::now().time_since_epoch().count() ) % 0xffffff); diff --git a/ext/ghoul b/ext/ghoul index fd1187437c..f0e8a06c9a 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit fd1187437c59553f2dba74684b791220cbb8d7fc +Subproject commit f0e8a06c9a92a282d2c7197c9388db1301d797ce diff --git a/ext/sgct b/ext/sgct index 52e2943cd7..03a8cd877e 160000 --- a/ext/sgct +++ b/ext/sgct @@ -1 +1 @@ -Subproject commit 52e2943cd74bb8346db0411bf17ed3dab4245e03 +Subproject commit 03a8cd877e540beb2e4762be6036cf895ee77647 diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h index ac7c325e27..63881b2dd3 100644 --- a/include/openspace/engine/configurationmanager.h +++ b/include/openspace/engine/configurationmanager.h @@ -86,9 +86,10 @@ public: /// The key that stores the factory documentation values static constexpr const char* KeyFactoryDocumentation = "FactoryDocumentation"; - /// The key that decides whether or not we should require incoming web socket connections - /// to authorize or not - static constexpr const char* KeyRequireSocketAuthentication = "RequireSocketAuthentication"; + /// The key that decides whether or not we should require incoming web socket + /// connections to authorize or not + static constexpr const char* KeyRequireSocketAuthentication = + "RequireSocketAuthentication"; /// The key that stores the location of the asset file that is initially loaded static constexpr const char* KeyConfigAsset = "Asset"; diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index e677f1f306..d542d99d68 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -206,7 +206,7 @@ struct TimeKeyframe { // Timestamp size = sizeof(_timestamp); memcpy(&_timestamp, buffer.data() + offset, size); - offset += size; + // offset += size; }; }; diff --git a/include/openspace/properties/binaryproperty.h b/include/openspace/properties/binaryproperty.h index d810a8b8b7..443216c6c3 100644 --- a/include/openspace/properties/binaryproperty.h +++ b/include/openspace/properties/binaryproperty.h @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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___BINARYPROPERTY___H__ #define __OPENSPACE_CORE___BINARYPROPERTY___H__ diff --git a/include/openspace/properties/numericalproperty.h b/include/openspace/properties/numericalproperty.h index 1be4a3a5d9..fb6c75d271 100644 --- a/include/openspace/properties/numericalproperty.h +++ b/include/openspace/properties/numericalproperty.h @@ -70,7 +70,7 @@ public: void setInterpolationTarget(ghoul::any value) override; void setLuaInterpolationTarget(lua_State* state) override; void setStringInterpolationTarget(std::string value) override; - + void interpolateValue(float t, ghoul::EasingFunc easingFunc = nullptr) override; diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index 91fe0ddee6..d4bfc6d9be 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -388,10 +388,14 @@ void NumericalProperty::setExponent(float exponent) { template std::string NumericalProperty::generateAdditionalJsonDescription() const { std::string result = "{ "; - result += "\"" + MinimumValueKey + "\": " + luaToJson(std::to_string(_minimumValue)) + ","; - result += "\"" + MaximumValueKey + "\": " + luaToJson(std::to_string(_maximumValue)) + ","; - result += "\"" + SteppingValueKey + "\": " + luaToJson(std::to_string(_stepping)) + ","; - result += "\"" + ExponentValueKey + "\": " + luaToJson(std::to_string(_exponent)); + result += + "\"" + MinimumValueKey + "\": " + luaToJson(std::to_string(_minimumValue)) + ","; + result += + "\"" + MaximumValueKey + "\": " + luaToJson(std::to_string(_maximumValue)) + ","; + result += + "\"" + SteppingValueKey + "\": " + luaToJson(std::to_string(_stepping)) + ","; + result += + "\"" + ExponentValueKey + "\": " + luaToJson(std::to_string(_exponent)); result += " }"; return result; } diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index 4e51e5e740..c90d7b53e3 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -396,8 +396,8 @@ public: const ghoul::Dictionary& metaData() const; /** - * Convert the Property into a string containing a JSON representation of the Property. - * Includes description of the object. + * Convert the Property into a string containing a JSON representation of the + * Property. Includes description of the object. * @return the JSON string */ virtual std::string toJson() const; @@ -412,7 +412,7 @@ public: virtual void setInterpolationTarget(ghoul::any value); virtual void setLuaInterpolationTarget(lua_State* state); virtual void setStringInterpolationTarget(std::string value); - + virtual void interpolateValue(float t, ghoul::EasingFunc easingFunction = nullptr); diff --git a/include/openspace/properties/propertyowner.h b/include/openspace/properties/propertyowner.h index fe0d367795..6be2ea0c19 100644 --- a/include/openspace/properties/propertyowner.h +++ b/include/openspace/properties/propertyowner.h @@ -83,8 +83,8 @@ public: /** * Sets the identifier for this PropertyOwner. If the PropertyOwner does not have an * owner itself, the identifier must be globally unique. If the PropertyOwner has an - * owner, the identifier must be unique to the owner (including the owner's - * properties). No uniqueness check will be preformed here, but rather in the + * owner, the identifier must be unique to the owner (including the owner's + * properties). No uniqueness check will be preformed here, but rather in the * PropertyOwner::addProperty and PropertyOwner::addPropertySubOwner methods). * * \param identifier The identifier of this PropertyOwner. It must not contain any @@ -102,7 +102,7 @@ public: std::string identifier() const; /** - * Sets the user-facing name of this PropertyOwner. This name does not have to be + * Sets the user-facing name of this PropertyOwner. This name does not have to be * unique, but it is recommended to be. * * \param guiName The new user-facing name for this PropertyOwner diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index 575045be36..3b6817ed9f 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -101,7 +101,7 @@ public: protected: properties::BoolProperty _enabled; properties::FloatProperty _opacity; - + void registerUpdateRenderBinFromOpacity(); private: diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index 5321349519..b07c8c3029 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -176,7 +176,7 @@ public: * Adds an interpolation request for the passed \p prop that will run for * \p durationSeconds seconds. Every time the #updateInterpolations method is called * the Property will be notified that it has to update itself using the stored - * interpolation values. If an interpolation record already exists for the passed + * interpolation values. If an interpolation record already exists for the passed * \p prop, the previous record will be overwritten and the remaining time of the old * interpolation is ignored. * @@ -186,7 +186,7 @@ public: * * \pre \p prop must not be \c nullptr * \pre \p durationSeconds must be positive and not 0 - * \post A new interpolation record exists for \p that is not expired + * \post A new interpolation record exists for \p that is not expired */ void addInterpolation(properties::Property* prop, float durationSeconds, ghoul::EasingFunction easingFunction = ghoul::EasingFunction::Linear); diff --git a/modules/atmosphere/atmospheremodule.cpp b/modules/atmosphere/atmospheremodule.cpp index 226c36ffab..82c50072b9 100644 --- a/modules/atmosphere/atmospheremodule.cpp +++ b/modules/atmosphere/atmospheremodule.cpp @@ -23,16 +23,15 @@ ****************************************************************************************/ #include + +#include +#include #include #include -#include - -#include - namespace openspace { -AtmosphereModule::AtmosphereModule() : OpenSpaceModule("Atmosphere") {} +AtmosphereModule::AtmosphereModule() : OpenSpaceModule(Name) {} void AtmosphereModule::internalInitialize(const ghoul::Dictionary&) { auto fRenderable = FactoryManager::ref().factory(); diff --git a/modules/atmosphere/atmospheremodule.h b/modules/atmosphere/atmospheremodule.h index 3553d9f3e6..e66485f29e 100644 --- a/modules/atmosphere/atmospheremodule.h +++ b/modules/atmosphere/atmospheremodule.h @@ -26,12 +26,13 @@ #define __OPENSPACE_MODULE_ATMOSPHERE___ATMOSPHERE_MODULE___H__ #include -#include namespace openspace { class AtmosphereModule : public OpenSpaceModule { public: + constexpr static const char* Name = "Atmosphere"; + AtmosphereModule(); private: diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 21692091ec..fb44789aad 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -59,14 +59,8 @@ */ #include -#include -#include -#include -#include -#include -#include -#include +#include #include #include #include @@ -74,12 +68,17 @@ #include #include #include +#include +#include +#include +#include +#include +#include #include #include #include #include #include - #include #include @@ -90,16 +89,16 @@ namespace { - const char* _loggerCat = "AtmosphereDeferredcaster"; - const char* GlslDeferredcastPath = + constexpr const char* _loggerCat = "AtmosphereDeferredcaster"; + constexpr const char* GlslDeferredcastPath = "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - const char* GlslDeferredcastFSPath = + constexpr const char* GlslDeferredcastFSPath = "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; - const char* GlslDeferredcastVsPath = + constexpr const char* GlslDeferredcastVsPath = "${MODULES}/atmosphere/shaders/atmosphere_deferred_vs.glsl"; - const float ATM_EPS = 2.0; - const double KM_TO_M = 1000.0; + constexpr const float ATM_EPS = 2.f; + constexpr const float KM_TO_M = 1000.f; } // namespace namespace openspace { diff --git a/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl index 9568c60136..76fae77721 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaE_calc_fs.glsl b/modules/atmosphere/shaders/deltaE_calc_fs.glsl index bacc9e0734..ce445632c9 100644 --- a/modules/atmosphere/shaders/deltaE_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaE_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaE_calc_vs.glsl b/modules/atmosphere/shaders/deltaE_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/deltaE_calc_vs.glsl +++ b/modules/atmosphere/shaders/deltaE_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaJ_calc_fs.glsl b/modules/atmosphere/shaders/deltaJ_calc_fs.glsl index 9598e4d5c9..80f02f1862 100644 --- a/modules/atmosphere/shaders/deltaJ_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaJ_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaJ_calc_gs.glsl b/modules/atmosphere/shaders/deltaJ_calc_gs.glsl index a4dd2d50b5..eb98fa1059 100644 --- a/modules/atmosphere/shaders/deltaJ_calc_gs.glsl +++ b/modules/atmosphere/shaders/deltaJ_calc_gs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaJ_calc_vs.glsl b/modules/atmosphere/shaders/deltaJ_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/deltaJ_calc_vs.glsl +++ b/modules/atmosphere/shaders/deltaJ_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaS_calc_fs.glsl b/modules/atmosphere/shaders/deltaS_calc_fs.glsl index 014cd535fb..1f66741387 100644 --- a/modules/atmosphere/shaders/deltaS_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaS_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * @@ -21,7 +21,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - + #version __CONTEXT__ #include "atmosphere_common.glsl" diff --git a/modules/atmosphere/shaders/deltaS_calc_gs.glsl b/modules/atmosphere/shaders/deltaS_calc_gs.glsl index a4dd2d50b5..eb98fa1059 100644 --- a/modules/atmosphere/shaders/deltaS_calc_gs.glsl +++ b/modules/atmosphere/shaders/deltaS_calc_gs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaS_calc_vs.glsl b/modules/atmosphere/shaders/deltaS_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/deltaS_calc_vs.glsl +++ b/modules/atmosphere/shaders/deltaS_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl index 09cf5026b3..0fc114328c 100644 --- a/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/deltaS_sup_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl index 8ca6044fd1..15b4964390 100644 --- a/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl +++ b/modules/atmosphere/shaders/deltaS_sup_calc_gs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl b/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl index 7e3574bd9d..7cb84d0439 100644 --- a/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl +++ b/modules/atmosphere/shaders/deltaS_sup_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_calc_fs.glsl index a55cbc78e1..f93fd6c304 100644 --- a/modules/atmosphere/shaders/inScattering_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_calc_gs.glsl b/modules/atmosphere/shaders/inScattering_calc_gs.glsl index aed3744bd2..93935134c4 100644 --- a/modules/atmosphere/shaders/inScattering_calc_gs.glsl +++ b/modules/atmosphere/shaders/inScattering_calc_gs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_calc_vs.glsl b/modules/atmosphere/shaders/inScattering_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/inScattering_calc_vs.glsl +++ b/modules/atmosphere/shaders/inScattering_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl index c7c4f09561..e07de3be1d 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl index 8ca6044fd1..15b4964390 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl +++ b/modules/atmosphere/shaders/inScattering_sup_calc_gs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl index 7e3574bd9d..7cb84d0439 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl +++ b/modules/atmosphere/shaders/inScattering_sup_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/irradiance_calc_fs.glsl b/modules/atmosphere/shaders/irradiance_calc_fs.glsl index 48cc7ce40f..7042c6bddd 100644 --- a/modules/atmosphere/shaders/irradiance_calc_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/irradiance_calc_vs.glsl b/modules/atmosphere/shaders/irradiance_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/irradiance_calc_vs.glsl +++ b/modules/atmosphere/shaders/irradiance_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/irradiance_final_fs.glsl b/modules/atmosphere/shaders/irradiance_final_fs.glsl index 47771e8898..a0800fc507 100644 --- a/modules/atmosphere/shaders/irradiance_final_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_final_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * @@ -21,6 +21,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #version __CONTEXT__ #include "atmosphere_common.glsl" diff --git a/modules/atmosphere/shaders/irradiance_final_vs.glsl b/modules/atmosphere/shaders/irradiance_final_vs.glsl index f55a966566..e266156549 100644 --- a/modules/atmosphere/shaders/irradiance_final_vs.glsl +++ b/modules/atmosphere/shaders/irradiance_final_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl index 005e1db59a..cdf31ca38c 100644 --- a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl b/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl index 578d7ab02f..b379e97bfe 100644 --- a/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl +++ b/modules/atmosphere/shaders/irradiance_sup_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/transmittance_calc_fs.glsl b/modules/atmosphere/shaders/transmittance_calc_fs.glsl index 7f57a7e0b2..411565b06c 100644 --- a/modules/atmosphere/shaders/transmittance_calc_fs.glsl +++ b/modules/atmosphere/shaders/transmittance_calc_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/atmosphere/shaders/transmittance_calc_vs.glsl b/modules/atmosphere/shaders/transmittance_calc_vs.glsl index d9ea954427..6e457a03e6 100644 --- a/modules/atmosphere/shaders/transmittance_calc_vs.glsl +++ b/modules/atmosphere/shaders/transmittance_calc_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2016 * + * 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 * diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index 181956704a..56843babde 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -32,15 +32,14 @@ #include #include #include - #include #include #include namespace { - const char* KeyFontMono = "Mono"; + constexpr const char* KeyFontMono = "Mono"; - const float DefaultFontSize = 10.f; + constexpr const float DefaultFontSize = 10.f; static const openspace::properties::Property::PropertyInfo FontNameInfo = { "FontName", @@ -106,6 +105,7 @@ namespace openspace { documentation::Documentation DashboardItemAngle::Documentation() { using namespace documentation; + return { "DashboardItem Angle", "base_dashboarditem_angle", diff --git a/modules/base/dashboard/dashboarditemangle.h b/modules/base/dashboard/dashboarditemangle.h index f61a23fbcf..34fdbdabee 100644 --- a/modules/base/dashboard/dashboarditemangle.h +++ b/modules/base/dashboard/dashboarditemangle.h @@ -30,7 +30,6 @@ #include #include #include - #include namespace ghoul::fontrendering { class Font; } diff --git a/modules/base/dashboard/dashboarditemdate.h b/modules/base/dashboard/dashboarditemdate.h index 8698948475..37e3f9b95b 100644 --- a/modules/base/dashboard/dashboarditemdate.h +++ b/modules/base/dashboard/dashboarditemdate.h @@ -30,9 +30,7 @@ #include #include -namespace ghoul::fontrendering { - class Font; -} // namespace ghoul::fontrendering +namespace ghoul::fontrendering { class Font; } namespace openspace { diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 3562b480b1..7e4911415b 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -176,7 +176,7 @@ void RenderablePlane::initializeGL() { absPath("${MODULE_BASE}/shaders/plane_fs.glsl") ); } - ); + ); } void RenderablePlane::deinitializeGL() { diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index 5f9ea9e638..33730c82e2 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -42,8 +42,6 @@ #include namespace { - const char* KeyName = "Name"; - static const openspace::properties::Property::PropertyInfo UseMainInfo = { "UseMainDashboard", "Use main dashboard", diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index e42c33db64..86d6705918 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -37,8 +37,6 @@ #include namespace { - const char* KeyName = "Name"; - static const openspace::properties::Property::PropertyInfo TexturePathInfo = { "TexturePath", "Texture path", diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index 4df3149a8e..8940ec8fa1 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -36,8 +36,6 @@ #include namespace { - constexpr const char* KeyName = "Name"; - static const openspace::properties::Property::PropertyInfo TextureInfo = { "URL", "Image URL", diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp index fdcb009971..bba3dc1566 100644 --- a/modules/base/rotation/fixedrotation.cpp +++ b/modules/base/rotation/fixedrotation.cpp @@ -335,7 +335,7 @@ FixedRotation::FixedRotation(const ghoul::Dictionary& dictionary) _attachedNode = sceneGraphNode(_attachedObject); }); - auto setPropertyVisibility = [this](Axis& axis) { + auto setPropertyVisibility = [](Axis& axis) { using Visibility = properties::Property::Visibility; switch (axis.type) { case Axis::Type::Object: diff --git a/modules/cefwebgui/CMakeLists.txt b/modules/cefwebgui/CMakeLists.txt index 32f763226c..d61943247a 100644 --- a/modules/cefwebgui/CMakeLists.txt +++ b/modules/cefwebgui/CMakeLists.txt @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2017 # +# 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 # diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index 123b69cd34..3186b1d326 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/cefwebgui/cefwebguimodule.h b/modules/cefwebgui/cefwebguimodule.h index 576bc39927..7c0bc93584 100644 --- a/modules/cefwebgui/cefwebguimodule.h +++ b/modules/cefwebgui/cefwebguimodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_CEFWEBGUIMODULE_H -#define OPENSPACE_CEFWEBGUIMODULE_H +#ifndef __OPENSPACE_MODULE_CEFWEBGUI___CEFWEBGUIMODULE___H__ +#define __OPENSPACE_MODULE_CEFWEBGUI___CEFWEBGUIMODULE___H__ #include #include @@ -45,4 +45,4 @@ private: } -#endif //OPENSPACE_WEBGUIMODULE_H +#endif // __OPENSPACE_MODULE_CEFWEBGUI___CEFWEBGUIMODULE___H__ diff --git a/modules/cefwebgui/include/guirenderhandler.h b/modules/cefwebgui/include/guirenderhandler.h index 88da19389e..659a5e5184 100644 --- a/modules/cefwebgui/include/guirenderhandler.h +++ b/modules/cefwebgui/include/guirenderhandler.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__ -#define __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__ +#ifndef __OPENSPACE_MODULE_CEFWEBGUI___GUI_RENDER_HANDLER___H__ +#define __OPENSPACE_MODULE_CEFWEBGUI___GUI_RENDER_HANDLER___H__ #include #include @@ -41,14 +41,16 @@ public: GUIRenderHandler(); void initializeGL(); - void draw(void); + void draw(); void render() {}; private: std::unique_ptr _programObject; - GLuint _program, _vao, _vbo; + GLuint _program; + GLuint _vao; + GLuint _vbo; }; } // namespace openspace -#endif // __OPENSPACE_MODULE_WEBBROWSER___GUI_RENDER_HANDLER___H__ +#endif // __OPENSPACE_MODULE_CEFWEBGUI___GUI_RENDER_HANDLER___H__ diff --git a/modules/cefwebgui/src/guirenderhandler.cpp b/modules/cefwebgui/src/guirenderhandler.cpp index 047c632e0e..d4de455ab2 100644 --- a/modules/cefwebgui/src/guirenderhandler.cpp +++ b/modules/cefwebgui/src/guirenderhandler.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index 81583ee16f..70b487955a 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -452,7 +452,9 @@ bool RenderableFieldlinesSequence::extractMandatoryInfoFromDictionary( } else { LERROR(fmt::format( - "{}: FieldlinesSequence {} is not a valid directory", _identifier, sourceFolderPath + "{}: FieldlinesSequence {} is not a valid directory", + _identifier, + sourceFolderPath )); return false; } diff --git a/modules/globebrowsing/rendering/layershadermanager.cpp b/modules/globebrowsing/rendering/layershadermanager.cpp index 9108e4f814..cbe2ea6588 100644 --- a/modules/globebrowsing/rendering/layershadermanager.cpp +++ b/modules/globebrowsing/rendering/layershadermanager.cpp @@ -219,7 +219,10 @@ void LayerShaderManager::recompileShaderProgram( ghoul::Dictionary layerGroupNames; for (int i = 0; i < layergroupid::NUM_LAYER_GROUPS; ++i) { - layerGroupNames.setValue(std::to_string(i), layergroupid::LAYER_GROUP_IDENTIFIERS[i]); + layerGroupNames.setValue( + std::to_string(i), + layergroupid::LAYER_GROUP_IDENTIFIERS[i] + ); } shaderDictionary.setValue("layerGroups", layerGroupNames); diff --git a/modules/imgui/src/guiglobebrowsingcomponent.cpp b/modules/imgui/src/guiglobebrowsingcomponent.cpp index 83e2a12f5d..a2606ba5a2 100644 --- a/modules/imgui/src/guiglobebrowsingcomponent.cpp +++ b/modules/imgui/src/guiglobebrowsingcomponent.cpp @@ -79,7 +79,7 @@ void GuiGlobeBrowsingComponent::render() { std::remove_if( nodes.begin(), nodes.end(), - [module](SceneGraphNode* n) { + [](SceneGraphNode* n) { Renderable* r = n->renderable(); return !r || r->identifier() != "RenderableGlobe"; } diff --git a/modules/kameleon/src/kameleonwrapper.cpp b/modules/kameleon/src/kameleonwrapper.cpp index 621a6c45ae..befdf6a92a 100644 --- a/modules/kameleon/src/kameleonwrapper.cpp +++ b/modules/kameleon/src/kameleonwrapper.cpp @@ -226,15 +226,15 @@ float* KameleonWrapper::getUniformSampledValues( LDEBUG(fmt::format("{} Max: {}", var, varMax)); // HISTOGRAM - const int bins = 200; + constexpr const int NBins = 200; const float truncLim = 0.9f; - std::vector histogram (bins,0); - auto mapToHistogram = [varMin, varMax, bins](double val) { + std::vector histogram (NBins, 0); + auto mapToHistogram = [NBins, varMin, varMax](double val) { double zeroToOne = (val-varMin)/(varMax-varMin); - zeroToOne *= static_cast(bins); + zeroToOne *= static_cast(NBins); int izerotoone = static_cast(zeroToOne); - return glm::clamp(izerotoone, 0, bins-1); + return glm::clamp(izerotoone, 0, NBins - 1); }; //ProgressBar pb(static_cast(outDimensions.x)); @@ -332,7 +332,7 @@ float* KameleonWrapper::getUniformSampledValues( // std::cout << std::endl; //} // - // for(int i = 0; i < bins-1; ++i) { + // for(int i = 0; i < NBins-1; ++i) { // // sum += histogram[i]; // // if(sum + histogram[i+1] > sumuntil) { // // stop = i; @@ -345,7 +345,7 @@ float* KameleonWrapper::getUniformSampledValues( int sum = 0; int stop = 0; const int sumuntil = static_cast(static_cast(size) * truncLim); - for(int i = 0; i < bins; ++i) { + for(int i = 0; i < NBins; ++i) { sum += histogram[i]; if(sum > sumuntil) { stop = i; @@ -356,7 +356,7 @@ float* KameleonWrapper::getUniformSampledValues( } double dist = varMax - varMin; - dist = (dist / static_cast(bins)) * static_cast(stop); + dist = (dist / static_cast(NBins)) * static_cast(stop); varMax = varMin + dist; //LDEBUG(var << "Min: " << varMin); diff --git a/modules/kameleonvolume/kameleonvolumereader.cpp b/modules/kameleonvolume/kameleonvolumereader.cpp index bbf9b30caa..1f547b303b 100644 --- a/modules/kameleonvolume/kameleonvolumereader.cpp +++ b/modules/kameleonvolume/kameleonvolumereader.cpp @@ -114,7 +114,7 @@ std::unique_ptr> KameleonVolumeReader::readFloatVolume( volumeCoords[2]); }; - auto sample = [this, &variable, &interpolate](glm::vec3 volumeCoords) { + auto sample = [&variable, &interpolate](glm::vec3 volumeCoords) { return interpolate(variable, volumeCoords); }; diff --git a/modules/kameleonvolume/kameleonvolumereader.h b/modules/kameleonvolume/kameleonvolumereader.h index 96d49b1931..0ff6011639 100644 --- a/modules/kameleonvolume/kameleonvolumereader.h +++ b/modules/kameleonvolume/kameleonvolumereader.h @@ -74,7 +74,7 @@ public: std::string simulationEnd() const; std::string getVisUnit(const std::string& variable) const; float elapsedTime() const; - + double minValue(const std::string& variable) const; double maxValue(const std::string& variable) const; diff --git a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp index c0c16da95a..90367eaa51 100644 --- a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp +++ b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp @@ -172,7 +172,9 @@ RenderableKameleonVolume::RenderableKameleonVolume(const ghoul::Dictionary& dict std::string transferFunctionPath; if (dictionary.getValue(KeyTransferFunction, transferFunctionPath)) { _transferFunctionPath = transferFunctionPath; - _transferFunctionHandler = std::make_shared(_transferFunctionPath); + _transferFunctionHandler = std::make_shared( + _transferFunctionPath + ); } std::string sourcePath; @@ -263,7 +265,11 @@ void RenderableKameleonVolume::initializeGL() { _volumeTexture->uploadTexture(); _transferFunctionHandler->initialize(); - _raycaster = std::make_unique(_volumeTexture, _transferFunctionHandler, _clipPlanes); + _raycaster = std::make_unique( + _volumeTexture, + _transferFunctionHandler, + _clipPlanes + ); _raycaster->setStepSize(_stepSize); _gridType.onChange([this] { diff --git a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp index 2fdd160b73..92cb361e8f 100644 --- a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp +++ b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp @@ -51,8 +51,6 @@ namespace { constexpr const char* KeyMaxValue = "MaxValue"; constexpr const char* KeyVisUnit = "VisUnit"; - constexpr const char* _loggerCat = "KameleonVolumeToRawTask"; - } // namespace namespace openspace { diff --git a/modules/server/CMakeLists.txt b/modules/server/CMakeLists.txt index 848a3001a7..f5755ab4ac 100644 --- a/modules/server/CMakeLists.txt +++ b/modules/server/CMakeLists.txt @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2017 # +# 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 # diff --git a/modules/server/include/authorizationtopic.h b/modules/server/include/authorizationtopic.h index edd6b83951..7c666a0039 100644 --- a/modules/server/include/authorizationtopic.h +++ b/modules/server/include/authorizationtopic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H -#define OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___AUTHORIZATION_TOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___AUTHORIZATION_TOPIC___H__ #include #include @@ -38,7 +38,6 @@ namespace openspace { class AuthorizationTopic : public Topic { public: AuthorizationTopic(); - ~AuthorizationTopic() {}; void handleJson(nlohmann::json json); bool isDone(); @@ -53,14 +52,16 @@ public: NotImplemented = 501 }; + private: bool _isAuthenticated; const std::string getKey() const; bool authorize(const std::string key); - nlohmann::json message(const std::string &message, StatusCode statusCode = StatusCode::NotImplemented); + nlohmann::json message(const std::string &message, + StatusCode statusCode = StatusCode::NotImplemented); }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__AUTHENTICATION_TOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___AUTHORIZATION_TOPIC___H__ diff --git a/modules/server/include/connection.h b/modules/server/include/connection.h index 9c9097ddb6..3cc26508f2 100644 --- a/modules/server/include/connection.h +++ b/modules/server/include/connection.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODOULES_SERVER__CONNECTION_H -#define OPENSPACE_MODOULES_SERVER__CONNECTION_H +#ifndef __OPENSPACE_MODULE_SERVER___CONNECTION___H__ +#define __OPENSPACE_MODULE_SERVER___CONNECTION___H__ #include #include @@ -53,8 +53,7 @@ public: void setAuthorized(const bool status); bool isAuthorized(); - - + std::shared_ptr socket(); std::thread& thread(); void setThread(std::thread&& thread); @@ -74,6 +73,6 @@ private: bool isWhitelisted(); }; -} +} // namespace openspace -#endif //OPENSPACE_MODOULES_SERVER__CONNECTION_H +#endif // __OPENSPACE_MODULE_SERVER___CONNECTION___H__ diff --git a/modules/server/include/connectionpool.h b/modules/server/include/connectionpool.h index f040cc9ff5..3f5ce55a21 100644 --- a/modules/server/include/connectionpool.h +++ b/modules/server/include/connectionpool.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -27,7 +27,6 @@ #include - #include #include #include @@ -36,25 +35,25 @@ #include #include - namespace openspace { class ConnectionPool { public: - ConnectionPool(std::function socket)> handleSocket); + ConnectionPool( + std::function socket)> handleSocket); ~ConnectionPool(); + void addServer(std::shared_ptr server); void removeServer(ghoul::io::SocketServer* server); void clearServers(); void updateConnections(); - -private: +private: void disconnectAllConnections(); std::mutex _connectionMutex; void removeDisconnectedSockets(); void acceptNewSockets(); - + std::function)> _handleSocket; std::vector> _socketServers; std::vector> _sockets; diff --git a/modules/server/include/getpropertytopic.h b/modules/server/include/getpropertytopic.h index fe00c2dcec..c8190577b8 100644 --- a/modules/server/include/getpropertytopic.h +++ b/modules/server/include/getpropertytopic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H -#define OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___GETPROPERTY_TOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___GETPROPERTY_TOPIC___H__ #include #include "topic.h" @@ -43,6 +43,6 @@ private: nlohmann::json getPropertyFromKey(const std::string& key); }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__GETPROPERTY_TOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___GETPROPERTY_TOPIC___H__ diff --git a/modules/server/include/jsonconverters.h b/modules/server/include/jsonconverters.h index b3009ddefb..0b7a4e2aec 100644 --- a/modules/server/include/jsonconverters.h +++ b/modules/server/include/jsonconverters.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__JSON_CONVERTERS_INL -#define OPENSPACE_MODULES_SERVER__JSON_CONVERTERS_INL +#ifndef __OPENSPACE_MODULE_SERVER___JSON_CONVERTERS___H__ +#define __OPENSPACE_MODULE_SERVER___JSON_CONVERTERS___H__ #include #include @@ -56,6 +56,6 @@ namespace glm { void to_json(json &j, const dvec3 &v); -} +} // namespace glm -#endif +#endif // __OPENSPACE_MODULE_SERVER___JSON_CONVERTERS___H__ diff --git a/modules/server/include/luascripttopic.h b/modules/server/include/luascripttopic.h index 0312259d17..0c45bcc305 100644 --- a/modules/server/include/luascripttopic.h +++ b/modules/server/include/luascripttopic.h @@ -1,29 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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_MODULES_SERVER__LUASCRIPTTOPIC_H -#define OPENSPACE_MODULES_SERVER__LUASCRIPTTOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___LUASCRIPTTOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___LUASCRIPTTOPIC___H__ #include #include @@ -38,6 +38,6 @@ public: bool isDone() { return true; }; }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__LUASCRIPTTOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___LUASCRIPTTOPIC___H__ diff --git a/modules/server/include/setpropertytopic.h b/modules/server/include/setpropertytopic.h index 45d760a50e..0ccd39da3e 100644 --- a/modules/server/include/setpropertytopic.h +++ b/modules/server/include/setpropertytopic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H -#define OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___SETPROPERTYTOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___SETPROPERTYTOPIC___H__ #include #include @@ -41,6 +41,6 @@ private: void setTime(const std::string& value); }; -} +} // namespace -#endif //OPENSPACE_MODULES_SERVER__SETPROPERTYTOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___SETPROPERTYTOPIC___H__ diff --git a/modules/server/include/subscriptiontopic.h b/modules/server/include/subscriptiontopic.h index ec7190887b..f805ee6cad 100644 --- a/modules/server/include/subscriptiontopic.h +++ b/modules/server/include/subscriptiontopic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H -#define OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___SUBSCRIPTION_TOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___SUBSCRIPTION_TOPIC___H__ #include #include @@ -47,6 +47,6 @@ private: properties::Property* _prop; }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__SUBSCRIPTION_TOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___SUBSCRIPTION_TOPIC___H__ diff --git a/modules/server/include/timetopic.h b/modules/server/include/timetopic.h index 884223380d..00d314984d 100644 --- a/modules/server/include/timetopic.h +++ b/modules/server/include/timetopic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__TIME_TOPIC_H -#define OPENSPACE_MODULES_SERVER__TIME_TOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___TIME_TOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___TIME_TOPIC___H__ #include #include "topic.h" @@ -36,7 +36,8 @@ public: ~TimeTopic(); void handleJson(nlohmann::json json); bool isDone(); -private: + +private: nlohmann::json currentTime(); nlohmann::json deltaTime(); @@ -45,6 +46,6 @@ private: std::chrono::system_clock::time_point _lastUpdateTime; }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__TIME_TOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___TIME_TOPIC___H__ diff --git a/modules/server/include/topic.h b/modules/server/include/topic.h index 7f233ef0a1..f3ed19938b 100644 --- a/modules/server/include/topic.h +++ b/modules/server/include/topic.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_MODULES_SERVER__TOPIC_H -#define OPENSPACE_MODULES_SERVER__TOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___TOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___TOPIC___H__ #include @@ -34,10 +34,12 @@ class Connection; class Topic { public: Topic() {}; - virtual ~Topic() {}; + virtual ~Topic() = default; + void initialize(Connection* connection, size_t topicId); nlohmann::json wrappedPayload(const nlohmann::json &payload) const; - nlohmann::json wrappedError(std::string message = "Could not complete request.", int code = 500); + nlohmann::json wrappedError(std::string message = "Could not complete request.", + int code = 500); virtual void handleJson(nlohmann::json json) = 0; virtual bool isDone() = 0; @@ -54,6 +56,6 @@ public: bool isDone() { return false; } }; -} +} // namespace openspace -#endif //OPENSPACE_MODULES_SERVER__TOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___TOPIC___H__ diff --git a/modules/server/include/triggerpropertytopic.h b/modules/server/include/triggerpropertytopic.h index 67ebc74e1b..f8deb135e5 100644 --- a/modules/server/include/triggerpropertytopic.h +++ b/modules/server/include/triggerpropertytopic.h @@ -1,29 +1,29 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H -#define OPENSPACE_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H +#ifndef __OPENSPACE_MODULE_SERVER___TRIGGERPROPERTYTOPIC___H__ +#define __OPENSPACE_MODULE_SERVER___TRIGGERPROPERTYTOPIC___H__ #include #include @@ -38,6 +38,6 @@ public: bool isDone() { return true; }; }; -} +} // namespace -#endif //OPENSPACE_MODULES_SERVER__TRIGGERPROPERTYTOPIC_H +#endif // __OPENSPACE_MODULE_SERVER___TRIGGERPROPERTYTOPIC___H__ diff --git a/modules/server/servermodule.cpp b/modules/server/servermodule.cpp index 7e2882e884..d1ef4b59d9 100644 --- a/modules/server/servermodule.cpp +++ b/modules/server/servermodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -87,7 +87,7 @@ void ServerModule::preSync() { // Join threads for sockets that disconnected. cleanUpFinishedThreads(); } - + void ServerModule::cleanUpFinishedThreads() { for (auto& connectionData : _connections) { std::shared_ptr& connection = connectionData.connection; @@ -106,7 +106,7 @@ void ServerModule::cleanUpFinishedThreads() { } ), _connections.end()); } - + void ServerModule::disconnectAll() { for (auto& connectionData : _connections) { std::shared_ptr& connection = connectionData.connection; @@ -117,7 +117,7 @@ void ServerModule::disconnectAll() { } } } - + void ServerModule::handleConnection(std::shared_ptr connection) { std::string messageString; while (connection->socket()->getMessage(messageString)) { diff --git a/modules/server/servermodule.h b/modules/server/servermodule.h index 2996e7fa5f..0c19ef95d5 100644 --- a/modules/server/servermodule.h +++ b/modules/server/servermodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/connection.cpp b/modules/server/src/connection.cpp index b584d245dc..e6e4e7a0fb 100644 --- a/modules/server/src/connection.cpp +++ b/modules/server/src/connection.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -32,23 +32,23 @@ #include namespace { -const char* _loggerCat = "ServerModule: Connection"; + constexpr const char* _loggerCat = "ServerModule: Connection"; -const char* MessageKeyType = "type"; -const char* MessageKeyPayload = "payload"; -const char* MessageKeyTopic = "topic"; + constexpr const char* MessageKeyType = "type"; + constexpr const char* MessageKeyPayload = "payload"; + constexpr const char* MessageKeyTopic = "topic"; -const char* AuthenticationTopicKey = "authorize"; -const char* GetPropertyTopicKey = "get"; -const char* LuaScriptTopicKey = "luascript"; -const char* SetPropertyTopicKey = "set"; -const char* SubscriptionTopicKey = "subscribe"; -const char* TimeTopicKey = "time"; -const char* TriggerPropertyTopicKey = "trigger"; -const char* BounceTopicKey = "bounce"; + constexpr const char* AuthenticationTopicKey = "authorize"; + constexpr const char* GetPropertyTopicKey = "get"; + constexpr const char* LuaScriptTopicKey = "luascript"; + constexpr const char* SetPropertyTopicKey = "set"; + constexpr const char* SubscriptionTopicKey = "subscribe"; + constexpr const char* TimeTopicKey = "time"; + constexpr const char* TriggerPropertyTopicKey = "trigger"; + constexpr const char* BounceTopicKey = "bounce"; -const int ThrottleMessageWaitInMs = 100; -} + constexpr const int ThrottleMessageWaitInMs = 100; +} // namespace namespace openspace { @@ -67,9 +67,10 @@ Connection::Connection(std::shared_ptr s, const std::string & _topicFactory.registerClass(BounceTopicKey); // see if the default config for requiring auth (on) is overwritten - const bool hasAuthenticationConfiguration = OsEng.configurationManager().hasKeyAndValue( - ConfigurationManager::KeyRequireSocketAuthentication); - if (hasAuthenticationConfiguration) { + const bool hasAuthConfiguration = OsEng.configurationManager().hasKeyAndValue( + ConfigurationManager::KeyRequireSocketAuthentication + ); + if (hasAuthConfiguration) { _requireAuthorization = OsEng.configurationManager().value( ConfigurationManager::KeyRequireSocketAuthentication); } else { diff --git a/modules/server/src/connectionpool.cpp b/modules/server/src/connectionpool.cpp index 28db0f4d00..413f373dde 100644 --- a/modules/server/src/connectionpool.cpp +++ b/modules/server/src/connectionpool.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -31,7 +31,8 @@ namespace openspace { -ConnectionPool::ConnectionPool(std::function socket)> handleSocket) +ConnectionPool::ConnectionPool( + std::function socket)> handleSocket) : _handleSocket(std::move(handleSocket)) {} @@ -69,9 +70,13 @@ void ConnectionPool::acceptNewSockets() { } void ConnectionPool::removeDisconnectedSockets() { - std::remove_if(_sockets.begin(), _sockets.end(), [](const std::shared_ptr socket) { - return !socket || !socket->isConnected(); - }); + std::remove_if( + _sockets.begin(), + _sockets.end(), + [](const std::shared_ptr socket) { + return !socket || !socket->isConnected(); + } + ); } void ConnectionPool::disconnectAllConnections() { diff --git a/modules/server/src/jsonconverters.cpp b/modules/server/src/jsonconverters.cpp index 72d355647a..e899af496c 100644 --- a/modules/server/src/jsonconverters.cpp +++ b/modules/server/src/jsonconverters.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/topics/authorizationtopic.cpp b/modules/server/src/topics/authorizationtopic.cpp index bc000989c3..c693dad79c 100644 --- a/modules/server/src/topics/authorizationtopic.cpp +++ b/modules/server/src/topics/authorizationtopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -52,9 +52,13 @@ void AuthorizationTopic::handleJson(nlohmann::json json) { _connection->sendJson(message("Invalid key", StatusCode::NotAcceptable)); } } catch (const std::out_of_range& e) { - _connection->sendJson(message("Invalid request, key must be provided.", StatusCode::BadRequest)); + _connection->sendJson( + message("Invalid request, key must be provided.", StatusCode::BadRequest) + ); } catch (const std::domain_error& e) { - _connection->sendJson(message("Invalid request, invalid key format.", StatusCode::BadRequest)); + _connection->sendJson( + message("Invalid request, invalid key format.", StatusCode::BadRequest) + ); } } }; @@ -65,7 +69,7 @@ bool AuthorizationTopic::authorize(const std::string key) { } const std::string AuthorizationTopic::getKey() const { - const bool hasConfigPassword = OsEng.configurationManager().hasKeyAndValue( + bool hasConfigPassword = OsEng.configurationManager().hasKeyAndValue( ConfigurationManager::KeyServerPasskey); if (hasConfigPassword) { return OsEng.configurationManager().value( @@ -75,9 +79,13 @@ const std::string AuthorizationTopic::getKey() const { return "17308"; } -nlohmann::json AuthorizationTopic::message(const std::string &message, StatusCode statusCode) { - nlohmann::json error = {{"message", message}, {"code", static_cast(statusCode)}}; - return error; +nlohmann::json AuthorizationTopic::message(const std::string& message, + StatusCode statusCode) +{ + return { + { "message", message }, + { "code", static_cast(statusCode) } + }; } -} +} // namespace openspace diff --git a/modules/server/src/topics/getpropertytopic.cpp b/modules/server/src/topics/getpropertytopic.cpp index 1297e9e422..d9e1c2387f 100644 --- a/modules/server/src/topics/getpropertytopic.cpp +++ b/modules/server/src/topics/getpropertytopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -65,7 +65,9 @@ void GetPropertyTopic::handleJson(json j) { response = wrappedPayload(sceneGraph()->allSceneGraphNodes()); } else if (requestedKey == AllScreenSpaceRenderablesValue) { - response = wrappedPayload({ { "value", OsEng.renderEngine().screenSpaceRenderables() } }); + response = wrappedPayload({ + { "value", OsEng.renderEngine().screenSpaceRenderables() } + }); } else if (requestedKey == RootPropertyOwner) { response = wrappedPayload(OsEng.rootPropertyOwner()); diff --git a/modules/server/src/topics/luascripttopic.cpp b/modules/server/src/topics/luascripttopic.cpp index 21c4bb3d9a..96c0c28e6a 100644 --- a/modules/server/src/topics/luascripttopic.cpp +++ b/modules/server/src/topics/luascripttopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -38,10 +38,13 @@ void LuaScriptTopic::handleJson(nlohmann::json json) { try { auto script = json.at(ScriptKey).get(); LDEBUG("Queueing Lua script: " + script); - OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::No); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::No + ); } - catch (std::out_of_range& e) { - LERROR("Could run script -- key or value is missing in payload"); + catch (const std::out_of_range& e) { + LERROR("Could not run script -- key or value is missing in payload"); LERROR(e.what()); } } diff --git a/modules/server/src/topics/setpropertytopic.cpp b/modules/server/src/topics/setpropertytopic.cpp index a371afcaed..9239e5f842 100644 --- a/modules/server/src/topics/setpropertytopic.cpp +++ b/modules/server/src/topics/setpropertytopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/topics/subscriptiontopic.cpp b/modules/server/src/topics/subscriptiontopic.cpp index bc1bd1845b..1860a22570 100644 --- a/modules/server/src/topics/subscriptiontopic.cpp +++ b/modules/server/src/topics/subscriptiontopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/topics/timetopic.cpp b/modules/server/src/topics/timetopic.cpp index 2f0f7419b2..31f3a713a3 100644 --- a/modules/server/src/topics/timetopic.cpp +++ b/modules/server/src/topics/timetopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/topics/topic.cpp b/modules/server/src/topics/topic.cpp index 6be5b7349b..dd84de279f 100644 --- a/modules/server/src/topics/topic.cpp +++ b/modules/server/src/topics/topic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/server/src/topics/triggerpropertytopic.cpp b/modules/server/src/topics/triggerpropertytopic.cpp index 144414a6a6..ad5b5a672d 100644 --- a/modules/server/src/topics/triggerpropertytopic.cpp +++ b/modules/server/src/topics/triggerpropertytopic.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -45,16 +45,16 @@ void TriggerPropertyTopic::handleJson(nlohmann::json json) { if (prop != nullptr) { LDEBUG("Triggering " + propertyKey); prop->set("poke"); - } + } else { LWARNING("Could not find property " + propertyKey); } } - catch (std::out_of_range& e) { + catch (const std::out_of_range& e) { LERROR("Could not poke property -- key or value is missing in payload"); LERROR(e.what()); } - catch (ghoul::RuntimeError e) { + catch (const ghoul::RuntimeError& e) { LERROR("Could not poke property -- runtime error:"); LERROR(e.what()); } diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp index 97a7099c0f..0280b9e11a 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp @@ -297,7 +297,7 @@ void RenderableShadowCylinder::deinitializeGL() { } ); _shader = nullptr; - + glDeleteVertexArrays(1, &_vao); _vao = 0; glDeleteBuffers(1, &_vbo); diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index 51a06cfe4b..365aa0523b 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -203,7 +203,7 @@ void UrlSynchronization::start() { // If we are forcing the override, we download to a temporary file first, // so when we are done here, we need to rename the file to the original // name - + const std::string& tempName = d->destination(); std::string originalName = tempName.substr( 0, diff --git a/modules/touch/ext/levmarq.cpp b/modules/touch/ext/levmarq.cpp index 2fecba156b..657ebef839 100644 --- a/modules/touch/ext/levmarq.cpp +++ b/modules/touch/ext/levmarq.cpp @@ -1,4 +1,4 @@ -/* +/* 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 @@ -26,6 +26,7 @@ OTHER DEALINGS IN THE SOFTWARE. #include #include #include +#include namespace { std::chrono::milliseconds TimeLimit(200); @@ -82,6 +83,20 @@ bool levmarq(int npar, double *par, int ny, double *dysq, double* d = new double[npar]; double* delta = new double[npar]; double* newpar = new double[npar]; + + defer { + // deallocate the arrays + for (i = 0; i < npar; i++) { + delete[] h[i]; + delete[] ch[i]; + } + delete[] h; + delete[] ch; + delete[] g; + delete[] d; + delete[] delta; + delete[] newpar; + }; verbose = lmstat->verbose; nit = lmstat->max_it; @@ -216,18 +231,6 @@ bool levmarq(int npar, double *par, int ny, double *dysq, lmstat->final_derr = derr; lmstat->data = data; - // deallocate the arrays - for (i = 0; i < npar; i++) { - delete[] h[i]; - delete[] ch[i]; - } - delete[] h; - delete[] ch; - delete[] g; - delete[] d; - delete[] delta; - delete[] newpar; - return (it != lmstat->max_it); } diff --git a/modules/touch/include/touchmarker.h b/modules/touch/include/touchmarker.h index b3aa625576..653284c8ab 100644 --- a/modules/touch/include/touchmarker.h +++ b/modules/touch/include/touchmarker.h @@ -70,7 +70,6 @@ private: std::vector _vertexData; GLuint _quad = 0; GLuint _vertexPositionBuffer = 0; - int _numFingers = 0; }; } // openspace namespace diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index e694c39505..9246f28462 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -607,7 +607,7 @@ void TouchInteraction::directControl(const std::vector& list) { _lmSuccess = levmarq( nDOF, par.data(), - screenPoints.size(), + static_cast(screenPoints.size()), nullptr, distToMinimize, gradient, @@ -905,11 +905,9 @@ int TouchInteraction::interpretInteraction(const std::vector& list, return ROT; } else { - float avgDistance = static_cast( - std::abs(dist - lastDist) / list.at(0).getMotionSpeed() - ); + float avgDistance = std::abs(dist - lastDist) / list.at(0).getMotionSpeed(); // if average distance between 3 fingers are constant we have panning - if (_panEnabled && (std::abs(dist - lastDist) / list.at(0).getMotionSpeed() < _interpretPan && list.size() == 3)) { + if (_panEnabled && (avgDistance < _interpretPan && list.size() == 3)) { return PAN; } @@ -917,9 +915,9 @@ int TouchInteraction::interpretInteraction(const std::vector& list, // centroid is over _rollAngleThreshold (_centroidStillThreshold is used to void // misinterpretations) else if (std::abs(minDiff) < _inputStillThreshold || - (std::abs(rollOn) < 100.0 && - normalizedCentroidDistance < _centroidStillThreshold)) { - + (std::abs(rollOn) < 100.0 && + normalizedCentroidDistance < _centroidStillThreshold)) + { return ROLL; } else { @@ -997,7 +995,10 @@ void TouchInteraction::computeVelocities(const std::vector& list, pinchConsecZoomFactor += zoomFactor; #endif if ((length(currDistanceToFocusNode) / distanceFromFocusSurface) > _zoomSensitivityDistanceThreshold) { - zoomFactor *= pow(distanceFromFocusSurface, (float)_zoomSensitivity); + zoomFactor *= pow( + distanceFromFocusSurface, + static_cast(_zoomSensitivity) + ); } _vel.zoom += zoomFactor * _sensitivity.zoom * std::max(_touchScreenSize.value() * 0.1, 1.0); diff --git a/modules/touch/src/touchmarker.cpp b/modules/touch/src/touchmarker.cpp index dfa5ebf227..5da6eaf0a8 100644 --- a/modules/touch/src/touchmarker.cpp +++ b/modules/touch/src/touchmarker.cpp @@ -33,7 +33,6 @@ namespace { const std::string _loggerCat = "TouchMarker"; - const int MAX_FINGERS = 20; static const openspace::properties::Property::PropertyInfo VisibilityInfo = { "Visibility", @@ -134,7 +133,7 @@ void TouchMarker::render(const std::vector& list) { glEnable(GL_PROGRAM_POINT_SIZE); // Enable gl_PointSize in vertex shader glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glBindVertexArray(_quad); - glDrawArrays(GL_POINTS, 0, _vertexData.size() / 2); + glDrawArrays(GL_POINTS, 0, static_cast(_vertexData.size() / 2)); _shader->deactivate(); } @@ -152,7 +151,12 @@ void TouchMarker::createVertexList(const std::vector& list) { glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, _vertexData.size() * sizeof(GLfloat), _vertexData.data(), GL_STATIC_DRAW); + glBufferData( + GL_ARRAY_BUFFER, + _vertexData.size() * sizeof(GLfloat), + _vertexData.data(), + GL_STATIC_DRAW + ); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, diff --git a/modules/volume/envelope.cpp b/modules/volume/envelope.cpp index e4db69a95b..8b74f5091a 100644 --- a/modules/volume/envelope.cpp +++ b/modules/volume/envelope.cpp @@ -1,176 +1,223 @@ +/***************************************************************************************** + * * + * 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 { - namespace volume { - Envelope::Envelope() { } +namespace openspace::volume { - Envelope::Envelope(std::vector vec) { - _points = vec; - } +EnvelopePoint::EnvelopePoint(glm::vec3 c, float x, float y) + : color(c) + , colorHex(getHexadecimalFromVec3(c)) + , position(std::make_pair(x, y)) +{} - bool Envelope::operator!=(const Envelope& env) const { - const double minDist = 0.0001; +EnvelopePoint::EnvelopePoint(std::string c, float x, float y) + : color(hexadecimalToRGBConversion(c)) + , colorHex(c) + , position(std::make_pair(x, y)) +{} - if (_points.size() != env._points.size()) - return true; +Envelope::Envelope() {} - auto iter = _points.begin(); - auto envIter = env._points.begin(); - for (; iter != _points.end(); ++iter, ++envIter) { - if (abs(iter->position.first - envIter->position.first) > minDist || - abs(iter->position.second - envIter->position.second) > minDist || - iter->color != envIter->color) - return true; - } - return false; - } +Envelope::Envelope(std::vector vec) { + _points = vec; +} +bool Envelope::operator!=(const Envelope& env) const { + const double minDist = 0.0001; - void Envelope::setPoints(std::vector vec) { - this->_points = vec; - } + if (_points.size() != env._points.size()) { + return true; + } - std::vector Envelope::getPoints() { - return _points; - } - - bool Envelope::isValueInEnvelope(float pos) const { - if (!_points.empty()) { - if (_points.front().position.first <= pos && _points.back().position.first >= pos) - return true; - } - return false; - } - - bool Envelope::isEnvelopeValid() const { - auto currentIter = _points.begin(); - auto nextIter = currentIter + 1; - for (; nextIter != _points.end(); ++currentIter, ++nextIter) { - if (currentIter->position.first > nextIter->position.first) - return false; - } + auto iter = _points.begin(); + auto envIter = env._points.begin(); + for (; iter != _points.end(); ++iter, ++envIter) { + if (abs(iter->position.first - envIter->position.first) > minDist || + abs(iter->position.second - envIter->position.second) > minDist || + iter->color != envIter->color) return true; - } + } + return false; +} - glm::vec3 Envelope::normalizeColor(glm::vec3 vec) const{ - return glm::vec3{ vec.r / 255.f, vec.g / 255.f , vec.b / 255.f }; - } - - glm::vec4 Envelope::getValueAtPosition(float pos) const { - auto afterIter = _points.begin(); - glm::vec4 color{ 0.f, 0.f , 0.f , 0.f }; - while (afterIter->position.first < pos ) { - if(afterIter == _points.end()) - return color; - ++afterIter; - } - if (afterIter->position.first == pos) { - return glm::vec4{ afterIter->color, afterIter->position.second }; - } - auto beforeIter = afterIter -1; +void Envelope::setPoints(std::vector vec) { + this->_points = vec; +} - float dist = afterIter->position.first - beforeIter->position.first; - float alpha; - if(dist < 0.0001) - color = { normalizeColor((beforeIter->color + afterIter->color) / 2.f), - std::max(beforeIter->position.second, afterIter->position.second) }; - else - color = { normalizeColor(beforeIter->color *(abs(pos - afterIter->position.first) / dist) + afterIter->color *(abs(pos - beforeIter->position.first) / dist)), - beforeIter->position.second *(abs(pos - afterIter->position.first) / dist) + afterIter->position.second *(abs(pos - beforeIter->position.first) / dist) }; +std::vector Envelope::getPoints() { + return _points; +} +bool Envelope::isValueInEnvelope(float pos) const { + if (!_points.empty()) { + if (_points.front().position.first <= pos && _points.back().position.first >= pos) + return true; + } + return false; +} + +bool Envelope::isEnvelopeValid() const { + auto currentIter = _points.begin(); + auto nextIter = currentIter + 1; + for (; nextIter != _points.end(); ++currentIter, ++nextIter) { + if (currentIter->position.first > nextIter->position.first) + return false; + } + return true; +} + +glm::vec3 Envelope::normalizeColor(glm::vec3 vec) const{ + + return glm::vec3{ vec.r / 255.f, vec.g / 255.f , vec.b / 255.f }; +} + +glm::vec4 Envelope::getValueAtPosition(float pos) const { + auto afterIter = _points.begin(); + glm::vec4 color{ 0.f, 0.f , 0.f , 0.f }; + while (afterIter->position.first < pos ) { + if(afterIter == _points.end()) return color; - } + ++afterIter; + } + if (afterIter->position.first == pos) { + return glm::vec4{ afterIter->color, afterIter->position.second }; + } + auto beforeIter = afterIter -1; - int EnvelopePoint::HexadecimalToDecimal(std::string hex) const { - int hexLength = hex.length(); - double dec = 0; - for (int i = 0; i < hexLength; ++i) - { - char b = hex[i]; + float dist = afterIter->position.first - beforeIter->position.first; + float alpha; + if(dist < 0.0001) + color = { normalizeColor((beforeIter->color + afterIter->color) / 2.f), + std::max(beforeIter->position.second, afterIter->position.second) }; + else + color = { + normalizeColor( + beforeIter->color * (abs(pos - afterIter->position.first) / dist) + + afterIter->color * (abs(pos - beforeIter->position.first) / dist) + ), + beforeIter->position.second * (abs(pos - afterIter->position.first) / dist) + + afterIter->position.second * + (abs(pos - beforeIter->position.first) / dist) + }; - if (b >= 48 && b <= 57) - b -= 48; - else if (b >= 65 && b <= 70) - b -= 55; - else if (b >= 97 && b <= 102) - b -= 87; - dec += b * pow(16, ((hexLength - i) - 1)); + return color; +} + +int EnvelopePoint::HexadecimalToDecimal(std::string hex) const { + int hexLength = hex.length(); + double dec = 0; + for (int i = 0; i < hexLength; ++i) + { + char b = hex[i]; + + if (b >= 48 && b <= 57) + b -= 48; + else if (b >= 65 && b <= 70) + b -= 55; + else if (b >= 97 && b <= 102) + b -= 87; + dec += b * pow(16, ((hexLength - i) - 1)); + } + return (int)dec; +} + +std::string EnvelopePoint::DecimalToHexadecimal(int dec) const { + if (dec < 1) return "00"; + + int hex = dec; + std::string hexStr = ""; + + while (dec > 0) + { + hex = dec % 16; + + if (hex < 10) + hexStr = hexStr.insert(0, std::string(1, (hex + 48))); + else + hexStr = hexStr.insert(0, std::string(1, (hex + 55))); + dec /= 16; + } + return hexStr; +} + +glm::vec3 EnvelopePoint::hexadecimalToRGBConversion(std::string hex) const { + float r = static_cast(HexadecimalToDecimal(hex.substr(1, 2))); + float g = static_cast(HexadecimalToDecimal(hex.substr(3, 2))); + float b = static_cast(HexadecimalToDecimal(hex.substr(5, 2))); + + return glm::vec3(r, g, b); +} + +std::string EnvelopePoint::getHexadecimalFromVec3(glm::vec3 vec) const { + + std::string r = DecimalToHexadecimal(static_cast(vec.r)); + std::string g = DecimalToHexadecimal(static_cast(vec.g)); + std::string b = DecimalToHexadecimal(static_cast(vec.b)); + + return ("#" + r + g + b); +} + +json Envelope::getJSONPoints() const { + json j; + for (int i = 0; i < _points.size(); i++) { + j[i] = { + { "color", _points.at(i).colorHex }, + { "position",{ + { "x", _points.at(i).position.first }, + { "y", _points.at(i).position.second }, + }, } - return (int)dec; - } + }; + } + return j; +} - std::string EnvelopePoint::DecimalToHexadecimal(int dec) const { - if (dec < 1) return "00"; +json Envelope::getJSONEnvelope() const { + json j; + j["points"] = getJSONPoints(); + return j; +} - int hex = dec; - std::string hexStr = ""; +void Envelope::setEnvelopeLuaTable(lua_State* state) const { + for (auto iter = _points.begin(); iter != _points.end(); ++iter) { + lua_newtable(state); + lua_pushstring(state, iter->colorHex.c_str()); + lua_setfield(state, -2, "color"); + lua_newtable(state); + lua_pushnumber(state, static_cast(iter->position.first)); + lua_setfield(state, -2, "x"); + lua_pushnumber(state, static_cast(iter->position.second)); + lua_setfield(state, -2, "y"); + lua_setfield(state, -2, "position"); + lua_setfield( + state, + -2, + ("[\"" + std::to_string(iter - _points.begin() + 1) + "\"]").c_str() + ); + } +} - while (dec > 0) - { - hex = dec % 16; - - if (hex < 10) - hexStr = hexStr.insert(0, std::string(1, (hex + 48))); - else - hexStr = hexStr.insert(0, std::string(1, (hex + 55))); - dec /= 16; - } - return hexStr; - } - - glm::vec3 EnvelopePoint::hexadecimalToRGBConversion(std::string hex) const { - float r = static_cast(HexadecimalToDecimal(hex.substr(1, 2))); - float g = static_cast(HexadecimalToDecimal(hex.substr(3, 2))); - float b = static_cast(HexadecimalToDecimal(hex.substr(5, 2))); - - return glm::vec3(r, g, b); - } - - std::string EnvelopePoint::getHexadecimalFromVec3(glm::vec3 vec) const { - - std::string r = DecimalToHexadecimal(static_cast(vec.r)); - std::string g = DecimalToHexadecimal(static_cast(vec.g)); - std::string b = DecimalToHexadecimal(static_cast(vec.b)); - - return ("#" + r + g + b); - } - - json Envelope::getJSONPoints() const { - json j; - for (int i = 0; i < _points.size(); i++) { - j[i] = { - { "color", _points.at(i).colorHex }, - { "position",{ - { "x", _points.at(i).position.first }, - { "y", _points.at(i).position.second }, - }, - } - }; - } - return j; - } - - json Envelope::getJSONEnvelope() const { - json j; - j["points"] = getJSONPoints(); - return j; - } - - void Envelope::setEnvelopeLuaTable(lua_State* state) const { - for (auto iter = _points.begin(); iter != _points.end(); ++iter) { - lua_newtable(state); - lua_pushstring(state, iter->colorHex.c_str()); - lua_setfield(state, -2, "color"); - lua_newtable(state); - lua_pushnumber(state, static_cast(iter->position.first)); - lua_setfield(state, -2, "x"); - lua_pushnumber(state, static_cast(iter->position.second)); - lua_setfield(state, -2, "y"); - lua_setfield(state, -2, "position"); - lua_setfield(state, -2, ("[\"" + std::to_string(iter - _points.begin() + 1) + "\"]").c_str()); - } - } - - }//namespace volume -}//namespace openspace +} //namespace openspace::volume diff --git a/modules/volume/envelope.h b/modules/volume/envelope.h index 5a251ed917..d9b98e1120 100644 --- a/modules/volume/envelope.h +++ b/modules/volume/envelope.h @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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_MODULE_VOLUME___ENVELOPE___H__ #define __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__ @@ -32,46 +32,46 @@ using json = nlohmann::json; -namespace openspace { - namespace volume { - class EnvelopePoint { - public: - EnvelopePoint(glm::vec3 c, float x, float y) : color(c), colorHex(getHexadecimalFromVec3(c)), position(std::make_pair(x, y)) {} - EnvelopePoint(std::string c, float x, float y) : color(hexadecimalToRGBConversion(c)), colorHex(c), position(std::make_pair(x, y)) {} +namespace openspace::volume { - int HexadecimalToDecimal(std::string hex) const; - std::string DecimalToHexadecimal(int dec) const; - glm::vec3 hexadecimalToRGBConversion(std::string hex) const; - std::string getHexadecimalFromVec3(glm::vec3 vec) const; +class EnvelopePoint { +public: + EnvelopePoint(glm::vec3 c, float x, float y); + EnvelopePoint(std::string c, float x, float y); - glm::vec3 color; - std::string colorHex; - std::pair position; - }; - class Envelope { - public: - Envelope(); - Envelope(std::vector vec); + int HexadecimalToDecimal(std::string hex) const; + std::string DecimalToHexadecimal(int dec) const; + glm::vec3 hexadecimalToRGBConversion(std::string hex) const; + std::string getHexadecimalFromVec3(glm::vec3 vec) const; - void setPoints(std::vector vec); - std::vector getPoints(); + glm::vec3 color; + std::string colorHex; + std::pair position; +}; - glm::vec4 getValueAtPosition(float pos) const; - glm::vec3 normalizeColor(glm::vec3 vec) const; - json getJSONPoints() const; - json getJSONEnvelope() const; - void setEnvelopeLuaTable(lua_State* state) const; +class Envelope { +public: + Envelope(); + Envelope(std::vector vec); - bool isValueInEnvelope(float pos) const; - bool isEnvelopeValid() const; + void setPoints(std::vector vec); + std::vector getPoints(); - bool operator!=(const Envelope& env) const; + glm::vec4 getValueAtPosition(float pos) const; + glm::vec3 normalizeColor(glm::vec3 vec) const; + json getJSONPoints() const; + json getJSONEnvelope() const; + void setEnvelopeLuaTable(lua_State* state) const; - private: - - std::vector _points; - }; + bool isValueInEnvelope(float pos) const; + bool isEnvelopeValid() const; - }//namespace volume -}//namespace openspace -#endif __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__ + bool operator!=(const Envelope& env) const; + +private: + std::vector _points; +}; + +} //namespace openspace::volume + +#endif // __OPENSPACE_MODULE_VOLUME___ENVELOPE___H__ diff --git a/modules/volume/rendering/basicvolumeraycaster.h b/modules/volume/rendering/basicvolumeraycaster.h index d15c3c8bd0..9c691ed68d 100644 --- a/modules/volume/rendering/basicvolumeraycaster.h +++ b/modules/volume/rendering/basicvolumeraycaster.h @@ -80,7 +80,8 @@ public: void setVolumeTexture(std::shared_ptr texture); std::shared_ptr volumeTexture() const; - void setTransferFunctionHandler(std::shared_ptr transferFunctionHandler); + void setTransferFunctionHandler( + std::shared_ptr transferFunctionHandler); void setStepSize(float stepSize); float opacity() const; diff --git a/modules/volume/transferfunction.cpp b/modules/volume/transferfunction.cpp index f6d4ff7c19..f4bdffca6b 100644 --- a/modules/volume/transferfunction.cpp +++ b/modules/volume/transferfunction.cpp @@ -1,28 +1,29 @@ -/**************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ +/***************************************************************************************** + * * + * 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 diff --git a/modules/volume/transferfunction.h b/modules/volume/transferfunction.h index 9f807788de..34327329db 100644 --- a/modules/volume/transferfunction.h +++ b/modules/volume/transferfunction.h @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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_MODULE_VOLUME___TRANSFERFUNCTION___H__ #define __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__ @@ -30,40 +30,39 @@ namespace ghoul { class Dictionary; } -namespace openspace { - namespace volume { - class TransferFunction { - public: - TransferFunction(); - TransferFunction(int s); - TransferFunction(std::string); - TransferFunction(const TransferFunction& tf); - TransferFunction(TransferFunction&& tf); +namespace openspace::volume { +class TransferFunction { +public: + TransferFunction(); + TransferFunction(int s); + TransferFunction(std::string); + TransferFunction(const TransferFunction& tf); + TransferFunction(TransferFunction&& tf); - bool getEnvelopesToLua(lua_State* state); - - bool setEnvelopesFromString(std::string s); - bool setEnvelopesFromLua(lua_State* lua); + bool getEnvelopesToLua(lua_State* state); - void loadEnvelopesFromFile(const std::string& path); - void saveEnvelopesToFile(const std::string& path); + bool setEnvelopesFromString(std::string s); + bool setEnvelopesFromLua(lua_State* lua); - TransferFunction& operator=(const TransferFunction& tf); - TransferFunction& operator=(TransferFunction&& tf); - bool operator!=(const TransferFunction& tf); - bool hasEnvelopes() const; + void loadEnvelopesFromFile(const std::string& path); + void saveEnvelopesToFile(const std::string& path); - bool createTexture(std::shared_ptr ptr); - std::string getSerializedToString() const; + TransferFunction& operator=(const TransferFunction& tf); + TransferFunction& operator=(TransferFunction&& tf); + bool operator!=(const TransferFunction& tf); + bool hasEnvelopes() const; - private: - int _width = 1024; - double lower = 0.0; - double upper = 1.0; - std::string _loadableFilePath; - std::vector _envelopes; - }; + bool createTexture(std::shared_ptr ptr); + std::string getSerializedToString() const; - }//namespace volume -}//namespace openspace -#endif __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__ +private: + int _width = 1024; + double lower = 0.0; + double upper = 1.0; + std::string _loadableFilePath; + std::vector _envelopes; +}; + +} // namespace openspace::volume + +#endif // __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTION___H__ diff --git a/modules/volume/transferfunctionhandler.cpp b/modules/volume/transferfunctionhandler.cpp index 82b75ae4d5..4e30c6c35b 100644 --- a/modules/volume/transferfunctionhandler.cpp +++ b/modules/volume/transferfunctionhandler.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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 diff --git a/modules/volume/transferfunctionhandler.h b/modules/volume/transferfunctionhandler.h index f526c61d21..cdfaaa567e 100644 --- a/modules/volume/transferfunctionhandler.h +++ b/modules/volume/transferfunctionhandler.h @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__ #define __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__ @@ -41,17 +41,16 @@ #include #include -namespace openspace { -namespace volume { +namespace openspace::volume { class Envelope; - + class TransferFunctionHandler : public properties::PropertyOwner{ public: TransferFunctionHandler(const properties::StringProperty& prop); - + void initialize(); - + void setHistogramProperty(std::shared_ptr histogram); void setTexture(); @@ -81,6 +80,6 @@ private: std::shared_ptr _texture = nullptr; }; -}//namespace volume -}//namespace openspace -#endif __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__ +} //namespace openspace::volume + +#endif // __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONHANDLER___H__ diff --git a/modules/volume/transferfunctionproperty.cpp b/modules/volume/transferfunctionproperty.cpp index 6c6a84d043..dbd8ab5b6c 100644 --- a/modules/volume/transferfunctionproperty.cpp +++ b/modules/volume/transferfunctionproperty.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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 diff --git a/modules/volume/transferfunctionproperty.h b/modules/volume/transferfunctionproperty.h index ccd981b23f..9754e4ee6b 100644 --- a/modules/volume/transferfunctionproperty.h +++ b/modules/volume/transferfunctionproperty.h @@ -1,37 +1,37 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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___TRANSFERFUNCTIONPROPERTY___H__ -#define __OPENSPACE_CORE___TRANSFERFUNCTIONPROPERTY___H__ +#ifndef __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONPROPERTY___H__ +#define __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONPROPERTY___H__ #include #include namespace openspace::properties { - REGISTER_TEMPLATEPROPERTY_HEADER(TransferFunctionProperty, volume::TransferFunction) +REGISTER_TEMPLATEPROPERTY_HEADER(TransferFunctionProperty, volume::TransferFunction) } // namespace openspace::properties -#endif // __OPENSPACE_CORE___TRANSFERFUNCTIONPROPERTY___H__ +#endif // __OPENSPACE_MODULE_VOLUME___TRANSFERFUNCTIONPROPERTY___H__ diff --git a/modules/volume/volumegridtype.cpp b/modules/volume/volumegridtype.cpp index 9c2d6f29e9..87fe622a12 100644 --- a/modules/volume/volumegridtype.cpp +++ b/modules/volume/volumegridtype.cpp @@ -26,8 +26,7 @@ #include -namespace openspace { -namespace volume { +namespace openspace::volume { VolumeGridType parseGridType(const std::string& gridType) { if (gridType == "Cartesian") { @@ -44,5 +43,4 @@ InvalidGridTypeError::InvalidGridTypeError(std::string gt) , gridType(std::move(gt)) {} -} // namespace volume -} // namespace openspace +} // namespace openspace::volume diff --git a/modules/volume/volumegridtype.h b/modules/volume/volumegridtype.h index 7993cadb4a..8997d699db 100644 --- a/modules/volume/volumegridtype.h +++ b/modules/volume/volumegridtype.h @@ -22,13 +22,12 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE_H__ -#define __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE_H__ +#ifndef __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE___H__ +#define __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE___H__ #include -namespace openspace { -namespace volume { +namespace openspace::volume { enum class VolumeGridType : int { Cartesian = 0, @@ -36,13 +35,12 @@ enum class VolumeGridType : int { }; struct InvalidGridTypeError : public ghoul::RuntimeError { - explicit InvalidGridTypeError(std::string gridType); - std::string gridType; + explicit InvalidGridTypeError(std::string gridType); + std::string gridType; }; VolumeGridType parseGridType(const std::string& gridType); -} // namespace volume -} // namespace openspace +} // namespace openspace::volume -#endif // __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE_H__ +#endif // __OPENSPACE_MODULE_VOLUME___VOLUMEGRIDTYPE___H__ diff --git a/modules/webbrowser/CMakeLists.txt b/modules/webbrowser/CMakeLists.txt index fcbd21acde..6bfd9f485c 100644 --- a/modules/webbrowser/CMakeLists.txt +++ b/modules/webbrowser/CMakeLists.txt @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2017 # +# 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 # @@ -152,7 +152,7 @@ if(OS_MACOSX) target_link_libraries(${CEF_HELPER_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) set_target_properties(${CEF_HELPER_TARGET} PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/helper-Info.plist - ) + ) # Fix the framework rpath in the helper executable. FIX_MACOSX_HELPER_FRAMEWORK_RPATH(${CEF_HELPER_TARGET}) diff --git a/modules/webbrowser/include/browserclient.h b/modules/webbrowser/include/browserclient.h index 1a2ed9937b..be1922626e 100644 --- a/modules/webbrowser/include/browserclient.h +++ b/modules/webbrowser/include/browserclient.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -51,4 +51,4 @@ private: } // namespace openspace -#endif // __OPENSPACE_MODULE_WEBBROWSER___BROWSER_CLIENT___H__ +#endif // __OPENSPACE_MODULE_WEBBROWSER___BROWSER_CLIENT___H__ diff --git a/modules/webbrowser/include/browserinstance.h b/modules/webbrowser/include/browserinstance.h index 0c9247df27..fc3f472e7e 100644 --- a/modules/webbrowser/include/browserinstance.h +++ b/modules/webbrowser/include/browserinstance.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -47,8 +47,9 @@ public: void close(bool force = false); bool sendKeyEvent(const CefKeyEvent &event); - bool sendMouseClickEvent(const CefMouseEvent &event, CefBrowserHost::MouseButtonType button, - bool mouseUp, int clickCount = SINGLE_CLICK); + bool sendMouseClickEvent(const CefMouseEvent &event, + CefBrowserHost::MouseButtonType button, bool mouseUp, + int clickCount = SINGLE_CLICK); bool sendMouseMoveEvent(const CefMouseEvent &event); bool sendMouseWheelEvent(const CefMouseEvent &event, glm::ivec2 delta); void reloadBrowser(); @@ -66,6 +67,6 @@ private: bool _isInitialized; }; -} +} // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER__BROWSER_INSTANCE_H +#endif // __OPENSPACE_MODULE_WEBBROWSER__BROWSER_INSTANCE_H diff --git a/modules/webbrowser/include/cefhost.h b/modules/webbrowser/include/cefhost.h index 886d3f70d4..cbede7013c 100644 --- a/modules/webbrowser/include/cefhost.h +++ b/modules/webbrowser/include/cefhost.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_WEBBROWSER__CEF_HOST_H -#define __OPENSPACE_MODULE_WEBBROWSER__CEF_HOST_H +#ifndef __OPENSPACE_MODULE_WEBBROWSER___CEF_HOST___H__ +#define __OPENSPACE_MODULE_WEBBROWSER___CEF_HOST___H__ #include #include @@ -46,4 +46,4 @@ private: } // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER__CEF_HOST_H +#endif // __OPENSPACE_MODULE_WEBBROWSER___CEF_HOST___H__ diff --git a/modules/webbrowser/include/defaultbrowserlauncher.h b/modules/webbrowser/include/defaultbrowserlauncher.h index 6b37809c74..436caa399c 100644 --- a/modules/webbrowser/include/defaultbrowserlauncher.h +++ b/modules/webbrowser/include/defaultbrowserlauncher.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -33,17 +33,13 @@ namespace openspace { class DefaultBrowserLauncher : public CefLifeSpanHandler, public CefRequestHandler { public: - bool OnBeforePopup(CefRefPtr parentBrowser, - const CefPopupFeatures& popupFeatures, - CefWindowInfo& windowInfo, - const CefString& url, - CefRefPtr& client, - CefBrowserSettings& settings); - bool OnOpenURLFromTab(CefRefPtr browser, - CefRefPtr frame, - const CefString& target_url, - CefRequestHandler::WindowOpenDisposition target_disposition, - bool user_gesture); + bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, + const CefString& url, CefRefPtr& client, CefBrowserSettings& settings); + + bool OnOpenURLFromTab(CefRefPtr browser, CefRefPtr frame, + const CefString& target_url, + CefRequestHandler::WindowOpenDisposition target_disposition, bool userGesture); private: void launchBrowser(const std::string &url) const; @@ -52,4 +48,4 @@ private: } // namespace openspace -#endif // __OPENSPACE_MODULE_WEBBROWSER___DEFAULT_BROWSER_LAUNCHER___H__ +#endif // __OPENSPACE_MODULE_WEBBROWSER___DEFAULT_BROWSER_LAUNCHER___H__ diff --git a/modules/webbrowser/include/eventhandler.h b/modules/webbrowser/include/eventhandler.h index 75813a3880..658810c80a 100644 --- a/modules/webbrowser/include/eventhandler.h +++ b/modules/webbrowser/include/eventhandler.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,7 +22,6 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ - #ifndef __OPENSPACE_MODULE_WEBBROWSER___EVENT_HANDLER___H__ #define __OPENSPACE_MODULE_WEBBROWSER___EVENT_HANDLER___H__ @@ -37,8 +36,6 @@ namespace openspace { class EventHandler { public: - EventHandler() : _mousePosition(0, 0), _browserInstance(nullptr), _lastClickPosition(0, 0) {}; - void initialize(); void setBrowser(const CefRefPtr &browser); void setBrowserInstance(const std::shared_ptr & browserInstance); @@ -62,8 +59,9 @@ private: bool _leftMouseDown = false; - std::shared_ptr _browserInstance; - glm::vec2 _mousePosition, _lastClickPosition; + std::shared_ptr _browserInstance = nullptr; + glm::vec2 _mousePosition = { 0.f, 0.f }; + glm::vec2 _lastClickPosition = { 0.f, 0.f }; std::chrono::high_resolution_clock::time_point _lastClickTime; /** @@ -73,19 +71,21 @@ private: bool isDoubleClick() const; /** - * get the number of milliseconds that is allowed between two clicks for it to count as a double click + * get the number of milliseconds that is allowed between two clicks for it to count + * as a double click * @return */ static int doubleClickTime(); /** - * get the rectangle width around the first click in a double click that the second click has to be _within_ + * get the rectangle width around the first click in a double click that the second + * click has to be _within_ * @return */ static int maxDoubleClickDistance(); }; -} +} // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER___EVENT_HANDLER___H__ +#endif // __OPENSPACE_MODULE_WEBBROWSER___EVENT_HANDLER___H__ diff --git a/modules/webbrowser/include/screenspacebrowser.h b/modules/webbrowser/include/screenspacebrowser.h index a02d39c89c..359ff6a78d 100644 --- a/modules/webbrowser/include/screenspacebrowser.h +++ b/modules/webbrowser/include/screenspacebrowser.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_WEBBROWSER__SCREEN_SPACE_BROWSER_H -#define __OPENSPACE_MODULE_WEBBROWSER__SCREEN_SPACE_BROWSER_H +#ifndef __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_BROWSER___H__ +#define __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_BROWSER___H__ #include #include @@ -36,19 +36,6 @@ #include "include/screenspacerenderhandler.h" #include "include/browserinstance.h" -namespace { -static const openspace::properties::Property::PropertyInfo BrowserDimensionsInfo = { - "Dimensions", - "Browser Dimensions", - "Set the dimensions of the web browser windows." -}; -static const openspace::properties::Property::PropertyInfo UrlInfo = { - "URL", - "url", - "The URL to load" -}; -} - namespace openspace { class ScreenSpaceBrowser : public ScreenSpaceRenderable { @@ -72,6 +59,6 @@ private: bool _dimensionsAreDirty; }; -}; +} // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER__SCREEN_SPACE_BROWSER_H +#endif // __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_BROWSER___H__ diff --git a/modules/webbrowser/include/screenspacerenderhandler.h b/modules/webbrowser/include/screenspacerenderhandler.h index f1de964115..28b8dffbc5 100644 --- a/modules/webbrowser/include/screenspacerenderhandler.h +++ b/modules/webbrowser/include/screenspacerenderhandler.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER_H -#define __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER_H +#ifndef __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER___H__ +#define __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER___H__ #include "include/webrenderhandler.h" @@ -31,14 +31,12 @@ namespace openspace { class ScreenSpaceRenderHandler : public WebRenderHandler { public: - ScreenSpaceRenderHandler() {}; - - void draw(void); + void draw(); void render(); void setTexture(const GLuint&); }; -} +} // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER_H +#endif // __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_RENDER_HANDLER___H__ diff --git a/modules/webbrowser/include/webbrowserapp.h b/modules/webbrowser/include/webbrowserapp.h index 0a84373e2a..7c8544135f 100644 --- a/modules/webbrowser/include/webbrowserapp.h +++ b/modules/webbrowser/include/webbrowserapp.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_MODULE_WEBBROWSER__WEBBROWSERAPP_H -#define __OPENSPACE_MODULE_WEBBROWSER__WEBBROWSERAPP_H +#ifndef __OPENSPACE_MODULE_WEBBROWSER___WEBBROWSERAPP___H__ +#define __OPENSPACE_MODULE_WEBBROWSER___WEBBROWSERAPP___H__ #include #include @@ -39,11 +39,13 @@ public: WebBrowserApp(); CefRefPtr GetRenderProcessHandler() override; - void OnContextCreated(CefRefPtr, CefRefPtr, CefRefPtr) override; + void OnContextCreated(CefRefPtr, CefRefPtr, + CefRefPtr) override; private: IMPLEMENT_REFCOUNTING(WebBrowserApp); }; -}; -#endif // __OPENSPACE_MODULE_WEBBROWSER__WEBBROWSERAPP_H +} // namespace openspace + +#endif // __OPENSPACE_MODULE_WEBBROWSER___WEBBROWSERAPP___H__ diff --git a/modules/webbrowser/include/webrenderhandler.h b/modules/webbrowser/include/webrenderhandler.h index 8e489d9bbc..e883465e9f 100644 --- a/modules/webbrowser/include/webrenderhandler.h +++ b/modules/webbrowser/include/webrenderhandler.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -47,8 +47,8 @@ public: void reshape(int, int); bool GetViewRect(CefRefPtr browser, CefRect &rect) override; - void OnPaint(CefRefPtr browser, PaintElementType type, const RectList &dirtyRects, const void *buffer, - int width, int height) override; + void OnPaint(CefRefPtr browser, PaintElementType type, + const RectList &dirtyRects, const void* buffer, int width, int height) override; bool hasContent(int x, int y); protected: @@ -73,4 +73,4 @@ protected: } // namespace openspace -#endif //__OPENSPACE_MODULE_WEBBROWSER__WEB_RENDER_HANDLER_H +#endif // __OPENSPACE_MODULE_WEBBROWSER__WEB_RENDER_HANDLER_H diff --git a/modules/webbrowser/src/browserclient.cpp b/modules/webbrowser/src/browserclient.cpp index 040021a160..ad9a17e113 100644 --- a/modules/webbrowser/src/browserclient.cpp +++ b/modules/webbrowser/src/browserclient.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/src/browserinstance.cpp b/modules/webbrowser/src/browserinstance.cpp index 1b8434e335..bd84354f45 100644 --- a/modules/webbrowser/src/browserinstance.cpp +++ b/modules/webbrowser/src/browserinstance.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -32,7 +32,9 @@ const bool DID_NOT_LEAVE_WINDOW = false; namespace openspace { -BrowserInstance::BrowserInstance(WebRenderHandler* renderer) : _isInitialized(false) { +BrowserInstance::BrowserInstance(WebRenderHandler* renderer) + : _isInitialized(false) +{ _renderHandler = renderer; _client = new BrowserClient(_renderHandler); @@ -44,7 +46,13 @@ BrowserInstance::BrowserInstance(WebRenderHandler* renderer) : _isInitialized(fa browserSettings.windowless_frame_rate = 60; std::string url = ""; - _browser = CefBrowserHost::CreateBrowserSync(windowInfo, _client.get(), url, browserSettings, NULL); + _browser = CefBrowserHost::CreateBrowserSync( + windowInfo, + _client.get(), + url, + browserSettings, + nullptr + ); } BrowserInstance::~BrowserInstance() { @@ -52,7 +60,7 @@ BrowserInstance::~BrowserInstance() { } void BrowserInstance::initialize() { - auto &wrapper = OsEng.windowWrapper(); + auto& wrapper = OsEng.windowWrapper(); reshape(wrapper.currentWindowSize()); _isInitialized = true; @@ -112,8 +120,10 @@ bool BrowserInstance::sendKeyEvent(const CefKeyEvent &event) { return false; } -bool BrowserInstance::sendMouseClickEvent(const CefMouseEvent &event, CefBrowserHost::MouseButtonType button, - bool mouseUp, int clickCount) { +bool BrowserInstance::sendMouseClickEvent(const CefMouseEvent &event, + CefBrowserHost::MouseButtonType button, + bool mouseUp, int clickCount) +{ _browser->GetHost()->SendMouseClickEvent(event, button, mouseUp, clickCount); return hasContent(event.x, event.y); } diff --git a/modules/webbrowser/src/cefhost.cpp b/modules/webbrowser/src/cefhost.cpp index 3ddee68ec8..d24434a35f 100644 --- a/modules/webbrowser/src/cefhost.cpp +++ b/modules/webbrowser/src/cefhost.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -35,7 +35,10 @@ CefHost::CefHost(std::string helperLocation) { CefMainArgs args; CefSettings settings; - CefString(&settings.browser_subprocess_path).FromASCII((char*) helperLocation.c_str()); + CefString(&settings.browser_subprocess_path).FromASCII( + // This is bad as it casts away the const + (char*) helperLocation.c_str() + ); attachDebugSettings(settings); #ifdef WIN32 @@ -55,7 +58,10 @@ CefHost::~CefHost() { void CefHost::attachDebugSettings(CefSettings &settings) { settings.remote_debugging_port = 8088; - LDEBUG(fmt::format("Remote WebBrowser debugging available on http://localhost:{}", settings.remote_debugging_port)); + LDEBUG(fmt::format( + "Remote WebBrowser debugging available on http://localhost:{}", + settings.remote_debugging_port + )); // settings.single_process = true; } diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index 87233d9f9a..229ff51a95 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/src/eventhandler.cpp b/modules/webbrowser/src/eventhandler.cpp index 174dd24109..62b3b35211 100644 --- a/modules/webbrowser/src/eventhandler.cpp +++ b/modules/webbrowser/src/eventhandler.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -28,10 +28,11 @@ #include "include/eventhandler.h" namespace { -const std::string _loggerCat = "WebBrowser:EventHandler"; -} + const std::string _loggerCat = "WebBrowser:EventHandler"; +} // namespace namespace openspace { + void EventHandler::initialize() { OsEng.registerModuleCharCallback( [this](unsigned int charCode, KeyModifier mod) -> bool { @@ -96,7 +97,12 @@ bool EventHandler::mouseButtonCallback(MouseButton button, MouseAction action) { _lastClickPosition = _mousePosition; } - return _browserInstance->sendMouseClickEvent(mouseEvent(), MBT_LEFT, !_leftMouseDown, clickCount); + return _browserInstance->sendMouseClickEvent( + mouseEvent(), + MBT_LEFT, + !_leftMouseDown, + clickCount + ); } bool EventHandler::isDoubleClick() const { @@ -159,7 +165,8 @@ bool EventHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction act } /** - * Detect if there is a special event that should be caught by the GUI before it is sent to CEF + * Detect if there is a special event that should be caught by the GUI before it is sent + * to CEF. * @param key the pressed key * @return true if event found, false otherwise */ @@ -222,14 +229,18 @@ CefMouseEvent EventHandler::mouseEvent() { return event; } -void EventHandler::setBrowserInstance(const std::shared_ptr &browserInstance) { +void EventHandler::setBrowserInstance( + const std::shared_ptr& browserInstance) +{ LDEBUG("Setting browser instance."); _browserInstance = browserInstance; } void EventHandler::detachBrowser() { if (_browserInstance) { - LDEBUG(fmt::format("Detaching browser instance with use count {}", _browserInstance.use_count())); + LDEBUG(fmt::format( + "Detaching browser instance with use count {}", _browserInstance.use_count() + )); } _browserInstance = nullptr; } diff --git a/modules/webbrowser/src/processhelpermac.cpp b/modules/webbrowser/src/processhelpermac.cpp index a1e5f189f1..e4b013c8ca 100644 --- a/modules/webbrowser/src/processhelpermac.cpp +++ b/modules/webbrowser/src/processhelpermac.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/src/processhelperwindows.cpp b/modules/webbrowser/src/processhelperwindows.cpp index f64f323975..98c7cce615 100644 --- a/modules/webbrowser/src/processhelperwindows.cpp +++ b/modules/webbrowser/src/processhelperwindows.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -30,15 +30,12 @@ #include "include/webbrowserapp.h" // Entry point function for sub-processes. -int main(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) { - // Provide CEF with command-line arguments. - CefMainArgs main_args(hInstance); +int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { + // Provide CEF with command-line arguments. + CefMainArgs main_args(hInstance); - CefRefPtr app(new openspace::WebBrowserApp); + CefRefPtr app(new openspace::WebBrowserApp); - // Execute the sub-process. - return CefExecuteProcess(main_args, app.get(), NULL); + // Execute the sub-process. + return CefExecuteProcess(main_args, app.get(), NULL); } diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index 7ae604f5e3..05c85f7578 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -30,6 +30,18 @@ namespace { const char* KeyIdentifier = "Indentifier"; const char* KeyUrl = "URL"; const std::string _loggerCat = "ScreenSpaceBrowser"; + +static const openspace::properties::Property::PropertyInfo BrowserDimensionsInfo = { + "Dimensions", + "Browser Dimensions", + "Set the dimensions of the web browser windows." +}; +static const openspace::properties::Property::PropertyInfo UrlInfo = { + "URL", + "url", + "The URL to load" +}; + } // namespace namespace openspace { @@ -60,7 +72,9 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) glm::vec2 windowDimensions = OsEng.windowWrapper().currentWindowSize(); _dimensions = windowDimensions; - _texture = std::make_unique(glm::uvec3(windowDimensions, 1.0f)); + _texture = std::make_unique( + glm::uvec3(windowDimensions, 1.0f) + ); _renderHandler = new ScreenSpaceRenderHandler(); _browserInstance = std::make_shared(_renderHandler); diff --git a/modules/webbrowser/src/screenspacerenderhandler.cpp b/modules/webbrowser/src/screenspacerenderhandler.cpp index 24162c3bfd..79d14c9d02 100644 --- a/modules/webbrowser/src/screenspacerenderhandler.cpp +++ b/modules/webbrowser/src/screenspacerenderhandler.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/src/webbrowserapp.cpp b/modules/webbrowser/src/webbrowserapp.cpp index 202bae5621..8846417322 100644 --- a/modules/webbrowser/src/webbrowserapp.cpp +++ b/modules/webbrowser/src/webbrowserapp.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/src/webrenderhandler.cpp b/modules/webbrowser/src/webrenderhandler.cpp index bd8165299d..d16a5c0b69 100644 --- a/modules/webbrowser/src/webrenderhandler.cpp +++ b/modules/webbrowser/src/webrenderhandler.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -28,23 +28,34 @@ namespace openspace { void WebRenderHandler::reshape(int w, int h) { -// LDEBUGC("WebRenderHandler", fmt::format("Reshaping browser window. Width: {}, height: {}", w, h)); _width = w; _height = h; _alphaMask.clear(); _alphaMask.resize(w * h); } -bool WebRenderHandler::GetViewRect(CefRefPtr browser, CefRect &rect) { +bool WebRenderHandler::GetViewRect(CefRefPtr browser, CefRect& rect) { rect = CefRect(0, 0, _width, _height); return true; } -void WebRenderHandler::OnPaint(CefRefPtr browser, CefRenderHandler::PaintElementType type, - const CefRenderHandler::RectList &dirtyRects, const void *buffer, - int w, int h) { +void WebRenderHandler::OnPaint(CefRefPtr browser, + CefRenderHandler::PaintElementType type, + const CefRenderHandler::RectList& dirtyRects, + const void* buffer, int w, int h) +{ glBindTexture(GL_TEXTURE_2D, _texture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, (unsigned char*) buffer); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + _width, + _height, + 0, + GL_BGRA_EXT, + GL_UNSIGNED_BYTE, + buffer + ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -66,4 +77,4 @@ bool WebRenderHandler::hasContent(int x, int y) { return _alphaMask[index]; } -} +} // namespace openspace diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index 575b6b02d9..9ef6cbc859 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -68,7 +68,9 @@ std::string WebBrowserModule::findHelperExecutable() { auto execLocation = absPath(OsEng.configurationManager().value( ConfigurationManager::KeyWebHelperLocation) + SUBPROCESS_ENDING); if (!FileSys.fileExists(execLocation)) { - LERROR(fmt::format("Could not find web helper executable at location: {}" , execLocation)); + LERROR(fmt::format( + "Could not find web helper executable at location: {}" , execLocation + )); } return execLocation; } @@ -78,19 +80,29 @@ std::string WebBrowserModule::findHelperExecutable() { LWARNING(fmt::format("Assuming web helper name is {}", subprocessName)); auto subLength = (int)subprocessName.length(); - Directory binDir("${BASE}/bin/openspace", Directory::AbsolutePath::No); - std::vector foundFiles = binDir.readFiles(Directory::Recursive::Yes, Directory::Sort::Yes); + Directory binDir("${BASE}/bin/openspace", Directory::RawPath::No); + std::vector foundFiles = binDir.readFiles( + Directory::Recursive::Yes, + Directory::Sort::Yes + ); // find files matching the given file name std::vector matchingFiles; - std::copy_if(foundFiles.begin(), foundFiles.end(), std::back_inserter(matchingFiles), + std::copy_if( + foundFiles.begin(), + foundFiles.end(), + std::back_inserter(matchingFiles), [subprocessName, subLength](std::string s) { - s = s.substr(s.size() - subLength); - return s == subprocessName; - }); + s = s.substr(s.size() - subLength); + return s == subprocessName; + } + ); if (matchingFiles.empty()) { - LERROR(fmt::format("Could not find requested sub process executable file name: {}", subprocessName)); + LERROR(fmt::format( + "Could not find requested sub process executable file name: {}", + subprocessName + )); } return matchingFiles.back(); @@ -125,7 +137,9 @@ void WebBrowserModule::removeBrowser(std::shared_ptr browser) { LDEBUG(fmt::format("Number of browsers stored: {}", _browsers.size())); } -void WebBrowserModule::attachEventHandler(std::shared_ptr browserInstance) { +void WebBrowserModule::attachEventHandler( + std::shared_ptr browserInstance) +{ _eventHandler.setBrowserInstance(browserInstance); } diff --git a/modules/webbrowser/webbrowsermodule.h b/modules/webbrowser/webbrowsermodule.h index 85c74902cf..319e4a88e3 100644 --- a/modules/webbrowser/webbrowsermodule.h +++ b/modules/webbrowser/webbrowsermodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webgui/CMakeLists.txt b/modules/webgui/CMakeLists.txt index 114b209408..b602c87287 100644 --- a/modules/webgui/CMakeLists.txt +++ b/modules/webgui/CMakeLists.txt @@ -2,7 +2,7 @@ # # # OpenSpace # # # -# Copyright (c) 2014-2017 # +# 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 # diff --git a/modules/webgui/webguimodule.cpp b/modules/webgui/webguimodule.cpp index 768944cc63..5dd1ebbd34 100644 --- a/modules/webgui/webguimodule.cpp +++ b/modules/webgui/webguimodule.cpp @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webgui/webguimodule.h b/modules/webgui/webguimodule.h index f5f3f06dcc..141551682e 100644 --- a/modules/webgui/webguimodule.h +++ b/modules/webgui/webguimodule.h @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * @@ -22,11 +22,10 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef OPENSPACE_WEBGUIMODULE_H -#define OPENSPACE_WEBGUIMODULE_H +#ifndef __OPENSPACE_MODULE_WEBGUI___WEBGUIMODULE___H__ +#define __OPENSPACE_MODULE_WEBGUI___WEBGUIMODULE___H__ #include -#include namespace openspace { @@ -36,6 +35,6 @@ public: WebGuiModule(); }; -} +} // namespace openspace -#endif //OPENSPACE_WEBGUIMODULE_H +#endif // __OPENSPACE_MODULE_WEBGUI___WEBGUIMODULE___H__ diff --git a/src/engine/configurationmanager.cpp b/src/engine/configurationmanager.cpp index 6f62e808d7..9db7940a23 100644 --- a/src/engine/configurationmanager.cpp +++ b/src/engine/configurationmanager.cpp @@ -47,81 +47,6 @@ namespace { namespace openspace { -// static constexpr const char* ConfigurationManager::KeyPaths = "Paths"; -// const string ConfigurationManager::KeyCache = "CACHE"; -// const string ConfigurationManager::KeyFonts = "Fonts"; -// const string ConfigurationManager::KeyConfigSgct = "SGCTConfig"; -// const string ConfigurationManager::KeyGlobalCustomizationScripts = - // "GlobalCustomizationScripts"; - -// const string ConfigurationManager::PartType = "Type"; -// const string ConfigurationManager::PartFile = "File"; - -// const string ConfigurationManager::KeyLuaDocumentation = "LuaDocumentation"; -// const string ConfigurationManager::KeyScriptLog = "ScriptLog"; -// const string ConfigurationManager::KeyPropertyDocumentation = "PropertyDocumentation"; -// const string ConfigurationManager::KeyScenePropertyDocumentation = - // "ScenePropertyDocumentation"; -// const string ConfigurationManager::KeyKeyboardShortcuts = "KeyboardShortcuts"; -// const string ConfigurationManager::KeyDocumentation = "Documentation"; -// const string ConfigurationManager::KeyFactoryDocumentation = "FactoryDocumentation"; - -// const string ConfigurationManager::KeyConfigAsset = "Asset"; -// const string ConfigurationManager::KeySceneLicenseDocumentation = "LicenseDocumentation"; - -// const string ConfigurationManager::KeyLogging = "Logging"; -// const string ConfigurationManager::PartLogDir = "LogDir"; -// const string ConfigurationManager::PartLogLevel = "LogLevel"; -// const string ConfigurationManager::PartImmediateFlush = "ImmediateFlush"; -// const string ConfigurationManager::PartLogPerformancePrefix = "PerformancePrefix"; - -// const string ConfigurationManager::PartLogs = "Logs"; -// const string ConfigurationManager::PartAppend = "Append"; -// const string ConfigurationManager::PartCapabilitiesVerbosity = "CapabilitiesVerbosity"; - -// const string ConfigurationManager::KeyLauncher = "Launcher"; - -// const string ConfigurationManager::KeyCapabilitiesVerbosity = - // KeyLogging + "." + PartCapabilitiesVerbosity; - -// const string ConfigurationManager::KeyShutdownCountdown = "ShutdownCountdown"; -// const string ConfigurationManager::KeyDisableMasterRendering = "DisableRenderingOnMaster"; -// const string ConfigurationManager::KeyDisableSceneOnMaster = "DisableSceneOnMaster"; -// const string ConfigurationManager::KeyPerSceneCache = "PerSceneCache"; -// const string ConfigurationManager::KeyRenderingMethod = "RenderingMethod"; - -// const string ConfigurationManager::KeyOnScreenTextScaling = "OnScreenTextScaling"; - -// const string ConfigurationManager::KeyHttpProxy = "HttpProxy"; -// const string ConfigurationManager::PartHttpProxyAddress = "Address"; -// const string ConfigurationManager::PartHttpProxyPort = "Port"; -// const string ConfigurationManager::PartHttpProxyAuthentication = "Authentication"; -// const string ConfigurationManager::PartHttpProxyUser = "User"; -// const string ConfigurationManager::PartHttpProxyPassword = "Password"; - -// const string ConfigurationManager::KeyOpenGLDebugContext = "OpenGLDebugContext"; -// const string ConfigurationManager::PartActivate = "Activate"; -// const string ConfigurationManager::PartSynchronous = "Synchronous"; -// const string ConfigurationManager::PartFilterIdentifier = "FilterIdentifier"; -// const string ConfigurationManager::PartFilterIdentifierSource = "Source"; -// const string ConfigurationManager::PartFilterIdentifierType = "Type"; -// const string ConfigurationManager::PartFilterIdentifierIdentifier = "Identifier"; -// const string ConfigurationManager::PartFilterSeverity = "PartFilterSeverity"; -// const string ConfigurationManager::KeyCheckOpenGLState = "CheckOpenGLState"; -// const string ConfigurationManager::KeyLogEachOpenGLCall = "LogEachOpenGLCall"; - -// const string ConfigurationManager::KeyUseMultithreadedInitialization = - // "UseMultithreadedInitialization"; - -// const string ConfigurationManager::KeyLoadingScreen = "LoadingScreen"; -// const string ConfigurationManager::PartShowMessage = "ShowMessage"; -// const string ConfigurationManager::PartShowNodeNames = "ShowNodeNames"; -// const string ConfigurationManager::PartShowProgressbar = "ShowProgressbar"; - -// const string ConfigurationManager::KeyScreenshotUseDate = "ScreenshotUseDate"; - -// const string ConfigurationManager::KeyModuleConfigurations = "ModuleConfigurations"; - string ConfigurationManager::findConfiguration(const string& filename) { using ghoul::filesystem::Directory; diff --git a/src/engine/configurationmanager_doc.inl b/src/engine/configurationmanager_doc.inl index 3650da9157..a365448508 100644 --- a/src/engine/configurationmanager_doc.inl +++ b/src/engine/configurationmanager_doc.inl @@ -69,7 +69,6 @@ documentation::Documentation ConfigurationManager::Documentation() { "in all other configuration files or scripts." }, { - ConfigurationManager::KeyCachePath, new StringVerifier, Optional::No, @@ -205,21 +204,21 @@ documentation::Documentation ConfigurationManager::Documentation() { ConfigurationManager::KeyRequireSocketAuthentication, new BoolVerifier, Optional::Yes, - "If socket connections should be authenticated or not before they are allowed to " - "get or set information. Defaults to `true`." + "If socket connections should be authenticated or not before they are " + "allowed to get or set information. Defaults to 'true'." }, { ConfigurationManager::KeyServerPasskey, - new StringVerifier, - Optional::Yes, - "Passkey to limit server access. Used to authorize incoming connections." + new StringVerifier, + Optional::Yes, + "Passkey to limit server access. Used to authorize incoming connections." }, { ConfigurationManager::KeyServerClientAddressWhitelist, - new StringVerifier, - Optional::Yes, - "String containing white listed client IP addresses that won't need to be" - "authorized with the server. Space separated" + new StringVerifier, + Optional::Yes, + "String containing white listed client IP addresses that won't need to be " + "authorized with the server. Space separated" }, { ConfigurationManager::KeySceneLicenseDocumentation, @@ -368,8 +367,8 @@ documentation::Documentation ConfigurationManager::Documentation() { new BoolVerifier, Optional::Yes, "Determines whether the OpenGL debug callbacks are performed " - "synchronously. If set to the callbacks are in the same thread " - "as the context and in the scope of the OpenGL function that " + "synchronously. If set to the callbacks are in the same " + "thread as the context and in the scope of the OpenGL function that " "triggered the message. The default value is ." }, { diff --git a/src/engine/downloadmanager.cpp b/src/engine/downloadmanager.cpp index d594a0218d..9f87dd24e0 100644 --- a/src/engine/downloadmanager.cpp +++ b/src/engine/downloadmanager.cpp @@ -91,8 +91,8 @@ namespace { ghoul_assert(p, "Passed progress information is nullptr"); ProgressInformation* i = static_cast(p); ghoul_assert(i, "Passed pointer is not a ProgressInformation"); - ghoul_assert(i->future, "FileFuture is not initialized"); - ghoul_assert(i->callback, "Callback pointer is nullptr"); + ghoul_assert(i && i->future, "FileFuture is not initialized"); + ghoul_assert(i && i->callback, "Callback pointer is nullptr"); if (i->future->abortDownload) { i->future->isAborted = true; diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index b9e1d2946c..a34b2252ac 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -293,7 +293,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Parse commandline arguments std::vector args(argv, argv + argc); - std::shared_ptr> arguments = + const std::vector& arguments = _engine->_commandlineParser->setCommandLine(args); bool showHelp = _engine->_commandlineParser->execute(); @@ -302,7 +302,8 @@ void OpenSpaceEngine::create(int argc, char** argv, requestClose = true; return; } - sgctArguments = *arguments; + std::vector argumentsCopy = arguments; + sgctArguments = std::move(argumentsCopy); // Find configuration std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName; @@ -1476,7 +1477,7 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action if (consumed) { // If the mouse was released, we still want to forward it to the navigation // handler in order to reliably terminate a rotation or zoom. Accidentally - // moving the cursor over a UI window is easy to miss and leads to weird + // moving the cursor over a UI window is easy to miss and leads to weird // continuing movement if (action == MouseAction::Release) { break; diff --git a/src/engine/virtualpropertymanager.cpp b/src/engine/virtualpropertymanager.cpp index 124f5bc96c..516b334c02 100644 --- a/src/engine/virtualpropertymanager.cpp +++ b/src/engine/virtualpropertymanager.cpp @@ -28,7 +28,9 @@ namespace openspace { -VirtualPropertyManager::VirtualPropertyManager() : properties::PropertyOwner({ "VirtualPropertyManager" }) {} +VirtualPropertyManager::VirtualPropertyManager() + : properties::PropertyOwner({ "VirtualPropertyManager" }) +{} void VirtualPropertyManager::addProperty(std::unique_ptr prop) { // PropertyOwner does not take the ownership of the pointer diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index fef3b7b9ff..f635b96bd7 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -176,9 +176,10 @@ int SGCTWindowWrapper::currentNumberOfAaSamples() const { bool SGCTWindowWrapper::isRegularRendering() const { sgct::SGCTWindow* w = sgct::Engine::instance()->getCurrentWindowPtr(); - std::size_t nViewports = w->getNumberOfViewports(); - (void)nViewports; // Unused in Release mode - ghoul_assert(nViewports > 0, "At least one viewport must exist at this time"); + 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; diff --git a/src/interaction/keybindingmanager_lua.inl b/src/interaction/keybindingmanager_lua.inl index 33f7edf830..0e3f6a27c9 100644 --- a/src/interaction/keybindingmanager_lua.inl +++ b/src/interaction/keybindingmanager_lua.inl @@ -172,7 +172,7 @@ int clearKey(lua_State* L) { // The user provided a list of keys ghoul::Dictionary d; ghoul::lua::luaDictionaryFromState(L, d); - for (int i = 1; i <= d.size(); ++i) { + for (size_t i = 1; i <= d.size(); ++i) { std::string k = d.value(std::to_string(i)); OsEng.keyBindingManager().removeKeyBinding(k); } diff --git a/src/interaction/touchbar.mm b/src/interaction/touchbar.mm index a1461a879b..813d0a1aa6 100644 --- a/src/interaction/touchbar.mm +++ b/src/interaction/touchbar.mm @@ -78,6 +78,8 @@ NSArray* focusIdentifiers; - (NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { + // @TODO(abock): Potential memory leak here by returning an alloc? + // Remove the unused variable warning (void)touchBar; diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index fb5694f308..516853901d 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -45,7 +45,9 @@ bool ParallelConnection::isConnectedOrConnecting() { return _socket->isConnected() || _socket->isConnecting(); } -void ParallelConnection::sendDataMessage(const ParallelConnection::DataMessage& dataMessage) { +void ParallelConnection::sendDataMessage( + const ParallelConnection::DataMessage& dataMessage) +{ uint32_t dataMessageTypeOut = static_cast(dataMessage.type); std::vector messageContent; @@ -57,7 +59,10 @@ void ParallelConnection::sendDataMessage(const ParallelConnection::DataMessage& dataMessage.content.begin(), dataMessage.content.end()); - sendMessage(ParallelConnection::Message(ParallelConnection::MessageType::Data, messageContent)); + sendMessage(ParallelConnection::Message( + ParallelConnection::MessageType::Data, + messageContent + )); } bool ParallelConnection::sendMessage(const ParallelConnection::Message& message) { @@ -112,7 +117,6 @@ ParallelConnection::Message ParallelConnection::receiveMessage() { std::vector headerBuffer(headerSize); std::vector messageBuffer; - // Receive the header data if (!_socket->get(headerBuffer.data(), headerSize)) { LERROR("Failed to read header from socket. Disconencting."); @@ -150,7 +154,10 @@ ParallelConnection::Message ParallelConnection::receiveMessage() { } // And delegate decoding depending on type - return ParallelConnection::Message(static_cast(messageTypeIn), messageBuffer); + return ParallelConnection::Message( + static_cast(messageTypeIn), + messageBuffer + ); } } // namespace openspace diff --git a/src/network/parallelpeer.cpp b/src/network/parallelpeer.cpp index e388914926..45fcf4102a 100644 --- a/src/network/parallelpeer.cpp +++ b/src/network/parallelpeer.cpp @@ -205,7 +205,10 @@ void ParallelPeer::sendAuthentication() { buffer.insert(buffer.end(), name.begin(), name.end()); // Send message - _connection.sendMessage(ParallelConnection::Message(ParallelConnection::MessageType::Authentication, buffer)); + _connection.sendMessage(ParallelConnection::Message( + ParallelConnection::MessageType::Authentication, + buffer + )); } void ParallelPeer::queueInMessage(const ParallelConnection::Message& message) { @@ -414,12 +417,18 @@ void ParallelPeer::requestHostship() { reinterpret_cast(&passwordHash), reinterpret_cast(&passwordHash) + sizeof(uint64_t) ); - _connection.sendMessage(ParallelConnection::Message(ParallelConnection::MessageType::HostshipRequest, buffer)); + _connection.sendMessage(ParallelConnection::Message( + ParallelConnection::MessageType::HostshipRequest, + buffer + )); } void ParallelPeer::resignHostship() { std::vector buffer; - _connection.sendMessage(ParallelConnection::Message(ParallelConnection::MessageType::HostshipResignation, buffer)); + _connection.sendMessage(ParallelConnection::Message( + ParallelConnection::MessageType::HostshipResignation, + buffer + )); } void ParallelPeer::setPassword(std::string pwd) { @@ -441,7 +450,10 @@ void ParallelPeer::sendScript(std::string script) { std::vector buffer; sm.serialize(buffer); - ParallelConnection::DataMessage message(datamessagestructures::Type::ScriptData, buffer); + ParallelConnection::DataMessage message( + datamessagestructures::Type::ScriptData, + buffer + ); _connection.sendDataMessage(message); } @@ -550,7 +562,10 @@ void ParallelPeer::sendCameraKeyframe() { kf.serialize(buffer); // Send message - _connection.sendDataMessage(ParallelConnection::DataMessage(datamessagestructures::Type::CameraData, buffer)); + _connection.sendDataMessage(ParallelConnection::DataMessage( + datamessagestructures::Type::CameraData, + buffer + )); } void ParallelPeer::sendTimeKeyframe() { @@ -574,7 +589,10 @@ void ParallelPeer::sendTimeKeyframe() { kf.serialize(buffer); // Send message - _connection.sendDataMessage(ParallelConnection::DataMessage(datamessagestructures::Type::TimeData, buffer)); + _connection.sendDataMessage(ParallelConnection::DataMessage( + datamessagestructures::Type::TimeData, + buffer + )); _timeJumped = false; } diff --git a/src/network/parallelserver.cpp b/src/network/parallelserver.cpp index bb9281d374..0f76f1348d 100644 --- a/src/network/parallelserver.cpp +++ b/src/network/parallelserver.cpp @@ -52,7 +52,7 @@ void ParallelServer::start( } void ParallelServer::setDefaultHostAddress(std::string defaultHostAddress) { - std::lock_guard lock(_hostInfoMutex); + std::lock_guard lock(_hostInfoMutex); _defaultHostAddress = std::move(defaultHostAddress); } @@ -89,7 +89,7 @@ void ParallelServer::handleNewPeers() { }); } } - + std::shared_ptr ParallelServer::peer(size_t id) { std::lock_guard lock(_peerListMutex); const auto& it = _peers.find(id); @@ -142,7 +142,7 @@ void ParallelServer::handlePeerMessage(PeerMessage peerMessage) { } std::shared_ptr& peer = it->second; - + switch (messageType) { case ParallelConnection::MessageType::Authentication: handleAuthentication(peer, std::move(data)); @@ -165,7 +165,7 @@ void ParallelServer::handlePeerMessage(PeerMessage peerMessage) { break; } } - + void ParallelServer::handleAuthentication(std::shared_ptr peer, std::vector message) { @@ -219,7 +219,7 @@ void ParallelServer::handleAuthentication(std::shared_ptr peer, setNConnections(nConnections() + 1); } - + void ParallelServer::handleData(std::shared_ptr peer, std::vector data) { if (peer->id != _hostPeerId) { LINFO(fmt::format( @@ -259,7 +259,7 @@ void ParallelServer::handleHostshipRequest(std::shared_ptr peer, assignHost(peer); LINFO(fmt::format("Switched host from {} to {}.", oldHostPeerId, peer->id)); } - + void ParallelServer::handleHostshipResignation(std::shared_ptr peer, std::vector data) { diff --git a/src/properties/binaryproperty.cpp b/src/properties/binaryproperty.cpp index 4c78a37d16..3ebb294761 100644 --- a/src/properties/binaryproperty.cpp +++ b/src/properties/binaryproperty.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** -* * -* OpenSpace * -* * -* Copyright (c) 2014-2017 * -* * -* 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. * -****************************************************************************************/ + * * + * 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 @@ -49,7 +49,7 @@ REGISTER_TEMPLATEPROPERTY_SOURCE( return result; }, [](std::string& outValue, std::vector inValue) -> bool { - // TODO: To json conversion + // TODO: To json conversion outValue = ""; return true; }, diff --git a/src/properties/property.cpp b/src/properties/property.cpp index 6fa6a8f80d..4678dc16ca 100644 --- a/src/properties/property.cpp +++ b/src/properties/property.cpp @@ -191,8 +191,11 @@ const ghoul::Dictionary& Property::metaData() const { std::string Property::toJson() const { std::string result = "{"; - result += "\"" + std::string(DescriptionKey) + "\": " + generateBaseJsonDescription() + ", "; - result += "\"" + std::string(JsonValueKey) + "\": " + jsonValue(); + result += + "\"" + std::string(DescriptionKey) + "\": " + + generateBaseJsonDescription() + ", "; + result += + "\"" + std::string(JsonValueKey) + "\": " + jsonValue(); result += "}"; return result; } @@ -280,13 +283,15 @@ void Property::notifyDeleteListeners() { } std::string Property::generateBaseJsonDescription() const { - return + return "{ \"" + std::string(TypeKey) + "\": \"" + className() + "\", " + - "\"" + std::string(IdentifierKey) + "\": \"" + fullyQualifiedIdentifier() + "\", " + + "\"" + std::string(IdentifierKey) + "\": \"" + + fullyQualifiedIdentifier() + "\", " + "\"" + std::string(NameKey) + "\": \"" + guiName() + "\", " + - "\"" + std::string(MetaDataKey) + "\": " + generateMetaDataJsonDescription() + ", " + - "\"" + std::string(AdditionalDataKey) + "\": " + generateAdditionalJsonDescription() + - " }"; + "\"" + std::string(MetaDataKey) + "\": " + + generateMetaDataJsonDescription() + ", " + + "\"" + std::string(AdditionalDataKey) + "\": " + + generateAdditionalJsonDescription() + " }"; } std::string Property::generateMetaDataJsonDescription() const { @@ -306,9 +311,13 @@ std::string Property::generateMetaDataJsonDescription() const { } std::string result = "{ "; - result += "\"" + std::string(MetaDataKeyGroup) + "\": \"" + groupIdentifier() + "\", "; - result += "\"" + std::string(MetaDataKeyVisibility) + "\": \"" + vis + "\", "; - result += "\"" + std::string(MetaDataKeyReadOnly) + "\": " + (isReadOnly ? "true" : "false"); + result += + "\"" + std::string(MetaDataKeyGroup) + "\": \"" + groupIdentifier() + "\", "; + result += + "\"" + std::string(MetaDataKeyVisibility) + "\": \"" + vis + "\", "; + result += + "\"" + std::string(MetaDataKeyReadOnly) + "\": " + + (isReadOnly ? "true" : "false"); result += " }"; return result; } diff --git a/src/properties/scalar/ucharproperty.cpp b/src/properties/scalar/ucharproperty.cpp index d8e34420a2..75f4fce161 100644 --- a/src/properties/scalar/ucharproperty.cpp +++ b/src/properties/scalar/ucharproperty.cpp @@ -50,7 +50,7 @@ bool toLuaConversion(lua_State* state, unsigned char value) { unsigned char fromStringConversion(std::string val, bool& success) { std::stringstream s(val); - unsigned char v; + unsigned char v = 0; s >> v; success = !s.fail(); if (success) { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 7984166b24..aedd04ed1a 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -539,7 +539,7 @@ void FramebufferRenderer::updateDeferredcastData() { absPath(vsPath), absPath(deferredShaderPath), deferredDict); - + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; _deferredcastPrograms[caster]->setIgnoreSubroutineUniformLocationError( IgnoreError::Yes @@ -547,7 +547,7 @@ void FramebufferRenderer::updateDeferredcastData() { _deferredcastPrograms[caster]->setIgnoreUniformLocationError( IgnoreError::Yes ); - + caster->initializeCachedVariables(*_deferredcastPrograms[caster]); } catch (ghoul::RuntimeError& e) { diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 8c95ec06ca..c6d1dc46ad 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -410,7 +410,7 @@ void RenderEngine::initialize() { #ifdef GHOUL_USE_STB_IMAGE ghoul::io::TextureReader::ref().addReader( std::make_shared() - ); + ); #endif // GHOUL_USE_STB_IMAGE ghoul::io::TextureReader::ref().addReader( @@ -596,8 +596,8 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat _camera->sgctInternal.setViewMatrix(viewMatrix * sceneMatrix); _camera->sgctInternal.setSceneMatrix(sceneMatrix); } + _camera->sgctInternal.setProjectionMatrix(projectionMatrix); } - _camera->sgctInternal.setProjectionMatrix(projectionMatrix); bool masterEnabled = wrapper.isMaster() ? !_disableMasterRendering : true; if (masterEnabled && !wrapper.isGuiWindow() && _globalBlackOutFactor > 0.f) { diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index a3361b0907..b4a4f25e7c 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -60,7 +60,6 @@ namespace { constexpr const char* _loggerCat = "Scene"; - constexpr const char* KeyName = "Name"; constexpr const char* KeyIdentifier = "Identifier"; constexpr const char* KeyParent = "Parent"; } // namespace diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index 6396222e34..d883056eed 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -627,7 +627,7 @@ Scene* SceneGraphNode::scene() { void SceneGraphNode::setScene(Scene* scene) { // Unregister from previous scene, bottom up - traversePostOrder([scene](SceneGraphNode* node) { + traversePostOrder([](SceneGraphNode* node) { if (node->_scene) { node->_scene->unregisterNode(node); } diff --git a/src/util/httprequest.cpp b/src/util/httprequest.cpp index 86a8765ad9..04b83213e8 100644 --- a/src/util/httprequest.cpp +++ b/src/util/httprequest.cpp @@ -362,7 +362,9 @@ bool HttpFileDownload::initDownload() { std::string message(Buffer, size); - LERROR(fmt::format("Cannot open file {}: {}", std::string(destinationFile), message)); + LERROR(fmt::format( + "Cannot open file {}: {}", std::string(destinationFile), message) + ); return false; } diff --git a/support/coding/check_style_guide.py b/support/coding/check_style_guide.py index 715b45632d..c53290df47 100644 --- a/support/coding/check_style_guide.py +++ b/support/coding/check_style_guide.py @@ -44,6 +44,7 @@ guards for correctness. At the moment this includes: * Checking whether a file as empty-only lines * Checking whether the default assert macros are used anywhere instead of the ghoul_assert macro + * Checking whether there are TABs in the file If this script is executed from the base directory of OpenSpace, no arguments need to be passed, otherwise the first and only argument has to point to the base directory. @@ -58,6 +59,7 @@ import sys current_year = '2018' is_strict_mode = False +is_silent_mode = False def get_ifndef_symbol(lines): index = [i for i,s in enumerate(lines) if '#ifndef ' in s] @@ -332,6 +334,12 @@ def check_empty_character_at_end(lines): return '' +def check_for_tab(lines): + index = [i + 1 for i, s in enumerate(lines) if '\t' in s] + if len(index) > 0: + return index + else: + return '' previousSymbols = {} def check_header_file(file, component): @@ -425,6 +433,10 @@ def check_header_file(file, component): if assert_usage: print(file, '\t', 'Wrong assert usage: ', assert_usage) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) + def check_inline_file(file, component): @@ -479,6 +491,11 @@ def check_inline_file(file, component): if assert_usage: print(file, '\t', 'Wrong assert usage: ', assert_usage) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) + + def check_source_file(file, component): @@ -522,11 +539,23 @@ def check_source_file(file, component): if assert_usage: print(file, '\t', 'Wrong assert usage: ', assert_usage) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) + + def check_files(positiveList, negativeList, component, check_function): - files = glob.glob(positiveList, recursive=True) - negativeFiles = glob.glob(negativeList, recursive=True) + files = [] + for p in positiveList: + f = glob.glob(p, recursive=True) + files.extend(f) + + negativeFiles = [] + for n in negativeList: + f = glob.glob(n, recursive=True) + negativeFiles.extend(f) files = [f for f in files if f not in negativeFiles] @@ -545,28 +574,106 @@ if len(sys.argv) > 1: for a in sys.argv: if a == "strict": is_strict_mode = True + if a == "silent": + is_silent_mode = True + # Check header files -print("Checking header files") -print("=====================") -check_files(basePath + 'include/**/*.h', '', 'openspace_core', check_header_file) -check_files(basePath + 'apps/**/*.h', basePath + 'apps/**/ext/**/*.h', 'openspace_app', check_header_file) -check_files(basePath + 'modules/**/*.h', basePath + 'modules/**/ext/**/*.h', 'openspace_module', check_header_file) -check_files(basePath + 'ext/ghoul/include/**/*.h', '', 'ghoul', check_header_file) -print("") +if not is_silent_mode: + print("Checking header files") + print("=====================") -print("Checking inline files") -print("=====================") -check_files(basePath + 'include/**/*.inl', '', 'openspace_core', check_inline_file) -check_files(basePath + 'src/**/*.inl', '', 'openspace_core', check_inline_file) -check_files(basePath + 'apps/**/*.inl', basePath + 'apps/**/ext/**/*.h', 'openspace_app', check_inline_file) -check_files(basePath + 'modules/**/*.inl', basePath + 'modules/**/ext/**/*.h', 'openspace_module', check_inline_file) -check_files(basePath + 'ext/ghoul/include/**/*.inl', '', 'ghoul', check_inline_file) -print("") +check_files( + [basePath + 'include/**/*.h'], + [], + 'openspace_core', + check_header_file +) +check_files( + [basePath + 'apps/**/*.h'], + [basePath + 'apps/**/ext/**/*.h'], + 'openspace_app', + check_header_file +) +check_files( + [basePath + 'modules/**/*.h'], + [ + basePath + 'modules/**/ext/**/*.h', + basePath + 'modules/**/node_modules/**/*.h', + basePath + 'modules/webbrowser/resource.h' + ], + 'openspace_module', + check_header_file +) +check_files( + [basePath + 'ext/ghoul/include/**/*.h'], + [], + 'ghoul', + check_header_file +) -print("Checking source files") -print("=====================") -check_files(basePath + 'src/**/*.cpp', '', 'openspace_core', check_source_file) -check_files(basePath + 'apps/**/*.cpp', basePath + 'apps/**/ext/**/*.cpp', 'openspace_app', check_source_file) -check_files(basePath + 'modules/**/*.cpp', basePath + 'modules/**/ext/**/*.cpp', 'openspace_module', check_source_file) -check_files(basePath + 'ext/ghoul/src/**/*.cpp', '', 'ghoul', check_source_file) +if not is_silent_mode: + print("") + print("Checking inline files") + print("=====================") + +check_files( + [basePath + 'include/**/*.inl'], + [], + 'openspace_core', + check_inline_file +) +check_files( + [basePath + 'src/**/*.inl'], + [], + 'openspace_core', + check_inline_file +) +check_files( + [basePath + 'apps/**/*.inl'], + [basePath + 'apps/**/ext/**/*.h'], + 'openspace_app', + check_inline_file +) +check_files( + [basePath + 'modules/**/*.inl'], + [basePath + 'modules/**/ext/**/*.h'], + 'openspace_module', + check_inline_file +) +check_files( + [basePath + 'ext/ghoul/include/**/*.inl'], + [], + 'ghoul', + check_inline_file +) + +if not is_silent_mode: + print("") + print("Checking source files") + print("=====================") + +check_files( + [basePath + 'src/**/*.cpp'], + [], + 'openspace_core', + check_source_file +) +check_files( + [basePath + 'apps/**/*.cpp'], + [basePath + 'apps/**/ext/**/*.cpp'], + 'openspace_app', + check_source_file +) +check_files( + [basePath + 'modules/**/*.cpp'], + [basePath + 'modules/**/ext/**/*.cpp', basePath + 'modules/**/node_modules/**/*.cpp'], + 'openspace_module', + check_source_file +) +check_files( + [basePath + 'ext/ghoul/src/**/*.cpp'], + [], + 'ghoul', + check_source_file +) diff --git a/tests/test_rawvolumeio.inl b/tests/test_rawvolumeio.inl index cacb18b60d..0450543e02 100644 --- a/tests/test_rawvolumeio.inl +++ b/tests/test_rawvolumeio.inl @@ -64,7 +64,7 @@ TEST_F(RawVolumeIoTest, BasicInputOutput) { glm::uvec3 dims{ 2, 4, 8 }; auto value = [dims](glm::uvec3 v) { - return v.z * 8 * 4 + v.y * 4 + v.x; + return v.z * dims.z * dims.y + v.y * dims.y + v.x; }; RawVolume vol(dims); From a1e1c3841a152d40e6710a6d28df2b3a022a6b05 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 19 Apr 2018 13:36:32 -0400 Subject: [PATCH 37/79] Remove option from torrentclient to auto-select a port --- modules/sync/torrentclient.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/sync/torrentclient.cpp b/modules/sync/torrentclient.cpp index 87905af398..4e65107798 100644 --- a/modules/sync/torrentclient.cpp +++ b/modules/sync/torrentclient.cpp @@ -72,7 +72,7 @@ void TorrentClient::initialize() { settings.set_str( libtorrent::settings_pack::listen_interfaces, - "0.0.0.0:6881,0.0.0.0:20280,0.0.0.0:20285,0.0.0.0:20290,0.0.0.0:0" + "0.0.0.0:6881,0.0.0.0:20280,0.0.0.0:20285,0.0.0.0:20290" ); settings.set_bool(libtorrent::settings_pack::allow_multiple_connections_per_ip, true); settings.set_bool(libtorrent::settings_pack::enable_upnp, true); From 3ea1e83aefcc97ec45afebc210c9a8b5856c3722 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 09:45:01 -0400 Subject: [PATCH 38/79] New performance matrices and new eye points for stereo. --- .../rendering/atmospheredeferredcaster.cpp | 2716 +++++++++-------- .../rendering/atmospheredeferredcaster.h | 3 +- .../shaders/atmosphere_deferred_fs.glsl | 379 +-- 3 files changed, 1589 insertions(+), 1509 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 088181189d..490fb4b407 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -1,61 +1,62 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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. * +****************************************************************************************/ - /*************************************************************************************** - * Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the - * following code. - ****************************************************************************************/ +/*************************************************************************************** +* Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the +* following code. +****************************************************************************************/ - /** - * Precomputed Atmospheric Scattering - * Copyright (c) 2008 INRIA - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ +/** +* Precomputed Atmospheric Scattering +* Copyright (c) 2008 INRIA +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* 1. Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. Neither the name of the copyright holders nor the names of its +* contributors may be used to endorse or promote products derived from +* this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +* THE POSSIBILITY OF SUCH DAMAGE. + +*/ #include #include @@ -103,1021 +104,870 @@ namespace { namespace openspace { -AtmosphereDeferredcaster::AtmosphereDeferredcaster() - : _transmittanceProgramObject(nullptr) - , _irradianceProgramObject(nullptr) - , _irradianceSupTermsProgramObject(nullptr) - , _irradianceFinalProgramObject(nullptr) - , _inScatteringProgramObject(nullptr) - , _inScatteringSupTermsProgramObject(nullptr) - , _deltaEProgramObject(nullptr) - , _deltaSProgramObject(nullptr) - , _deltaSSupTermsProgramObject(nullptr) - , _deltaJProgramObject(nullptr) - , _atmosphereProgramObject(nullptr) - , _transmittanceTableTexture(0) - , _irradianceTableTexture(0) - , _inScatteringTableTexture(0) - , _deltaETableTexture(0) - , _deltaSRayleighTableTexture(0) - , _deltaSMieTableTexture(0) - , _deltaJTableTexture(0) - , _atmosphereTexture(0) - , _atmosphereCalculated(false) - , _ozoneEnabled(false) - , _sunFollowingCameraEnabled(false) - , _atmosphereRadius(0.f) - , _atmospherePlanetRadius(0.f) - , _planetAverageGroundReflectance(0.f) - , _planetGroundRadianceEmittion(0.f) - , _rayleighHeightScale(0.f) - , _ozoneHeightScale(0.f) - , _mieHeightScale(0.f) - , _miePhaseConstant(0.f) - , _sunRadianceIntensity(50.0f) - , _rayleighScatteringCoeff(glm::vec3(0.f)) - , _ozoneExtinctionCoeff(glm::vec3(0.f)) - , _mieScatteringCoeff(glm::vec3(0.f)) - , _mieExtinctionCoeff(glm::vec3(0.f)) - , _ellipsoidRadii(glm::dvec3(0.0)) - , _transmittance_table_width(256) - , _transmittance_table_height(64) - , _irradiance_table_width(64) - , _irradiance_table_height(16) - , _delta_e_table_width(64) - , _delta_e_table_height(16) - , _r_samples(32) - , _mu_samples(128) - , _mu_s_samples(32) - , _nu_samples(8) - , _hardShadowsEnabled(false) - , _calculationTextureScale(1.0) - , _saveCalculationTextures(false) -{} + AtmosphereDeferredcaster::AtmosphereDeferredcaster() + : _transmittanceProgramObject(nullptr) + , _irradianceProgramObject(nullptr) + , _irradianceSupTermsProgramObject(nullptr) + , _irradianceFinalProgramObject(nullptr) + , _inScatteringProgramObject(nullptr) + , _inScatteringSupTermsProgramObject(nullptr) + , _deltaEProgramObject(nullptr) + , _deltaSProgramObject(nullptr) + , _deltaSSupTermsProgramObject(nullptr) + , _deltaJProgramObject(nullptr) + , _atmosphereProgramObject(nullptr) + , _transmittanceTableTexture(0) + , _irradianceTableTexture(0) + , _inScatteringTableTexture(0) + , _deltaETableTexture(0) + , _deltaSRayleighTableTexture(0) + , _deltaSMieTableTexture(0) + , _deltaJTableTexture(0) + , _atmosphereTexture(0) + , _atmosphereCalculated(false) + , _ozoneEnabled(false) + , _sunFollowingCameraEnabled(false) + , _atmosphereRadius(0.f) + , _atmospherePlanetRadius(0.f) + , _planetAverageGroundReflectance(0.f) + , _planetGroundRadianceEmittion(0.f) + , _rayleighHeightScale(0.f) + , _ozoneHeightScale(0.f) + , _mieHeightScale(0.f) + , _miePhaseConstant(0.f) + , _sunRadianceIntensity(50.0f) + , _rayleighScatteringCoeff(glm::vec3(0.f)) + , _ozoneExtinctionCoeff(glm::vec3(0.f)) + , _mieScatteringCoeff(glm::vec3(0.f)) + , _mieExtinctionCoeff(glm::vec3(0.f)) + , _ellipsoidRadii(glm::dvec3(0.0)) + , _transmittance_table_width(256) + , _transmittance_table_height(64) + , _irradiance_table_width(64) + , _irradiance_table_height(16) + , _delta_e_table_width(64) + , _delta_e_table_height(16) + , _r_samples(32) + , _mu_samples(128) + , _mu_s_samples(32) + , _nu_samples(8) + , _hardShadowsEnabled(false) + , _calculationTextureScale(1.0) + , _saveCalculationTextures(false) + {} -void AtmosphereDeferredcaster::initialize() { - if (!_atmosphereCalculated) { - preCalculateAtmosphereParam(); + void AtmosphereDeferredcaster::initialize() { + if (!_atmosphereCalculated) { + preCalculateAtmosphereParam(); + } } -} -void AtmosphereDeferredcaster::update(const UpdateData&) {}; + void AtmosphereDeferredcaster::deinitialize() { + _transmittanceProgramObject = nullptr; + _irradianceProgramObject = nullptr; + _irradianceSupTermsProgramObject = nullptr; + _inScatteringProgramObject = nullptr; + _inScatteringSupTermsProgramObject = nullptr; + _deltaEProgramObject = nullptr; + _deltaSProgramObject = nullptr; + _deltaSSupTermsProgramObject = nullptr; + _deltaJProgramObject = nullptr; -void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramObject&) {} - -void AtmosphereDeferredcaster::deinitialize() { - _transmittanceProgramObject = nullptr; - _irradianceProgramObject = nullptr; - _irradianceSupTermsProgramObject = nullptr; - _inScatteringProgramObject = nullptr; - _inScatteringSupTermsProgramObject = nullptr; - _deltaEProgramObject = nullptr; - _deltaSProgramObject = nullptr; - _deltaSSupTermsProgramObject = nullptr; - _deltaJProgramObject = nullptr; - - glDeleteTextures(1, &_transmittanceTableTexture); - glDeleteTextures(1, &_irradianceTableTexture); - glDeleteTextures(1, &_inScatteringTableTexture); - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); - glDeleteTextures(1, &_atmosphereTexture); -} - -void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, - const DeferredcastData&, - ghoul::opengl::ProgramObject& program) -{ - // Atmosphere Frustum Culling - glm::dvec3 tPlanetPosWorld = glm::dvec3( - _modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0) - ); - - double distance = glm::distance(tPlanetPosWorld, renderData.camera.eyePositionVec3()); - if (distance > DISTANCE_CULLING) { - program.setUniform("cullAtmosphere", 1); + glDeleteTextures(1, &_transmittanceTableTexture); + glDeleteTextures(1, &_irradianceTableTexture); + glDeleteTextures(1, &_inScatteringTableTexture); + glDeleteTextures(1, &_deltaETableTexture); + glDeleteTextures(1, &_deltaSRayleighTableTexture); + glDeleteTextures(1, &_deltaSMieTableTexture); + glDeleteTextures(1, &_deltaJTableTexture); + glDeleteTextures(1, &_atmosphereTexture); } - else { - glm::dmat4 MV = glm::dmat4( - renderData.camera.sgctInternal.projectionMatrix() - ) * renderData.camera.combinedViewMatrix(); - if (!isAtmosphereInFrustum( - glm::value_ptr(MV), - tPlanetPosWorld, - (_atmosphereRadius + ATM_EPS)*KM_TO_M) - ) - { + void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, + const DeferredcastData&, + ghoul::opengl::ProgramObject& program) + { + // Atmosphere Frustum Culling + glm::dvec3 tPlanetPosWorld = glm::dvec3( + _modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0) + ); + + double distance = glm::distance(tPlanetPosWorld, renderData.camera.eyePositionVec3()); + if (distance > DISTANCE_CULLING) { program.setUniform("cullAtmosphere", 1); } else { - program.setUniform("cullAtmosphere", 0); - program.setUniform("Rg", _atmospherePlanetRadius); - program.setUniform("Rt", _atmosphereRadius); - program.setUniform( - "AverageGroundReflectance", - _planetAverageGroundReflectance - ); - program.setUniform("groundRadianceEmittion", _planetGroundRadianceEmittion); - program.setUniform("HR", _rayleighHeightScale); - program.setUniform("betaRayleigh", _rayleighScatteringCoeff); - program.setUniform("HM", _mieHeightScale); - program.setUniform("betaMieScattering", _mieScatteringCoeff); - program.setUniform("betaMieExtinction", _mieExtinctionCoeff); - program.setUniform("mieG", _miePhaseConstant); - program.setUniform("sunRadiance", _sunRadianceIntensity); - program.setUniform("ozoneLayerEnabled", _ozoneEnabled); - program.setUniform("HO", _ozoneHeightScale); - program.setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); + glm::dmat4 MV = glm::dmat4( + renderData.camera.sgctInternal.projectionMatrix() + ) * renderData.camera.combinedViewMatrix(); - program.setUniform("TRANSMITTANCE_W", _transmittance_table_width); - program.setUniform("TRANSMITTANCE_H", _transmittance_table_height); - program.setUniform("SKY_W", _irradiance_table_width); - program.setUniform("SKY_H", _irradiance_table_height); - program.setUniform("OTHER_TEXTURES_W", _delta_e_table_width); - program.setUniform("OTHER_TEXTURES_H", _delta_e_table_height); - program.setUniform("SAMPLES_R", _r_samples); - program.setUniform("SAMPLES_MU", _mu_samples); - program.setUniform("SAMPLES_MU_S", _mu_s_samples); - program.setUniform("SAMPLES_NU", _nu_samples); - - // Object Space - program.setUniform("dModelTransformMatrix", _modelTransform); - - glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); - glm::vec3 eyePosModelCoords = inverseModelMatrix * - glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); - program.setUniform("eyePosModelCoords", eyePosModelCoords); - - glm::dmat4 eyeToModel = - inverseModelMatrix * - glm::inverse(renderData.camera.combinedViewMatrix()); - - program.setUniform("eyeToModel", - glm::mat4(eyeToModel)); - - float viewScaling = renderData.camera.scaling(); - program.setUniform("viewScaling", viewScaling); - - glm::mat4 invProjection = - glm::inverse(renderData.camera.projectionMatrix()); - program.setUniform("inverseProjection", invProjection); - - glm::dmat4 eyeToWorldTransform = - glm::inverse(renderData.camera.combinedViewMatrix()); - program.setUniform("eyeToWorld", eyeToWorldTransform); - - double lt; - glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( - "SUN", - "SUN", - "GALACTIC", - {}, - _time, - lt - ); - glm::dvec4 sunPosObj = glm::dvec4(0.0); - - // Sun following camera position - if (_sunFollowingCameraEnabled) { - sunPosObj = inverseModelMatrix * glm::dvec4( - renderData.camera.eyePositionVec3(), - 1.0 - ); + if (!isAtmosphereInFrustum( + glm::value_ptr(MV), + tPlanetPosWorld, + (_atmosphereRadius + ATM_EPS)*KM_TO_M) + ) + { + program.setUniform(_uniformCache.cullAtmosphere, 1); } else { - sunPosObj = inverseModelMatrix * - glm::dvec4(sunPosWorld - renderData.modelTransform.translation, 1.0); - } + program.setUniform(_uniformCache.cullAtmosphere, 0); + program.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); + program.setUniform(_uniformCache.Rt, _atmosphereRadius); + program.setUniform(_uniformCache.groundRadianceEmittion, _planetGroundRadianceEmittion); + program.setUniform(_uniformCache.HR, _rayleighHeightScale); + program.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); + program.setUniform(_uniformCache.HM, _mieHeightScale); + program.setUniform(_uniformCache.betaMieExtinction, _mieExtinctionCoeff); + program.setUniform(_uniformCache.mieG, _miePhaseConstant); + program.setUniform(_uniformCache.sunRadiance, _sunRadianceIntensity); + program.setUniform(_uniformCache.ozoneLayerEnabled, _ozoneEnabled); + program.setUniform(_uniformCache.HO, _ozoneHeightScale); + program.setUniform(_uniformCache.betaOzoneExtinction, _ozoneExtinctionCoeff); + program.setUniform(_uniformCache.SAMPLES_R, _r_samples); + program.setUniform(_uniformCache.SAMPLES_MU, _mu_samples); + program.setUniform(_uniformCache.SAMPLES_MU_S, _mu_s_samples); + program.setUniform(_uniformCache.SAMPLES_NU, _nu_samples); - // Sun Position in Object Space - program.setUniform("sunDirectionObj", glm::normalize(glm::dvec3(sunPosObj))); + // Object Space + glm::dmat4 inverseModelMatrix = glm::inverse(_modelTransform); + program.setUniform(_uniformCache2.dInverseModelTransformMatrix, inverseModelMatrix); + program.setUniform(_uniformCache2.dModelTransformMatrix, _modelTransform); - program.setUniform("ellipsoidRadii", _ellipsoidRadii); + // Eye Space in SGCT to Eye Space in OS (SGCT View to OS Camera Rig) + glm::dmat4 dSgctEye2OSEye = glm::inverse( + glm::dmat4(renderData.camera.viewMatrix())); - // Shadow calculations.. - if (!_shadowConfArray.empty()) { - std::vector shadowDataArray; - shadowDataArray.reserve(_shadowConfArray.size()); + glm::dmat4 dSGCTViewToWorldMatrix = glm::inverse(renderData.camera.combinedViewMatrix()); - for (const auto & shadowConf : _shadowConfArray) { - // TO REMEMBER: all distances and lengths in world coordinates are in - // meters!!! We need to move this to view space... - // Getting source and caster: - glm::dvec3 sourcePos = SpiceManager::ref().targetPosition( - shadowConf.source.first, - "SUN", "GALACTIC", - {}, - _time, - lt + // Eye Space in SGCT to OS World Space + program.setUniform(_uniformCache2.dSGCTViewToWorldMatrix, + dSGCTViewToWorldMatrix); + + // SGCT Projection to SGCT Eye Space + glm::dmat4 dInverseProjection = glm::inverse( + glm::dmat4(renderData.camera.projectionMatrix())); + + // SGCT Projection to OS Camera Before Rotation + glm::dmat4 dProjectionToTmpRotTransformMatrix = + glm::mat4_cast( + static_cast(renderData.camera.rotationQuaternion()) + ) * + dSgctEye2OSEye * + glm::inverse(renderData.camera.viewScaleMatrix()) * + dInverseProjection; + + // SGCT Projection to World Space + glm::dmat4 dSgctProjectionToWorldTransformMatrix(dProjectionToTmpRotTransformMatrix); + double *mSource = (double*)glm::value_ptr(dSgctProjectionToWorldTransformMatrix); + + mSource[12] += renderData.camera.eyePositionVec3().x; + mSource[13] += renderData.camera.eyePositionVec3().y; + mSource[14] += renderData.camera.eyePositionVec3().z; + /* + mSource[12] += renderData.camera.positionVec3().x; + mSource[13] += renderData.camera.positionVec3().y; + mSource[14] += renderData.camera.positionVec3().z; + */ + mSource[15] = 1.0; + + + // SGCT Projection to Object Space + glm::dmat4 inverseWholeMatrixPipeline = inverseModelMatrix * + dSgctProjectionToWorldTransformMatrix; + program.setUniform(_uniformCache2.dSgctProjectionToModelTransformMatrix, + inverseWholeMatrixPipeline); + + glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.eyePositionVec3(), 1.0); + //glm::dvec4 camPosObjCoords = inverseModelMatrix * glm::dvec4(renderData.camera.positionVec3(), 1.0); + program.setUniform(_uniformCache2.dCamPosObj, camPosObjCoords); + + double lt; + glm::dvec3 sunPosWorld = SpiceManager::ref().targetPosition( + "SUN", + "SUN", + "GALACTIC", + {}, + _time, + lt + ); + glm::dvec4 sunPosObj = glm::dvec4(0.0); + + // Sun following camera position + if (_sunFollowingCameraEnabled) { + sunPosObj = inverseModelMatrix * glm::dvec4( + renderData.camera.eyePositionVec3(), + 1.0 ); - sourcePos *= KM_TO_M; // converting to meters - glm::dvec3 casterPos = SpiceManager::ref().targetPosition( - shadowConf.caster.first, - "SUN", "GALACTIC", - {}, - _time, - lt - ); - casterPos *= KM_TO_M; // converting to meters - - // First we determine if the caster is shadowing the current planet - // (all calculations in World Coordinates): - glm::dvec3 planetCasterVec = casterPos - renderData.position.dvec3(); - glm::dvec3 sourceCasterVec = casterPos - sourcePos; - double sc_length = glm::length(sourceCasterVec); - glm::dvec3 planetCaster_proj = ( - glm::dot(planetCasterVec, sourceCasterVec) / - (sc_length*sc_length)) * sourceCasterVec; - double d_test = glm::length(planetCasterVec - planetCaster_proj); - double xp_test = shadowConf.caster.second * - sc_length / (shadowConf.source.second + shadowConf.caster.second); - double rp_test = shadowConf.caster.second * - (glm::length(planetCaster_proj) + xp_test) / xp_test; - - double casterDistSun = glm::length(casterPos - sunPosWorld); - double planetDistSun = glm::length( - renderData.position.dvec3() - sunPosWorld - ); - - ShadowRenderingStruct shadowData; - shadowData.isShadowing = false; - - if (((d_test - rp_test) < (_atmospherePlanetRadius * KM_TO_M)) && - (casterDistSun < planetDistSun)) { - // The current caster is shadowing the current planet - shadowData.isShadowing = true; - shadowData.rs = shadowConf.source.second; - shadowData.rc = shadowConf.caster.second; - shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); - shadowData.xp = xp_test; - shadowData.xu = shadowData.rc * sc_length / - (shadowData.rs - shadowData.rc); - shadowData.casterPositionVec = casterPos; - } - shadowDataArray.push_back(shadowData); + } + else { + sunPosObj = inverseModelMatrix * + glm::dvec4(sunPosWorld - renderData.modelTransform.translation, 1.0); } - const std::string uniformVarName("shadowDataArray["); - unsigned int counter = 0; - for (const auto & sd : shadowDataArray) { - std::stringstream ss; - ss << uniformVarName << counter << "].isShadowing"; - program.setUniform(ss.str(), sd.isShadowing); - if (sd.isShadowing) { - ss.str(std::string()); - ss << uniformVarName << counter << "].xp"; - program.setUniform(ss.str(), sd.xp); - ss.str(std::string()); - ss << uniformVarName << counter << "].xu"; - program.setUniform(ss.str(), sd.xu); - /*ss.str(std::string()); - ss << uniformVarName << counter << "].rs"; - program.setUniform(ss.str(), sd.rs);*/ - ss.str(std::string()); - ss << uniformVarName << counter << "].rc"; - program.setUniform(ss.str(), sd.rc); - ss.str(std::string()); - ss << uniformVarName << counter << "].sourceCasterVec"; - program.setUniform(ss.str(), sd.sourceCasterVec); - ss.str(std::string()); - ss << uniformVarName << counter << "].casterPositionVec"; - program.setUniform(ss.str(), sd.casterPositionVec); + // Sun Position in Object Space + program.setUniform(_uniformCache2.sunDirectionObj, glm::normalize(glm::dvec3(sunPosObj))); + + // Shadow calculations.. + if (!_shadowConfArray.empty()) { + std::vector shadowDataArray; + shadowDataArray.reserve(_shadowConfArray.size()); + + for (const auto & shadowConf : _shadowConfArray) { + // TO REMEMBER: all distances and lengths in world coordinates are in + // meters!!! We need to move this to view space... + // Getting source and caster: + glm::dvec3 sourcePos = SpiceManager::ref().targetPosition( + shadowConf.source.first, + "SUN", "GALACTIC", + {}, + _time, + lt + ); + sourcePos *= KM_TO_M; // converting to meters + glm::dvec3 casterPos = SpiceManager::ref().targetPosition( + shadowConf.caster.first, + "SUN", "GALACTIC", + {}, + _time, + lt + ); + casterPos *= KM_TO_M; // converting to meters + + // First we determine if the caster is shadowing the current planet + // (all calculations in World Coordinates): + glm::dvec3 planetCasterVec = casterPos - renderData.position.dvec3(); + glm::dvec3 sourceCasterVec = casterPos - sourcePos; + double sc_length = glm::length(sourceCasterVec); + glm::dvec3 planetCaster_proj = ( + glm::dot(planetCasterVec, sourceCasterVec) / + (sc_length*sc_length)) * sourceCasterVec; + double d_test = glm::length(planetCasterVec - planetCaster_proj); + double xp_test = shadowConf.caster.second * + sc_length / (shadowConf.source.second + shadowConf.caster.second); + double rp_test = shadowConf.caster.second * + (glm::length(planetCaster_proj) + xp_test) / xp_test; + + double casterDistSun = glm::length(casterPos - sunPosWorld); + double planetDistSun = glm::length( + renderData.position.dvec3() - sunPosWorld + ); + + ShadowRenderingStruct shadowData; + shadowData.isShadowing = false; + + if (((d_test - rp_test) < (_atmospherePlanetRadius * KM_TO_M)) && + //if (((d_test - rp_test) < (_atmosphereRadius * KM_TO_M)) && + (casterDistSun < planetDistSun)) { + // The current caster is shadowing the current planet + shadowData.isShadowing = true; + shadowData.rs = shadowConf.source.second; + shadowData.rc = shadowConf.caster.second; + shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); + shadowData.xp = xp_test; + shadowData.xu = shadowData.rc * sc_length / + (shadowData.rs - shadowData.rc); + shadowData.casterPositionVec = casterPos; + } + shadowDataArray.push_back(shadowData); } - counter++; + + const std::string uniformVarName("shadowDataArray["); + unsigned int counter = 0; + for (const auto & sd : shadowDataArray) { + std::stringstream ss; + ss << uniformVarName << counter << "].isShadowing"; + program.setUniform(ss.str(), sd.isShadowing); + if (sd.isShadowing) { + ss.str(std::string()); + ss << uniformVarName << counter << "].xp"; + program.setUniform(ss.str(), sd.xp); + ss.str(std::string()); + ss << uniformVarName << counter << "].xu"; + program.setUniform(ss.str(), sd.xu); + /*ss.str(std::string()); + ss << uniformVarName << counter << "].rs"; + program.setUniform(ss.str(), sd.rs);*/ + ss.str(std::string()); + ss << uniformVarName << counter << "].rc"; + program.setUniform(ss.str(), sd.rc); + ss.str(std::string()); + ss << uniformVarName << counter << "].sourceCasterVec"; + program.setUniform(ss.str(), sd.sourceCasterVec); + ss.str(std::string()); + ss << uniformVarName << counter << "].casterPositionVec"; + program.setUniform(ss.str(), sd.casterPositionVec); + } + counter++; + } + program.setUniform(_uniformCache2.hardShadows, _hardShadowsEnabled); } - program.setUniform("hardShadows", _hardShadowsEnabled); } } - } - _transmittanceTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - program.setUniform("transmittanceTexture", _transmittanceTableTextureUnit); - - _irradianceTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); - program.setUniform("irradianceTexture", _irradianceTableTextureUnit); - - _inScatteringTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); - program.setUniform("inscatterTexture", _inScatteringTableTextureUnit); -} - -void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, - ghoul::opengl::ProgramObject&) -{ - // Deactivate the texture units - _transmittanceTableTextureUnit.deactivate(); - _irradianceTableTextureUnit.deactivate(); - _inScatteringTableTextureUnit.deactivate(); -} - -std::string AtmosphereDeferredcaster::deferredcastPath() const { - return GlslDeferredcastPath; -} - -std::string AtmosphereDeferredcaster::deferredcastFSPath() const { - return GlslDeferredcastFSPath; -} - -std::string AtmosphereDeferredcaster::deferredcastVSPath() const { - return GlslDeferredcastVsPath; -} - -std::string AtmosphereDeferredcaster::helperPath() const { - return ""; // no helper file -} - -void AtmosphereDeferredcaster::setModelTransform(const glm::dmat4& transform) { - _modelTransform = transform; -} - -void AtmosphereDeferredcaster::setTime(double time) { - _time = time; -} - -void AtmosphereDeferredcaster::setAtmosphereRadius(float atmRadius) { - _atmosphereRadius = atmRadius; -} - -void AtmosphereDeferredcaster::setPlanetRadius(float planetRadius) { - _atmospherePlanetRadius = planetRadius; -} - -void AtmosphereDeferredcaster::setPlanetAverageGroundReflectance( - float averageGReflectance) -{ - _planetAverageGroundReflectance = averageGReflectance; -} - -void AtmosphereDeferredcaster::setPlanetGroundRadianceEmittion( - float groundRadianceEmittion) -{ - _planetGroundRadianceEmittion = groundRadianceEmittion; -} - -void AtmosphereDeferredcaster::setRayleighHeightScale(float rayleighHeightScale) { - _rayleighHeightScale = rayleighHeightScale; -} - -void AtmosphereDeferredcaster::enableOzone(bool enable) { - _ozoneEnabled = enable; -} - -void AtmosphereDeferredcaster::setOzoneHeightScale(float ozoneHeightScale) { - _ozoneHeightScale = ozoneHeightScale; -} - - -void AtmosphereDeferredcaster::setMieHeightScale(float mieHeightScale) { - _mieHeightScale = mieHeightScale; -} - -void AtmosphereDeferredcaster::setMiePhaseConstant(float miePhaseConstant) { - _miePhaseConstant = miePhaseConstant; -} - -void AtmosphereDeferredcaster::setSunRadianceIntensity(float sunRadiance) { - _sunRadianceIntensity = sunRadiance; -} - -void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( - const glm::vec3& rayScattCoeff) -{ - _rayleighScatteringCoeff = rayScattCoeff; -} - -void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( - const glm::vec3& ozoneExtCoeff) -{ - _ozoneExtinctionCoeff = ozoneExtCoeff; -} - -void AtmosphereDeferredcaster::setMieScatteringCoefficients( - const glm::vec3& mieScattCoeff) -{ - _mieScatteringCoeff = mieScattCoeff; -} - -void AtmosphereDeferredcaster::setMieExtinctionCoefficients(const glm::vec3& mieExtCoeff) -{ - _mieExtinctionCoeff = mieExtCoeff; -} - -void AtmosphereDeferredcaster::setEllipsoidRadii(const glm::dvec3& radii) { - _ellipsoidRadii = radii; -} - -void AtmosphereDeferredcaster::setHardShadows(bool enabled) { - _hardShadowsEnabled = enabled; -} - -void AtmosphereDeferredcaster::setShadowConfigArray( - const std::vector& shadowConfigArray) -{ - _shadowConfArray = shadowConfigArray; -} - -void AtmosphereDeferredcaster::enableSunFollowing(bool enable) { - _sunFollowingCameraEnabled = enable; -} - -void AtmosphereDeferredcaster::setPrecalculationTextureScale( - float preCalculatedTexturesScale) -{ - _calculationTextureScale = preCalculatedTexturesScale; - _transmittance_table_width *= static_cast(_calculationTextureScale); - _transmittance_table_height *= static_cast(_calculationTextureScale); - _irradiance_table_width *= static_cast(_calculationTextureScale); - _irradiance_table_height *= static_cast(_calculationTextureScale); - _delta_e_table_width *= static_cast(_calculationTextureScale); - _delta_e_table_height *= static_cast(_calculationTextureScale); - _r_samples *= static_cast(_calculationTextureScale); - _mu_samples *= static_cast(_calculationTextureScale); - _mu_s_samples *= static_cast(_calculationTextureScale); - _nu_samples *= static_cast(_calculationTextureScale); -} - -void AtmosphereDeferredcaster::enablePrecalculationTexturesSaving() { - _saveCalculationTextures = true; -} - -void AtmosphereDeferredcaster::loadComputationPrograms() { - //============== Transmittance T ================= - if (!_transmittanceProgramObject) { - _transmittanceProgramObject = ghoul::opengl::ProgramObject::Build( - "transmittanceCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl")); - } - using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; - _transmittanceProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); - _transmittanceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Irradiance E ================= - if (!_irradianceProgramObject) { - _irradianceProgramObject = ghoul::opengl::ProgramObject::Build( - "irradianceCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_fs.glsl")); - } - _irradianceProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _irradianceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (!_irradianceSupTermsProgramObject) { - _irradianceSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( - "irradianceSupTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_fs.glsl")); - } - _irradianceSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); - _irradianceSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== InScattering S ================= - if (!_inScatteringProgramObject) { - _inScatteringProgramObject = ghoul::opengl::ProgramObject::Build( - "inScatteringCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_gs.glsl")); - } - _inScatteringProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _inScatteringProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (!_inScatteringSupTermsProgramObject) { - _inScatteringSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( - "inScatteringSupTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_gs.glsl")); - } - _inScatteringSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); - _inScatteringSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta E ================= - if (!_deltaEProgramObject) { - _deltaEProgramObject = ghoul::opengl::ProgramObject::Build( - "deltaECalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_fs.glsl")); - } - _deltaEProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaEProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Irradiance finel E ================= - if (!_irradianceFinalProgramObject) { - _irradianceFinalProgramObject = ghoul::opengl::ProgramObject::Build( - "irradianceEFinalProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_fs.glsl")); - } - _irradianceFinalProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); - _irradianceFinalProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta S ================= - if (!_deltaSProgramObject) { - _deltaSProgramObject = ghoul::opengl::ProgramObject::Build( - "deltaSCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_gs.glsl")); - } - _deltaSProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaSProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - if (!_deltaSSupTermsProgramObject) { - _deltaSSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( - "deltaSSUPTermsCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_gs.glsl")); - } - _deltaSSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( - IgnoreError::Yes - ); - _deltaSSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); - - //============== Delta J (Radiance Scattered) ================= - if (!_deltaJProgramObject) { - _deltaJProgramObject = ghoul::opengl::ProgramObject::Build( - "deltaJCalcProgram", - absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_fs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_gs.glsl")); - } - _deltaJProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _deltaJProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); -} - -void AtmosphereDeferredcaster::unloadComputationPrograms() { - _transmittanceProgramObject = nullptr; - _irradianceProgramObject = nullptr; - _irradianceSupTermsProgramObject = nullptr; - _inScatteringProgramObject = nullptr; - _inScatteringSupTermsProgramObject = nullptr; - _deltaEProgramObject = nullptr; - _irradianceFinalProgramObject = nullptr; - _deltaSProgramObject = nullptr; - _deltaSSupTermsProgramObject = nullptr; - _deltaJProgramObject = nullptr; -} - -void AtmosphereDeferredcaster::createComputationTextures() { - if (!_atmosphereCalculated) { - //============== Transmittance ================= - ghoul::opengl::TextureUnit transmittanceTableTextureUnit; - transmittanceTableTextureUnit.activate(); - glGenTextures(1, &_transmittanceTableTexture); + _transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _transmittance_table_width, - _transmittance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + program.setUniform(_uniformCache2.transmittanceTexture, _transmittanceTableTextureUnit); - //============== Irradiance ================= - ghoul::opengl::TextureUnit irradianceTableTextureUnit; - irradianceTableTextureUnit.activate(); - glGenTextures(1, &_irradianceTableTexture); + _irradianceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); + program.setUniform(_uniformCache2.irradianceTexture, _irradianceTableTextureUnit); + + _inScatteringTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); + program.setUniform(_uniformCache2.inscatterTexture, _inScatteringTableTextureUnit); + } + + void AtmosphereDeferredcaster::postRaycast(const RenderData&, + const DeferredcastData&, + ghoul::opengl::ProgramObject&) + { + // Deactivate the texture units + _transmittanceTableTextureUnit.deactivate(); + _irradianceTableTextureUnit.deactivate(); + _inScatteringTableTextureUnit.deactivate(); + } + + std::string AtmosphereDeferredcaster::deferredcastPath() const { + return GlslDeferredcastPath; + } + + std::string AtmosphereDeferredcaster::deferredcastFSPath() const { + return GlslDeferredcastFSPath; + } + + std::string AtmosphereDeferredcaster::deferredcastVSPath() const { + return GlslDeferredcastVsPath; + } + + std::string AtmosphereDeferredcaster::helperPath() const { + return ""; // no helper file + } + + void AtmosphereDeferredcaster::initializeCachedVariables(ghoul::opengl::ProgramObject& program) { + _uniformCache.cullAtmosphere = program.uniformLocation("cullAtmosphere"); + _uniformCache.Rg = program.uniformLocation("Rg"); + _uniformCache.Rt = program.uniformLocation("Rt"); + _uniformCache.groundRadianceEmittion = program.uniformLocation("groundRadianceEmittion"); + _uniformCache.HR = program.uniformLocation("HR"); + _uniformCache.betaRayleigh = program.uniformLocation("betaRayleigh"); + _uniformCache.HM = program.uniformLocation("HM"); + _uniformCache.betaMieExtinction = program.uniformLocation("betaMieExtinction"); + _uniformCache.mieG = program.uniformLocation("mieG"); + _uniformCache.sunRadiance = program.uniformLocation("sunRadiance"); + _uniformCache.ozoneLayerEnabled = program.uniformLocation("ozoneLayerEnabled"); + _uniformCache.HO = program.uniformLocation("HO"); + _uniformCache.betaOzoneExtinction = program.uniformLocation("betaOzoneExtinction"); + _uniformCache.SAMPLES_R = program.uniformLocation("SAMPLES_R"); + _uniformCache.SAMPLES_MU = program.uniformLocation("SAMPLES_MU"); + _uniformCache.SAMPLES_MU_S = program.uniformLocation("SAMPLES_MU_S"); + _uniformCache.SAMPLES_NU = program.uniformLocation("SAMPLES_NU"); + _uniformCache2.dInverseModelTransformMatrix = program.uniformLocation("dInverseModelTransformMatrix"); + _uniformCache2.dModelTransformMatrix = program.uniformLocation("dModelTransformMatrix"); + _uniformCache2.dSgctProjectionToModelTransformMatrix = program.uniformLocation("dSgctProjectionToModelTransformMatrix"); + _uniformCache2.dSGCTViewToWorldMatrix = program.uniformLocation("dSGCTViewToWorldMatrix"); + _uniformCache2.dCamPosObj = program.uniformLocation("dCamPosObj"); + _uniformCache2.sunDirectionObj = program.uniformLocation("sunDirectionObj"); + _uniformCache2.hardShadows = program.uniformLocation("hardShadows"); + _uniformCache2.transmittanceTexture = program.uniformLocation("transmittanceTexture"); + _uniformCache2.irradianceTexture = program.uniformLocation("irradianceTexture"); + _uniformCache2.inscatterTexture = program.uniformLocation("inscatterTexture"); + } + + void AtmosphereDeferredcaster::update(const UpdateData&) { + + } + + void AtmosphereDeferredcaster::setModelTransform(const glm::dmat4& transform) { + _modelTransform = transform; + } + + void AtmosphereDeferredcaster::setTime(double time) { + _time = time; + } + + void AtmosphereDeferredcaster::setAtmosphereRadius(float atmRadius) { + _atmosphereRadius = atmRadius; + } + + void AtmosphereDeferredcaster::setPlanetRadius(float planetRadius) { + _atmospherePlanetRadius = planetRadius; + } + + void AtmosphereDeferredcaster::setPlanetAverageGroundReflectance( + float averageGReflectance) + { + _planetAverageGroundReflectance = averageGReflectance; + } + + void AtmosphereDeferredcaster::setPlanetGroundRadianceEmittion( + float groundRadianceEmittion) + { + _planetGroundRadianceEmittion = groundRadianceEmittion; + } + + void AtmosphereDeferredcaster::setRayleighHeightScale(float rayleighHeightScale) { + _rayleighHeightScale = rayleighHeightScale; + } + + void AtmosphereDeferredcaster::enableOzone(bool enable) { + _ozoneEnabled = enable; + } + + void AtmosphereDeferredcaster::setOzoneHeightScale(float ozoneHeightScale) { + _ozoneHeightScale = ozoneHeightScale; + } + + + void AtmosphereDeferredcaster::setMieHeightScale(float mieHeightScale) { + _mieHeightScale = mieHeightScale; + } + + void AtmosphereDeferredcaster::setMiePhaseConstant(float miePhaseConstant) { + _miePhaseConstant = miePhaseConstant; + } + + void AtmosphereDeferredcaster::setSunRadianceIntensity(float sunRadiance) { + _sunRadianceIntensity = sunRadiance; + } + + void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( + const glm::vec3& rayScattCoeff) + { + _rayleighScatteringCoeff = rayScattCoeff; + } + + void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( + const glm::vec3& ozoneExtCoeff) + { + _ozoneExtinctionCoeff = ozoneExtCoeff; + } + + void AtmosphereDeferredcaster::setMieScatteringCoefficients( + const glm::vec3& mieScattCoeff) + { + _mieScatteringCoeff = mieScattCoeff; + } + + void AtmosphereDeferredcaster::setMieExtinctionCoefficients(const glm::vec3& mieExtCoeff) + { + _mieExtinctionCoeff = mieExtCoeff; + } + + void AtmosphereDeferredcaster::setEllipsoidRadii(const glm::dvec3& radii) { + _ellipsoidRadii = radii; + } + + void AtmosphereDeferredcaster::setHardShadows(bool enabled) { + _hardShadowsEnabled = enabled; + } + + void AtmosphereDeferredcaster::setShadowConfigArray( + const std::vector& shadowConfigArray) + { + _shadowConfArray = shadowConfigArray; + } + + void AtmosphereDeferredcaster::enableSunFollowing(bool enable) { + _sunFollowingCameraEnabled = enable; + } + + void AtmosphereDeferredcaster::setPrecalculationTextureScale( + float preCalculatedTexturesScale) + { + _calculationTextureScale = preCalculatedTexturesScale; + _transmittance_table_width *= static_cast(_calculationTextureScale); + _transmittance_table_height *= static_cast(_calculationTextureScale); + _irradiance_table_width *= static_cast(_calculationTextureScale); + _irradiance_table_height *= static_cast(_calculationTextureScale); + _delta_e_table_width *= static_cast(_calculationTextureScale); + _delta_e_table_height *= static_cast(_calculationTextureScale); + _r_samples *= static_cast(_calculationTextureScale); + _mu_samples *= static_cast(_calculationTextureScale); + _mu_s_samples *= static_cast(_calculationTextureScale); + _nu_samples *= static_cast(_calculationTextureScale); + } + + void AtmosphereDeferredcaster::enablePrecalculationTexturesSaving() { + _saveCalculationTextures = true; + } + + void AtmosphereDeferredcaster::loadComputationPrograms() { + //============== Transmittance T ================= + if (!_transmittanceProgramObject) { + _transmittanceProgramObject = ghoul::opengl::ProgramObject::Build( + "transmittanceCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl")); + } + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; + _transmittanceProgramObject->setIgnoreSubroutineUniformLocationError( + IgnoreError::Yes + ); + _transmittanceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== Irradiance E ================= + if (!_irradianceProgramObject) { + _irradianceProgramObject = ghoul::opengl::ProgramObject::Build( + "irradianceCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_fs.glsl")); + } + _irradianceProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _irradianceProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + if (!_irradianceSupTermsProgramObject) { + _irradianceSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( + "irradianceSupTermsCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_fs.glsl")); + } + _irradianceSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( + IgnoreError::Yes + ); + _irradianceSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== InScattering S ================= + if (!_inScatteringProgramObject) { + _inScatteringProgramObject = ghoul::opengl::ProgramObject::Build( + "inScatteringCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_fs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_gs.glsl")); + } + _inScatteringProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _inScatteringProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + if (!_inScatteringSupTermsProgramObject) { + _inScatteringSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( + "inScatteringSupTermsCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_fs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_gs.glsl")); + } + _inScatteringSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( + IgnoreError::Yes + ); + _inScatteringSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== Delta E ================= + if (!_deltaEProgramObject) { + _deltaEProgramObject = ghoul::opengl::ProgramObject::Build( + "deltaECalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_fs.glsl")); + } + _deltaEProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _deltaEProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== Irradiance finel E ================= + if (!_irradianceFinalProgramObject) { + _irradianceFinalProgramObject = ghoul::opengl::ProgramObject::Build( + "irradianceEFinalProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_fs.glsl")); + } + _irradianceFinalProgramObject->setIgnoreSubroutineUniformLocationError( + IgnoreError::Yes + ); + _irradianceFinalProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== Delta S ================= + if (!_deltaSProgramObject) { + _deltaSProgramObject = ghoul::opengl::ProgramObject::Build( + "deltaSCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_fs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_gs.glsl")); + } + _deltaSProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _deltaSProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + if (!_deltaSSupTermsProgramObject) { + _deltaSSupTermsProgramObject = ghoul::opengl::ProgramObject::Build( + "deltaSSUPTermsCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_fs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_gs.glsl")); + } + _deltaSSupTermsProgramObject->setIgnoreSubroutineUniformLocationError( + IgnoreError::Yes + ); + _deltaSSupTermsProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + + //============== Delta J (Radiance Scattered) ================= + if (!_deltaJProgramObject) { + _deltaJProgramObject = ghoul::opengl::ProgramObject::Build( + "deltaJCalcProgram", + absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_vs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_fs.glsl"), + absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_gs.glsl")); + } + _deltaJProgramObject->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _deltaJProgramObject->setIgnoreUniformLocationError(IgnoreError::Yes); + } + + void AtmosphereDeferredcaster::unloadComputationPrograms() { + _transmittanceProgramObject = nullptr; + _irradianceProgramObject = nullptr; + _irradianceSupTermsProgramObject = nullptr; + _inScatteringProgramObject = nullptr; + _inScatteringSupTermsProgramObject = nullptr; + _deltaEProgramObject = nullptr; + _irradianceFinalProgramObject = nullptr; + _deltaSProgramObject = nullptr; + _deltaSSupTermsProgramObject = nullptr; + _deltaJProgramObject = nullptr; + } + + void AtmosphereDeferredcaster::createComputationTextures() { + if (!_atmosphereCalculated) { + //============== Transmittance ================= + ghoul::opengl::TextureUnit transmittanceTableTextureUnit; + transmittanceTableTextureUnit.activate(); + glGenTextures(1, &_transmittanceTableTexture); + glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _transmittance_table_width, + _transmittance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + + //============== Irradiance ================= + ghoul::opengl::TextureUnit irradianceTableTextureUnit; + irradianceTableTextureUnit.activate(); + glGenTextures(1, &_irradianceTableTexture); + glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _irradiance_table_width, + _irradiance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + + //============== InScattering ================= + ghoul::opengl::TextureUnit inScatteringTableTextureUnit; + inScatteringTableTextureUnit.activate(); + glGenTextures(1, &_inScatteringTableTexture); + glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, _mu_s_samples * _nu_samples, + _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); + } + + //============== Delta E ================= + ghoul::opengl::TextureUnit deltaETableTextureUnit; + deltaETableTextureUnit.activate(); + glGenTextures(1, &_deltaETableTexture); + glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _irradiance_table_width, - _irradiance_table_height, 0, GL_RGB, GL_FLOAT, nullptr); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _delta_e_table_width, + _delta_e_table_height, 0, GL_RGB, GL_FLOAT, nullptr); - //============== InScattering ================= - ghoul::opengl::TextureUnit inScatteringTableTextureUnit; - inScatteringTableTextureUnit.activate(); - glGenTextures(1, &_inScatteringTableTexture); - glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); + //============== Delta S ================= + ghoul::opengl::TextureUnit deltaSRayleighTableTextureUnit; + deltaSRayleighTableTextureUnit.activate(); + glGenTextures(1, &_deltaSRayleighTableTexture); + glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, _mu_s_samples * _nu_samples, + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - } - //============== Delta E ================= - ghoul::opengl::TextureUnit deltaETableTextureUnit; - deltaETableTextureUnit.activate(); - glGenTextures(1, &_deltaETableTexture); - glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, _delta_e_table_width, - _delta_e_table_height, 0, GL_RGB, GL_FLOAT, nullptr); - - //============== Delta S ================= - ghoul::opengl::TextureUnit deltaSRayleighTableTextureUnit; - deltaSRayleighTableTextureUnit.activate(); - glGenTextures(1, &_deltaSRayleighTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - - ghoul::opengl::TextureUnit deltaSMieTableTextureUnit; - deltaSMieTableTextureUnit.activate(); - glGenTextures(1, &_deltaSMieTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - - //============== Delta J (Radiance Scattered) ================= - ghoul::opengl::TextureUnit deltaJTableTextureUnit; - deltaJTableTextureUnit.activate(); - glGenTextures(1, &_deltaJTableTexture); - glBindTexture(GL_TEXTURE_3D, _deltaJTableTexture); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, - _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - -} - -void AtmosphereDeferredcaster::deleteComputationTextures() { - // Cleaning up - glDeleteTextures(1, &_transmittanceTableTexture); - glDeleteTextures(1, &_irradianceTableTexture); - glDeleteTextures(1, &_inScatteringTableTexture); - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); -} - -void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { - glDeleteTextures(1, &_deltaETableTexture); - glDeleteTextures(1, &_deltaSRayleighTableTexture); - glDeleteTextures(1, &_deltaSMieTableTexture); - glDeleteTextures(1, &_deltaJTableTexture); -} - -void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, - GLenum drawBuffers[1], - GLsizei vertexSize) -{ - ghoul::opengl::TextureUnit transmittanceTableTextureUnit; - ghoul::opengl::TextureUnit irradianceTableTextureUnit; - ghoul::opengl::TextureUnit inScatteringTableTextureUnit; - ghoul::opengl::TextureUnit deltaETableTextureUnit; - ghoul::opengl::TextureUnit deltaSRayleighTableTextureUnit; - ghoul::opengl::TextureUnit deltaSMieTableTextureUnit; - ghoul::opengl::TextureUnit deltaJTableTextureUnit; - - // Saving current OpenGL state - GLboolean blendEnabled = glIsEnabled(GL_BLEND); - GLenum blendEquationRGB; - GLenum blendEquationAlpha; - GLenum blendDestAlpha; - GLenum blendDestRGB; - GLenum blendSrcAlpha; - GLenum blendSrcRGB; - - if (blendEnabled) { - glDisable(GL_BLEND); - } - glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); - glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); - glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); - glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); - glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); - glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); - - // =========================================================== - // See Precomputed Atmosphere Scattering from Bruneton et al. paper, algorithm 4.1: - // =========================================================== - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - _transmittanceTableTexture, - 0 - ); - checkFrameBufferState("_transmittanceTableTexture"); - glViewport(0, 0, _transmittance_table_width, _transmittance_table_height); - _transmittanceProgramObject->activate(); - loadAtmosphereDataIntoShaderProgram(_transmittanceProgramObject); - //glClear(GL_COLOR_BUFFER_BIT); - static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glClearBufferfv(GL_COLOR, 0, black); - renderQuadForCalc(quadCalcVAO, vertexSize); - if (_saveCalculationTextures) { - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT0, - std::string("transmittance_texture.ppm"), - _transmittance_table_width, - _transmittance_table_height - ); - } - _transmittanceProgramObject->deactivate(); - - // line 2 in algorithm 4.1 - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _deltaETableTexture, 0); - checkFrameBufferState("_deltaETableTexture"); - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); - _irradianceProgramObject->activate(); - transmittanceTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - _irradianceProgramObject->setUniform( - "transmittanceTexture", - transmittanceTableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_irradianceProgramObject); - glClear(GL_COLOR_BUFFER_BIT); - renderQuadForCalc(quadCalcVAO, vertexSize); - if (_saveCalculationTextures) { - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT0, - std::string("deltaE_table_texture.ppm"), - _delta_e_table_width, - _delta_e_table_height - ); - } - _irradianceProgramObject->deactivate(); - - // line 3 in algorithm 4.1 - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - _deltaSRayleighTableTexture, - 0 - ); - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT1, - _deltaSMieTableTexture, - 0 - ); - GLenum colorBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - glDrawBuffers(2, colorBuffers); - checkFrameBufferState("_deltaSRay and _deltaSMie TableTexture"); - glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); - _inScatteringProgramObject->activate(); - transmittanceTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - _inScatteringProgramObject->setUniform( - "transmittanceTexture", - transmittanceTableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_inScatteringProgramObject); - glClear(GL_COLOR_BUFFER_BIT); - for (int layer = 0; layer < static_cast(_r_samples); ++layer) { - step3DTexture(_inScatteringProgramObject, layer); - renderQuadForCalc(quadCalcVAO, vertexSize); - } - if (_saveCalculationTextures) { - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT0, - std::string("deltaS_rayleigh_texture.ppm"), - _mu_s_samples * _nu_samples, - _mu_samples - ); - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT1, - std::string("deltaS_mie_texture.ppm"), - _mu_s_samples * _nu_samples, - _mu_samples - ); - } - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); - glDrawBuffers(1, drawBuffers); - - _inScatteringProgramObject->deactivate(); - - // line 4 in algorithm 4.1 - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - _irradianceTableTexture, - 0 - ); - checkFrameBufferState("_irradianceTableTexture"); - glDrawBuffer(GL_COLOR_ATTACHMENT0); - - glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); - _deltaEProgramObject->activate(); - //_deltaEProgramObject->setUniform("line", 4); - deltaETableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); - _deltaEProgramObject->setUniform("deltaETexture", deltaETableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaEProgramObject); - glClear(GL_COLOR_BUFFER_BIT); - renderQuadForCalc(quadCalcVAO, vertexSize); - if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("irradiance_texture.ppm"), - _delta_e_table_width, _delta_e_table_height); - } - _deltaEProgramObject->deactivate(); - - // line 5 in algorithm 4.1 - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - _inScatteringTableTexture, - 0 - ); - checkFrameBufferState("_inScatteringTableTexture"); - glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); - _deltaSProgramObject->activate(); - deltaSRayleighTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - deltaSMieTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); - _deltaSProgramObject->setUniform("deltaSRTexture", deltaSRayleighTableTextureUnit); - _deltaSProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaSProgramObject); - glClear(GL_COLOR_BUFFER_BIT); - for (int layer = 0; layer < static_cast(_r_samples); ++layer) { - step3DTexture(_deltaSProgramObject, layer, false); - renderQuadForCalc(quadCalcVAO, vertexSize); - } - if (_saveCalculationTextures) { - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("S_texture.ppm"), - _mu_s_samples * _nu_samples, _mu_samples); - } - _deltaSProgramObject->deactivate(); - - // loop in line 6 in algorithm 4.1 - for (int scatteringOrder = 2; scatteringOrder <= 4; ++scatteringOrder) { - // line 7 in algorithm 4.1 - glFramebufferTexture( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - _deltaJTableTexture, - 0 - ); - checkFrameBufferState("_deltaJTableTexture"); - glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); - _deltaJProgramObject->activate(); - if (scatteringOrder == 2) { - _deltaJProgramObject->setUniform("firstIteraction", 1); - } - else { - _deltaJProgramObject->setUniform("firstIteraction", 0); - } - transmittanceTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - _deltaJProgramObject->setUniform( - "transmittanceTexture", - transmittanceTableTextureUnit - ); - deltaETableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); - _deltaJProgramObject->setUniform("deltaETexture", deltaETableTextureUnit); - deltaSRayleighTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - _deltaJProgramObject->setUniform( - "deltaSRTexture", - deltaSRayleighTableTextureUnit - ); + ghoul::opengl::TextureUnit deltaSMieTableTextureUnit; deltaSMieTableTextureUnit.activate(); + glGenTextures(1, &_deltaSMieTableTexture); glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); - _deltaJProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); - loadAtmosphereDataIntoShaderProgram(_deltaJProgramObject); - for (int layer = 0; layer < static_cast(_r_samples); ++layer) { - step3DTexture(_deltaJProgramObject, layer); - renderQuadForCalc(quadCalcVAO, vertexSize); - } - std::stringstream sst; - if (_saveCalculationTextures) { - sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _mu_s_samples * _nu_samples, _mu_samples); - } - _deltaJProgramObject->deactivate(); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, + _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); - // line 8 in algorithm 4.1 + //============== Delta J (Radiance Scattered) ================= + ghoul::opengl::TextureUnit deltaJTableTextureUnit; + deltaJTableTextureUnit.activate(); + glGenTextures(1, &_deltaJTableTexture); + glBindTexture(GL_TEXTURE_3D, _deltaJTableTexture); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F, _mu_s_samples * _nu_samples, + _mu_samples, _r_samples, 0, GL_RGB, GL_FLOAT, nullptr); + + } + + void AtmosphereDeferredcaster::deleteComputationTextures() { + // Cleaning up + glDeleteTextures(1, &_transmittanceTableTexture); + glDeleteTextures(1, &_irradianceTableTexture); + glDeleteTextures(1, &_inScatteringTableTexture); + glDeleteTextures(1, &_deltaETableTexture); + glDeleteTextures(1, &_deltaSRayleighTableTexture); + glDeleteTextures(1, &_deltaSMieTableTexture); + glDeleteTextures(1, &_deltaJTableTexture); + } + + void AtmosphereDeferredcaster::deleteUnusedComputationTextures() { + glDeleteTextures(1, &_deltaETableTexture); + glDeleteTextures(1, &_deltaSRayleighTableTexture); + glDeleteTextures(1, &_deltaSMieTableTexture); + glDeleteTextures(1, &_deltaJTableTexture); + } + + void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, + GLenum drawBuffers[1], + GLsizei vertexSize) + { + ghoul::opengl::TextureUnit transmittanceTableTextureUnit; + ghoul::opengl::TextureUnit irradianceTableTextureUnit; + ghoul::opengl::TextureUnit inScatteringTableTextureUnit; + ghoul::opengl::TextureUnit deltaETableTextureUnit; + ghoul::opengl::TextureUnit deltaSRayleighTableTextureUnit; + ghoul::opengl::TextureUnit deltaSMieTableTextureUnit; + ghoul::opengl::TextureUnit deltaJTableTextureUnit; + + // Saving current OpenGL state + GLboolean blendEnabled = glIsEnabled(GL_BLEND); + GLenum blendEquationRGB; + GLenum blendEquationAlpha; + GLenum blendDestAlpha; + GLenum blendDestRGB; + GLenum blendSrcAlpha; + GLenum blendSrcRGB; + + if (blendEnabled) { + glDisable(GL_BLEND); + } + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); + + // =========================================================== + // See Precomputed Atmosphere Scattering from Bruneton et al. paper, algorithm 4.1: + // =========================================================== glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - _deltaETableTexture, + _transmittanceTableTexture, 0 ); + checkFrameBufferState("_transmittanceTableTexture"); + glViewport(0, 0, _transmittance_table_width, _transmittance_table_height); + _transmittanceProgramObject->activate(); + loadAtmosphereDataIntoShaderProgram(_transmittanceProgramObject); + //glClear(GL_COLOR_BUFFER_BIT); + static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + glClearBufferfv(GL_COLOR, 0, black); + renderQuadForCalc(quadCalcVAO, vertexSize); + if (_saveCalculationTextures) { + saveTextureToPPMFile( + GL_COLOR_ATTACHMENT0, + std::string("transmittance_texture.ppm"), + _transmittance_table_width, + _transmittance_table_height + ); + } + _transmittanceProgramObject->deactivate(); + + // line 2 in algorithm 4.1 + glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _deltaETableTexture, 0); checkFrameBufferState("_deltaETableTexture"); glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); - _irradianceSupTermsProgramObject->activate(); - if (scatteringOrder == 2) { - _irradianceSupTermsProgramObject->setUniform( - "firstIteraction", - static_cast(1) - ); - } - else { - _irradianceSupTermsProgramObject->setUniform( - "firstIteraction", - static_cast(0) - ); - } + _irradianceProgramObject->activate(); transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - _irradianceSupTermsProgramObject->setUniform( + _irradianceProgramObject->setUniform( "transmittanceTexture", transmittanceTableTextureUnit ); - deltaSRayleighTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - _irradianceSupTermsProgramObject->setUniform( - "deltaSRTexture", - deltaSRayleighTableTextureUnit - ); - deltaSMieTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); - _irradianceSupTermsProgramObject->setUniform( - "deltaSMTexture", - deltaSMieTableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); + loadAtmosphereDataIntoShaderProgram(_irradianceProgramObject); + glClear(GL_COLOR_BUFFER_BIT); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), - _delta_e_table_width, _delta_e_table_height); + saveTextureToPPMFile( + GL_COLOR_ATTACHMENT0, + std::string("deltaE_table_texture.ppm"), + _delta_e_table_width, + _delta_e_table_height + ); } - _irradianceSupTermsProgramObject->deactivate(); + _irradianceProgramObject->deactivate(); - // line 9 in algorithm 4.1 + // line 3 in algorithm 4.1 glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _deltaSRayleighTableTexture, 0 ); - checkFrameBufferState("_deltaSRayleighTableTexture"); + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT1, + _deltaSMieTableTexture, + 0 + ); + GLenum colorBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; + glDrawBuffers(2, colorBuffers); + checkFrameBufferState("_deltaSRay and _deltaSMie TableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); - _inScatteringSupTermsProgramObject->activate(); + _inScatteringProgramObject->activate(); transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - _inScatteringSupTermsProgramObject->setUniform( + _inScatteringProgramObject->setUniform( "transmittanceTexture", transmittanceTableTextureUnit ); - deltaJTableTextureUnit.activate(); - glBindTexture(GL_TEXTURE_3D, _deltaJTableTexture); - _inScatteringSupTermsProgramObject->setUniform( - "deltaJTexture", - deltaJTableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_inScatteringSupTermsProgramObject); + loadAtmosphereDataIntoShaderProgram(_inScatteringProgramObject); + glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < static_cast(_r_samples); ++layer) { - step3DTexture(_inScatteringSupTermsProgramObject, layer); + step3DTexture(_inScatteringProgramObject, layer); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; saveTextureToPPMFile( GL_COLOR_ATTACHMENT0, - sst.str(), + std::string("deltaS_rayleigh_texture.ppm"), + _mu_s_samples * _nu_samples, + _mu_samples + ); + saveTextureToPPMFile( + GL_COLOR_ATTACHMENT1, + std::string("deltaS_mie_texture.ppm"), _mu_s_samples * _nu_samples, _mu_samples ); } - _inScatteringSupTermsProgramObject->deactivate(); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); + glDrawBuffers(1, drawBuffers); - glEnable(GL_BLEND); - glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); - glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); + _inScatteringProgramObject->deactivate(); - // line 10 in algorithm 4.1 + // line 4 in algorithm 4.1 glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, @@ -1125,25 +975,24 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, 0 ); checkFrameBufferState("_irradianceTableTexture"); + glDrawBuffer(GL_COLOR_ATTACHMENT0); + glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); - _irradianceFinalProgramObject->activate(); + _deltaEProgramObject->activate(); + //_deltaEProgramObject->setUniform("line", 4); deltaETableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); - _irradianceFinalProgramObject->setUniform( - "deltaETexture", - deltaETableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_irradianceFinalProgramObject); + _deltaEProgramObject->setUniform("deltaETexture", deltaETableTextureUnit); + loadAtmosphereDataIntoShaderProgram(_deltaEProgramObject); + glClear(GL_COLOR_BUFFER_BIT); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("irradiance_texture.ppm"), _delta_e_table_width, _delta_e_table_height); } - _irradianceFinalProgramObject->deactivate(); + _deltaEProgramObject->deactivate(); - // line 11 in algorithm 4.1 + // line 5 in algorithm 4.1 glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, @@ -1152,370 +1001,565 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, ); checkFrameBufferState("_inScatteringTableTexture"); glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); - _deltaSSupTermsProgramObject->activate(); + _deltaSProgramObject->activate(); deltaSRayleighTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); - _deltaSSupTermsProgramObject->setUniform( - "deltaSTexture", - deltaSRayleighTableTextureUnit - ); - loadAtmosphereDataIntoShaderProgram(_deltaSSupTermsProgramObject); + deltaSMieTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); + _deltaSProgramObject->setUniform("deltaSRTexture", deltaSRayleighTableTextureUnit); + _deltaSProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); + loadAtmosphereDataIntoShaderProgram(_deltaSProgramObject); + glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < static_cast(_r_samples); ++layer) { - step3DTexture(_deltaSSupTermsProgramObject, layer, false); + step3DTexture(_deltaSProgramObject, layer, false); renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, std::string("S_texture.ppm"), _mu_s_samples * _nu_samples, _mu_samples); } - _deltaSSupTermsProgramObject->deactivate(); + _deltaSProgramObject->deactivate(); - glDisable(GL_BLEND); - } - - // Restores OpenGL blending state - if (blendEnabled) - glEnable(GL_BLEND); - - glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); - glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); -} - -void AtmosphereDeferredcaster::preCalculateAtmosphereParam() { - //========================================================== - //========= Load Shader Programs for Calculations ========== - //========================================================== - loadComputationPrograms(); - - //========================================================== - //============ Create Textures for Calculations ============ - //========================================================== - createComputationTextures(); - - // Saves current FBO first - GLint defaultFBO; - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - - GLint m_viewport[4]; - glGetIntegerv(GL_VIEWPORT, m_viewport); - - // Creates the FBO for the calculations - GLuint calcFBO; - glGenFramebuffers(1, &calcFBO); - glBindFramebuffer(GL_FRAMEBUFFER, calcFBO); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); - - // Prepare for rendering/calculations - GLuint quadCalcVAO; - GLuint quadCalcVBO; - createRenderQuad(&quadCalcVAO, &quadCalcVBO, 1.0f); - - // Starting Calculations... - LDEBUG("Starting precalculations for scattering effects..."); - - //========================================================== - //=================== Execute Calculations ================= - //========================================================== - executeCalculations(quadCalcVAO, drawBuffers, 6); - - deleteUnusedComputationTextures(); - - // Restores system state - glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport( - m_viewport[0], - m_viewport[1], - m_viewport[2], - m_viewport[3] - ); - glDeleteBuffers(1, &quadCalcVBO); - glDeleteVertexArrays(1, &quadCalcVAO); - glDeleteFramebuffers(1, &calcFBO); - - LDEBUG("Ended precalculations for Atmosphere effects..."); -} - -void AtmosphereDeferredcaster::resetAtmosphereTextures() {} - -void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloat size) { - glGenVertexArrays(1, vao); - glGenBuffers(1, vbo); - glBindVertexArray(*vao); - glBindBuffer(GL_ARRAY_BUFFER, *vbo); - - const GLfloat vertex_data[] = { - // x y z w - -size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f, - -size, size, 0.0f, 1.0f, - -size, -size, 0.0f, 1.0f, - size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f - }; - - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 4, - reinterpret_cast(0) - ); - glEnableVertexAttribArray(0); - - glBindVertexArray(0); -} - -void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( - std::unique_ptr& shaderProg) -{ - shaderProg->setUniform("Rg", _atmospherePlanetRadius); - shaderProg->setUniform("Rt", _atmosphereRadius); - shaderProg->setUniform("AverageGroundReflectance", _planetAverageGroundReflectance); - shaderProg->setUniform("groundRadianceEmittion", _planetGroundRadianceEmittion); - shaderProg->setUniform("HR", _rayleighHeightScale); - shaderProg->setUniform("betaRayleigh", _rayleighScatteringCoeff); - shaderProg->setUniform("HM", _mieHeightScale); - shaderProg->setUniform("betaMieScattering", _mieScatteringCoeff); - shaderProg->setUniform("betaMieExtinction", _mieExtinctionCoeff); - shaderProg->setUniform("mieG", _miePhaseConstant); - shaderProg->setUniform("sunRadiance", _sunRadianceIntensity); - shaderProg->setUniform( - "TRANSMITTANCE_W", - static_cast(_transmittance_table_width) - ); - shaderProg->setUniform( - "TRANSMITTANCE_H", - static_cast(_transmittance_table_height) - ); - shaderProg->setUniform("SKY_W", static_cast(_irradiance_table_width)); - shaderProg->setUniform("SKY_H", static_cast(_irradiance_table_height)); - shaderProg->setUniform("OTHER_TEXTURES_W", static_cast(_delta_e_table_width)); - shaderProg->setUniform("OTHER_TEXTURES_H", static_cast(_delta_e_table_height)); - shaderProg->setUniform("SAMPLES_R", static_cast(_r_samples)); - shaderProg->setUniform("SAMPLES_MU", static_cast(_mu_samples)); - shaderProg->setUniform("SAMPLES_MU_S", static_cast(_mu_s_samples)); - shaderProg->setUniform("SAMPLES_NU", static_cast(_nu_samples)); - shaderProg->setUniform("ozoneLayerEnabled", _ozoneEnabled); - shaderProg->setUniform("HO", _ozoneHeightScale); - shaderProg->setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); -} - -void AtmosphereDeferredcaster::checkFrameBufferState( - const std::string& codePosition) const -{ - if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - LERROR("Framework not built. " + codePosition); - GLenum fbErr = glCheckFramebufferStatus(GL_FRAMEBUFFER); - switch (fbErr) { - case GL_FRAMEBUFFER_UNDEFINED: - LERROR("Indefined framebuffer."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - LERROR("Incomplete, missing attachement."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - LERROR("Framebuffer doesn't have at least one image attached to it."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - LERROR("Returned if the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is " - "GL_NONE for any color attachment point(s) named by GL_DRAW_BUFFERi."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - LERROR("Returned if GL_READ_BUFFER is not GL_NONE and the value of " - "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color attachment " - "point named by GL_READ_BUFFER."); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - LERROR("Returned if the combination of internal formats of the attached " - "images violates an implementation - dependent set of restrictions."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - LERROR("Returned if the value of GL_RENDERBUFFE_r_samples is not the same " - "for all attached renderbuffers; if the value of GL_TEXTURE_SAMPLES is " - "the not same for all attached textures; or , if the attached images are " - "a mix of renderbuffers and textures, the value of " - "GL_RENDERBUFFE_r_samples does not match the value of " - "GL_TEXTURE_SAMPLES."); - LERROR("Returned if the value of GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not " - "the same for all attached textures; or , if the attached images are a " - "mix of renderbuffers and textures, the value of " - "GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not GL_TRUE for all attached " - "textures."); - break; - case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: - LERROR("Returned if any framebuffer attachment is layered, and any populated " - "attachment is not layered, or if all populated color attachments are " - "not from textures of the same target."); - break; - default: - LDEBUG("No error found checking framebuffer: " + codePosition); - break; - } - } -} - -void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVertices) { - glBindVertexArray(vao); - glDrawArrays(GL_TRIANGLES, 0, numberOfVertices); - glBindVertexArray(0); -} - -void AtmosphereDeferredcaster::step3DTexture( - std::unique_ptr& shaderProg, - int layer, bool doCalc) -{ - // See OpenGL redbook 8th Edition page 556 for Layered Rendering - if (doCalc) { - float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; - float atm2 = _atmosphereRadius * _atmosphereRadius; - float diff = atm2 - earth2; - float ri = static_cast(layer) / static_cast(_r_samples - 1); - float ri_2 = ri * ri; - float epsilon = - (layer == 0) ? - 0.01f : - (layer == (static_cast(_r_samples) - 1)) ? -0.001f : 0.0f; - float r = sqrtf(earth2 + ri_2 * diff) + epsilon; - float dminG = r - _atmospherePlanetRadius; - float dminT = _atmosphereRadius - r; - float dh = sqrtf(r * r - earth2); - float dH = dh + sqrtf(diff); - - shaderProg->setUniform("r", r); - shaderProg->setUniform("dhdH", dminT, dH, dminG, dh); - } - - shaderProg->setUniform("layer", static_cast(layer)); -} - -void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, - const std::string& fileName, - int width, - int height) const -{ - std::fstream ppmFile; - - ppmFile.open(fileName.c_str(), std::fstream::out); - if (ppmFile.is_open()) { - unsigned char * pixels = new unsigned char[width*height * 3]; - for (int t = 0; t < width*height * 3; ++t) - pixels[t] = 255; - - if (color_buffer_attachment != GL_DEPTH_ATTACHMENT) { - glReadBuffer(color_buffer_attachment); - glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); - - } - else { - glReadPixels( - 0, - 0, - width, - height, - GL_DEPTH_COMPONENT, - GL_UNSIGNED_BYTE, - pixels + // loop in line 6 in algorithm 4.1 + for (int scatteringOrder = 2; scatteringOrder <= 4; ++scatteringOrder) { + // line 7 in algorithm 4.1 + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _deltaJTableTexture, + 0 ); - } - - ppmFile << "P3" << std::endl; - ppmFile << width << " " << height << std::endl; - ppmFile << "255" << std::endl; - - std::cout << "\n\nFILE\n\n"; - int k = 0; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - ppmFile << static_cast(pixels[k]) << " " - << static_cast(pixels[k + 1]) << " " - << static_cast(pixels[k + 2]) << " "; - k += 3; + checkFrameBufferState("_deltaJTableTexture"); + glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); + _deltaJProgramObject->activate(); + if (scatteringOrder == 2) { + _deltaJProgramObject->setUniform("firstIteraction", 1); } - ppmFile << std::endl; + else { + _deltaJProgramObject->setUniform("firstIteraction", 0); + } + transmittanceTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); + _deltaJProgramObject->setUniform( + "transmittanceTexture", + transmittanceTableTextureUnit + ); + deltaETableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); + _deltaJProgramObject->setUniform("deltaETexture", deltaETableTextureUnit); + deltaSRayleighTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); + _deltaJProgramObject->setUniform( + "deltaSRTexture", + deltaSRayleighTableTextureUnit + ); + deltaSMieTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); + _deltaJProgramObject->setUniform("deltaSMTexture", deltaSMieTableTextureUnit); + loadAtmosphereDataIntoShaderProgram(_deltaJProgramObject); + for (int layer = 0; layer < static_cast(_r_samples); ++layer) { + step3DTexture(_deltaJProgramObject, layer); + renderQuadForCalc(quadCalcVAO, vertexSize); + } + std::stringstream sst; + if (_saveCalculationTextures) { + sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _mu_s_samples * _nu_samples, _mu_samples); + } + _deltaJProgramObject->deactivate(); + + // line 8 in algorithm 4.1 + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _deltaETableTexture, + 0 + ); + checkFrameBufferState("_deltaETableTexture"); + glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + _irradianceSupTermsProgramObject->activate(); + if (scatteringOrder == 2) { + _irradianceSupTermsProgramObject->setUniform( + "firstIteraction", + static_cast(1) + ); + } + else { + _irradianceSupTermsProgramObject->setUniform( + "firstIteraction", + static_cast(0) + ); + } + transmittanceTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); + _irradianceSupTermsProgramObject->setUniform( + "transmittanceTexture", + transmittanceTableTextureUnit + ); + deltaSRayleighTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); + _irradianceSupTermsProgramObject->setUniform( + "deltaSRTexture", + deltaSRayleighTableTextureUnit + ); + deltaSMieTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSMieTableTexture); + _irradianceSupTermsProgramObject->setUniform( + "deltaSMTexture", + deltaSMieTableTextureUnit + ); + loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); + renderQuadForCalc(quadCalcVAO, vertexSize); + if (_saveCalculationTextures) { + sst.str(std::string()); + sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _delta_e_table_width, _delta_e_table_height); + } + _irradianceSupTermsProgramObject->deactivate(); + + // line 9 in algorithm 4.1 + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _deltaSRayleighTableTexture, + 0 + ); + checkFrameBufferState("_deltaSRayleighTableTexture"); + glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); + _inScatteringSupTermsProgramObject->activate(); + transmittanceTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); + _inScatteringSupTermsProgramObject->setUniform( + "transmittanceTexture", + transmittanceTableTextureUnit + ); + deltaJTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaJTableTexture); + _inScatteringSupTermsProgramObject->setUniform( + "deltaJTexture", + deltaJTableTextureUnit + ); + loadAtmosphereDataIntoShaderProgram(_inScatteringSupTermsProgramObject); + for (int layer = 0; layer < static_cast(_r_samples); ++layer) { + step3DTexture(_inScatteringSupTermsProgramObject, layer); + renderQuadForCalc(quadCalcVAO, vertexSize); + } + if (_saveCalculationTextures) { + sst.str(std::string()); + sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile( + GL_COLOR_ATTACHMENT0, + sst.str(), + _mu_s_samples * _nu_samples, + _mu_samples + ); + } + _inScatteringSupTermsProgramObject->deactivate(); + + glEnable(GL_BLEND); + glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); + glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); + + // line 10 in algorithm 4.1 + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _irradianceTableTexture, + 0 + ); + checkFrameBufferState("_irradianceTableTexture"); + glViewport(0, 0, _delta_e_table_width, _delta_e_table_height); + _irradianceFinalProgramObject->activate(); + deltaETableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _deltaETableTexture); + _irradianceFinalProgramObject->setUniform( + "deltaETexture", + deltaETableTextureUnit + ); + loadAtmosphereDataIntoShaderProgram(_irradianceFinalProgramObject); + renderQuadForCalc(quadCalcVAO, vertexSize); + if (_saveCalculationTextures) { + sst.str(std::string()); + sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _delta_e_table_width, _delta_e_table_height); + } + _irradianceFinalProgramObject->deactivate(); + + // line 11 in algorithm 4.1 + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _inScatteringTableTexture, + 0 + ); + checkFrameBufferState("_inScatteringTableTexture"); + glViewport(0, 0, _mu_s_samples * _nu_samples, _mu_samples); + _deltaSSupTermsProgramObject->activate(); + deltaSRayleighTableTextureUnit.activate(); + glBindTexture(GL_TEXTURE_3D, _deltaSRayleighTableTexture); + _deltaSSupTermsProgramObject->setUniform( + "deltaSTexture", + deltaSRayleighTableTextureUnit + ); + loadAtmosphereDataIntoShaderProgram(_deltaSSupTermsProgramObject); + for (int layer = 0; layer < static_cast(_r_samples); ++layer) { + step3DTexture(_deltaSSupTermsProgramObject, layer, false); + renderQuadForCalc(quadCalcVAO, vertexSize); + } + if (_saveCalculationTextures) { + sst.str(std::string()); + sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + _mu_s_samples * _nu_samples, _mu_samples); + } + _deltaSSupTermsProgramObject->deactivate(); + + glDisable(GL_BLEND); } - delete[] pixels; - ppmFile.close(); + // Restores OpenGL blending state + if (blendEnabled) + glEnable(GL_BLEND); + + glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); } -} -bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, - const glm::dvec3& position, - double radius) const -{ + void AtmosphereDeferredcaster::preCalculateAtmosphereParam() { + //========================================================== + //========= Load Shader Programs for Calculations ========== + //========================================================== + loadComputationPrograms(); - // Frustum Planes - glm::dvec3 col1(MVMatrix[0], MVMatrix[4], MVMatrix[8]); - glm::dvec3 col2(MVMatrix[1], MVMatrix[5], MVMatrix[9]); - glm::dvec3 col3(MVMatrix[2], MVMatrix[6], MVMatrix[10]); - glm::dvec3 col4(MVMatrix[3], MVMatrix[7], MVMatrix[11]); + //========================================================== + //============ Create Textures for Calculations ============ + //========================================================== + createComputationTextures(); - glm::dvec3 leftNormal = col4 + col1; - glm::dvec3 rightNormal = col4 - col1; - glm::dvec3 bottomNormal = col4 + col2; - glm::dvec3 topNormal = col4 - col2; - glm::dvec3 nearNormal = col3 + col4; - glm::dvec3 farNormal = col4 - col3; + // Saves current FBO first + GLint defaultFBO; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - // Plane Distances - double leftDistance = MVMatrix[15] + MVMatrix[12]; - double rightDistance = MVMatrix[15] - MVMatrix[12]; - double bottomDistance = MVMatrix[15] + MVMatrix[13]; - double topDistance = MVMatrix[15] - MVMatrix[13]; - double nearDistance = MVMatrix[15] + MVMatrix[14]; - double farDistance = MVMatrix[15] - MVMatrix[14]; + GLint m_viewport[4]; + glGetIntegerv(GL_VIEWPORT, m_viewport); - // Normalize Planes - double invMag = 1.0 / glm::length(leftNormal); - leftNormal *= invMag; - leftDistance *= invMag; + // Creates the FBO for the calculations + GLuint calcFBO; + glGenFramebuffers(1, &calcFBO); + glBindFramebuffer(GL_FRAMEBUFFER, calcFBO); + GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, drawBuffers); - invMag = 1.0 / glm::length(rightNormal); - rightNormal *= invMag; - rightDistance *= invMag; + // Prepare for rendering/calculations + GLuint quadCalcVAO; + GLuint quadCalcVBO; + createRenderQuad(&quadCalcVAO, &quadCalcVBO, 1.0f); - invMag = 1.0 / glm::length(bottomNormal); - bottomNormal *= invMag; - bottomDistance *= invMag; + // Starting Calculations... + LDEBUG("Starting precalculations for scattering effects..."); - invMag = 1.0 / glm::length(topNormal); - topNormal *= invMag; - topDistance *= invMag; + //========================================================== + //=================== Execute Calculations ================= + //========================================================== + executeCalculations(quadCalcVAO, drawBuffers, 6); - invMag = 1.0 / glm::length(nearNormal); - nearNormal *= invMag; - nearDistance *= invMag; + deleteUnusedComputationTextures(); - invMag = 1.0 / glm::length(farNormal); - farNormal *= invMag; - farDistance *= invMag; + // Restores system state + glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); + glViewport( + m_viewport[0], + m_viewport[1], + m_viewport[2], + m_viewport[3] + ); + glDeleteBuffers(1, &quadCalcVBO); + glDeleteVertexArrays(1, &quadCalcVAO); + glDeleteFramebuffers(1, &calcFBO); - if ((glm::dot(leftNormal, position) + leftDistance) < -radius) { + LDEBUG("Ended precalculations for Atmosphere effects..."); + } + + void AtmosphereDeferredcaster::resetAtmosphereTextures() {} + + void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloat size) { + glGenVertexArrays(1, vao); + glGenBuffers(1, vbo); + glBindVertexArray(*vao); + glBindBuffer(GL_ARRAY_BUFFER, *vbo); + + const GLfloat vertex_data[] = { + // x y z w + -size, -size, 0.0f, 1.0f, + size, size, 0.0f, 1.0f, + -size, size, 0.0f, 1.0f, + -size, -size, 0.0f, 1.0f, + size, -size, 0.0f, 1.0f, + size, size, 0.0f, 1.0f + }; + + glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 4, + reinterpret_cast(0) + ); + glEnableVertexAttribArray(0); + + glBindVertexArray(0); + } + + void AtmosphereDeferredcaster::loadAtmosphereDataIntoShaderProgram( + std::unique_ptr& shaderProg) + { + shaderProg->setUniform("Rg", _atmospherePlanetRadius); + shaderProg->setUniform("Rt", _atmosphereRadius); + shaderProg->setUniform("AverageGroundReflectance", _planetAverageGroundReflectance); + shaderProg->setUniform("groundRadianceEmittion", _planetGroundRadianceEmittion); + shaderProg->setUniform("HR", _rayleighHeightScale); + shaderProg->setUniform("betaRayleigh", _rayleighScatteringCoeff); + shaderProg->setUniform("HM", _mieHeightScale); + shaderProg->setUniform("betaMieScattering", _mieScatteringCoeff); + shaderProg->setUniform("betaMieExtinction", _mieExtinctionCoeff); + shaderProg->setUniform("mieG", _miePhaseConstant); + shaderProg->setUniform("sunRadiance", _sunRadianceIntensity); + shaderProg->setUniform( + "TRANSMITTANCE_W", + static_cast(_transmittance_table_width) + ); + shaderProg->setUniform( + "TRANSMITTANCE_H", + static_cast(_transmittance_table_height) + ); + shaderProg->setUniform("SKY_W", static_cast(_irradiance_table_width)); + shaderProg->setUniform("SKY_H", static_cast(_irradiance_table_height)); + shaderProg->setUniform("OTHER_TEXTURES_W", static_cast(_delta_e_table_width)); + shaderProg->setUniform("OTHER_TEXTURES_H", static_cast(_delta_e_table_height)); + shaderProg->setUniform("SAMPLES_R", static_cast(_r_samples)); + shaderProg->setUniform("SAMPLES_MU", static_cast(_mu_samples)); + shaderProg->setUniform("SAMPLES_MU_S", static_cast(_mu_s_samples)); + shaderProg->setUniform("SAMPLES_NU", static_cast(_nu_samples)); + shaderProg->setUniform("ozoneLayerEnabled", _ozoneEnabled); + shaderProg->setUniform("HO", _ozoneHeightScale); + shaderProg->setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); + } + + void AtmosphereDeferredcaster::checkFrameBufferState( + const std::string& codePosition) const + { + if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + LERROR("Framework not built. " + codePosition); + GLenum fbErr = glCheckFramebufferStatus(GL_FRAMEBUFFER); + switch (fbErr) { + case GL_FRAMEBUFFER_UNDEFINED: + LERROR("Indefined framebuffer."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + LERROR("Incomplete, missing attachement."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + LERROR("Framebuffer doesn't have at least one image attached to it."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + LERROR("Returned if the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is " + "GL_NONE for any color attachment point(s) named by GL_DRAW_BUFFERi."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + LERROR("Returned if GL_READ_BUFFER is not GL_NONE and the value of " + "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color attachment " + "point named by GL_READ_BUFFER."); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + LERROR("Returned if the combination of internal formats of the attached " + "images violates an implementation - dependent set of restrictions."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + LERROR("Returned if the value of GL_RENDERBUFFE_r_samples is not the same " + "for all attached renderbuffers; if the value of GL_TEXTURE_SAMPLES is " + "the not same for all attached textures; or , if the attached images are " + "a mix of renderbuffers and textures, the value of " + "GL_RENDERBUFFE_r_samples does not match the value of " + "GL_TEXTURE_SAMPLES."); + LERROR("Returned if the value of GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not " + "the same for all attached textures; or , if the attached images are a " + "mix of renderbuffers and textures, the value of " + "GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not GL_TRUE for all attached " + "textures."); + break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + LERROR("Returned if any framebuffer attachment is layered, and any populated " + "attachment is not layered, or if all populated color attachments are " + "not from textures of the same target."); + break; + default: + LDEBUG("No error found checking framebuffer: " + codePosition); + break; + } + } + } + + void AtmosphereDeferredcaster::renderQuadForCalc(GLuint vao, GLsizei numberOfVertices) { + glBindVertexArray(vao); + glDrawArrays(GL_TRIANGLES, 0, numberOfVertices); + glBindVertexArray(0); + } + + void AtmosphereDeferredcaster::step3DTexture( + std::unique_ptr& shaderProg, + int layer, bool doCalc) + { + // See OpenGL redbook 8th Edition page 556 for Layered Rendering + if (doCalc) { + float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; + float atm2 = _atmosphereRadius * _atmosphereRadius; + float diff = atm2 - earth2; + float ri = static_cast(layer) / static_cast(_r_samples - 1); + float ri_2 = ri * ri; + float epsilon = + (layer == 0) ? + 0.01f : + (layer == (static_cast(_r_samples) - 1)) ? -0.001f : 0.0f; + float r = sqrtf(earth2 + ri_2 * diff) + epsilon; + float dminG = r - _atmospherePlanetRadius; + float dminT = _atmosphereRadius - r; + float dh = sqrtf(r * r - earth2); + float dH = dh + sqrtf(diff); + + shaderProg->setUniform("r", r); + shaderProg->setUniform("dhdH", dminT, dH, dminG, dh); + } + + shaderProg->setUniform("layer", static_cast(layer)); + } + + void AtmosphereDeferredcaster::saveTextureToPPMFile(GLenum color_buffer_attachment, + const std::string& fileName, + int width, int height) const + { + std::fstream ppmFile; + + ppmFile.open(fileName.c_str(), std::fstream::out); + if (ppmFile.is_open()) { + unsigned char * pixels = new unsigned char[width*height * 3]; + for (int t = 0; t < width*height * 3; ++t) + pixels[t] = 255; + + if (color_buffer_attachment != GL_DEPTH_ATTACHMENT) { + glReadBuffer(color_buffer_attachment); + glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); + + } + else { + glReadPixels( + 0, + 0, + width, + height, + GL_DEPTH_COMPONENT, + GL_UNSIGNED_BYTE, + pixels + ); + } + + ppmFile << "P3" << std::endl; + ppmFile << width << " " << height << std::endl; + ppmFile << "255" << std::endl; + + std::cout << "\n\nFILE\n\n"; + int k = 0; + for (int i = 0; i < width; i++) { + for (int j = 0; j < height; j++) { + ppmFile << static_cast(pixels[k]) << " " + << static_cast(pixels[k + 1]) << " " + << static_cast(pixels[k + 2]) << " "; + k += 3; + } + ppmFile << std::endl; + } + delete[] pixels; + + ppmFile.close(); + } + } + + bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, + const glm::dvec3& position, + double radius) const + { + + // Frustum Planes + glm::dvec3 col1(MVMatrix[0], MVMatrix[4], MVMatrix[8]); + glm::dvec3 col2(MVMatrix[1], MVMatrix[5], MVMatrix[9]); + glm::dvec3 col3(MVMatrix[2], MVMatrix[6], MVMatrix[10]); + glm::dvec3 col4(MVMatrix[3], MVMatrix[7], MVMatrix[11]); + + glm::dvec3 leftNormal = col4 + col1; + glm::dvec3 rightNormal = col4 - col1; + glm::dvec3 bottomNormal = col4 + col2; + glm::dvec3 topNormal = col4 - col2; + glm::dvec3 nearNormal = col3 + col4; + glm::dvec3 farNormal = col4 - col3; + + // Plane Distances + double leftDistance = MVMatrix[15] + MVMatrix[12]; + double rightDistance = MVMatrix[15] - MVMatrix[12]; + double bottomDistance = MVMatrix[15] + MVMatrix[13]; + double topDistance = MVMatrix[15] - MVMatrix[13]; + double nearDistance = MVMatrix[15] + MVMatrix[14]; + double farDistance = MVMatrix[15] - MVMatrix[14]; + + // Normalize Planes + double invMag = 1.0 / glm::length(leftNormal); + leftNormal *= invMag; + leftDistance *= invMag; + + invMag = 1.0 / glm::length(rightNormal); + rightNormal *= invMag; + rightDistance *= invMag; + + invMag = 1.0 / glm::length(bottomNormal); + bottomNormal *= invMag; + bottomDistance *= invMag; + + invMag = 1.0 / glm::length(topNormal); + topNormal *= invMag; + topDistance *= invMag; + + invMag = 1.0 / glm::length(nearNormal); + nearNormal *= invMag; + nearDistance *= invMag; + + invMag = 1.0 / glm::length(farNormal); + farNormal *= invMag; + farDistance *= invMag; + + if ((glm::dot(leftNormal, position) + leftDistance) < -radius) { + return false; + } + else if ((glm::dot(rightNormal, position) + rightDistance) < -radius) { + return false; + } + else if ((glm::dot(bottomNormal, position) + bottomDistance) < -radius) { + return false; + } + else if ((glm::dot(topNormal, position) + topDistance) < -radius) { + return false; + } + else if ((glm::dot(nearNormal, position) + nearDistance) < -radius) { + return false; + } + // The far plane testing is disabled because the atm has no depth. + /*else if ((glm::dot(farNormal, position) + farDistance) < -radius) { return false; - } - else if ((glm::dot(rightNormal, position) + rightDistance) < -radius) { - return false; - } - else if ((glm::dot(bottomNormal, position) + bottomDistance) < -radius) { - return false; - } - else if ((glm::dot(topNormal, position) + topDistance) < -radius) { - return false; - } - else if ((glm::dot(nearNormal, position) + nearDistance) < -radius) { - return false; - } - // The far plane testing is disabled because the atm has no depth. - /*else if ((glm::dot(farNormal, position) + farDistance) < -radius) { - return false; - }*/ + }*/ - return true; -} + return true; + } } // namespace openspace diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index f371174516..33184628f1 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -136,8 +136,7 @@ private: SAMPLES_MU, SAMPLES_MU_S, SAMPLES_NU) _uniformCache; UniformCache(dInverseModelTransformMatrix, dModelTransformMatrix, dSgctProjectionToModelTransformMatrix, - dFragmentToWorldMatrix, - dCamRigPos, dCamPosObj, sunDirectionObj, + dSGCTViewToWorldMatrix, dCamPosObj, sunDirectionObj, hardShadows, transmittanceTexture, irradianceTexture, inscatterTexture) _uniformCache2; diff --git a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl index 50578be199..f911c4c061 100644 --- a/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl +++ b/modules/atmosphere/shaders/atmosphere_deferred_fs.glsl @@ -77,7 +77,6 @@ uniform int cullAtmosphere; uniform float backgroundConstant; uniform bool firstPaint; uniform float atmExposure; -uniform float viewScaling; uniform sampler2D irradianceTexture; uniform sampler3D inscatterTexture; @@ -85,18 +84,13 @@ uniform sampler2DMS mainPositionTexture; uniform sampler2DMS mainNormalTexture; uniform sampler2DMS mainColorTexture; -// Model Transform Matrix Used for Globe Rendering - +uniform dmat4 dInverseModelTransformMatrix; uniform dmat4 dModelTransformMatrix; -uniform dmat4 eyeToWorld; - -uniform mat4 eyeToModel; -uniform mat4 inverseProjection; - -uniform vec3 eyePosModelCoords; +uniform dmat4 dSGCTViewToWorldMatrix; +uniform dmat4 dSgctProjectionToModelTransformMatrix; +uniform dvec4 dCamPosObj; uniform dvec3 sunDirectionObj; -uniform dvec3 ellipsoidRadii; /******************************************************************************* ***** ALL CALCULATIONS FOR ECLIPSE ARE IN METERS AND IN WORLD SPACE SYSTEM **** @@ -245,25 +239,35 @@ bool dAtmosphereIntersection(const dvec3 planetPosition, const dRay ray, const d * This method avoids matrices multiplications * wherever is possible. */ -void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray) { - // Compute positions and directions in world space. - vec2 samplePos = vec2(msaaSamplePatter[mssaSample], - msaaSamplePatter[mssaSample+1]); +void dCalculateRayRenderableGlobe(in int mssaSample, out dRay ray, + out dvec4 planetPositionObjectCoords, + out dvec4 cameraPositionInObject) { + // ====================================== + // ======= Avoiding Some Matrices ======= - dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 0.0, 1.0); - vec4 eyeSpaceCoords = inverseProjection * vec4(clipCoords); - eyeSpaceCoords.w = 1.0; + // Compute positions and directions in object space. + dvec2 samplePos = dvec2(msaaSamplePatter[mssaSample], + msaaSamplePatter[mssaSample+1]); + //dvec4 clipCoords = dvec4(interpolatedNDCPos.xy + samplePos, 0.0, 1.0); + dvec4 clipCoords = dvec4(interpolatedNDCPos.xy, 0.0, 1.0); - // Scale the vector to avoid floating point inaccuracy. - eyeSpaceCoords.xyz *= viewScaling * 1000000.0; - - dvec4 objectCoords = eyeToModel * eyeSpaceCoords; + // Clip to Object Coords + dvec4 objectCoords = dSgctProjectionToModelTransformMatrix * clipCoords; + + // Planet Position in Object Space + // JCC: Applying the inverse of the model transformation on the object postion in World + // space results in imprecision. + planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); + // Camera Position in Object Space (in meters) + cameraPositionInObject = dCamPosObj; + // ============================ // ====== Building Ray ======== // Ray in object space (in KM) - ray.origin = dvec4(vec4(eyePosModelCoords, 1.0) * dvec4(0.001, 0.001, 0.001, 1.0)); - ray.direction = dvec4(normalize(objectCoords.xyz - eyePosModelCoords.xyz), 0.0); + ray.origin = cameraPositionInObject * dvec4(0.001, 0.001, 0.001, 1.0); + //ray.direction = dvec4(normalize(objectCoords.xyz - cameraPositionInObject.xyz), 0.0); + ray.direction = dvec4(normalize((objectCoords.xyz * dvec3(0.001))- ray.origin.xyz), 0.0); } /* @@ -370,11 +374,12 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor // From cosine law where t = distance between x and x0 // r0^2 = r^2 + t^2 - 2 * r * t * cos(PI-theta) r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); + float invr0 = 1.0/r0; // From the dot product: cos(theta0) = (x0 dot v)/(||ro||*||v||) // mu0 = ((x + t) dot v) / r0 // mu0 = (x dot v + t dot v) / r0 // mu0 = (r*mu + t) / r0 - mu0 = (r * mu + t) / r0; + mu0 = (r * mu + t) * invr0; vec4 inScatterAboveX = texture4D(inscatterTexture, r, mu, muSun, nu); vec4 inScatterAboveXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); // Attention for the attenuation.r value applied to the S_Mie @@ -383,7 +388,7 @@ vec3 inscatterRadiance(inout vec3 x, inout float t, inout float irradianceFactor // Below Horizon mu = muHorizon + INTERPOLATION_EPS; r0 = sqrt(r2 + t2 + 2.0f * r * t * mu); - mu0 = (r * mu + t) / r0; + mu0 = (r * mu + t) * invr0; vec4 inScatterBelowX = texture4D(inscatterTexture, r, mu, muSun, nu); vec4 inScatterBelowXs = texture4D(inscatterTexture, r0, mu0, muSun0, nu); // Attention for the attenuation.r value applied to the S_Mie @@ -448,7 +453,8 @@ vec3 groundColor(const vec3 x, const float t, const vec3 v, const vec3 s, const vec3 x0 = x + t * v; float r0 = length(x0); // Normal of intersection point. - vec3 n = normalize(normal); + // Normal must be normalized. + vec3 n = normal; //vec4 groundReflectance = groundColor * vec4(.37); vec4 groundReflectance = groundColor * vec4(groundRadianceEmittion, groundRadianceEmittion, groundRadianceEmittion, 1.0f); @@ -526,154 +532,185 @@ vec3 sunColor(const vec3 x, const float t, const vec3 v, const vec3 s, const flo return transmittance * sunFinalColor; } -int chooseNumberOfSamples() { - vec4 firstColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), 0); - for (int i = 1; i < nAaSamples; i++) { - vec4 currentColor = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); - if (currentColor != firstColor) { - return nAaSamples > 1 ? nAaSamples/2 : nAaSamples; - } - } - return 1; -} - -vec4 getColorWithoutAtmosphere() { - if (firstPaint) { - vec4 bColor = vec4(0.0f); - for (int f = 0; f < nAaSamples; f++) { - bColor += texelFetch(mainColorTexture, ivec2(gl_FragCoord), f); - } - bColor /= float(nAaSamples); - return vec4(HDR(bColor.xyz * backgroundConstant, atmExposure), bColor.a); - } - else { - discard; - } -} - void main() { - if (cullAtmosphere == 1) { - renderTarget = getColorWithoutAtmosphere(); - return; - } + ivec2 fragCoords = ivec2(gl_FragCoord); - vec4 atmosphereFinalColor = vec4(0.0f); - int nSamples = chooseNumberOfSamples(); + if (cullAtmosphere == 0) { + vec4 atmosphereFinalColor = vec4(0.0f); + int nSamples = 1; + // First we determine if the pixel is complex (different fragments on it) + bool complex = false; + vec4 oldColor, currentColor; + //vec4 colorArray[16]; + //int colorIndexArray[16]; - for (int i = 0; i < nSamples; i++) { - vec4 normal = texelFetch(mainNormalTexture, ivec2(gl_FragCoord), i); - vec4 color = texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); - // Data in the mainPositionTexture are written in camera rig space - // (identical positions for all projectors and eyes) - vec4 position = texelFetch(mainPositionTexture, ivec2(gl_FragCoord), i); - - // Ray in object space - dRay ray; - dvec4 planetPositionObjectCoords = dvec4(0.0, 0.0, 0.0, 1.0); - dvec4 cameraPositionInObject = dvec4(eyePosModelCoords, 1.0); - - // Get the ray from camera to atm in object space - dCalculateRayRenderableGlobe(i, ray); - - bool insideATM = false; - double offset = 0.0; - double maxLength = 0.0; - - bool intersectATM = false; - - // Instead of ray-ellipsoid intersection let's transform the ray to a sphere: - intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, ray, - Rt - ATM_EPSILON/100.0, insideATM, offset, maxLength ); - - if ( intersectATM ) { - // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel - // in the depth buffer is less than the distance to the atmosphere then the atmosphere - // is occluded - // Fragments positions into G-Buffer are written in eye space. - // When using their positions later, one must convert them to the planet's coords - - dvec4 fragObjectCoords = dvec4(eyeToModel * position); - dvec4 fragWorldCoords = dvec4(eyeToWorld * position); - - // Distance of the pixel in the gBuffer to the observer - // JCC (12/12/2017): AMD distance function is buggy. - //double pixelDepth = distance(cameraPositionInObject.xyz, fragObjectCoords.xyz); - double pixelDepth = length(cameraPositionInObject.xyz - fragObjectCoords.xyz); - - // JCC (12/13/2017): TRick to remove floating error in texture. - // We see a squared noise on planet's surface when seeing the planet - // from far away. - float dC = float(length(cameraPositionInObject.xyz)); - float x1 = 1e8; - if (dC > x1) { - pixelDepth += 1000.0; - float alpha = 1000.0; - float beta = 1000000.0; - float x2 = 1e9; - float diffGreek = beta - alpha; - float diffDist = x2 - x1; - float varA = diffGreek/diffDist; - float varB = (alpha - varA * x1); - pixelDepth += double(varA * dC + varB); - } - - // All calculations are done in Km: - pixelDepth *= 0.001; - fragObjectCoords.xyz *= 0.001; - - if (position.xyz != vec3(0.0) && (pixelDepth < offset)) { - atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); - //discard; - } else { - // Following paper nomenclature - double t = offset; - vec3 attenuation; - - // Moving observer from camera location to top atmosphere - // If the observer is already inside the atm, offset = 0.0 - // and no changes at all. - vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); - float r = 0.0;//length(x); - vec3 v = vec3(ray.direction.xyz); - float mu = 0.0;//dot(x, v) / r; - vec3 s = vec3(sunDirectionObj); - float tF = float(maxLength - t); - - // Because we may move the camera origin to the top of atmosphere - // we also need to adjust the pixelDepth for tdCalculateRayRenderableGlobehis offset so the - // next comparison with the planet's ground make sense: - pixelDepth -= offset; - - dvec4 onATMPos = dModelTransformMatrix * dvec4(x*1000.0, 1.0); - vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); - vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, fragWorldCoords.xyz, true); - - float sunIntensityInscatter = sunRadiance * eclipseShadowATM.x; - float sunIntensityGround = sunRadiance * eclipseShadowPlanet.x; - - float irradianceFactor = 0.0; - - vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, - s, r, mu, attenuation, - vec3(fragObjectCoords.xyz), - maxLength, pixelDepth, - color, sunIntensityInscatter); - vec3 groundColor = groundColor(x, tF, v, s, r, mu, attenuation, - color, normal.xyz, irradianceFactor, - normal.a, sunIntensityGround); - vec3 sunColor = sunColor(x, tF, v, s, r, mu, irradianceFactor); - - // Final Color of ATM plus terrain: - vec4 finalRadiance = vec4(HDR(inscatterColor + groundColor + sunColor, atmExposure), 1.0); - - atmosphereFinalColor += finalRadiance; - } - } - else { // no intersection - //discard; - atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); + oldColor = texelFetch(mainColorTexture, fragCoords, 0); + //colorArray[0] = oldColor; + //colorIndexArray[0] = 0; + for (int i = 1; i < nAaSamples; i++) { + //vec4 normal = texelFetch(mainNormalTexture, fragCoords, i); + vec4 currentColor = texelFetch(mainColorTexture, fragCoords, i); + //colorArray[i] = currentColor; + if (currentColor != oldColor) { + complex = true; + //nSamples = nAaSamples; + nSamples = nAaSamples > 1 ? nAaSamples / 2 : nAaSamples; + break; + // for (int c = 0; c < nAaSamples; c++) { + // if (currentColor == colorArray[c]) { + // colorIndexArray[i] = c; + // break; + // } + // } + } + //else { + // for (int c = 0; c < nAaSamples; c++) { + // if (currentColor == colorArray[c]) { + // colorIndexArray[i] = c; + // break; + // } + // } + // } + oldColor = currentColor; } - } + + for (int i = 0; i < nSamples; i++) { + // Color from G-Buffer + vec4 color = texelFetch(mainColorTexture, fragCoords, i); + + // Ray in object space + dRay ray; + dvec4 planetPositionObjectCoords = dvec4(0.0); + dvec4 cameraPositionInObject = dvec4(0.0); + + // Get the ray from camera to atm in object space + dCalculateRayRenderableGlobe(i * 3, ray, planetPositionObjectCoords, + cameraPositionInObject); + + bool insideATM = false; + double offset = 0.0; // in Km + double maxLength = 0.0; // in Km - renderTarget = atmosphereFinalColor / float(nSamples); + bool intersectATM = false; + + intersectATM = dAtmosphereIntersection(planetPositionObjectCoords.xyz, ray, + Rt - (ATM_EPSILON * 0.001), insideATM, offset, maxLength ); + + if ( intersectATM ) { + // Now we check is if the atmosphere is occluded, i.e., if the distance to the pixel + // in the depth buffer is less than the distance to the atmosphere then the atmosphere + // is occluded + // Fragments positions into G-Buffer are written in SGCT Eye Space (View plus Camera Rig Coords) + // when using their positions later, one must convert them to the planet's coords + + // Get data from G-Buffer + vec4 normal = texelFetch(mainNormalTexture, fragCoords, i); + // Data in the mainPositionTexture are written in view space (view plus camera rig) + vec4 position = texelFetch(mainPositionTexture, fragCoords, i); + + // OS Eye to World coords + dvec4 positionWorldCoords = dSGCTViewToWorldMatrix * position; + + // World to Object (Normal and Position in meters) + dvec4 positionObjectsCoords = dInverseModelTransformMatrix * positionWorldCoords; + + + // Distance of the pixel in the gBuffer to the observer + // JCC (12/12/2017): AMD distance function is buggy. + //double pixelDepth = distance(cameraPositionInObject.xyz, positionObjectsCoords.xyz); + double pixelDepth = length(cameraPositionInObject.xyz - positionObjectsCoords.xyz); + + // JCC (12/13/2017): Trick to remove floating error in texture. + // We see a squared noise on planet's surface when seeing the planet + // from far away. + float dC = float(length(cameraPositionInObject.xyz)); + float x1 = 1e8; + if (dC > x1) { + pixelDepth += 1000.0; + float alpha = 1000.0; + float beta = 1000000.0; + float x2 = 1e9; + float diffGreek = beta - alpha; + float diffDist = x2 - x1; + float varA = diffGreek/diffDist; + float varB = (alpha - varA * x1); + pixelDepth += double(varA * dC + varB); + } + + // All calculations are done in Km: + pixelDepth *= 0.001; + positionObjectsCoords.xyz *= 0.001; + + if (position.xyz != vec3(0.0) && (pixelDepth < offset)) { + atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); + //discard; + } else { + // Following paper nomenclature + double t = offset; + vec3 attenuation; + + // Moving observer from camera location to top atmosphere + // If the observer is already inside the atm, offset = 0.0 + // and no changes at all. + vec3 x = vec3(ray.origin.xyz + t*ray.direction.xyz); + float r = 0.0f;//length(x); + vec3 v = vec3(ray.direction.xyz); + float mu = 0.0f;//dot(x, v) / r; + vec3 s = vec3(sunDirectionObj); + float tF = float(maxLength - t); + + // Because we may move the camera origin to the top of atmosphere + // we also need to adjust the pixelDepth for tdCalculateRayRenderableGlobehis offset so the + // next comparison with the planet's ground make sense: + pixelDepth -= offset; + + dvec4 onATMPos = dModelTransformMatrix * dvec4(x * 1000.0, 1.0); + vec4 eclipseShadowATM = calcShadow(shadowDataArray, onATMPos.xyz, false); + vec4 eclipseShadowPlanet = calcShadow(shadowDataArray, positionWorldCoords.xyz, true); + + float sunIntensityInscatter = sunRadiance * eclipseShadowATM.x; + float sunIntensityGround = sunRadiance * eclipseShadowPlanet.x; + + float irradianceFactor = 0.0; + + vec3 inscatterColor = inscatterRadiance(x, tF, irradianceFactor, v, + s, r, mu, attenuation, + vec3(positionObjectsCoords.xyz), + maxLength, pixelDepth, + color, sunIntensityInscatter); + vec3 groundColor = groundColor(x, tF, v, s, r, mu, attenuation, + color, normal.xyz, irradianceFactor, + normal.a, sunIntensityGround); + vec3 sunColor = sunColor(x, tF, v, s, r, mu, irradianceFactor); + + // Final Color of ATM plus terrain: + vec4 finalRadiance = vec4(HDR(inscatterColor + groundColor + sunColor, atmExposure), 1.0); + + atmosphereFinalColor += finalRadiance; + } + } + else { // no intersection + //discard; + atmosphereFinalColor += vec4(HDR(color.xyz * backgroundConstant, atmExposure), color.a); + } + } + + renderTarget = atmosphereFinalColor / float(nSamples); + } + else { // culling + if (firstPaint) { + vec4 bColor = vec4(0.0f); + for (int f = 0; f < nAaSamples; f++) { + bColor += texelFetch(mainColorTexture, fragCoords, f); + } + bColor /= float(nAaSamples); + renderTarget = vec4(HDR(bColor.xyz * backgroundConstant, atmExposure), bColor.a); + } + else { + discard; + } + //renderTarget = vec4(1.0, 0.0, 0.0, 1.0); + + } } + From 1e0d41fb300012fd76ecc90eb9771a9754962ba6 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 10:24:37 -0400 Subject: [PATCH 39/79] Fixed accurate normals. --- modules/globebrowsing/shaders/tilefragment.hglsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/globebrowsing/shaders/tilefragment.hglsl b/modules/globebrowsing/shaders/tilefragment.hglsl index f7c3b1e954..a0b1e1bc59 100644 --- a/modules/globebrowsing/shaders/tilefragment.hglsl +++ b/modules/globebrowsing/shaders/tilefragment.hglsl @@ -175,7 +175,7 @@ Fragment getTileFragment() { ); // Once deferred light calculations are done in view space this can be removed // so that we only need one normal; in view space. - normalModelSpace = mat3(invViewModelTransform) * normal; + normalModelSpace = normalize(mat3(invViewModelTransform) * normal); #endif /// USE_ACCURATE_NORMALS #if USE_COLORTEXTURE From 5079beba78c0ed1d50b6e44eb056e2f3ff3e4167 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 11:22:23 -0400 Subject: [PATCH 40/79] Added new method to get the right viewport size in stereo (side-by-side) and fix font rendering. --- .../engine/wrapper/sgctwindowwrapper.h | 1 + .../openspace/engine/wrapper/windowwrapper.h | 7 ++++ src/engine/openspaceengine.cpp | 36 ++++++++++--------- src/engine/wrapper/sgctwindowwrapper.cpp | 11 ++++++ src/engine/wrapper/windowwrapper.cpp | 4 +++ src/rendering/renderengine.cpp | 3 +- 6 files changed, 44 insertions(+), 18 deletions(-) diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h index 4bb68cf43f..d76ec15a94 100644 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ b/include/openspace/engine/wrapper/sgctwindowwrapper.h @@ -56,6 +56,7 @@ public: 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; diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index 34c4832f21..6bec15b1e0 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -160,6 +160,13 @@ public: */ 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. diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index a34b2252ac..5b38e33d3c 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -899,23 +899,6 @@ void OpenSpaceEngine::loadFonts() { LERROR(fmt::format("Error registering font '{}' with key '{}'", font, key)); } } - - try { - bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); - if (!initSuccess) { - LERROR("Error initializing default font renderer"); - } - - using FR = ghoul::fontrendering::FontRenderer; - FR::defaultRenderer().setFramebufferSize(_renderEngine->fontResolution()); - - FR::defaultProjectionRenderer().setFramebufferSize( - _renderEngine->renderingResolution() - ); - } - catch (const ghoul::RuntimeError& err) { - LERRORC(err.component, err.message); - } } void OpenSpaceEngine::configureLogging(bool consoleLog) { @@ -1227,6 +1210,16 @@ void OpenSpaceEngine::initializeGL() { } } + try { + bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); + if (!initSuccess) { + LERROR("Error initializing default font renderer"); + } + } + catch (const ghoul::RuntimeError& err) { + LERRORC(err.component, err.message); + } + LDEBUG("Initializing Rendering Engine"); _renderEngine->initializeGL(); @@ -1313,6 +1306,15 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { bool master = _windowWrapper->isMaster(); _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::defaultProjectionRenderer().setFramebufferSize( + _renderEngine->renderingResolution() + ); + if (_shutdown.inShutdown) { if (_shutdown.timer <= 0.f) { _windowWrapper->terminate(); diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index d9f7741209..e85923bb70 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -170,6 +170,17 @@ glm::ivec2 SGCTWindowWrapper::currentDrawBufferResolution() const { 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(), diff --git a/src/engine/wrapper/windowwrapper.cpp b/src/engine/wrapper/windowwrapper.cpp index 718747e09f..db77a37077 100644 --- a/src/engine/wrapper/windowwrapper.cpp +++ b/src/engine/wrapper/windowwrapper.cpp @@ -121,6 +121,10 @@ glm::ivec2 WindowWrapper::currentDrawBufferResolution() const { return currentWindowSize(); } +glm::ivec2 WindowWrapper::getCurrentViewportSize() const { + return currentWindowSize(); +} + glm::vec2 WindowWrapper::dpiScaling() const { return glm::vec2(1.f); } diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index c6d1dc46ad..b07dc76c7c 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -537,7 +537,8 @@ glm::ivec2 RenderEngine::fontResolution() const { value ); if (hasValue && value == "framebuffer") { - return OsEng.windowWrapper().currentWindowResolution(); + return OsEng.windowWrapper().getCurrentViewportSize(); + //return OsEng.windowWrapper().currentWindowResolution(); } else { // The default is to use the window size From cec7d45fed68a47c9595a5908f813d26af769f9e Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 11:35:13 -0400 Subject: [PATCH 41/79] Added missing changes from SunEarth day for the stereo branch. --- modules/fieldlines/shaders/fieldline_fs.glsl | 7 +++++++ .../fieldlinessequence/shaders/fieldlinessequence_fs.glsl | 8 ++++++++ .../fieldlinessequence/shaders/fieldlinessequence_vs.glsl | 4 +++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/modules/fieldlines/shaders/fieldline_fs.glsl b/modules/fieldlines/shaders/fieldline_fs.glsl index e020568602..ec8d7b5ea7 100644 --- a/modules/fieldlines/shaders/fieldline_fs.glsl +++ b/modules/fieldlines/shaders/fieldline_fs.glsl @@ -45,5 +45,12 @@ Fragment getFragment() { } frag.depth = pscDepth(gs_position); + + // G-Buffer + frag.gPosition = vec4(0.0);//vs_gPosition; + // There is no normal here + // TODO: Add the correct normal if necessary (JCC) + frag.gNormal = vec4(0.0, 0.0, -1.0, 1.0); + return frag; } diff --git a/modules/fieldlinessequence/shaders/fieldlinessequence_fs.glsl b/modules/fieldlinessequence/shaders/fieldlinessequence_fs.glsl index 0b5cee187b..8877501e38 100644 --- a/modules/fieldlinessequence/shaders/fieldlinessequence_fs.glsl +++ b/modules/fieldlinessequence/shaders/fieldlinessequence_fs.glsl @@ -40,6 +40,14 @@ Fragment getFragment() { frag.depth = vs_depth; frag.color = fragColor; + // G-Buffer + frag.gPosition = vec4(0.0);//vs_gPosition; + // There is no normal here + // TODO: Add the correct normal if necessary (JCC) + frag.gNormal = vec4(0.0, 0.0, -1.0, 1.0); + + + if (usingAdditiveBlending) { frag.blend = BLEND_MODE_ADDITIVE; } diff --git a/modules/fieldlinessequence/shaders/fieldlinessequence_vs.glsl b/modules/fieldlinessequence/shaders/fieldlinessequence_vs.glsl index ee93ca17a3..98f18d61ec 100644 --- a/modules/fieldlinessequence/shaders/fieldlinessequence_vs.glsl +++ b/modules/fieldlinessequence/shaders/fieldlinessequence_vs.glsl @@ -63,7 +63,7 @@ const int colorByQuantity = 1; out vec4 vs_color; out float vs_depth; - +//out vec4 vs_gPosition; vec4 getTransferFunctionColor() { // Remap the color scalar to a [0,1] range @@ -121,6 +121,8 @@ void main() { vec4 position_in_meters = vec4(in_position, 1); vec4 positionClipSpace = modelViewProjection * position_in_meters; + //vs_gPosition = vec4(modelViewTransform * dvec4(in_point_position, 1)); gl_Position = vec4(positionClipSpace.xy, 0, positionClipSpace.w); + vs_depth = gl_Position.w; } From a9fa9117f62e5fd1e8c94f09702912e242257498 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 20 Apr 2018 15:39:43 -0400 Subject: [PATCH 42/79] Update Ghoul --- ext/ghoul | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/ghoul b/ext/ghoul index f0e8a06c9a..9a7c0e600b 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit f0e8a06c9a92a282d2c7197c9388db1301d797ce +Subproject commit 9a7c0e600b21c2f39b025f2ab4742b4574ee382a From 38102093659b0a9a0ebec0a284c76afb9e2c8d7f Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 20 Apr 2018 16:12:18 -0400 Subject: [PATCH 43/79] Issue/451 (#595) * Add ability for Joystick input * Change location of LuaConsole files --- apps/OpenSpace/main.cpp | 89 ++ data/assets/default.scene | 1 + data/assets/util/default_joystick.asset | 136 +++ include/openspace/engine/openspaceengine.h | 6 +- ...mousestate.h => camerainteractionstates.h} | 58 +- .../openspace/interaction/inputdevicestates.h | 81 ++ include/openspace/interaction/inputstate.h | 28 +- .../interaction/joystickcamerastates.h | 122 +++ .../interaction/joystickinputstate.h | 126 +++ .../openspace/interaction/keybindingmanager.h | 1 - .../{controller.h => mousecamerastates.h} | 24 +- .../openspace/interaction/navigationhandler.h | 27 +- .../openspace/interaction/orbitalnavigator.h | 62 +- .../{interaction => rendering}/luaconsole.h | 0 modules/imgui/CMakeLists.txt | 2 + modules/imgui/imguimodule.cpp | 2 +- modules/imgui/include/gui.h | 2 + .../imgui/include/guijoystickcomponent.h | 19 +- modules/imgui/src/gui.cpp | 70 +- modules/imgui/src/guijoystickcomponent.cpp | 111 +++ .../server/src/topics/getpropertytopic.cpp | 2 +- src/CMakeLists.txt | 16 +- src/engine/openspaceengine.cpp | 16 +- src/interaction/camerainteractionstates.cpp | 101 ++ src/interaction/inputdevicestates.cpp | 101 ++ src/interaction/inputstate.cpp | 30 +- src/interaction/joystickcamerastates.cpp | 272 ++++++ src/interaction/joystickinputstate.cpp | 100 ++ src/interaction/luaconsole.cpp | 2 +- src/interaction/mousecamerastates.cpp | 125 +++ src/interaction/mousestate.cpp | 179 ---- src/interaction/navigationhandler.cpp | 114 ++- src/interaction/navigationhandler_lua.inl | 129 +++ src/interaction/orbitalnavigator.cpp | 111 ++- src/rendering/luaconsole.cpp | 916 ++++++++++++++++++ src/rendering/renderengine.cpp | 4 +- 36 files changed, 2794 insertions(+), 391 deletions(-) create mode 100644 data/assets/util/default_joystick.asset rename include/openspace/interaction/{mousestate.h => camerainteractionstates.h} (70%) create mode 100644 include/openspace/interaction/inputdevicestates.h create mode 100644 include/openspace/interaction/joystickcamerastates.h create mode 100644 include/openspace/interaction/joystickinputstate.h rename include/openspace/interaction/{controller.h => mousecamerastates.h} (83%) rename include/openspace/{interaction => rendering}/luaconsole.h (100%) rename src/interaction/controller.cpp => modules/imgui/include/guijoystickcomponent.h (83%) create mode 100644 modules/imgui/src/guijoystickcomponent.cpp create mode 100644 src/interaction/camerainteractionstates.cpp create mode 100644 src/interaction/inputdevicestates.cpp create mode 100644 src/interaction/joystickcamerastates.cpp create mode 100644 src/interaction/joystickinputstate.cpp create mode 100644 src/interaction/mousecamerastates.cpp delete mode 100644 src/interaction/mousestate.cpp create mode 100644 src/rendering/luaconsole.cpp diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index b97d159420..765ce7f5df 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -74,6 +74,8 @@ namespace { constexpr const char* _loggerCat = "main"; sgct::Engine* SgctEngine; +openspace::interaction::JoystickInputStates joystickInputStates; + constexpr const char* OpenVRTag = "OpenVR"; constexpr const char* SpoutTag = "Spout"; @@ -345,12 +347,99 @@ void mainInitFunc() { } } + OsEng.setJoystickInputStates(joystickInputStates); + LTRACE("main::mainInitFunc(end)"); } void mainPreSyncFunc() { LTRACE("main::mainPreSyncFunc(begin)"); OsEng.preSynchronization(); + + // Query joystick status + using namespace openspace::interaction; + + for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { + JoystickInputState& state = 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 { + state.isConnected = false; + } + } + LTRACE("main::mainPreSyncFunc(end)"); } diff --git a/data/assets/default.scene b/data/assets/default.scene index aa54ad4635..d5b4467a9c 100644 --- a/data/assets/default.scene +++ b/data/assets/default.scene @@ -12,6 +12,7 @@ assetHelper.requestAll(asset, 'scene/digitaluniverse') -- Load default key bindings applicable to most scenes asset.require('util/default_keybindings') asset.require('util/default_dashboard') +asset.require('util/default_joystick') asset.request('customization/globebrowsing') diff --git a/data/assets/util/default_joystick.asset b/data/assets/util/default_joystick.asset new file mode 100644 index 0000000000..64be2b36c3 --- /dev/null +++ b/data/assets/util/default_joystick.asset @@ -0,0 +1,136 @@ +local propertyHelper = asset.require('./property_helper') + +-- Allowed values for the second parameter of bindJoystickAxis: +-- "None" +-- "Orbit X" +-- "Orbit Y" +-- "Zoom In" +-- "Zoom Out" +-- "LocalRoll X" +-- "LocalRoll Y" +-- "GlobalRoll X" +-- "GlobalRoll Y" +-- "Pan X" +-- "Pan Y" +-- Third parameter determines whether the axis should be inverted +-- Fourth parameter determines whether the axis should be normalized from [-1,1] to [0,1] + + +local XBoxController = { + LeftThumbStick = { 0 , 1 }, + RightThumbStick = { 2, 3 }, + LeftTrigger = 4, + RightTrigger = 5, + A = 0, + B = 1, + X = 2, + Y = 3, + LB = 4, + RB = 5, + Select = 6, + Start = 7, + LeftStick = 8, + RightStick = 9, + DPad = { + Up = 10, + Right = 11, + Down = 12, + Left = 13 + } +} + +local PS4Controller = { + LeftThumbStick = { 0 , 1 }, + RightThumbStick = { 2, 5 }, + LeftTrigger = 3, + RightTrigger = 4, + A = 3, -- Triangle + B = 0, -- Square + X = 2, -- Circle + Y = 1, -- Cross + LB = 4, + RB = 5, + Select = 9, -- options + Start = 12, -- PS button + LeftStick = 10, + RightStick = 11, + DPad = { + Up = 14, + Right = 15, + Down = 16, + Left = 17 + } +} + +-- Variables to store the state of the joystick between frames +Joystick = {} +Joystick.State = {} +Joystick.State.IsInRollMode = false +Joystick.State.Axis = {} + +local bindLocalRoll = function(axis) +return [[ + -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup + if not Joystick.State.IsInRollMode then + -- Save current axis state + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized = openspace.navigation.joystickAxis(]] .. axis .. [[) + end + + -- Set new axis state + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "LocalRoll X", true); + Joystick.State.IsInRollMode = true + ]] +end + +local bindGlobalRoll = function(axis) + return [[ + -- We only want to store the current state in the first mode that is enabled, otherwise we will overwrite the backup + if not Joystick.State.IsInRollMode then + -- Save current axis state + Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized = openspace.navigation.joystickAxis(]] .. axis .. [[) + end + + -- Set new axis state + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, "GlobalRoll X", true); + Joystick.State.IsInRollMode = true + ]] +end + +local unbindRoll = function(axis) + return [[ + -- Reset previous state + openspace.navigation.bindJoystickAxis(]] .. axis .. [[, Joystick.State.Axis.Type, Joystick.State.Axis.Inverted, Joystick.State.Axis.Normalized); +]] +end + +asset.onInitialize(function() + -- Set the controller to the connected controller + -- Currently: XBoxController or PS4Controller + local controller = XBoxController; + + openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[1], 0.05) + openspace.navigation.setAxisDeadZone(controller.LeftThumbStick[2], 0.05) + openspace.navigation.setAxisDeadZone(controller.RightThumbStick[1], 0.05) + openspace.navigation.setAxisDeadZone(controller.RightThumbStick[2], 0.05) + openspace.navigation.setAxisDeadZone(controller.LeftTrigger, 0.05) + openspace.navigation.setAxisDeadZone(controller.RightTrigger, 0.05) + + 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.LeftTrigger, "Zoom Out", false, true); + openspace.navigation.bindJoystickAxis(controller.RightTrigger, "Zoom In", false, true); + + openspace.navigation.bindJoystickButton(controller.LB, bindLocalRoll(controller.RightThumbStick[1])) + openspace.navigation.bindJoystickButton(controller.LB, unbindRoll(controller.RightThumbStick[1]), "Release") + openspace.navigation.bindJoystickButton(controller.RB, bindGlobalRoll(controller.RightThumbStick[1])) + openspace.navigation.bindJoystickButton(controller.RB, unbindRoll(controller.RightThumbStick[1]), "Release") + + openspace.navigation.bindJoystickButton(controller.A, propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.ZoomFriction')) + openspace.navigation.bindJoystickButton(controller.B, propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RotationalFriction')) + openspace.navigation.bindJoystickButton(controller.DPad.Left, propertyHelper.invert('NavigationHandler.OrbitalNavigator.Friction.RollFriction')) + + openspace.navigation.bindJoystickButton(controller.X, "openspace.setPropertyValue('NavigationHandler.Origin', 'Earth')") + openspace.navigation.bindJoystickButton(controller.Y, "openspace.setPropertyValue('NavigationHandler.Origin', 'Mars')") +end) diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 8b2e3e49aa..400aba618a 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -25,6 +25,7 @@ #ifndef __OPENSPACE_CORE___OPENSPACEENGINE___H__ #define __OPENSPACE_CORE___OPENSPACEENGINE___H__ +#include #include #include #include @@ -60,9 +61,9 @@ class VirtualPropertyManager; class WindowWrapper; namespace interaction { - class NavigationHandler; class KeyBindingManager; -} + class NavigationHandler; +} // namespace interaction namespace gui { class GUI; } namespace properties { class PropertyOwner; } namespace scripting { @@ -111,6 +112,7 @@ 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(); diff --git a/include/openspace/interaction/mousestate.h b/include/openspace/interaction/camerainteractionstates.h similarity index 70% rename from include/openspace/interaction/mousestate.h rename to include/openspace/interaction/camerainteractionstates.h index 91cebb327b..abf4abff56 100644 --- a/include/openspace/interaction/mousestate.h +++ b/include/openspace/interaction/camerainteractionstates.h @@ -22,56 +22,60 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___MOUSESTATE___H__ -#define __OPENSPACE_CORE___MOUSESTATE___H__ +#ifndef __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#define __OPENSPACE_CORE___INPUTDEVICESTATES___H__ #include -#include - #include namespace openspace::interaction { -struct MouseState { - MouseState(double scaleFactor); - void setFriction(double friction); - void setVelocityScaleFactor(double scaleFactor); +class InputState; - glm::dvec2 previousPosition; - DelayedVariable velocity; -}; - -class MouseStates { +class CameraInteractionStates { public: /** * \param sensitivity * \param velocityScaleFactor can be set to 60 to remove the inertia of the * interaction. Lower value will make it harder to move the camera. */ - MouseStates(double sensitivity, double velocityScaleFactor); - void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); + CameraInteractionStates(double sensitivity, double velocityScaleFactor); + virtual ~CameraInteractionStates() = default; + + virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; + void setRotationalFriction(double friction); void setHorizontalFriction(double friction); void setVerticalFriction(double friction); void setSensitivity(double sensitivity); void setVelocityScaleFactor(double scaleFactor); - glm::dvec2 globalRotationMouseVelocity() const; - glm::dvec2 localRotationMouseVelocity() const; - glm::dvec2 truckMovementMouseVelocity() const; - glm::dvec2 localRollMouseVelocity() const; - glm::dvec2 globalRollMouseVelocity() const; + glm::dvec2 globalRotationVelocity() const; + glm::dvec2 localRotationVelocity() const; + glm::dvec2 truckMovementVelocity() const; + glm::dvec2 localRollVelocity() const; + glm::dvec2 globalRollVelocity() const; + +protected: + struct InteractionState { + InteractionState(double scaleFactor); + void setFriction(double friction); + void setVelocityScaleFactor(double scaleFactor); + + glm::dvec2 previousPosition; + DelayedVariable velocity; + }; + -private: double _sensitivity; - MouseState _globalRotationMouseState; - MouseState _localRotationMouseState; - MouseState _truckMovementMouseState; - MouseState _localRollMouseState; - MouseState _globalRollMouseState; + InteractionState _globalRotationState; + InteractionState _localRotationState; + InteractionState _truckMovementState; + InteractionState _localRollState; + InteractionState _globalRollState; }; } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___MOUSESTATE___H__ +#endif // __OPENSPACE_CORE___INPUTDEVICESTATES___H__ diff --git a/include/openspace/interaction/inputdevicestates.h b/include/openspace/interaction/inputdevicestates.h new file mode 100644 index 0000000000..11db6993a0 --- /dev/null +++ b/include/openspace/interaction/inputdevicestates.h @@ -0,0 +1,81 @@ +/***************************************************************************************** + * * + * 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___CAMERAINTERACTIONSTATES___H__ +#define __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ + +#include +#include + +namespace openspace::interaction { + +class InputState; + +class CameraInteractionStates { +public: + /** + * \param sensitivity + * \param velocityScaleFactor can be set to 60 to remove the inertia of the + * interaction. Lower value will make it harder to move the camera. + */ + CameraInteractionStates(double sensitivity, double velocityScaleFactor); + virtual ~CameraInteractionStates() = default; + + virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; + + void setRotationalFriction(double friction); + void setHorizontalFriction(double friction); + void setVerticalFriction(double friction); + void setSensitivity(double sensitivity); + void setVelocityScaleFactor(double scaleFactor); + + glm::dvec2 globalRotationVelocity() const; + glm::dvec2 localRotationVelocity() const; + glm::dvec2 truckMovementVelocity() const; + glm::dvec2 localRollVelocity() const; + glm::dvec2 globalRollVelocity() const; + +protected: + struct InteractionState { + InteractionState(double scaleFactor); + void setFriction(double friction); + void setVelocityScaleFactor(double scaleFactor); + + glm::dvec2 previousPosition; + DelayedVariable velocity; + }; + + + double _sensitivity; + + InteractionState _globalRotationState; + InteractionState _localRotationState; + InteractionState _truckMovementState; + InteractionState _localRollState; + InteractionState _globalRollState; +}; + +} // namespace openspace::interaction + +#endif // __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ diff --git a/include/openspace/interaction/inputstate.h b/include/openspace/interaction/inputstate.h index 7475a7942f..9ab85ffe8f 100644 --- a/include/openspace/interaction/inputstate.h +++ b/include/openspace/interaction/inputstate.h @@ -25,15 +25,15 @@ #ifndef __OPENSPACE_CORE___INPUTSTATE___H__ #define __OPENSPACE_CORE___INPUTSTATE___H__ +#include #include #include - #include - #include namespace openspace::interaction { +// This class represents the global input state of interaction devices class InputState { public: InputState() = default; @@ -45,22 +45,34 @@ public: void mousePositionCallback(double mouseX, double mouseY); void mouseScrollWheelCallback(double mouseScrollDelta); - // Accessors - const std::list>& getPressedKeys() const; - const std::list& getPressedMouseButtons() const; - glm::dvec2 getMousePosition() const; - double getMouseScrollDelta() const; + void setJoystickInputStates(JoystickInputStates& states); + // Accessors + const std::list>& pressedKeys() const; bool isKeyPressed(std::pair keyModPair) const; bool isKeyPressed(Key key) const; + + const std::list& pressedMouseButtons() const; + glm::dvec2 mousePosition() const; + double mouseScrollDelta() const; bool isMouseButtonPressed(MouseButton mouseButton) const; + const JoystickInputStates& joystickInputStates() const; + float joystickAxis(int i) const; + bool joystickButton(int i) const; + private: - // Input from keyboard and mouse + // Input from keyboard std::list> _keysDown; + + // Input from mouse std::list _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/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h new file mode 100644 index 0000000000..89e19488ee --- /dev/null +++ b/include/openspace/interaction/joystickcamerastates.h @@ -0,0 +1,122 @@ +/***************************************************************************************** + * * + * 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___JOYSTICKSTATE___H__ +#define __OPENSPACE_CORE___JOYSTICKSTATE___H__ + +#include + +#include +#include +#include +#include +#include + +namespace openspace::interaction { + +class JoystickCameraStates : public CameraInteractionStates { +public: + enum class AxisType { + None = 0, + OrbitX, + OrbitY, + ZoomIn, + ZoomOut, + LocalRollX, + LocalRollY, + GlobalRollX, + GlobalRollY, + PanX, + PanY + }; + + BooleanType(AxisInvert); + BooleanType(AxisNormalize); + BooleanType(ButtonCommandRemote); + + struct AxisInformation { + AxisType type = AxisType::None; + AxisInvert invert = AxisInvert::No; + AxisNormalize normalize = AxisNormalize::No; + + float deadzone = 0.f; + }; + + + JoystickCameraStates(double sensitivity, double velocityScaleFactor); + + void updateStateFromInput(const InputState& inputState, double deltaTime) override; + + void setAxisMapping( + int axis, + AxisType mapping, + AxisInvert shouldInvert = AxisInvert::No, + AxisNormalize shouldNormalize = AxisNormalize::No + ); + + AxisInformation axisMapping(int axis) const; + + void setDeadzone(int axis, float deadzone); + float deadzone(int axis) const; + + + void bindButtonCommand(int button, std::string command, JoystickAction action, + ButtonCommandRemote local); + void clearButtonCommand(int button); + std::vector buttonCommand(int button) const; + +private: + // We use an array for the axes and a map for the buttons since the axis are going to + // be accessed much more often and thus have to be more efficient. And storing a few + // extra AxisInformation that are not used will not matter that much; finding an axis + // location in a potential map each frame, however, would + + std::array _axisMapping; + + struct ButtonInformation { + std::string command; + JoystickAction action; + ButtonCommandRemote synchronization; + std::string documentation; + }; + + std::multimap _buttonMapping; +}; + +} // namespace openspace::interaction + +namespace std { + +std::string to_string(const openspace::interaction::JoystickCameraStates::AxisType& type); + +} // namespace std + +namespace ghoul { + +template <> +openspace::interaction::JoystickCameraStates::AxisType from_string(const std::string& string); + +} // namespace ghoul + +#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h new file mode 100644 index 0000000000..baf75c43d5 --- /dev/null +++ b/include/openspace/interaction/joystickinputstate.h @@ -0,0 +1,126 @@ +/***************************************************************************************** + * * + * 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___JOYSTICKINPUTSTATE___H__ +#define __OPENSPACE_CORE___JOYSTICKINPUTSTATE___H__ + +#include +#include +#include +#include + +namespace openspace::interaction { + +/** + * Actions that any button of a joystick can have. Each button must be in one of these + * states + */ +enum class JoystickAction : uint8_t { + /// Idle state if the button is unpressed and has been unpressed since last frame + Idle = 0, + /// If the button has been pressed since the last frame + Press, + /// If the button has been pressed since longer than last frame + Repeat, + /// If the button was released since the last frame + Release +}; + +/** + * The input state of a single joystick. + */ +struct JoystickInputState { + /// The maximum number of supported axes + static const int MaxAxes = 8; + /// The maximum number of supported buttons + static const int MaxButtons = 32; + + /// Marks whether this joystick is connected. If this value is \c false, all other + /// members of this struct are undefined + bool isConnected = false; + + /// The name of this joystick + std::string name; + + /// The number of axes that this joystick supports + int nAxes = 0; + /// The values for each axis. Each value is in the range [-1, 1]. Only the first + /// \c nAxes values are defined values, the rest are undefined + std::array axes; + + /// The number of buttons that this joystick possesses + int nButtons = 0; + /// The status of each button. Only the first \c nButtons values are defined, the rest + /// are undefined + std::array buttons; +}; + +/// The maximum number of joysticks that are supported by this system. This number is +/// derived from the available GLFW constants +constexpr const int MaxJoysticks = 16; +struct JoystickInputStates : public std::array { + /** + * This function adds the contributions of all connected joysticks for the provided + * \p axis. After adding each joysticks contribution, the result is clamped to [-1,1]. + * If a joystick does not possess a particular axis, it's does not contribute to the + * sum. + * + * \param axis The numerical axis for which the values are added + * \return The summed axis values of all connected joysticks + * + * \pre \p axis must be 0 or positive + */ + float axis(int axis) const; + + /** + * This functions checks whether any connected joystick has its \p button in the + * passed \p action. Any joystick that does not posses the \p button, it will be + * ignored. + * + * \param button The button that is to be checked + * \param action The action which is checked for each button + * \return \c true if there is at least one joystick whose \param button is in the + * \p action state + * + * \pre \p button must be 0 or positive + */ + bool button(int button, JoystickAction action) const; +}; + +} // namespace openspace::interaction + +namespace std { + +std::string to_string(openspace::interaction::JoystickAction action); + +} // namespace std + +namespace ghoul { + +template <> +openspace::interaction::JoystickAction from_string(const std::string& str); + +} // namespace ghoul + +#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ diff --git a/include/openspace/interaction/keybindingmanager.h b/include/openspace/interaction/keybindingmanager.h index c4a47d7631..11138eae38 100644 --- a/include/openspace/interaction/keybindingmanager.h +++ b/include/openspace/interaction/keybindingmanager.h @@ -79,7 +79,6 @@ public: void keyboardCallback(Key key, KeyModifier modifier, KeyAction action); private: - std::string generateJson() const override; std::multimap _keyLua; diff --git a/include/openspace/interaction/controller.h b/include/openspace/interaction/mousecamerastates.h similarity index 83% rename from include/openspace/interaction/controller.h rename to include/openspace/interaction/mousecamerastates.h index 6375de8aa6..6e45af34df 100644 --- a/include/openspace/interaction/controller.h +++ b/include/openspace/interaction/mousecamerastates.h @@ -22,30 +22,20 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___CONTROLLER___H__ -#define __OPENSPACE_CORE___CONTROLLER___H__ +#ifndef __OPENSPACE_CORE___MOUSECAMERASTATES___H__ +#define __OPENSPACE_CORE___MOUSECAMERASTATES___H__ -#include - -#include -#include +#include namespace openspace::interaction { -class NavigationHandler; - -class Controller { +class MouseCameraStates : public CameraInteractionStates { public: - Controller() : - _handler(nullptr) - {} + MouseCameraStates(double sensitivity, double velocityScaleFactor); - void setHandler(NavigationHandler* handler); - -protected: - NavigationHandler* _handler; + void updateStateFromInput(const InputState& inputState, double deltaTime) override; }; } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___CONTROLLER___H__ +#endif // __OPENSPACE_CORE___MOUSECAMERASTATES___H__ diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index 9ab9e08f20..e906700333 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -29,6 +29,8 @@ #include #include +#include +#include #include #include #include @@ -63,7 +65,7 @@ public: void updateCamera(double deltaTime); // Accessors - ghoul::Dictionary getCameraStateDictionary(); + ghoul::Dictionary cameraStateDictionary(); SceneGraphNode* focusNode() const; glm::dvec3 focusNodeToCameraVector() const; glm::quat focusNodeToCameraRotation() const; @@ -74,10 +76,33 @@ public: // Callback functions void keyboardCallback(Key key, KeyModifier modifier, KeyAction action); + void mouseButtonCallback(MouseButton button, MouseAction action); 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, + JoystickCameraStates::AxisNormalize shouldNormalize = JoystickCameraStates::AxisNormalize::No + ); + + JoystickCameraStates::AxisInformation joystickAxisMapping(int axis) const; + + void setJoystickAxisDeadzone(int axis, float deadzone); + float joystickAxisDeadzone(int axis) const; + + void bindJoystickButtonCommand(int button, std::string command, JoystickAction action, + JoystickCameraStates::ButtonCommandRemote remote); + + void clearJoystickButtonCommand(int button); + std::vector joystickButtonCommand(int button) const; + + + void saveCameraStateToFile(const std::string& filepath); void restoreCameraStateFromFile(const std::string& filepath); diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index 38c569b34b..b31965b517 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -28,7 +28,8 @@ #include #include #include -#include +#include +#include #include #include @@ -50,11 +51,14 @@ public: OrbitalNavigator(); ~OrbitalNavigator(); - void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); - void updateCameraStateFromMouseStates(Camera& camera, double deltaTime); + void updateStatesFromInput(const InputState& inputState, double deltaTime); + void updateCameraStateFromStates(Camera& camera, double deltaTime); + void setFocusNode(SceneGraphNode* focusNode); void startInterpolateCameraDirection(const Camera& camera); + JoystickCameraStates& joystickStates(); + bool followingNodeRotation() const; SceneGraphNode* focusNode() const; @@ -82,9 +86,12 @@ private: properties::FloatProperty _followFocusNodeRotationDistance; properties::FloatProperty _minimumAllowedDistance; - properties::FloatProperty _sensitivity; + + properties::FloatProperty _mouseSensitivity; + properties::FloatProperty _joystickSensitivity; - MouseStates _mouseStates; + MouseCameraStates _mouseStates; + JoystickCameraStates _joystickStates; SceneGraphNode* _focusNode = nullptr; glm::dvec3 _previousFocusNodePosition; @@ -116,14 +123,14 @@ private: * \returns a local camera rotation modified with two degrees of freedom. */ glm::dquat rotateLocally(double deltaTime, - const glm::dquat& localCameraRotation) const; + const glm::dquat& localCameraRotation) const; /** * Interpolates the local rotation towards a 0 rotation. * \returns a modified local rotation interpolated towards 0. */ glm::dquat interpolateLocalRotation(double deltaTime, - const glm::dquat& localCameraRotation); + const glm::dquat& localCameraRotation); /** * Translates the horizontal direction. If far from the focus object, this will @@ -132,10 +139,9 @@ private: * \returns a position vector adjusted in the horizontal direction. */ glm::dvec3 translateHorizontally(double deltaTime, const glm::dvec3& cameraPosition, - const glm::dvec3& objectPosition, - const glm::dquat& focusNodeRotationDiff, - const glm::dquat& globalCameraRotation, - const SurfacePositionHandle& positionHandle) const; + const glm::dvec3& objectPosition, const glm::dquat& focusNodeRotationDiff, + const glm::dquat& globalCameraRotation, + const SurfacePositionHandle& positionHandle) const; /* * Adds rotation to the camera position so that it follows the rotation of the focus @@ -143,35 +149,32 @@ private: * \returns a position updated with the rotation defined by focusNodeRotationDiff */ glm::dvec3 followFocusNodeRotation(const glm::dvec3& cameraPosition, - const glm::dvec3& objectPosition, - const glm::dquat& focusNodeRotationDiff) const; + const glm::dvec3& objectPosition, const glm::dquat& focusNodeRotationDiff) const; /** * Updates the global rotation so that it points towards the focus node. * \returns a global rotation quaternion defining a rotation towards the focus node. */ glm::dquat rotateGlobally(const glm::dquat& globalCameraRotation, - const glm::dvec3& objectPosition, - const glm::dquat& focusNodeRotationDiff, - const glm::dvec3& cameraPosition, - const SurfacePositionHandle& positionHandle) const; + const glm::dvec3& objectPosition, const glm::dquat& focusNodeRotationDiff, + const glm::dvec3& cameraPosition, + const SurfacePositionHandle& positionHandle) const; /** * Translates the camera position towards or away from the focus node. * \returns a position vector adjusted in the vertical direction. */ glm::dvec3 translateVertically(double deltaTime, const glm::dvec3& cameraPosition, - const glm::dvec3& objectPosition, - const SurfacePositionHandle& positionHandle) const; + const glm::dvec3& objectPosition, + const SurfacePositionHandle& positionHandle) const; /** * Rotates the camera around the out vector of the surface. * \returns a quaternion adjusted to rotate around the out vector of the surface. */ glm::dquat rotateHorizontally(double deltaTime, - const glm::dquat& globalCameraRotation, - const glm::dvec3& cameraPosition, - const SurfacePositionHandle& positionHandle) const; + const glm::dquat& globalCameraRotation, const glm::dvec3& cameraPosition, + const SurfacePositionHandle& positionHandle) const; /** * Push the camera out to the surface of the object. @@ -179,19 +182,16 @@ private: * above the actual surface of the object */ glm::dvec3 pushToSurface(double minHeightAboveGround, - const glm::dvec3& cameraPosition, - const glm::dvec3& objectPosition, - const SurfacePositionHandle& positionHandle) const; + const glm::dvec3& cameraPosition, const glm::dvec3& objectPosition, + const SurfacePositionHandle& positionHandle) const; /** * Interpolates between rotationDiff and a 0 rotation. */ - glm::dquat interpolateRotationDifferential( - double deltaTime, double interpolationTime, - const glm::dquat& rotationDiff, - const glm::dvec3& objectPosition, - const glm::dvec3& cameraPosition, - const SurfacePositionHandle& positionHandle); + glm::dquat interpolateRotationDifferential(double deltaTime, + double interpolationTime, const glm::dquat& rotationDiff, + const glm::dvec3& objectPosition, const glm::dvec3& cameraPosition, + const SurfacePositionHandle& positionHandle); /** * Calculates a SurfacePositionHandle given a camera position in world space. diff --git a/include/openspace/interaction/luaconsole.h b/include/openspace/rendering/luaconsole.h similarity index 100% rename from include/openspace/interaction/luaconsole.h rename to include/openspace/rendering/luaconsole.h diff --git a/modules/imgui/CMakeLists.txt b/modules/imgui/CMakeLists.txt index f590d19d58..01a5cf9ccf 100644 --- a/modules/imgui/CMakeLists.txt +++ b/modules/imgui/CMakeLists.txt @@ -33,6 +33,7 @@ set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/include/guifilepathcomponent.h ${CMAKE_CURRENT_SOURCE_DIR}/include/guiglobebrowsingcomponent.h ${CMAKE_CURRENT_SOURCE_DIR}/include/guihelpcomponent.h + ${CMAKE_CURRENT_SOURCE_DIR}/include/guijoystickcomponent.h ${CMAKE_CURRENT_SOURCE_DIR}/include/guimissioncomponent.h ${CMAKE_CURRENT_SOURCE_DIR}/include/guiperformancecomponent.h ${CMAKE_CURRENT_SOURCE_DIR}/include/guiparallelcomponent.h @@ -51,6 +52,7 @@ set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/guifilepathcomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guiglobebrowsingcomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guihelpcomponent.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/guijoystickcomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guimissioncomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guiperformancecomponent.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/guiparallelcomponent.cpp diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index 9d1dda9c23..0f8acadadd 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -31,9 +31,9 @@ #include #include #include -#include #include #include +#include #include #include #include diff --git a/modules/imgui/include/gui.h b/modules/imgui/include/gui.h index f4646ec0ef..4626ea1cd6 100644 --- a/modules/imgui/include/gui.h +++ b/modules/imgui/include/gui.h @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -87,6 +88,7 @@ public: #ifdef OPENSPACE_MODULE_ISWA_ENABLED GuiIswaComponent _iswa; #endif // OPENSPACE_MODULE_ISWA_ENABLED + GuiJoystickComponent _joystick; GuiParallelComponent _parallel; GuiPropertyComponent _featuredProperties; diff --git a/src/interaction/controller.cpp b/modules/imgui/include/guijoystickcomponent.h similarity index 83% rename from src/interaction/controller.cpp rename to modules/imgui/include/guijoystickcomponent.h index 0b52cf7cf1..9b891d00e9 100644 --- a/src/interaction/controller.cpp +++ b/modules/imgui/include/guijoystickcomponent.h @@ -22,15 +22,20 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#ifndef __OPENSPACE_MODULE_IMGUI___GUIJOYSTICKCOMPONENT___H__ +#define __OPENSPACE_MODULE_IMGUI___GUIJOYSTICKCOMPONENT___H__ -#include +#include -namespace openspace::interaction { +namespace openspace::gui { -void Controller::setHandler(NavigationHandler* handler) { - _handler = handler; -} +class GuiJoystickComponent : public GuiComponent { +public: + GuiJoystickComponent(); -} // namespace openspace::interaction + void render() override; +}; +} // namespace openspace::gui + +#endif // __OPENSPACE_MODULE_IMGUI___GUIJOYSTICKCOMPONENT___H__ diff --git a/modules/imgui/src/gui.cpp b/modules/imgui/src/gui.cpp index 0e1ec88796..032080ef21 100644 --- a/modules/imgui/src/gui.cpp +++ b/modules/imgui/src/gui.cpp @@ -160,60 +160,6 @@ static void RenderDrawLists(ImDrawData* drawData) { } } - - //// Grow our buffer according to what we need - //size_t totalVertexCount = 0; - //for (int i = 0; i < nCommandLists; ++i) - // totalVertexCount += commandLists[i]->vtx_buffer.size(); - - //glBindBuffer(GL_ARRAY_BUFFER, vbo); - //size_t neededBufferSize = totalVertexCount * sizeof(ImDrawVert); - //if (neededBufferSize > vboMaxSize) { - // // Grow buffer - // vboMaxSize = neededBufferSize * 1.25f; - // glBufferData(GL_ARRAY_BUFFER, vboMaxSize, NULL, GL_STREAM_DRAW); - //} - - //// Copy and convert all vertices into a single contiguous buffer - //unsigned char* bufferData = reinterpret_cast( - // glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY) - // ); - - //if (!bufferData) { - // LFATAL("Error mapping ImGui buffer"); - // return; - //} - - //for (int i = 0; i < nCommandLists; ++i) { - // const ImDrawList* cmd_list = commandLists[i]; - // memcpy( - // bufferData, - // &cmd_list->vtx_buffer[0], - // cmd_list->vtx_buffer.size() * sizeof(ImDrawVert) - // ); - // bufferData += (cmd_list->vtx_buffer.size() * sizeof(ImDrawVert)); - //} - //glUnmapBuffer(GL_ARRAY_BUFFER); - //glBindBuffer(GL_ARRAY_BUFFER, 0); - //glBindVertexArray(vao); - - //int cmdOffset = 0; - //for (int i = 0; i < nCommandLists; ++i) { - // const ImDrawList* cmd_list = commandLists[i]; - // int vtxOffset = cmdOffset; - // for (const auto& pcmd : cmd_list->commands) { - // glScissor( - // static_cast(pcmd.clip_rect.x), - // static_cast(height - pcmd.clip_rect.w), - // static_cast(pcmd.clip_rect.z - pcmd.clip_rect.x), - // static_cast(pcmd.clip_rect.w - pcmd.clip_rect.y) - // ); - // glDrawArrays(GL_TRIANGLES, vtxOffset, pcmd.vtx_count); - // vtxOffset += pcmd.vtx_count; - // } - // cmdOffset = vtxOffset; - //} - glBindVertexArray(0); _program->deactivate(); glDisable(GL_SCISSOR_TEST); @@ -310,6 +256,7 @@ GUI::GUI() #ifdef GLOBEBROWSING_USE_GDAL addPropertySubOwner(_globeBrowsing); #endif // GLOBEBROWSING_USE_GDAL + addPropertySubOwner(_joystick); addPropertySubOwner(_filePath); addPropertySubOwner(_asset); _spaceTime.setEnabled(true); @@ -337,6 +284,7 @@ GUI::GUI() #ifdef OPENSPACE_MODULE_ISWA_ENABLED _iswa.setShowHelpTooltip(_showHelpText); #endif // OPENSPACE_MODULE_ISWA_ENABLED + _joystick.setShowHelpTooltip(_showHelpText); _parallel.setShowHelpTooltip(_showHelpText); _featuredProperties.setShowHelpTooltip(_showHelpText); }; @@ -363,6 +311,7 @@ GUI::GUI() #ifdef OPENSPACE_MODULE_ISWA_ENABLED _iswa.setShowHelpTooltipDelay(_helpTextDelay); #endif // OPENSPACE_MODULE_ISWA_ENABLED + _joystick.setShowHelpTooltipDelay(_helpTextDelay); _parallel.setShowHelpTooltipDelay(_helpTextDelay); _featuredProperties.setShowHelpTooltipDelay(_helpTextDelay); }; @@ -502,6 +451,7 @@ void GUI::initialize() { #ifdef GLOBEBROWSING_USE_GDAL _globeBrowsing.initialize(); #endif // GLOBEBROWSING_USE_GDAL + _joystick.initialize(); _performance.initialize(); _help.initialize(); _parallel.initialize(); @@ -525,6 +475,7 @@ void GUI::deinitialize() { _mission.deinitialize(); _parallel.deinitialize(); _help.deinitialize(); + _joystick.deinitialize(); _performance.deinitialize(); _globalProperty.deinitialize(); _moduleProperty.deinitialize(); @@ -629,6 +580,7 @@ void GUI::initializeGL() { _globalProperty.initializeGL(); _moduleProperty.initializeGL(); _featuredProperties.initializeGL(); + _joystick.initializeGL(); _performance.initializeGL(); _help.initializeGL(); #ifdef GLOBEBROWSING_USE_GDAL @@ -667,6 +619,7 @@ void GUI::deinitializeGL() { _performance.deinitializeGL(); _featuredProperties.deinitializeGL(); _globalProperty.deinitializeGL(); + _joystick.deinitializeGL(); _moduleProperty.deinitializeGL(); _screenSpaceProperty.deinitializeGL(); #ifdef GLOBEBROWSING_USE_GDAL @@ -744,6 +697,11 @@ void GUI::endFrame() { _iswa.render(); } #endif // OPENSPACE_MODULE_ISWA_ENABLED + + if (_joystick.isEnabled()) { + _joystick.render(); + } + if (_filePath.isEnabled()) { _filePath.render(); } @@ -883,6 +841,10 @@ void GUI::render() { ImGui::Checkbox("Mission Information", &mission); _mission.setEnabled(mission); + bool joystick = _joystick.isEnabled(); + ImGui::Checkbox("Joystick Information", &joystick); + _joystick.setEnabled(joystick); + bool filePath = _filePath.isEnabled(); ImGui::Checkbox("File Paths", &filePath); _filePath.setEnabled(filePath); diff --git a/modules/imgui/src/guijoystickcomponent.cpp b/modules/imgui/src/guijoystickcomponent.cpp new file mode 100644 index 0000000000..03c49fdbd6 --- /dev/null +++ b/modules/imgui/src/guijoystickcomponent.cpp @@ -0,0 +1,111 @@ +/***************************************************************************************** + * * + * 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 + +namespace { + const ImVec2 Size = ImVec2(350, 500); +} // namespace + +namespace openspace::gui { + +GuiJoystickComponent::GuiJoystickComponent() + : GuiComponent("joystick_information", "Joystick Information") +{} + +void GuiJoystickComponent::render() { + using namespace interaction; + + ImGui::SetNextWindowCollapsed(_isCollapsed); + + bool v = _isEnabled; + ImGui::Begin("Joystick Information", &v, Size, 0.5f); + _isEnabled = v; + _isCollapsed = ImGui::IsWindowCollapsed(); + + const JoystickInputStates& states = + OsEng.navigationHandler().inputState().joystickInputStates(); + + for (int i = 0; i < states.size(); ++i) { + const JoystickInputState& state = states[i]; + if (!state.isConnected) { + continue; + } + + ImGui::Text("%s [%i]", state.name.c_str(), i); + ImGui::Text("%s", "Axes"); + for (int j = 0; j < state.nAxes; ++j) { + float f = state.axes[j]; + ImGui::SliderFloat( + std::to_string(j).c_str(), + &f, + -1.f, + 1.f + ); + } + ImGui::Text("%s", "Buttons"); + for (int j = 0; j < state.nButtons; ++j) { + ImGui::RadioButton( + std::to_string(j).c_str(), + state.buttons[j] == JoystickAction::Press || + state.buttons[j] == JoystickAction::Repeat + ); + } + + ImGui::Separator(); + } + + ImGui::Separator(); + ImGui::Separator(); + + ImGui::Text("%s", "Summed contributions"); + ImGui::Text("%s", "Axes"); + for (int i = 0; i < JoystickInputState::MaxAxes; ++i) { + float f = states.axis(i); + ImGui::SliderFloat( + std::to_string(i).c_str(), + &f, + -1.f, + 1.f + ); + } + ImGui::Text("%s", "Buttons"); + 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) + ); + } + + ImGui::End(); +} + +} // namespace openspace::gui diff --git a/modules/server/src/topics/getpropertytopic.cpp b/modules/server/src/topics/getpropertytopic.cpp index d9e1c2387f..c109634d41 100644 --- a/modules/server/src/topics/getpropertytopic.cpp +++ b/modules/server/src/topics/getpropertytopic.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e592f4d3e2..e1821936f3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -42,15 +42,16 @@ set(OPENSPACE_SOURCE ${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/controller.cpp + ${OPENSPACE_BASE_DIR}/src/interaction/camerainteractionstates.cpp ${OPENSPACE_BASE_DIR}/src/interaction/inputstate.cpp + ${OPENSPACE_BASE_DIR}/src/interaction/joystickinputstate.cpp + ${OPENSPACE_BASE_DIR}/src/interaction/joystickcamerastates.cpp ${OPENSPACE_BASE_DIR}/src/interaction/keybindingmanager.cpp ${OPENSPACE_BASE_DIR}/src/interaction/keybindingmanager_lua.inl ${OPENSPACE_BASE_DIR}/src/interaction/keyframenavigator.cpp - ${OPENSPACE_BASE_DIR}/src/interaction/luaconsole.cpp ${OPENSPACE_BASE_DIR}/src/interaction/navigationhandler.cpp ${OPENSPACE_BASE_DIR}/src/interaction/navigationhandler_lua.inl - ${OPENSPACE_BASE_DIR}/src/interaction/mousestate.cpp + ${OPENSPACE_BASE_DIR}/src/interaction/mousecamerastates.cpp ${OPENSPACE_BASE_DIR}/src/interaction/orbitalnavigator.cpp ${OPENSPACE_BASE_DIR}/src/mission/mission.cpp ${OPENSPACE_BASE_DIR}/src/mission/missionmanager.cpp @@ -128,6 +129,7 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/rendering/framebufferrenderer.cpp ${OPENSPACE_BASE_DIR}/src/rendering/deferredcastermanager.cpp ${OPENSPACE_BASE_DIR}/src/rendering/loadingscreen.cpp + ${OPENSPACE_BASE_DIR}/src/rendering/luaconsole.cpp ${OPENSPACE_BASE_DIR}/src/rendering/raycastermanager.cpp ${OPENSPACE_BASE_DIR}/src/rendering/renderable.cpp ${OPENSPACE_BASE_DIR}/src/rendering/renderengine.cpp @@ -209,16 +211,17 @@ set(OPENSPACE_HEADER ${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/interaction/controller.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 ${OPENSPACE_BASE_DIR}/include/openspace/interaction/inputstate.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/interpolator.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/interpolator.inl + ${OPENSPACE_BASE_DIR}/include/openspace/interaction/joystickinputstate.h + ${OPENSPACE_BASE_DIR}/include/openspace/interaction/joystickcamerastates.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/keybindingmanager.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/keyframenavigator.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/luaconsole.h - ${OPENSPACE_BASE_DIR}/include/openspace/interaction/mousestate.h + ${OPENSPACE_BASE_DIR}/include/openspace/interaction/mousecamerastates.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/navigationhandler.h ${OPENSPACE_BASE_DIR}/include/openspace/interaction/orbitalnavigator.h ${OPENSPACE_BASE_DIR}/include/openspace/mission/mission.h @@ -305,6 +308,7 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/rendering/deferredcasterlistener.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/deferredcastermanager.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/loadingscreen.h + ${OPENSPACE_BASE_DIR}/include/openspace/rendering/luaconsole.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/raycasterlistener.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/raycastermanager.h ${OPENSPACE_BASE_DIR}/include/openspace/rendering/renderable.h diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index a34b2252ac..ddbea6a0e9 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -35,9 +35,8 @@ #include #include #include -#include #include -#include +#include #include #include @@ -46,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -293,7 +293,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Parse commandline arguments std::vector args(argv, argv + argc); - const std::vector& arguments = + std::vector arguments = _engine->_commandlineParser->setCommandLine(args); bool showHelp = _engine->_commandlineParser->execute(); @@ -302,8 +302,8 @@ void OpenSpaceEngine::create(int argc, char** argv, requestClose = true; return; } - std::vector argumentsCopy = arguments; - sgctArguments = std::move(argumentsCopy); + + sgctArguments = std::move(arguments); // Find configuration std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName; @@ -1283,7 +1283,7 @@ void OpenSpaceEngine::preSynchronization() { } _renderEngine->updateScene(); - _navigationHandler->updateCamera(dt); + //_navigationHandler->updateCamera(dt); Camera* camera = _renderEngine->camera(); if (camera) { @@ -1510,6 +1510,10 @@ void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY) { _navigationHandler->mouseScrollWheelCallback(posY); } +void OpenSpaceEngine::setJoystickInputStates(interaction::JoystickInputStates& states) { + _navigationHandler->setJoystickInputStates(states); +} + void OpenSpaceEngine::encode() { _syncEngine->encodeSyncables(); diff --git a/src/interaction/camerainteractionstates.cpp b/src/interaction/camerainteractionstates.cpp new file mode 100644 index 0000000000..ae0af29f03 --- /dev/null +++ b/src/interaction/camerainteractionstates.cpp @@ -0,0 +1,101 @@ +/***************************************************************************************** + * * + * 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 + +namespace openspace::interaction { + +CameraInteractionStates::InteractionState::InteractionState(double scaleFactor) + : previousPosition(0.0, 0.0) + , velocity(scaleFactor, 1) +{} + +void CameraInteractionStates::InteractionState::setFriction(double friction) { + velocity.setFriction(friction); +} + +void CameraInteractionStates::InteractionState::setVelocityScaleFactor(double scaleFactor) +{ + velocity.setScaleFactor(scaleFactor); +} + +CameraInteractionStates::CameraInteractionStates(double sensitivity, + double velocityScaleFactor) + : _sensitivity(sensitivity) + , _globalRotationState(velocityScaleFactor) + , _localRotationState(velocityScaleFactor) + , _truckMovementState(velocityScaleFactor) + , _localRollState(velocityScaleFactor) + , _globalRollState(velocityScaleFactor) +{} + +void CameraInteractionStates::setRotationalFriction(double friction) { + _localRotationState.setFriction(friction); + _localRollState.setFriction(friction); + _globalRollState.setFriction(friction); +} + +void CameraInteractionStates::setHorizontalFriction(double friction) { + _globalRotationState.setFriction(friction); +} + +void CameraInteractionStates::setVerticalFriction(double friction) { + _truckMovementState.setFriction(friction); +} + +void CameraInteractionStates::setSensitivity(double sensitivity) { + _sensitivity = sensitivity; +} + +void CameraInteractionStates::setVelocityScaleFactor(double scaleFactor) { + _globalRotationState.setVelocityScaleFactor(scaleFactor); + _localRotationState.setVelocityScaleFactor(scaleFactor); + _truckMovementState.setVelocityScaleFactor(scaleFactor); + _localRollState.setVelocityScaleFactor(scaleFactor); + _globalRollState.setVelocityScaleFactor(scaleFactor); +} + +glm::dvec2 CameraInteractionStates::globalRotationVelocity() const{ + return _globalRotationState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::localRotationVelocity() const{ + return _localRotationState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::truckMovementVelocity() const{ + return _truckMovementState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::localRollVelocity() const{ + return _localRollState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::globalRollVelocity() const{ + return _globalRollState.velocity.get(); +} + +} // namespace openspace::interaction diff --git a/src/interaction/inputdevicestates.cpp b/src/interaction/inputdevicestates.cpp new file mode 100644 index 0000000000..9b1f05e8a7 --- /dev/null +++ b/src/interaction/inputdevicestates.cpp @@ -0,0 +1,101 @@ +/***************************************************************************************** + * * + * 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 + +namespace openspace::interaction { + +CameraInteractionStates::InteractionState::InteractionState(double scaleFactor) + : previousPosition(0.0, 0.0) + , velocity(scaleFactor, 1) +{} + +void CameraInteractionStates::InteractionState::setFriction(double friction) { + velocity.setFriction(friction); +} + +void CameraInteractionStates::InteractionState::setVelocityScaleFactor(double scaleFactor) +{ + velocity.setScaleFactor(scaleFactor); +} + +CameraInteractionStates::CameraInteractionStates(double sensitivity, + double velocityScaleFactor) + : _sensitivity(sensitivity) + , _globalRotationState(velocityScaleFactor) + , _localRotationState(velocityScaleFactor) + , _truckMovementState(velocityScaleFactor) + , _localRollState(velocityScaleFactor) + , _globalRollState(velocityScaleFactor) +{} + +void CameraInteractionStates::setRotationalFriction(double friction) { + _localRotationState.setFriction(friction); + _localRollState.setFriction(friction); + _globalRollState.setFriction(friction); +} + +void CameraInteractionStates::setHorizontalFriction(double friction) { + _globalRotationState.setFriction(friction); +} + +void CameraInteractionStates::setVerticalFriction(double friction) { + _truckMovementState.setFriction(friction); +} + +void CameraInteractionStates::setSensitivity(double sensitivity) { + _sensitivity = sensitivity; +} + +void CameraInteractionStates::setVelocityScaleFactor(double scaleFactor) { + _globalRotationState.setVelocityScaleFactor(scaleFactor); + _localRotationState.setVelocityScaleFactor(scaleFactor); + _truckMovementState.setVelocityScaleFactor(scaleFactor); + _localRollState.setVelocityScaleFactor(scaleFactor); + _globalRollState.setVelocityScaleFactor(scaleFactor); +} + +glm::dvec2 CameraInteractionStates::globalRotationVelocity() const{ + return _globalRotationState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::localRotationVelocity() const{ + return _localRotationState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::truckMovementVelocity() const{ + return _truckMovementState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::localRollVelocity() const{ + return _localRollState.velocity.get(); +} + +glm::dvec2 CameraInteractionStates::globalRollVelocity() const{ + return _globalRollState.velocity.get(); +} + +} // namespace openspace::interaction diff --git a/src/interaction/inputstate.cpp b/src/interaction/inputstate.cpp index d22c2619b6..4976263f0b 100644 --- a/src/interaction/inputstate.cpp +++ b/src/interaction/inputstate.cpp @@ -24,8 +24,8 @@ #include +#include #include - #include namespace openspace::interaction { @@ -46,9 +46,7 @@ void InputState::mouseButtonCallback(MouseButton button, MouseAction action) { _mouseButtonsDown.push_back(button); } else if (action == MouseAction::Release) { - // Remove all key pressings for 'button' - _mouseButtonsDown.remove_if([button](MouseButton buttonInList) - { return button == buttonInList; }); + _mouseButtonsDown.remove(button); } } @@ -60,19 +58,23 @@ void InputState::mouseScrollWheelCallback(double mouseScrollDelta) { _mouseScrollDelta = mouseScrollDelta; } -const std::list >& InputState::getPressedKeys() const { +void InputState::setJoystickInputStates(JoystickInputStates& states) { + _joystickInputStates = &states; +} + +const std::list>& InputState::pressedKeys() const { return _keysDown; } -const std::list& InputState::getPressedMouseButtons() const { +const std::list& InputState::pressedMouseButtons() const { return _mouseButtonsDown; } -glm::dvec2 InputState::getMousePosition() const { +glm::dvec2 InputState::mousePosition() const { return _mousePosition; } -double InputState::getMouseScrollDelta() const { +double InputState::mouseScrollDelta() const { return _mouseScrollDelta; } @@ -92,4 +94,16 @@ bool InputState::isMouseButtonPressed(MouseButton mouseButton) const { mouseButton) != _mouseButtonsDown.end(); } +const JoystickInputStates& InputState::joystickInputStates() const { + return *_joystickInputStates; +} + +float InputState::joystickAxis(int i) const { + return _joystickInputStates->axis(i); +} + +bool InputState::joystickButton(int i) const{ + return _joystickInputStates->button(i, JoystickAction::Press); +} + } // namespace openspace::interaction diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp new file mode 100644 index 0000000000..6309dfff5b --- /dev/null +++ b/src/interaction/joystickcamerastates.cpp @@ -0,0 +1,272 @@ +/***************************************************************************************** + * * + * 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 + +namespace openspace::interaction { + +JoystickCameraStates::JoystickCameraStates(double sensitivity, double velocityScaleFactor) + : CameraInteractionStates(sensitivity, velocityScaleFactor) +{} + +void JoystickCameraStates::updateStateFromInput(const InputState& inputState, + double deltaTime) +{ + std::pair globalRotation = { false, glm::dvec2(0.0) }; + std::pair zoom = { false, 0.0 }; + std::pair localRoll = { false, glm::dvec2(0.0) }; + std::pair globalRoll = { false, glm::dvec2(0.0) }; + std::pair localRotation = { false, glm::dvec2(0.0) }; + + for (int i = 0; i < JoystickInputState::MaxAxes; ++i) { + AxisInformation t = _axisMapping[i]; + if (t.type == AxisType::None) { + continue; + } + + bool hasValue = true; + float value = inputState.joystickAxis(i); + + if (abs(value) <= t.deadzone) { + value = 0.f; + hasValue = false; + } + + if (t.normalize) { + value = (value + 1.f) / 2.f; + } + + if (t.invert) { + value *= -1.f; + } + + value *= _sensitivity; + + switch (t.type) { + case AxisType::None: + break; + case AxisType::OrbitX: + globalRotation.first = hasValue; + globalRotation.second.x = value; + break; + case AxisType::OrbitY: + globalRotation.first = hasValue; + globalRotation.second.y = value; + break; + case AxisType::ZoomIn: + zoom.first = hasValue; + zoom.second += value; + break; + case AxisType::ZoomOut: + zoom.first = hasValue; + zoom.second -= value; + break; + case AxisType::LocalRollX: + localRoll.first = hasValue; + localRoll.second.x = value; + break; + case AxisType::LocalRollY: + localRoll.first = hasValue; + localRoll.second.y = value; + break; + case AxisType::GlobalRollX: + globalRoll.first = hasValue; + globalRoll.second.x = value; + break; + case AxisType::GlobalRollY: + globalRoll.first = hasValue; + globalRoll.second.y = value; + break; + case AxisType::PanX: + localRotation.first = hasValue; + localRotation.second.x = value; + break; + case AxisType::PanY: + localRotation.first = hasValue; + localRotation.second.y = value; + break; + } + } + + if (globalRotation.first) { + _globalRotationState.velocity.set(globalRotation.second, deltaTime); + } + else { + _globalRotationState.velocity.decelerate(deltaTime); + } + + if (zoom.first) { + _truckMovementState.velocity.set(glm::dvec2(zoom.second), deltaTime); + } + else { + _truckMovementState.velocity.decelerate(deltaTime); + } + + if (localRoll.first) { + _localRollState.velocity.set(localRoll.second, deltaTime); + } + else { + _localRollState.velocity.decelerate(deltaTime); + } + + if (globalRoll.first) { + _globalRollState.velocity.set(globalRoll.second, deltaTime); + } + else { + _globalRollState.velocity.decelerate(deltaTime); + } + + if (localRotation.first) { + _localRotationState.velocity.set(localRotation.second, deltaTime); + } + else { + _localRotationState.velocity.decelerate(deltaTime); + } + + + 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); + + if (active) { + OsEng.scriptEngine().queueScript( + it->second.command, + scripting::ScriptEngine::RemoteScripting(it->second.synchronization) + ); + } + } + } +} + +void JoystickCameraStates::setAxisMapping(int axis, AxisType mapping, + AxisInvert shouldInvert, + AxisNormalize shouldNormalize) +{ + ghoul_assert(axis < JoystickInputState::MaxAxes, "axis must be < MaxAxes"); + + _axisMapping[axis] = { mapping, shouldInvert, shouldNormalize }; +} + +JoystickCameraStates::AxisInformation JoystickCameraStates::axisMapping(int axis) const { + return _axisMapping[axis]; +} + +void JoystickCameraStates::setDeadzone(int axis, float deadzone) { + _axisMapping[axis].deadzone = deadzone; +} + +float JoystickCameraStates::deadzone(int axis) const { + return _axisMapping[axis].deadzone; +} + +void JoystickCameraStates::bindButtonCommand(int button, std::string command, + JoystickAction action, + ButtonCommandRemote remote) +{ + _buttonMapping.insert({ + button, + { std::move(command), action, remote } + }); +} + +void JoystickCameraStates::clearButtonCommand(int button) { + for (auto it = _buttonMapping.begin(); it != _buttonMapping.end();) { + // If the current iterator is the button that we are looking for, delete it + // (std::multimap::erase will return the iterator to the next element for us) + if (it->first == button) { + it = _buttonMapping.erase(it); + } + else { + ++it; + } + } +} + +std::vector JoystickCameraStates::buttonCommand(int button) const { + std::vector result; + auto itRange = _buttonMapping.equal_range(button); + for (auto it = itRange.first; it != itRange.second; ++it) { + result.push_back(it->second.command); + } + return result; +} + + +} // namespace openspace::interaction + +namespace std { + +std::string to_string(const openspace::interaction::JoystickCameraStates::AxisType& type) +{ + using T = openspace::interaction::JoystickCameraStates::AxisType; + switch (type) { + case T::None: return "None"; + case T::OrbitX: return "Orbit X"; + case T::OrbitY: return "Orbit Y"; + case T::ZoomIn: return "Zoom In"; + case T::ZoomOut: return "Zoom Out"; + case T::LocalRollX: return "LocalRoll X"; + case T::LocalRollY: return "LocalRoll Y"; + case T::GlobalRollX: return "GlobalRoll X"; + case T::GlobalRollY: return "GlobalRoll Y"; + case T::PanX: return "Pan X"; + case T::PanY: return "Pan Y"; + default: return ""; + } +} + +} // namespace std + +namespace ghoul { + +template <> +openspace::interaction::JoystickCameraStates::AxisType from_string( + const std::string& string) +{ + using T = openspace::interaction::JoystickCameraStates::AxisType; + + static const std::map Map = { + { "None", T::None }, + { "Orbit X", T::OrbitX }, + { "Orbit Y", T::OrbitY }, + { "Zoom In", T::ZoomIn }, + { "Zoom Out", T::ZoomOut }, + { "LocalRoll X", T::LocalRollX }, + { "LocalRoll Y", T::LocalRollY }, + { "GlobalRoll X", T::GlobalRollX }, + { "GlobalRoll Y", T::GlobalRollY }, + { "Pan X", T::PanX }, + { "Pan Y", T::PanY } + }; + + return Map.at(string); +} + +} // namespace ghoul diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp new file mode 100644 index 0000000000..a3c9ebaf5d --- /dev/null +++ b/src/interaction/joystickinputstate.cpp @@ -0,0 +1,100 @@ +/***************************************************************************************** + * * + * 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 + +namespace openspace::interaction { + +float JoystickInputStates::axis(int axis) const { + ghoul_precondition(axis >= 0, "axis must be 0 or positive"); + + float res = std::accumulate( + begin(), + end(), + 0.f, + [axis](float value, const JoystickInputState& state) { + if (state.isConnected) { + value += state.axes[axis]; + } + return value; + } + ); + + // If multiple joysticks are connected, we might get values outside the -1,1 range by + // summing them up + glm::clamp(res, -1.f, 1.f); + return res; +} + +bool JoystickInputStates::button(int button, JoystickAction action) const { + ghoul_precondition(button >= 0, "button must be 0 or positive"); + + bool res = std::any_of( + begin(), + end(), + [button, action](const JoystickInputState& state) { + return state.isConnected ? (state.buttons[button] == action) : false; + } + ); + return res; +} + +} // namespace openspace::interaction + +namespace std { + +std::string to_string(openspace::interaction::JoystickAction action) { + switch (action) { + case openspace::interaction::JoystickAction::Idle: return "Idle"; + case openspace::interaction::JoystickAction::Press: return "Press"; + case openspace::interaction::JoystickAction::Repeat: return "Repeat"; + case openspace::interaction::JoystickAction::Release: return "Release"; + default: return ""; + } +} + +} // namespace std + +namespace ghoul { + +template <> +openspace::interaction::JoystickAction from_string(const std::string& string) { + static const std::map Map = { + { "Idle", openspace::interaction::JoystickAction::Idle }, + { "Press", openspace::interaction::JoystickAction::Press }, + { "Repeat", openspace::interaction::JoystickAction::Repeat }, + { "Release", openspace::interaction::JoystickAction::Release } + }; + + return Map.at(string); + +} + +} // namespace ghoul diff --git a/src/interaction/luaconsole.cpp b/src/interaction/luaconsole.cpp index d87905c31c..bb04359b78 100644 --- a/src/interaction/luaconsole.cpp +++ b/src/interaction/luaconsole.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include diff --git a/src/interaction/mousecamerastates.cpp b/src/interaction/mousecamerastates.cpp new file mode 100644 index 0000000000..c79edcf343 --- /dev/null +++ b/src/interaction/mousecamerastates.cpp @@ -0,0 +1,125 @@ +/***************************************************************************************** + * * + * 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 + +namespace openspace::interaction { + +MouseCameraStates::MouseCameraStates(double sensitivity, double velocityScaleFactor) + : CameraInteractionStates(sensitivity, velocityScaleFactor) +{} + +void MouseCameraStates::updateStateFromInput(const InputState& inputState, double deltaTime) { + glm::dvec2 mousePosition = inputState.mousePosition(); + + bool button1Pressed = inputState.isMouseButtonPressed(MouseButton::Button1); + bool button2Pressed = inputState.isMouseButtonPressed(MouseButton::Button2); + bool button3Pressed = inputState.isMouseButtonPressed(MouseButton::Button3); + bool keyCtrlPressed = inputState.isKeyPressed(Key::LeftControl) | + inputState.isKeyPressed(Key::RightControl); + bool keyShiftPressed = inputState.isKeyPressed(Key::LeftShift) | + inputState.isKeyPressed(Key::RightShift); + bool keyAltPressed = inputState.isKeyPressed(Key::LeftAlt) | + inputState.isKeyPressed(Key::RightAlt); + + // Update the mouse states + if (button1Pressed && !keyShiftPressed && !keyAltPressed) { + if (keyCtrlPressed) { + glm::dvec2 mousePositionDelta = + _localRotationState.previousPosition - mousePosition; + _localRotationState.velocity.set( + mousePositionDelta * _sensitivity, + deltaTime + ); + + _globalRotationState.previousPosition = mousePosition; + _globalRotationState.velocity.decelerate(deltaTime); + } + else { + glm::dvec2 mousePositionDelta = + _globalRotationState.previousPosition - mousePosition; + _globalRotationState.velocity.set( + mousePositionDelta * _sensitivity, + deltaTime + ); + + _localRotationState.previousPosition = mousePosition; + _localRotationState.velocity.decelerate(deltaTime); + } + } + else { // !button1Pressed + _localRotationState.previousPosition = mousePosition; + _localRotationState.velocity.decelerate(deltaTime); + + _globalRotationState.previousPosition = mousePosition; + _globalRotationState.velocity.decelerate(deltaTime); + } + if (button2Pressed || (keyAltPressed && button1Pressed)) { + glm::dvec2 mousePositionDelta = + _truckMovementState.previousPosition - mousePosition; + _truckMovementState.velocity.set( + mousePositionDelta * _sensitivity, + deltaTime + ); + } + else { // !button2Pressed + _truckMovementState.previousPosition = mousePosition; + _truckMovementState.velocity.decelerate(deltaTime); + } + if (button3Pressed || (keyShiftPressed && button1Pressed)) { + if (keyCtrlPressed) { + glm::dvec2 mousePositionDelta = + _localRollState.previousPosition - mousePosition; + _localRollState.velocity.set( + mousePositionDelta * _sensitivity, + deltaTime + ); + + _globalRollState.previousPosition = mousePosition; + _globalRollState.velocity.decelerate(deltaTime); + } + else { + glm::dvec2 mousePositionDelta = + _globalRollState.previousPosition - mousePosition; + _globalRollState.velocity.set( + mousePositionDelta * _sensitivity, + deltaTime + ); + + _localRollState.previousPosition = mousePosition; + _localRollState.velocity.decelerate(deltaTime); + } + } + else { // !button3Pressed + _globalRollState.previousPosition = mousePosition; + _globalRollState.velocity.decelerate(deltaTime); + + _localRollState.previousPosition = mousePosition; + _localRollState.velocity.decelerate(deltaTime); + } +} + +} // namespace openspace::interaction diff --git a/src/interaction/mousestate.cpp b/src/interaction/mousestate.cpp deleted file mode 100644 index 9325eaf650..0000000000 --- a/src/interaction/mousestate.cpp +++ /dev/null @@ -1,179 +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 - -namespace openspace::interaction { - -MouseState::MouseState(double scaleFactor) - : previousPosition(0.0, 0.0) - , velocity(scaleFactor, 1) -{} - -void MouseState::setFriction(double friction) { - velocity.setFriction(friction); -} - -void MouseState::setVelocityScaleFactor(double scaleFactor) { - velocity.setScaleFactor(scaleFactor); -} - -MouseStates::MouseStates(double sensitivity, double velocityScaleFactor) - : _sensitivity(sensitivity) - , _globalRotationMouseState(velocityScaleFactor) - , _localRotationMouseState(velocityScaleFactor) - , _truckMovementMouseState(velocityScaleFactor) - , _localRollMouseState(velocityScaleFactor) - , _globalRollMouseState(velocityScaleFactor) -{ } - -void MouseStates::updateMouseStatesFromInput(const InputState& inputState, - double deltaTime) -{ - glm::dvec2 mousePosition = inputState.getMousePosition(); - - bool button1Pressed = inputState.isMouseButtonPressed(MouseButton::Button1); - bool button2Pressed = inputState.isMouseButtonPressed(MouseButton::Button2); - bool button3Pressed = inputState.isMouseButtonPressed(MouseButton::Button3); - bool keyCtrlPressed = inputState.isKeyPressed(Key::LeftControl) | - inputState.isKeyPressed(Key::RightControl); - bool keyShiftPressed = inputState.isKeyPressed(Key::LeftShift) | - inputState.isKeyPressed(Key::RightShift); - bool keyAltPressed = inputState.isKeyPressed(Key::LeftAlt) | - inputState.isKeyPressed(Key::RightAlt); - - // Update the mouse states - if (button1Pressed && !keyShiftPressed && !keyAltPressed) { - if (keyCtrlPressed) { - glm::dvec2 mousePositionDelta = - _localRotationMouseState.previousPosition - mousePosition; - _localRotationMouseState.velocity.set( - mousePositionDelta * _sensitivity, deltaTime); - - _globalRotationMouseState.previousPosition = mousePosition; - _globalRotationMouseState.velocity.decelerate(deltaTime); - } - else { - glm::dvec2 mousePositionDelta = - _globalRotationMouseState.previousPosition - mousePosition; - _globalRotationMouseState.velocity.set( - mousePositionDelta * _sensitivity, deltaTime); - - _localRotationMouseState.previousPosition = mousePosition; - _localRotationMouseState.velocity.decelerate(deltaTime); - } - } - else { // !button1Pressed - _localRotationMouseState.previousPosition = mousePosition; - _localRotationMouseState.velocity.decelerate(deltaTime); - - _globalRotationMouseState.previousPosition = mousePosition; - _globalRotationMouseState.velocity.decelerate(deltaTime); - } - if (button2Pressed || (keyAltPressed && button1Pressed)) { - glm::dvec2 mousePositionDelta = - _truckMovementMouseState.previousPosition - mousePosition; - _truckMovementMouseState.velocity.set( - mousePositionDelta * _sensitivity, deltaTime); - } - else { // !button2Pressed - _truckMovementMouseState.previousPosition = mousePosition; - _truckMovementMouseState.velocity.decelerate(deltaTime); - } - if (button3Pressed || (keyShiftPressed && button1Pressed)) { - if (keyCtrlPressed) { - glm::dvec2 mousePositionDelta = - _localRollMouseState.previousPosition - mousePosition; - _localRollMouseState.velocity.set( - mousePositionDelta * _sensitivity, deltaTime); - - _globalRollMouseState.previousPosition = mousePosition; - _globalRollMouseState.velocity.decelerate(deltaTime); - } - else { - glm::dvec2 mousePositionDelta = - _globalRollMouseState.previousPosition - mousePosition; - _globalRollMouseState.velocity.set( - mousePositionDelta * _sensitivity, deltaTime); - - _localRollMouseState.previousPosition = mousePosition; - _localRollMouseState.velocity.decelerate(deltaTime); - } - } - else { // !button3Pressed - _globalRollMouseState.previousPosition = mousePosition; - _globalRollMouseState.velocity.decelerate(deltaTime); - - _localRollMouseState.previousPosition = mousePosition; - _localRollMouseState.velocity.decelerate(deltaTime); - } -} - -void MouseStates::setRotationalFriction(double friction) { - _localRotationMouseState.setFriction(friction); - _localRollMouseState.setFriction(friction); - _globalRollMouseState.setFriction(friction); -} - -void MouseStates::setHorizontalFriction(double friction) { - _globalRotationMouseState.setFriction(friction); -} - -void MouseStates::setVerticalFriction(double friction) { - _truckMovementMouseState.setFriction(friction); -} - -void MouseStates::setSensitivity(double sensitivity) { - _sensitivity = sensitivity; -} - -void MouseStates::setVelocityScaleFactor(double scaleFactor) { - _globalRotationMouseState.setVelocityScaleFactor(scaleFactor); - _localRotationMouseState.setVelocityScaleFactor(scaleFactor); - _truckMovementMouseState.setVelocityScaleFactor(scaleFactor); - _localRollMouseState.setVelocityScaleFactor(scaleFactor); - _globalRollMouseState.setVelocityScaleFactor(scaleFactor); -} - -glm::dvec2 MouseStates::globalRotationMouseVelocity() const{ - return _globalRotationMouseState.velocity.get(); -} - -glm::dvec2 MouseStates::localRotationMouseVelocity() const{ - return _localRotationMouseState.velocity.get(); -} - -glm::dvec2 MouseStates::truckMovementMouseVelocity() const{ - return _truckMovementMouseState.velocity.get(); -} - -glm::dvec2 MouseStates::localRollMouseVelocity() const{ - return _localRollMouseState.velocity.get(); -} - -glm::dvec2 MouseStates::globalRollMouseVelocity() const{ - return _globalRollMouseState.velocity.get(); -} - -} // namespace openspace::interaction diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index fb9631345a..2fff65ded4 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -153,8 +153,8 @@ void NavigationHandler::updateCamera(double deltaTime) { _keyframeNavigator->updateCamera(*_camera); } else { - _orbitalNavigator->updateMouseStatesFromInput(*_inputState, deltaTime); - _orbitalNavigator->updateCameraStateFromMouseStates(*_camera, deltaTime); + _orbitalNavigator->updateStatesFromInput(*_inputState, deltaTime); + _orbitalNavigator->updateCameraStateFromStates(*_camera, deltaTime); } _camera->setFocusPositionVec3(focusNode()->worldPosition()); } @@ -201,6 +201,10 @@ 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; @@ -226,7 +230,7 @@ void NavigationHandler::setCameraStateFromDictionary(const ghoul::Dictionary& ca cameraRotation.x, cameraRotation.y, cameraRotation.z, cameraRotation.w)); } -ghoul::Dictionary NavigationHandler::getCameraStateDictionary() { +ghoul::Dictionary NavigationHandler::cameraStateDictionary() { glm::dvec3 cameraPosition; glm::dquat quat; glm::dvec4 cameraRotation; @@ -248,7 +252,7 @@ void NavigationHandler::saveCameraStateToFile(const std::string& filepath) { std::string fullpath = absPath(filepath); LINFO(fmt::format("Saving camera position: {}", filepath)); - ghoul::Dictionary cameraDict = getCameraStateDictionary(); + ghoul::Dictionary cameraDict = cameraStateDictionary(); // TODO : Should get the camera state as a dictionary and save the dictionary to // a file in form of a lua state and not use ofstreams here. @@ -293,6 +297,52 @@ void NavigationHandler::restoreCameraStateFromFile(const std::string& filepath) } } +void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, + JoystickCameraStates::AxisInvert shouldInvert, + JoystickCameraStates::AxisNormalize shouldNormalize) +{ + _orbitalNavigator->joystickStates().setAxisMapping( + axis, + mapping, + shouldInvert, + shouldNormalize + ); +} + +JoystickCameraStates::AxisInformation NavigationHandler::joystickAxisMapping(int axis) const { + return _orbitalNavigator->joystickStates().axisMapping(axis); +} + +void NavigationHandler::setJoystickAxisDeadzone(int axis, float deadzone) { + _orbitalNavigator->joystickStates().setDeadzone(axis, deadzone); +} + +float NavigationHandler::joystickAxisDeadzone(int axis) const { + return _orbitalNavigator->joystickStates().deadzone(axis); +} + +void NavigationHandler::bindJoystickButtonCommand(int button, std::string command, + JoystickAction action, + JoystickCameraStates::ButtonCommandRemote remote) +{ + _orbitalNavigator->joystickStates().bindButtonCommand( + button, + std::move(command), + action, + remote + ); +} + +void NavigationHandler::clearJoystickButtonCommand(int button) { + _orbitalNavigator->joystickStates().clearButtonCommand(button); +} + +std::vector NavigationHandler::joystickButtonCommand(int button) const { + return _orbitalNavigator->joystickStates().buttonCommand(button); +} + + + scripting::LuaLibrary NavigationHandler::luaLibrary() { return { "navigation", @@ -324,6 +374,62 @@ scripting::LuaLibrary NavigationHandler::luaLibrary() { {}, "void", "Reset the camera direction to point at the focus node" + }, + { + "bindJoystickAxis", + &luascriptfunctions::bindJoystickAxis, + {}, + "int, axisType [, isInverted, isNormalized]", + "Binds the axis identified by the first argument to be used as the type " + "identified by the second argument. If 'isInverted' is 'true', the axis " + "value is inverted, if 'isNormalized' is true the axis value is " + "normalized from [-1, 1] to [0,1]." + }, + { + "joystickAxis", + &luascriptfunctions::joystickAxis, + {}, + "int", + "Returns the joystick axis information for the passed axis. The " + "information that is returned is the current axis binding as a string, " + "whether the values are inverted as bool, and whether the value are " + "normalized as a bool" + }, + { + "setAxisDeadZone", + &luascriptfunctions::setJoystickAxisDeadzone, + {}, + "int, float", + "Sets the deadzone for a particular joystick axis which means that any " + "input less than this value is completely ignored." + }, + { + "bindJoystickButton", + &luascriptfunctions::bindJoystickButton, + {}, + "int, string [, string, bool]", + "Binds a Lua script to be executed when the joystick button identified " + "by the first argument is triggered. The third argument determines when " + "the script should be executed, this defaults to 'pressed', which means " + "that the script is run when the user presses the button. The last " + "argument determines whether the command is going to be executable " + "locally or remotely. The latter being the default." + }, + { + "clearJoystickButotn", + &luascriptfunctions::clearJoystickButton, + {}, + "int", + "Removes all commands that are currently bound to the button identified " + "by the first argument" + }, + { + "joystickButton", + &luascriptfunctions::joystickButton, + {}, + "int", + "Returns the script that is currently bound to be executed when the " + "provided button is pressed" } } }; diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 8ad65f406e..5a640be04e 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -22,6 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include +#include + namespace openspace::luascriptfunctions { int restoreCameraStateFromFile(lua_State* L) { @@ -88,4 +91,130 @@ int resetCameraDirection(lua_State* L) { return 0; } +int bindJoystickAxis(lua_State* L) { + int n = ghoul::lua::checkArgumentsAndThrow(L, { 2, 4 }, "lua::bindJoystickAxis"); + + int axis = static_cast(lua_tonumber(L, 1)); + std::string axisType = lua_tostring(L, 2); + + bool shouldInvert = false; + if (n > 2) { + shouldInvert = lua_toboolean(L, 3); + } + + bool shouldNormalize = false; + if (n > 3) { + shouldNormalize = lua_toboolean(L, 4); + } + + OsEng.navigationHandler().setJoystickAxisMapping( + axis, + ghoul::from_string(axisType), + interaction::JoystickCameraStates::AxisInvert(shouldInvert), + interaction::JoystickCameraStates::AxisNormalize(shouldNormalize) + ); + + + return 0; +} + +int joystickAxis(lua_State* L) { + ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::joystickAxis"); + + int axis = static_cast(lua_tonumber(L, 1)); + + using AI = interaction::JoystickCameraStates::AxisInformation; + AI info = OsEng.navigationHandler().joystickAxisMapping(axis); + + lua_settop(L, 0); + lua_pushstring(L, std::to_string(info.type).c_str()); + lua_pushboolean(L, info.invert); + lua_pushboolean(L, info.normalize); + + return 3; +} + +int setJoystickAxisDeadzone(lua_State* L) { + ghoul::lua::checkArgumentsAndThrow(L, 2, "lua::setJoystickAxisDeadzone"); + + int axis = static_cast(lua_tointeger(L, 1)); + float deadzone = static_cast(lua_tonumber(L, 2)); + + OsEng.navigationHandler().setJoystickAxisDeadzone(axis, deadzone); + + return 0; +} + +int joystickAxisDeadzone(lua_State* L) { + ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::setJoystickAxisDeadzone"); + + int axis = static_cast(lua_tointeger(L, 1)); + + float deadzone = OsEng.navigationHandler().joystickAxisDeadzone(axis); + + lua_pushnumber(L, deadzone); + return 1; +} + +int bindJoystickButton(lua_State* L) { + int n = ghoul::lua::checkArgumentsAndThrow(L, { 2, 4 }, "lua::bindJoystickButton"); + + int button = static_cast(lua_tonumber(L, 1)); + std::string command = lua_tostring(L, 2); + + interaction::JoystickAction action = interaction::JoystickAction::Press; + if (n >= 3) { + action = ghoul::from_string(lua_tostring(L, 3)); + } + + bool isRemote = true; + if (n == 4) { + isRemote = lua_toboolean(L, 4); + } + + OsEng.navigationHandler().bindJoystickButtonCommand( + button, + std::move(command), + action, + interaction::JoystickCameraStates::ButtonCommandRemote(isRemote) + ); + + lua_settop(L, 0); + return 0; +} + +int clearJoystickButton(lua_State* L) { + int n = ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); + + int button = static_cast(lua_tonumber(L, 1)); + + OsEng.navigationHandler().clearJoystickButtonCommand(button); + + lua_settop(L, 0); + return 0; +} + +int joystickButton(lua_State* L) { + int n = ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); + + int button = static_cast(lua_tonumber(L, 1)); + + std::vector cmds = OsEng.navigationHandler().joystickButtonCommand( + button + ); + + std::string cmd = std::accumulate( + cmds.begin(), + cmds.end(), + std::string(), + [](std::string lhs, std::string rhs) { + return lhs + ";" + rhs; + } + ); + + lua_settop(L, 0); + lua_pushstring(L, cmd.c_str()); + return 1; +} + } // namespace openspace::luascriptfunctions diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index 29de597abe..b0e1fd439b 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -58,11 +58,18 @@ namespace { "disabled, the camera will zoom in or out forever." }; - static const openspace::properties::Property::PropertyInfo SensitivityInfo = { - "Sensitivity", - "Sensitivity", - "Determines the sensitivity of the camera motion. The lower the sensitivity is " - "the less impact a mouse mothion will have." + static const openspace::properties::Property::PropertyInfo MouseSensitivityInfo = { + "MouseSensitivity", + "Mouse Sensitivity", + "Determines the sensitivity of the camera motion thorugh the mouse. The lower " + "the sensitivity is the less impact a mouse motion will have." + }; + + static const openspace::properties::Property::PropertyInfo JoystickSensitivityInfo = { + "JoystickSensitivity", + "Joystick Sensitivity", + "Determines the sensitivity of the camera motion thorugh a joystick. The lower " + "the sensitivity is the less impact a joystick motion will have." }; static const openspace::properties::Property::PropertyInfo FrictionInfo = { @@ -105,8 +112,10 @@ OrbitalNavigator::OrbitalNavigator() : properties::PropertyOwner({ "OrbitalNavigator" }) , _followFocusNodeRotationDistance(FollowFocusNodeInfo, 5.0f, 0.0f, 20.f) , _minimumAllowedDistance(MinimumDistanceInfo, 10.0f, 0.0f, 10000.f) - , _sensitivity(SensitivityInfo, 15.0f, 1.0f, 50.f) - , _mouseStates(_sensitivity * pow(10.0, -4), 1 / (_friction.friction + 0.0000001)) + , _mouseSensitivity(MouseSensitivityInfo, 15.0f, 1.0f, 50.f) + , _joystickSensitivity(JoystickSensitivityInfo, 10.0f, 1.0f, 50.f) + , _mouseStates(_mouseSensitivity * 0.0001, 1 / (_friction.friction + 0.0000001)) + , _joystickStates(_joystickSensitivity * 0.1, 1 / (_friction.friction + 0.0000001)) { auto smoothStep = [](double t) { @@ -138,37 +147,47 @@ OrbitalNavigator::OrbitalNavigator() // Define callback functions for changed properties _friction.roll.onChange([&]() { _mouseStates.setRotationalFriction(_friction.roll); + _joystickStates.setRotationalFriction(_friction.roll); }); _friction.rotational.onChange([&]() { _mouseStates.setHorizontalFriction(_friction.rotational); + _joystickStates.setHorizontalFriction(_friction.rotational); }); _friction.zoom.onChange([&]() { _mouseStates.setVerticalFriction(_friction.zoom); + _joystickStates.setVerticalFriction(_friction.zoom); }); _friction.friction.onChange([&]() { _mouseStates.setVelocityScaleFactor(1 / (_friction.friction + 0.0000001)); + _joystickStates.setVelocityScaleFactor(1 / (_friction.friction + 0.0000001)); }); - _sensitivity.onChange([&]() { - _mouseStates.setSensitivity(_sensitivity * pow(10.0,-4)); + _mouseSensitivity.onChange([&]() { + _mouseStates.setSensitivity(_mouseSensitivity * pow(10.0, -4)); }); + _joystickSensitivity.onChange([&]() { + _joystickStates.setSensitivity(_joystickSensitivity * pow(10.0, -4)); + }); + addPropertySubOwner(_friction); addProperty(_followFocusNodeRotationDistance); addProperty(_minimumAllowedDistance); - addProperty(_sensitivity); + addProperty(_mouseSensitivity); + addProperty(_joystickSensitivity); } OrbitalNavigator::~OrbitalNavigator() {} -void OrbitalNavigator::updateMouseStatesFromInput(const InputState& inputState, +void OrbitalNavigator::updateStatesFromInput(const InputState& inputState, double deltaTime) { - _mouseStates.updateMouseStatesFromInput(inputState, deltaTime); + _mouseStates.updateStateFromInput(inputState, deltaTime); + _joystickStates.updateStateFromInput(inputState, deltaTime); } -void OrbitalNavigator::updateCameraStateFromMouseStates(Camera& camera, double deltaTime){ +void OrbitalNavigator::updateCameraStateFromStates(Camera& camera, double deltaTime){ if (_focusNode) { // Read the current state of the camera glm::dvec3 camPos = camera.positionVec3(); @@ -347,23 +366,31 @@ OrbitalNavigator::CameraRotationDecomposition glm::dquat OrbitalNavigator::roll(double deltaTime, const glm::dquat& localCameraRotation) const { - glm::dquat rollQuat = glm::angleAxis( - _mouseStates.localRollMouseVelocity().x * deltaTime, + glm::dquat mouseRollQuat = glm::angleAxis( + _mouseStates.localRollVelocity().x * deltaTime + + _joystickStates.localRollVelocity().x * deltaTime, glm::dvec3(0.0, 0.0, 1.0) ); - return localCameraRotation * rollQuat; + return localCameraRotation * mouseRollQuat; } glm::dquat OrbitalNavigator::rotateLocally(double deltaTime, const glm::dquat& localCameraRotation) const { - glm::dvec3 eulerAngles( - _mouseStates.localRotationMouseVelocity().y, - _mouseStates.localRotationMouseVelocity().x, + glm::dquat mouseRotationDiff = glm::dquat(glm::dvec3( + _mouseStates.localRotationVelocity().y, + _mouseStates.localRotationVelocity().x, 0.0 - ); - glm::dquat rotationDiff = glm::dquat(eulerAngles * deltaTime); - return localCameraRotation * rotationDiff; + ) * deltaTime); + + glm::dquat joystickRotationDiff = glm::dquat(glm::dvec3( + _joystickStates.localRotationVelocity().y, + _joystickStates.localRotationVelocity().x, + 0.0 + ) * deltaTime); + + + return localCameraRotation * joystickRotationDiff * mouseRotationDiff; } glm::dquat OrbitalNavigator::interpolateLocalRotation(double deltaTime, @@ -425,16 +452,21 @@ glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, 1.0; // Get rotation in camera space - glm::dvec3 eulerAngles = glm::dvec3( - -_mouseStates.globalRotationMouseVelocity().y * deltaTime, - -_mouseStates.globalRotationMouseVelocity().x * deltaTime, - 0) * speedScale; - glm::dquat rotationDiffCamSpace = glm::dquat(eulerAngles); + glm::dquat mouseRotationDiffCamSpace = glm::dquat(glm::dvec3( + -_mouseStates.globalRotationVelocity().y * deltaTime, + -_mouseStates.globalRotationVelocity().x * deltaTime, + 0) * speedScale); + + glm::dquat joystickRotationDiffCamSpace = glm::dquat(glm::dvec3( + -_joystickStates.globalRotationVelocity().y * deltaTime, + -_joystickStates.globalRotationVelocity().x * deltaTime, + 0) * speedScale); // Transform to world space glm::dquat rotationDiffWorldSpace = globalCameraRotation * - rotationDiffCamSpace * + joystickRotationDiffCamSpace * + mouseRotationDiffCamSpace * glm::inverse(globalCameraRotation); // Rotate and find the difference vector @@ -501,8 +533,12 @@ glm::dvec3 OrbitalNavigator::translateVertically( glm::dmat3(modelTransform) * centerToActualSurfaceModelSpace; glm::dvec3 actualSurfaceToCamera = posDiff - centerToActualSurface; + const double totalVelocity = + _joystickStates.truckMovementVelocity().y + + _mouseStates.truckMovementVelocity().y; + return cameraPosition - - actualSurfaceToCamera * _mouseStates.truckMovementMouseVelocity().y * deltaTime; + actualSurfaceToCamera * totalVelocity * deltaTime; } glm::dquat OrbitalNavigator::rotateHorizontally( @@ -518,12 +554,12 @@ glm::dquat OrbitalNavigator::rotateHorizontally( glm::dvec3 directionFromSurfaceToCamera = glm::normalize(glm::dmat3(modelTransform) * directionFromSurfaceToCameraModelSpace); - glm::dquat cameraRollRotation = - glm::angleAxis( - _mouseStates.globalRollMouseVelocity().x * - deltaTime, directionFromSurfaceToCamera - ); - return cameraRollRotation * globalCameraRotation; + glm::dquat mouseCameraRollRotation = glm::angleAxis( + _mouseStates.globalRollVelocity().x * deltaTime + + _joystickStates.globalRollVelocity().x * deltaTime, + directionFromSurfaceToCamera + ); + return mouseCameraRollRotation * globalCameraRotation; } glm::dvec3 OrbitalNavigator::pushToSurface( @@ -597,4 +633,9 @@ SurfacePositionHandle OrbitalNavigator::calculateSurfacePositionHandle( return posHandle; } +JoystickCameraStates& OrbitalNavigator::joystickStates() { + return _joystickStates; +} + + } // namespace openspace::interaction diff --git a/src/rendering/luaconsole.cpp b/src/rendering/luaconsole.cpp new file mode 100644 index 0000000000..bb04359b78 --- /dev/null +++ b/src/rendering/luaconsole.cpp @@ -0,0 +1,916 @@ +/***************************************************************************************** + * * + * 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 + +namespace { + const char* HistoryFile = "ConsoleHistory"; + + const int NoAutoComplete = -1; + + const int MaximumHistoryLength = 1000; + + // A high number is chosen since we didn't have a version number before + // any small number might also be equal to the console history length + + const uint64_t CurrentVersion = 0xFEEE'FEEE'0000'0001; + + const openspace::Key CommandInputButton = openspace::Key::GraveAccent; + + const char* FontName = "Console"; + const float EntryFontSize = 14.0f; + const float HistoryFontSize = 11.0f; + + // Additional space between the entry text and the history (in pixels) + const float SeparatorSpace = 30.f; + + // Determines at which speed the console opens. + const float ConsoleOpenSpeed = 2.5; + + // The number of characters to display after the cursor + // when horizontal scrolling is required. + const int NVisibleCharsAfterCursor = 5; + + const static openspace::properties::Property::PropertyInfo VisibleInfo = { + "IsVisible", + "Is Visible", + "Determines whether the Lua console is shown on the screen or not. Toggling it " + "will fade the console in and out." + }; + + const static openspace::properties::Property::PropertyInfo RemoveScriptingInfo = { + "RemoteScripting", + "Remote scripting", + "Determines whether the entered commands will only be executed locally (if this " + "is disabled), or whether they will be send to connected remove instances." + }; + + const static openspace::properties::Property::PropertyInfo BackgroundColorInfo = { + "BackgroundColor", + "Background Color", + "Sets the background color of the console." + }; + + const static openspace::properties::Property::PropertyInfo HighlightColorInfo = { + "HighlightColor", + "Highlight Color", + "Sets the color of the lines below the console." + }; + + const static openspace::properties::Property::PropertyInfo SeparatorColorInfo = { + "SeparatorColor", + "Separator Color", + "Sets the color of the separator between the history part and the entry part of " + "the console." + }; + + const static openspace::properties::Property::PropertyInfo EntryTextColorInfo = { + "EntryTextColor", + "Entry Text Color", + "Sets the text color of the entry area of the console." + }; + + const static openspace::properties::Property::PropertyInfo HistoryTextColorInfo = { + "HistoryTextColor", + "History Text Color", + "Sets the text color of the history area of the console." + }; + + const static openspace::properties::Property::PropertyInfo HistoryLengthInfo = { + "HistoryLength", + "History Length", + "Determines the length of the history in number of lines." + }; +} // namespace + +namespace openspace { + +LuaConsole::LuaConsole() + : properties::PropertyOwner({ "LuaConsole" }) + , _isVisible(VisibleInfo, false) + , _remoteScripting(RemoveScriptingInfo, false) + , _backgroundColor( + BackgroundColorInfo, + glm::vec4(21.f / 255.f, 23.f / 255.f, 28.f / 255.f, 0.8f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _highlightColor( + HighlightColorInfo, + glm::vec4(1.f, 1.f, 1.f, 0.f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _separatorColor( + SeparatorColorInfo, + glm::vec4(0.4f, 0.4f, 0.4f, 0.f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _entryTextColor( + EntryTextColorInfo, + glm::vec4(1.f, 1.f, 1.f, 1.f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _historyTextColor( + HistoryTextColorInfo, + glm::vec4(1.0f, 1.0f, 1.0f, 0.65f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _historyLength(HistoryLengthInfo, 13, 0, 100) + , _inputPosition(0) + , _activeCommand(0) + , _autoCompleteInfo({NoAutoComplete, false, ""}) + , _currentHeight(0.f) + , _targetHeight(0.f) + , _fullHeight(0.f) +{ + addProperty(_isVisible); + addProperty(_remoteScripting); + addProperty(_historyLength); + + _backgroundColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_backgroundColor); + _highlightColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_highlightColor); + _separatorColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_separatorColor); + _entryTextColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_entryTextColor); + _historyTextColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_historyTextColor); +} + +void LuaConsole::initialize() { + const std::string filename = FileSys.cacheManager()->cachedFilename( + HistoryFile, + "", + ghoul::filesystem::CacheManager::Persistent::Yes + ); + + if (FileSys.fileExists(filename)) { + std::ifstream file(filename, std::ios::binary | std::ios::in); + + if (file.good()) { + // Read the number of commands from the history + uint64_t version; + file.read(reinterpret_cast(&version), sizeof(uint64_t)); + + if (version != CurrentVersion) { + LWARNINGC( + "LuaConsole", + fmt::format("Outdated console history version: {}", version) + ); + } + else { + int64_t nCommands; + file.read(reinterpret_cast(&nCommands), sizeof(int64_t)); + + for (int64_t i = 0; i < nCommands; ++i) { + int64_t length; + file.read(reinterpret_cast(&length), sizeof(int64_t)); + + std::vector tmp(length); + file.read(tmp.data(), length); + _commandsHistory.emplace_back(std::string(tmp.begin(), tmp.end())); + } + } + } + } + + _commands = _commandsHistory; + _commands.push_back(""); + _activeCommand = _commands.size() - 1; + + _program = ghoul::opengl::ProgramObject::Build( + "Console", + absPath("${SHADERS}/luaconsole.vert"), + absPath("${SHADERS}/luaconsole.frag") + ); + + _uniformCache.res = _program->uniformLocation("res"); + _uniformCache.color = _program->uniformLocation("color"); + _uniformCache.height = _program->uniformLocation("height"); + _uniformCache.ortho = _program->uniformLocation("ortho"); + + GLfloat data[] = { + 0.f, 0.f, + 1.f, 1.f, + 0.f, 1.f, + + 0.f, 0.f, + 1.f, 0.f, + 1.f, 1.f + }; + + glGenVertexArrays(1, &_vao); + glBindVertexArray(_vao); + glGenBuffers(1, &_vbo); + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); + + glEnableVertexAttribArray(0); + glVertexAttribPointer( + 0, + 2, + GL_FLOAT, + GL_FALSE, + 2 * sizeof(GLfloat), + nullptr + ); + + glBindVertexArray(0); + + _font = OsEng.fontManager().font( + FontName, + EntryFontSize, + ghoul::fontrendering::FontManager::Outline::No + ); + + _historyFont = OsEng.fontManager().font( + FontName, + HistoryFontSize, + ghoul::fontrendering::FontManager::Outline::No + ); + + OsEng.parallelPeer().connectionEvent()->subscribe( + "luaConsole", + "statusChanged", + [this]() { + ParallelConnection::Status status = OsEng.parallelPeer().status(); + parallelConnectionChanged(status); + } + ); +} + +void LuaConsole::deinitialize() { + const std::string filename = FileSys.cacheManager()->cachedFilename( + HistoryFile, + "", + ghoul::filesystem::CacheManager::Persistent::Yes + ); + + // We want to limit the command history to a realistic value, so that it doesn't + // grow without bounds + if (_commandsHistory.size() > MaximumHistoryLength) { + _commandsHistory = std::vector( + _commandsHistory.end() - MaximumHistoryLength, + _commandsHistory.end() + ); + } + + std::ofstream file(filename, std::ios::binary); + if (file.good()) { + uint64_t version = CurrentVersion; + file.write(reinterpret_cast(&version), sizeof(uint64_t)); + + int64_t nCommands = _commandsHistory.size(); + file.write(reinterpret_cast(&nCommands), sizeof(int64_t)); + + for (const std::string& s : _commandsHistory) { + int64_t length = s.length(); + file.write(reinterpret_cast(&length), sizeof(int64_t)); + // We don't write the \0 at the end on purpose + file.write(s.c_str(), length); + } + } + + _program = nullptr; + + OsEng.parallelPeer().connectionEvent()->unsubscribe("luaConsole"); +} + +bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { + if (action != KeyAction::Press && action != KeyAction::Repeat) { + return false; + } + + if (key == CommandInputButton) { + // Button left of 1 and above TAB + // How to deal with different keyboard languages? ---abock + if (_isVisible) { + if (_remoteScripting) { + _remoteScripting = false; + } + else { + _isVisible = false; + _commands.back() = ""; + _inputPosition = 0; + } + } + else { + _isVisible = true; + if (OsEng.parallelPeer().status() == ParallelConnection::Status::Host) { + _remoteScripting = true; + } + } + + return true; + } + + if (!_isVisible) { + return false; + } + + if (key == Key::Escape) { + _isVisible = false; + return true; + } + + + const bool modifierControl = (modifier == KeyModifier::Control); + const bool modifierShift = (modifier == KeyModifier::Shift); + + // Paste from clipboard + if (modifierControl && (key == Key::V || key == Key::Y)) { + addToCommand(sanitizeInput(ghoul::clipboardText())); + return true; + } + + // Copy to clipboard + if (modifierControl && key == Key::C) { + ghoul::setClipboardText(_commands.at(_activeCommand)); + return true; + } + + // Cut to clipboard + if (modifierControl && key == Key::X) { + ghoul::setClipboardText(_commands.at(_activeCommand)); + _commands.at(_activeCommand).clear(); + _inputPosition = 0; + } + + // Cut part after cursor to clipboard ("Kill") + if (modifierControl && key == Key::K) { + auto here = _commands.at(_activeCommand).begin() + _inputPosition; + auto end = _commands.at(_activeCommand).end(); + ghoul::setClipboardText(std::string(here, end)); + _commands.at(_activeCommand).erase(here, end); + } + + // Go to the previous character + if (key == Key::Left || (modifierControl && key == Key::B)) { + if (_inputPosition > 0) { + --_inputPosition; + } + return true; + } + + // Go to the next character + if (key == Key::Right || (modifierControl && key == Key::F)) { + _inputPosition = std::min( + _inputPosition + 1, + _commands.at(_activeCommand).length() + ); + return true; + } + + // Go to previous command + if (key == Key::Up) { + if (_activeCommand > 0) { + --_activeCommand; + } + _inputPosition = _commands.at(_activeCommand).length(); + return true; + } + + // Go to next command (the last is empty) + if (key == Key::Down) { + if (_activeCommand < _commands.size() - 1) { + ++_activeCommand; + } + _inputPosition = _commands.at(_activeCommand).length(); + return true; + } + + // Remove character before _inputPosition + if (key == Key::BackSpace) { + if (_inputPosition > 0) { + _commands.at(_activeCommand).erase(_inputPosition - 1, 1); + --_inputPosition; + } + return true; + } + + // Remove character after _inputPosition + if (key == Key::Delete) { + if (_inputPosition <= _commands.at(_activeCommand).size()) { + _commands.at(_activeCommand).erase(_inputPosition, 1); + } + return true; + } + + // Go to the beginning of command string + if (key == Key::Home || (modifierControl && key == Key::A)) { + _inputPosition = 0; + return true; + } + + // Go to the end of command string + if (key == Key::End || (modifierControl && key == Key::E)) { + _inputPosition = _commands.at(_activeCommand).size(); + return true; + } + + if (key == Key::Enter || key == Key::KeypadEnter) { + std::string cmd = _commands.at(_activeCommand); + if (cmd != "") { + using RemoteScripting = scripting::ScriptEngine::RemoteScripting; + OsEng.scriptEngine().queueScript( + cmd, + _remoteScripting ? RemoteScripting::Yes : RemoteScripting::No + ); + + // 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 + if (_commandsHistory.empty() || (cmd != _commandsHistory.back())) { + _commandsHistory.push_back(_commands.at(_activeCommand)); + } + } + + // Some clean up after the execution of the command + _commands = _commandsHistory; + _commands.push_back(""); + _activeCommand = _commands.size() - 1; + _inputPosition = 0; + return true; + } + + if (key == Key::Tab) { + // We get a list of all the available commands and initially find the first + // command that starts with how much we typed sofar. We store the index so + // that in subsequent "tab" presses, we will discard previous commands. This + // implements the 'hop-over' behavior. As soon as another key is pressed, + // everything is set back to normal + + // If the shift key is pressed, we decrement the current index so that we will + // find the value before the one that was previously found + if (_autoCompleteInfo.lastIndex != NoAutoComplete && modifierShift) { + _autoCompleteInfo.lastIndex -= 2; + } + std::vector allCommands = OsEng.scriptEngine().allLuaFunctions(); + std::sort(allCommands.begin(), allCommands.end()); + + std::string currentCommand = _commands.at(_activeCommand); + + // Check if it is the first time the tab has been pressed. If so, we need to + // store the already entered command so that we can later start the search + // from there. We will overwrite the 'currentCommand' thus making the storage + // necessary + if (!_autoCompleteInfo.hasInitialValue) { + _autoCompleteInfo.initialValue = currentCommand; + _autoCompleteInfo.hasInitialValue = true; + } + + for (int i = 0; i < static_cast(allCommands.size()); ++i) { + const std::string& command = allCommands[i]; + + // Check if the command has enough length (we don't want crashes here) + // Then check if the iterator-command's start is equal to what we want + // then check if we need to skip the first found values as the user has + // pressed TAB repeatedly + size_t fullLength = _autoCompleteInfo.initialValue.length(); + bool correctLength = command.length() >= fullLength; + + std::string commandLowerCase; + std::transform( + command.begin(), command.end(), + std::back_inserter(commandLowerCase), + [](char v) { return static_cast(tolower(v)); } + ); + + std::string initialValueLowerCase; + std::transform( + _autoCompleteInfo.initialValue.begin(), + _autoCompleteInfo.initialValue.end(), + std::back_inserter(initialValueLowerCase), + [](char v) { return static_cast(tolower(v)); } + ); + + bool correctCommand = + commandLowerCase.substr(0, fullLength) == initialValueLowerCase; + + if (correctLength && correctCommand && (i > _autoCompleteInfo.lastIndex)) { + // We found our index, so store it + _autoCompleteInfo.lastIndex = i; + + // We only want to auto-complete until the next separator "." + size_t pos = command.find('.', fullLength); + if (pos == std::string::npos) { + // If we don't find a separator, we autocomplete until the end + // Set the found command as active command + _commands.at(_activeCommand) = command + "();"; + // Set the cursor position to be between the brackets + _inputPosition = _commands.at(_activeCommand).size() - 2; + } + else { + // If we find a separator, we autocomplete until and including the + // separator unless the autocompletion would be the same that we + // already have (the case if there are multiple commands in the + // same group + std::string subCommand = command.substr(0, pos + 1); + if (subCommand == _commands.at(_activeCommand)) { + continue; + } + else { + _commands.at(_activeCommand) = command.substr(0, pos + 1); + _inputPosition = _commands.at(_activeCommand).length(); + // We only want to remove the autocomplete info if we just + // entered the 'default' openspace namespace + if (command.substr(0, pos + 1) == "openspace.") { + _autoCompleteInfo = { NoAutoComplete, false, "" }; + } + } + } + + break; + } + } + return true; + } + else { + // If any other key is pressed, we want to remove our previous findings + // The special case for Shift is necessary as we want to allow Shift+TAB + if (!modifierShift) { + _autoCompleteInfo = { NoAutoComplete, false, "" }; + } + } + + // We want to ignore the function keys as they don't translate to text anyway + if (key >= Key::F1 && key <= Key::F25) { + return false; + } + + // Do not consume modifier keys + switch (key) { + case Key::LeftShift: + case Key::RightShift: + case Key::LeftAlt: + case Key::RightAlt: + case Key::LeftControl: + case Key::RightControl: + return false; + default: + return true; + } +} + +void LuaConsole::charCallback(unsigned int codepoint, + [[maybe_unused]] KeyModifier modifier) +{ + if (!_isVisible) { + return; + } + + if (codepoint == static_cast(CommandInputButton)) { + return; + } + +#ifndef WIN32 + const bool modifierControl = (modifier == KeyModifier::Control); + + const int codepoint_C = 99; + const int codepoint_V = 118; + if (modifierControl && (codepoint == codepoint_C || codepoint == codepoint_V)) { + return; + } +#endif + + // Disallow all non ASCII characters for now + if (codepoint > 0x7f) { + return; + } + + addToCommand(std::string(1, static_cast(codepoint))); +} + +void LuaConsole::update() { + // Compute the height by simulating _historyFont number of lines and checking + // what the bounding box for that text would be. + using namespace ghoul::fontrendering; + const size_t nLines = std::min( + static_cast(_historyLength), + _commandsHistory.size() + ); + const auto bbox = FontRenderer::defaultRenderer().boundingBox( + *_historyFont, + std::string(nLines, '\n').c_str() + ); + + // Update the full height and the target height. + // Add the height of the entry line and space for a separator. + _fullHeight = (bbox.boundingBox.y + EntryFontSize + SeparatorSpace); + _targetHeight = _isVisible ? _fullHeight : 0; + + // The first frame is going to be finished in approx 10 us, which causes a floating + // point overflow when computing dHeight + const double frametime = std::max( + OsEng.windowWrapper().deltaTime(), + 1e-4 + ); + + // 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 double dHeight = (_targetHeight - _currentHeight) * + std::pow(0.98, 1.0 / (ConsoleOpenSpeed / dpiScaling.y * frametime)); + + _currentHeight += static_cast(dHeight); + + _currentHeight = std::max(0.0f, _currentHeight); + _currentHeight = std::min(static_cast(res.y), _currentHeight); +} + +void LuaConsole::render() { + using namespace ghoul::fontrendering; + + // Don't render the console if it's collapsed. + if (_currentHeight < 1.0f) { + return; + } + + if (_program->isDirty()) { + _program->rebuildFromFile(); + + _uniformCache.res = _program->uniformLocation("res"); + _uniformCache.color = _program->uniformLocation("color"); + _uniformCache.height = _program->uniformLocation("height"); + _uniformCache.ortho = _program->uniformLocation("ortho"); + } + + const glm::vec2 dpiScaling = OsEng.windowWrapper().dpiScaling(); + const glm::ivec2 res = + glm::vec2(OsEng.windowWrapper().currentWindowResolution()) / dpiScaling; + + + // Render background + glDisable(GL_CULL_FACE); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_DEPTH_TEST); + + _program->activate(); + + _program->setUniform(_uniformCache.res, res); + _program->setUniform(_uniformCache.color, _backgroundColor); + _program->setUniform(_uniformCache.height, _currentHeight / res.y); + _program->setUniform( + _uniformCache.ortho, + glm::ortho( + 0.f, static_cast(res.x), 0.f, static_cast(res.y) + ) + ); + + // Draw the background color + glBindVertexArray(_vao); + glDrawArrays(GL_TRIANGLES, 0, 6); + + // Draw the highlight lines above and below the background + _program->setUniform(_uniformCache.color, _highlightColor); + glDrawArrays(GL_LINES, 1, 4); + + // Draw the separator between the current entry box and the history + _program->setUniform(_uniformCache.color, _separatorColor); + _program->setUniform( + _uniformCache.height, + _currentHeight / res.y - 2.5f * EntryFontSize / res.y + ); + glDrawArrays(GL_LINES, 1, 2); + + _program->deactivate(); + + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); + + // Render text on top of the background + glm::vec2 inputLocation = glm::vec2( + EntryFontSize / 2.f, + res.y - _currentHeight + EntryFontSize + ); + + // Render the current command + std::string currentCommand = _commands.at(_activeCommand); + // We chop off the beginning and end of the string until it fits on the screen (with + // a margin) this should be replaced as soon as the mono-spaced fonts work properly. + // Right now, every third character is a bit wider than the others + + size_t nChoppedCharsBeginning = 0, nChoppedCharsEnd = 0; + + const size_t inputPositionFromEnd = currentCommand.size() - _inputPosition; + while (true) { + using namespace ghoul::fontrendering; + // Compute the current width of the string and console prefix. + const float currentWidth = FontRenderer::defaultRenderer().boundingBox( + *_font, + "> %s", + currentCommand.c_str() + ).boundingBox.x + inputLocation.x; + + // Compute the overflow in pixels + const float overflow = currentWidth - res.x * 0.995f; + if (overflow <= 0.f) { + break; + } + + // Since the overflow is positive, at least one character needs to be removed. + const size_t nCharsOverflow = static_cast(std::min( + std::max(1.f, overflow / _font->glyph('m')->width()), + static_cast(currentCommand.size()) + )); + + // Do not hide the cursor and `NVisibleCharsAfterCursor` characters in the end. + const size_t maxAdditionalCharsToChopEnd = std::max( + 0, + static_cast(inputPositionFromEnd) - + (NVisibleCharsAfterCursor + 1) - + static_cast(nChoppedCharsEnd) + ); + + // Do not hide the cursor in the beginning. + const size_t maxAdditionalCharsToChopBeginning = std::max( + 0, + static_cast(_inputPosition) - 1 - + static_cast(nChoppedCharsBeginning) + ); + + // Prioritize chopping in the end of the string. + const size_t nCharsToChopEnd = std::min( + nCharsOverflow, + maxAdditionalCharsToChopEnd + ); + const size_t nCharsToChopBeginning = std::min( + nCharsOverflow - nCharsToChopEnd, + maxAdditionalCharsToChopBeginning + ); + + nChoppedCharsBeginning += nCharsToChopBeginning; + nChoppedCharsEnd += nCharsToChopEnd; + + const size_t displayLength = + _commands.at(_activeCommand).size() - + nChoppedCharsBeginning - nChoppedCharsEnd; + + currentCommand = _commands.at(_activeCommand).substr( + nChoppedCharsBeginning, + displayLength + ); + } + + RenderFontCr( + *_font, + inputLocation, + _entryTextColor, + "> %s", + currentCommand.c_str() + ); + + // Just offset the ^ marker slightly for a nicer look + inputLocation.y += 3 * dpiScaling.y; + + // Render the ^ marker below the text to show where the current entry point is + RenderFont( + *_font, + inputLocation, + _entryTextColor, + (std::string(_inputPosition - nChoppedCharsBeginning + 2, ' ') + "^").c_str() + ); + + glm::vec2 historyInputLocation = glm::vec2( + HistoryFontSize / 2.f, + res.y - HistoryFontSize * 1.5f + _fullHeight - _currentHeight + ); + + // @CPP: Replace with array_view + std::vector commandSubset; + if (_commandsHistory.size() < static_cast(_historyLength)) { + commandSubset = _commandsHistory; + } + else { + commandSubset = std::vector( + _commandsHistory.end() - _historyLength, + _commandsHistory.end() + ); + } + + for (const std::string& cmd : commandSubset) { + RenderFontCr( + *_historyFont, + historyInputLocation, + _historyTextColor, + "%s", + cmd.c_str() + ); + } + + // Computes the location for right justified text on the same y height as the entry + auto locationForRightJustifiedText = [&](const std::string& text) { + using namespace ghoul::fontrendering; + + const glm::vec2 loc = glm::vec2( + EntryFontSize / 2.f, + res.y - _currentHeight + EntryFontSize + ); + + const auto bbox = FontRenderer::defaultRenderer().boundingBox( + *_font, text.c_str() + ); + return glm::vec2( + loc.x + res.x - bbox.boundingBox.x - 10.f, + loc.y + ); + }; + + if (_remoteScripting) { + const glm::vec4 red(1, 0, 0, 1); + + ParallelConnection::Status status = OsEng.parallelPeer().status(); + const int nClients = + status != ParallelConnection::Status::Disconnected ? + OsEng.parallelPeer().nConnections() - 1 : + 0; + + const std::string nClientsText = + nClients == 1 ? + "Broadcasting script to 1 client" : + "Broadcasting script to " + std::to_string(nClients) + " clients"; + + const glm::vec2 loc = locationForRightJustifiedText(nClientsText); + RenderFont(*_font, loc, red, nClientsText.c_str()); + } else if (OsEng.parallelPeer().isHost()) { + const glm::vec4 lightBlue(0.4, 0.4, 1, 1); + + const std::string localExecutionText = "Local script execution"; + const glm::vec2 loc = locationForRightJustifiedText(localExecutionText); + RenderFont(*_font, loc, lightBlue, localExecutionText.c_str()); + } +} + +float LuaConsole::currentHeight() const { + return _currentHeight; +} + +void LuaConsole::addToCommand(std::string c) { + const size_t length = c.length(); + _commands.at(_activeCommand).insert(_inputPosition, std::move(c)); + _inputPosition += length; +} + +std::string LuaConsole::sanitizeInput(std::string str) { + // Remove carriage returns. + str.erase(std::remove(str.begin(), str.end(), '\r'), str.end()); + + // Replace newlines with spaces. + const std::function replace = [](char c) { + return c == '\n' ? ' ' : c; + }; + std::transform(str.begin(), str.end(), str.begin(), replace); + + return str; +} + +void LuaConsole::parallelConnectionChanged(const ParallelConnection::Status& status) { + _remoteScripting = (status == ParallelConnection::Status::Host); +} + +} // namespace openspace diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index c6d1dc46ad..4b0254e367 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -31,15 +31,15 @@ #include #include #include -#include #include #include #include #include #include #include -#include #include +#include +#include #include #include #include From b4be63af657242b73eff3c6fd52e11dfe5b02b8a Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 20 Apr 2018 18:40:21 -0400 Subject: [PATCH 44/79] Feature/configuration (#605) * Switch openspace.cfg file from a Dictionary-based loading to a variable based loading * Change ConfigurationManager to not use Dictionary anymore, but a struct with explicit configuration values instead --- apps/OpenSpace/main.cpp | 6 +- apps/Sync/main.cpp | 1 - apps/TaskRunner/main.cpp | 1 - include/openspace/engine/configuration.h | 134 ++++ .../openspace/engine/configurationmanager.h | 282 -------- include/openspace/engine/moduleengine.h | 3 +- include/openspace/engine/openspaceengine.h | 8 +- .../rendering/renderableatmosphere.cpp | 1 - modules/base/rendering/renderablemodel.cpp | 1 - .../rendering/renderablesphericalgrid.cpp | 1 - .../tile/rawtiledatareader/gdalwrapper.cpp | 72 +- .../rawtiledatareader/rawtiledatareader.cpp | 2 - .../rendering/renderablemultiresvolume.cpp | 1 - modules/server/include/connection.h | 1 - modules/server/src/connection.cpp | 24 +- .../server/src/topics/authorizationtopic.cpp | 22 +- .../rendering/renderableplaneprojection.cpp | 1 - modules/sync/syncmodule.cpp | 1 - openspace.cfg | 221 ++++--- src/CMakeLists.txt | 8 +- src/documentation/core_registration.cpp | 2 - src/engine/configuration.cpp | 350 ++++++++++ ...nmanager_doc.inl => configuration_doc.inl} | 244 ++++--- src/engine/configurationmanager.cpp | 144 ---- src/engine/moduleengine.cpp | 9 +- src/engine/openspaceengine.cpp | 620 +++++++----------- src/rendering/renderengine.cpp | 51 +- src/scene/scene.cpp | 1 - src/scripting/scriptengine.cpp | 14 +- tests/main.cpp | 1 - 30 files changed, 1026 insertions(+), 1201 deletions(-) create mode 100644 include/openspace/engine/configuration.h delete mode 100644 include/openspace/engine/configurationmanager.h create mode 100644 src/engine/configuration.cpp rename src/engine/{configurationmanager_doc.inl => configuration_doc.inl} (74%) delete mode 100644 src/engine/configurationmanager.cpp diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index 765ce7f5df..150b507a87 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include #include @@ -313,10 +313,10 @@ void mainInitFunc() { #endif // OPENSPACE_HAS_SPOUT } - std::string k = openspace::ConfigurationManager::KeyScreenshotUseDate; std::string screenshotPath = "${SCREENSHOTS}"; std::string screenshotNames = "OpenSpace"; - if (OsEng.configurationManager().hasKey(k)) { + + if (OsEng.configuration().shouldUseScreenshotDate) { std::time_t now = std::time(nullptr); std::tm* nowTime = std::localtime(&now); char mbstr[100]; diff --git a/apps/Sync/main.cpp b/apps/Sync/main.cpp index 22ecaa259f..202b717c67 100644 --- a/apps/Sync/main.cpp +++ b/apps/Sync/main.cpp @@ -23,7 +23,6 @@ ****************************************************************************************/ #include -#include #include #include #include diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 85a206d436..34219a479f 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -44,7 +44,6 @@ #include #include #include -#include #include #include #include diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h new file mode 100644 index 0000000000..1b2ef2760c --- /dev/null +++ b/include/openspace/engine/configuration.h @@ -0,0 +1,134 @@ +/***************************************************************************************** + * * + * 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___CONFIGURATION___H__ +#define __OPENSPACE_CORE___CONFIGURATION___H__ + +#include +#include +#include +#include +#include + +namespace openspace { + +namespace documentation { struct Documentation; } + +struct Configuration { + std::string windowConfiguration = "${CONFIG}/single.xml"; + std::string asset = "default"; + std::vector globalCustomizationScripts; + std::map pathTokens; + std::map fonts; + + struct Logging { + std::string level = "Info"; + std::string directory = "${BASE}"; + std::string performancePrefix = "PM-"; + bool forceImmediateFlush = false; + std::string capabilitiesVerbosity = "Default"; + std::vector logs; + }; + Logging logging; + + std::string scriptLog = ""; + + struct DocumentationInfo { + std::string lua = ""; + std::string property = ""; + std::string sceneProperty = ""; + std::string keyboard = ""; + std::string documentation = ""; + std::string factory = ""; + std::string license = ""; + }; + DocumentationInfo documentation; + + bool useMultithreadedInitialization = false; + + struct LoadingScreen { + bool isShowingMessages = true; + bool isShowingNodeNames = true; + bool isShowingProgressbar = true; + }; + LoadingScreen loadingScreen; + + bool isCheckingOpenGLState = false; + bool isLoggingOpenGLCalls = false; + + float shutdownCountdown = 0.f; + + bool shouldUseScreenshotDate = false; + + std::string onScreenTextScaling = "window"; + bool usePerSceneCache = false; + + bool isRenderingOnMasterDisabled = false; + bool isSceneTranslationOnMasterDisabled = false; + + std::map moduleConfigurations; + + std::string renderingMethod = "Framebuffer"; + + struct OpenGLDebugContext { + bool isActive = false; + bool isSynchronous = true; + struct IdentifierFilter { + std::string type = ""; + std::string source = ""; + unsigned int identifier = 0; + }; + std::vector identifierFilters; + std::vector severityFilters; + }; + OpenGLDebugContext openGLDebugContext; + + std::string serverPasskey = "17308"; + bool doesRequireSocketAuthentication = true; + std::vector clientAddressWhitelist = {}; + std::string webHelperLocation = ""; + std::string cefWebGuiUrl = ""; + + struct HTTPProxy { + bool usingHttpProxy = false; + std::string address; + unsigned int port = 0; + std::string authentication = "BASIC"; + std::string user; + std::string password; + }; + HTTPProxy httpProxy; + + + static documentation::Documentation Documentation; + ghoul::lua::LuaState state; +}; + +std::string findConfiguration(const std::string& filename = "openspace.cfg"); + +Configuration loadConfigurationFromFile(const std::string& filename); + +} // namespace openspace + +#endif // __OPENSPACE_CORE___CONFIGURATION___H__ diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h deleted file mode 100644 index 63881b2dd3..0000000000 --- a/include/openspace/engine/configurationmanager.h +++ /dev/null @@ -1,282 +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___CONFIGURATIONMANAGER___H__ -#define __OPENSPACE_CORE___CONFIGURATIONMANAGER___H__ - -#include - -namespace openspace { - -namespace documentation { struct Documentation; } - -/** - * The ConfigurationManager takes care of loading the major configuration file - * openspace.cfg and making it available to the rest of the application. The - * exposed keys in the ghoul::Dictionary are declared in this class as static constants. - * The findConfiguration method walks the filesystem from a provided starting point until - * it found the requested file or throws a ghoul::RuntimeError if it could not find the - * file. The loadFromFile method then loads the file into a ghoul::Dictionary format. - */ -class ConfigurationManager : public ghoul::Dictionary { -public: - /// The key that stores the subdirectory containing all predefined path tokens - static constexpr const char* KeyPaths = "Paths"; - - /// The key that stores the location to the cache directory used to store all the - /// permanent and non-permanent cached files - static constexpr const char* KeyCachePath = "Paths.CACHE"; - - /// The key that stores the main directory for fonts - static constexpr const char* KeyFonts = "Fonts"; - - /// The key that stores the location of the SGCT configuration file that is used on - /// application launch - static constexpr const char* KeyConfigSgct = "SGCTConfig"; - - /// The key that defines a list of scripts for global customization that get executed - /// regardless of which scene is loaded - static constexpr const char* KeyGlobalCustomizationScripts = - "GlobalCustomizationScripts"; - - /// The part of the key that defines the type - // static constexpr const char* PartType = "Type"; - /// The part of the key that defines the file - // static constexpr const char* PartFile = "File"; - - /// The key that stores the Lua documentation - static constexpr const char* KeyLuaDocumentation = "LuaDocumentation"; - - /// The key that stores the scripting log - static constexpr const char* KeyScriptLog = "ScriptLog"; - - /// The key that stores the Scene Property documentation - static constexpr const char* KeyScenePropertyDocumentation = - "ScenePropertyDocumentation"; - - /// The key that stores the Root Property documentation - static constexpr const char* KeyPropertyDocumentation = "PropertyDocumentation"; - - /// The key that stores the keyboard bindings that should be stored - static constexpr const char* KeyKeyboardShortcuts = "KeyboardShortcuts"; - - /// The key that stores the main documentation - static constexpr const char* KeyDocumentation = "Documentation"; - - /// The key that stores the factory documentation values - static constexpr const char* KeyFactoryDocumentation = "FactoryDocumentation"; - /// The key that decides whether or not we should require incoming web socket - /// connections to authorize or not - static constexpr const char* KeyRequireSocketAuthentication = - "RequireSocketAuthentication"; - - /// The key that stores the location of the asset file that is initially loaded - static constexpr const char* KeyConfigAsset = "Asset"; - - /// The key that stores the scene license documentation values - static constexpr const char* KeySceneLicenseDocumentation = "LicenseDocumentation"; - - /// The key that stores the settings for determining log-related settings - static constexpr const char* KeyLogging = "Logging"; - - /// The key that stores the directory for Logging - static constexpr const char* LoggingDirectory = "Logging.LogDir"; - static constexpr const char* PartLogDir = "LogDir"; - - /// The key that stores the desired LogLevel for the whole application - /// \sa ghoul::logging::LogManager - static constexpr const char* KeyLoggingLogLevel = "Logging.LogLevel"; - static constexpr const char* PartLogLevel = "LogLevel"; - - /// The key that stores whether the log should be immediately flushed after a n - /// \sa ghoul::logging::LogManager - static constexpr const char* KeyLoggingImmediateFlush = "Logging.ImmediateFlush"; - static constexpr const char* PartImmediateFlush = "ImmediateFlush"; - - /// The key for prefixing PerformanceMeasurement logfiles - static constexpr const char* LoggingPerformancePrefix = "Logging.PerformancePrefix"; - static constexpr const char* PartLogPerformancePrefix = "PerformancePrefix"; - /// The key that stores a subdirectory with a description for additional - /// ghoul::logging::Log%s to be created - /// \sa LogFactory - static constexpr const char* KeyLoggingLogs = "Logging.Logs"; - static constexpr const char* PartLogs = "Logs"; - - /// The key that stores whether a log should be appended to or should be overwritten - static constexpr const char* PartAppend = "Append"; - - /// The key that stores the verbosity (None, Minimal, Default, Full) of the system - /// capabilities components - static constexpr const char* PartCapabilitiesVerbosity = "CapabilitiesVerbosity"; - - /// The key that stores the settings for determining Launcher-related settings - static constexpr const char* KeyLauncher = "Launcher"; - - /// The full key that stores the verbosity of the system capabilities component - static constexpr const char* KeyCapabilitiesVerbosity = - "Logging.CapabilitiesVerbosity"; - - /// The key that stores the time (in seconds) that the application will wait before - /// shutting down after the shutdown call is made - static constexpr const char* KeyShutdownCountdown = "ShutdownCountdown"; - - /// The key that stores whether the onscreen text should be scaled to the window size - /// or the window resolution - static constexpr const char* KeyOnScreenTextScaling = "OnScreenTextScaling"; - - /// The key that stores whether the master node should perform rendering just function - /// as a pure manager - static constexpr const char* KeyDisableMasterRendering = "DisableRenderingOnMaster"; - - /// The key that stores whether the master node should apply the scene transformation - static constexpr const char* KeyDisableSceneOnMaster = "DisableSceneOnMaster"; - - /// The key that stores the switch for enabling/disabling the rendering on a master - /// computer - static constexpr const char* KeyRenderingMethod = "RenderingMethod"; - - /// The key that determines whether a new cache folder is used for each scene file - static constexpr const char* KeyPerSceneCache = "PerSceneCache"; - - /// The key that stores the http proxy settings for the downloadmanager - static constexpr const char* KeyHttpProxy = "HttpProxy"; - - /// The key that stores the address of the http proxy - static constexpr const char* PartHttpProxyAddress = "Address"; - - /// The key that stores the port of the http proxy - static constexpr const char* PartHttpProxyPort = "Port"; - - /// The key that stores the authentication method of the http proxy - static constexpr const char* PartHttpProxyAuthentication = "Authentication"; - - /// Key that stores the username to use for authentication to access the http proxy - static constexpr const char* PartHttpProxyUser = "User"; - - /// Key that stores the password to use for authentication to access the http proxy - static constexpr const char* PartHttpProxyPassword = "Password"; - - /// The key that stores the dictionary containing information about debug contexts - static constexpr const char* KeyOpenGLDebugContext = "OpenGLDebugContext"; - - /// The part of the key storing whether an OpenGL Debug context should be created - static constexpr const char* PartActivate = "Activate"; - - /// The part of the key storing whether the debug callbacks are performed synchronous - static constexpr const char* PartSynchronous = "Synchronous"; - - /// The part of the key storing a list of identifiers that should be filtered out - static constexpr const char* PartFilterIdentifier = "FilterIdentifier"; - - /// The part of the key that stores the source of the ignored identifier - static constexpr const char* PartFilterIdentifierSource = "Source"; - - /// The part of the key that stores the type of the ignored identifier - static constexpr const char* PartFilterIdentifierType = "Type"; - - /// The part of the key that stores the identifier of the ignored identifier - static constexpr const char* PartFilterIdentifierIdentifier = "Identifier"; - - /// The part of the key storing a list of severities that should be filtered out - static constexpr const char* PartFilterSeverity = "PartFilterSeverity"; - - /// The part of the key storing whether the OpenGL state should be checked each call - static constexpr const char* KeyCheckOpenGLState = "CheckOpenGLState"; - - /// The part of the key storing whether the OpenGL state should be checked each call - static constexpr const char* KeyServerPasskey = "ServerPasskey"; - - /// Whitelist of client addresses that won't need autorization - static constexpr const char* KeyServerClientAddressWhitelist = - "ClientAddressWhitelist"; - - static constexpr const char* KeyLogEachOpenGLCall = "LogEachOpenGLCall"; - - /// This key determines whether the scene graph nodes should initialized multithreaded - static constexpr const char* KeyUseMultithreadedInitialization = - "UseMultithreadedInitialization"; - - /// The key under which all of the loading settings are grouped - static constexpr const char* KeyLoadingScreen = "LoadingScreen"; - - /// The part of the key storing whether the loading screen should display the message - /// about current status - static constexpr const char* KeyLoadingScreenShowMessage = - "LoadingScreen.ShowMessage"; - static constexpr const char* PartShowMessage = "ShowMessage"; - - /// The part of the key storing whether the loading screen should display node names - static constexpr const char* KeyLoadingScreenShowNodeNames = - "LoadingScreen.ShowNodeNames"; - static constexpr const char* PartShowNodeNames = "ShowNodeNames"; - - /// The part of the key storing whether the loading screen should contain a progress - /// bar - static constexpr const char* KeyLoadingScreenShowProgressbar = - "LoadingScreen.ShowProgressbar"; - static constexpr const char* PartShowProgressbar = "ShowProgressbar"; - - /// The key used to specify module specific configurations - static constexpr const char* KeyModuleConfigurations = "ModuleConfigurations"; - - /// The key used to specify whether screenshots should contain the current date - static constexpr const char* KeyScreenshotUseDate = "ScreenshotUseDate"; - - static constexpr const char* KeyWebHelperLocation = "WebHelperLocation"; - static constexpr const char* KeyCefWebGuiUrl = "CefWebGuiUrl"; - - /** - * Iteratively walks the directory structure starting with \p filename to find the - * base name compoenent of \p filename. The directory structure is searched by first - * searching the current directory and then moving iteratively to the the parent - * directory. - * \param filename The fully qualified filename to be searched for - * \return The path to the file that was found with the same base name as \p filename - * but higher up in the file structure. - * \throw ghoul::RuntimeError If the configuration could not be found - */ - static std::string findConfiguration(const std::string& filename); - - /** - * Load the provided configuration file (\p filename) into this Dictionary. All paths - * that are specified in the configuration file will automatically be registered in - * the ghoul::filesystem::FileSystem. - * \param filename The filename to be loaded - * \throw SpecificationError If the configuration file was not complete (i.e., did - * not specify the necessary keys KeyPaths, KeyPaths.KeyCache, KeyFonts, and - * KeyConfigSgct) - * \throw ghoul::lua::LuaRuntimeException If there was Lua-based error loading the - * configuration file - * \pre \p filename must not be empty - * \pre \p filename must exist - */ - void loadFromFile(const std::string& filename); - - - static documentation::Documentation Documentation(); -}; - -} // namespace openspace - -#endif // __OPENSPACE_CORE___CONFIGURATIONMANAGER___H__ diff --git a/include/openspace/engine/moduleengine.h b/include/openspace/engine/moduleengine.h index 57f6766e63..51cf4b43ec 100644 --- a/include/openspace/engine/moduleengine.h +++ b/include/openspace/engine/moduleengine.h @@ -33,6 +33,7 @@ #include #include +#include namespace ghoul::systemcapabilities { struct Version; } @@ -59,7 +60,7 @@ public: * \throw ghoul::RuntimeError If two modules in the default modules have the same * name */ - void initialize(const ghoul::Dictionary& moduleConfigurations); + void initialize(const std::map& moduleConfigurations); /** * Calls the initializeGL functions of all registered OpenSpaceModule%s. diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 400aba618a..efc6f9b511 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -44,7 +44,7 @@ namespace ghoul::fontrendering { class FontManager; } namespace openspace { class AssetManager; -class ConfigurationManager; +struct Configuration; class Dashboard; class DownloadManager; class GUI; @@ -121,8 +121,9 @@ public: void scheduleLoadSingleAsset(std::string assetPath); void toggleShutdownMode(); + const Configuration& configuration() const; + // Guaranteed to return a valid pointer - ConfigurationManager& configurationManager(); LuaConsole& console(); AssetManager& assetManager(); Dashboard& dashboard(); @@ -205,8 +206,9 @@ private: void runGlobalCustomizationScripts(); void configureLogging(); + std::unique_ptr _configuration; + // Components - std::unique_ptr _configurationManager; std::unique_ptr _scene; std::unique_ptr _assetManager; std::unique_ptr _dashboard; diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index 7c42e0d450..cc3cdbd9e2 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -42,7 +42,6 @@ #include #include -#include #include #include #include diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index a59d9b850d..8230576c5b 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include diff --git a/modules/base/rendering/renderablesphericalgrid.cpp b/modules/base/rendering/renderablesphericalgrid.cpp index e59f0a274e..560d85b485 100644 --- a/modules/base/rendering/renderablesphericalgrid.cpp +++ b/modules/base/rendering/renderablesphericalgrid.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include #include diff --git a/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp b/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp index b4c139a39b..99152c8343 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/gdalwrapper.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include // abspath #include @@ -142,64 +142,24 @@ GdalWrapper::GdalWrapper(size_t maximumCacheSize, size_t maximumMaximumCacheSize } void GdalWrapper::setGdalProxyConfiguration() { - ghoul::Dictionary proxySettings; - bool proxyEnabled = OsEng.configurationManager().getValue( - ConfigurationManager::KeyHttpProxy, proxySettings - ); - if (proxyEnabled) { - std::string proxyAddress, proxyPort, proxyUser, proxyPassword, - proxyAuth; + if (OsEng.configuration().httpProxy.usingHttpProxy) { + std::string address = OsEng.configuration().httpProxy.address; + unsigned int port = OsEng.configuration().httpProxy.port; + std::string user = OsEng.configuration().httpProxy.user; + std::string password = OsEng.configuration().httpProxy.password; + std::string auth = OsEng.configuration().httpProxy.authentication; + std::transform(auth.begin(), auth.end(), auth.begin(), ::toupper); - bool success = proxySettings.getValue( - ConfigurationManager::PartHttpProxyAddress, - proxyAddress - ); - success &= proxySettings.getValue( - ConfigurationManager::PartHttpProxyPort, - proxyPort - ); - proxySettings.getValue( - ConfigurationManager::PartHttpProxyAuthentication, - proxyAuth - ); + std::string proxy = address + ":" + std::to_string(port); + CPLSetConfigOption("GDAL_HTTP_PROXY", proxy.c_str()); + LDEBUG(fmt::format("Using proxy server {}", proxy)); - std::string proxyAuthString = "BASIC"; - if (proxyAuth == "basic" || proxyAuth == "") { - proxyAuthString = "BASIC"; - } else if (proxyAuth == "ntlm") { - proxyAuthString = "NTLM"; - } else if (proxyAuth == "digest") { - proxyAuthString = "DIGEST"; - } else if (proxyAuth == "any") { - proxyAuthString = "ANY"; - } else { - success = false; + if (!user.empty() && !password.empty()) { + std::string userPwd = user + ":" + password; + CPLSetConfigOption("GDAL_HTTP_PROXYUSERPWD", userPwd.c_str()); + CPLSetConfigOption("GDAL_HTTP_PROXYAUTH", auth.c_str()); + LDEBUG(fmt::format("Using authentication method: {}", auth)); } - - bool userAndPassword = proxySettings.getValue( - ConfigurationManager::PartHttpProxyUser, - proxyUser - ); - userAndPassword &= proxySettings.getValue( - ConfigurationManager::PartHttpProxyPassword, - proxyPassword - ); - - if (success) { - std::string proxy = proxyAddress + ":" + proxyPort; - CPLSetConfigOption("GDAL_HTTP_PROXY", proxy.c_str()); - LDEBUG(fmt::format("Using proxy server {}", proxy)); - if (userAndPassword) { - std::string proxyUserPwd = proxyUser + ":" + proxyPassword; - CPLSetConfigOption("GDAL_HTTP_PROXYUSERPWD", proxyUserPwd.c_str()); - CPLSetConfigOption("GDAL_HTTP_PROXYAUTH", proxyAuthString.c_str()); - LDEBUG(fmt::format("Using authentication method: {}", proxyAuthString)); - } - } else { - LERROR("Invalid proxy settings for GDAL"); - } - } else { - LDEBUG("Setting up GDAL without proxy server"); } } diff --git a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp index 80693eac88..14826c1b3a 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp @@ -38,8 +38,6 @@ #include #include -#include - #include #include #include diff --git a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp index 2c4defa9fe..f23dd643e2 100644 --- a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp +++ b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include diff --git a/modules/server/include/connection.h b/modules/server/include/connection.h index 3cc26508f2..c025a6b667 100644 --- a/modules/server/include/connection.h +++ b/modules/server/include/connection.h @@ -34,7 +34,6 @@ #include #include #include -#include #include "topic.h" diff --git a/modules/server/src/connection.cpp b/modules/server/src/connection.cpp index e6e4e7a0fb..bc7eab0b11 100644 --- a/modules/server/src/connection.cpp +++ b/modules/server/src/connection.cpp @@ -23,6 +23,7 @@ ****************************************************************************************/ #include + #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include namespace { constexpr const char* _loggerCat = "ServerModule: Connection"; @@ -67,15 +69,7 @@ Connection::Connection(std::shared_ptr s, const std::string & _topicFactory.registerClass(BounceTopicKey); // see if the default config for requiring auth (on) is overwritten - const bool hasAuthConfiguration = OsEng.configurationManager().hasKeyAndValue( - ConfigurationManager::KeyRequireSocketAuthentication - ); - if (hasAuthConfiguration) { - _requireAuthorization = OsEng.configurationManager().value( - ConfigurationManager::KeyRequireSocketAuthentication); - } else { - _requireAuthorization = true; - } + _requireAuthorization = OsEng.configuration().doesRequireSocketAuthentication; } void Connection::handleMessage(std::string message) { @@ -186,16 +180,8 @@ void Connection::setAuthorized(const bool status) { } bool Connection::isWhitelisted() { - const bool hasWhitelist = OsEng.configurationManager().hasKeyAndValue( - ConfigurationManager::KeyServerClientAddressWhitelist); - - if (!hasWhitelist) { - return false; - } - - const auto whitelist = OsEng.configurationManager().value( - ConfigurationManager::KeyServerClientAddressWhitelist); - return whitelist.find(_address) != std::string::npos; + const std::vector& wl = OsEng.configuration().clientAddressWhitelist; + return std::find(wl.begin(), wl.end(), _address) != wl.end(); } } // namespace openspace diff --git a/modules/server/src/topics/authorizationtopic.cpp b/modules/server/src/topics/authorizationtopic.cpp index c693dad79c..dc7c811c4b 100644 --- a/modules/server/src/topics/authorizationtopic.cpp +++ b/modules/server/src/topics/authorizationtopic.cpp @@ -24,15 +24,18 @@ #include "include/authorizationtopic.h" +#include + namespace { -std::string _loggerCat = "AuthorizationTopic"; -} + constexpr const char* _loggerCat = "AuthorizationTopic"; +} // namespace namespace openspace { - AuthorizationTopic::AuthorizationTopic() - : Topic() - , _isAuthenticated(false) {}; +AuthorizationTopic::AuthorizationTopic() + : Topic() + , _isAuthenticated(false) +{}; bool AuthorizationTopic::isDone() { return _isAuthenticated; @@ -69,14 +72,7 @@ bool AuthorizationTopic::authorize(const std::string key) { } const std::string AuthorizationTopic::getKey() const { - bool hasConfigPassword = OsEng.configurationManager().hasKeyAndValue( - ConfigurationManager::KeyServerPasskey); - if (hasConfigPassword) { - return OsEng.configurationManager().value( - ConfigurationManager::KeyServerPasskey); - } - - return "17308"; + return OsEng.configuration().serverPasskey; } nlohmann::json AuthorizationTopic::message(const std::string& message, diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 9abaf7762f..4cb55d409e 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -27,7 +27,6 @@ #include #include -#include #include #include #include diff --git a/modules/sync/syncmodule.cpp b/modules/sync/syncmodule.cpp index 1a42018370..b206a5c177 100644 --- a/modules/sync/syncmodule.cpp +++ b/modules/sync/syncmodule.cpp @@ -30,7 +30,6 @@ #include #include -#include #include #include #include diff --git a/openspace.cfg b/openspace.cfg index c50197e970..d2c01f1da4 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -2,135 +2,134 @@ -- require('scripts/configuration_helper.lua') -- which defines helper functions useful to customize the configuration -return { - -- Determines which SGCT configuration file is loaded, that is, if there rendering - -- occurs in a single window, a fisheye projection, or a dome cluster system +-- Determines which SGCT configuration file is loaded, that is, if there rendering +-- occurs in a single window, a fisheye projection, or a dome cluster system - -- A regular 1280x720 window - SGCTConfig = sgct.config.single{}, +-- A regular 1280x720 window +SGCTConfig = sgct.config.single{} - -- A regular 1920x1080 window - -- SGCTConfig = sgct.config.single{1920, 1080}, +-- A regular 1920x1080 window +-- SGCTConfig = sgct.config.single{1920, 1080} - -- A windowed 1920x1080 fullscreen - -- SGCTConfig = sgct.config.single{1920, 1080, border=false, windowPos={0,0}, shared=true, name="WV_OBS_SPOUT1"}, +-- A windowed 1920x1080 fullscreen +-- SGCTConfig = sgct.config.single{1920, 1080, border=false, windowPos={0,0}, shared=true, name="WV_OBS_SPOUT1"} - -- A 1k fisheye rendering - -- SGCTConfig = sgct.config.fisheye{1024, 1024}, +-- A 1k fisheye rendering +-- SGCTConfig = sgct.config.fisheye{1024, 1024} - -- A 4k fisheye rendering in a 1024x1024 window - -- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27}, +-- A 4k fisheye rendering in a 1024x1024 window +-- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} - -- Streaming OpenSpace via Spout to OBS - -- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"}, +-- Streaming OpenSpace via Spout to OBS +-- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"} - -- SGCTConfig = "${CONFIG}/spout_output.xml", +-- SGCTConfig = "${CONFIG}/spout_output.xml" - --SGCTConfig = "${CONFIG}/openvr_oculusRiftCv1.xml", - --SGCTConfig = "${CONFIG}/openvr_htcVive.xml", +--SGCTConfig = "${CONFIG}/openvr_oculusRiftCv1.xml" +--SGCTConfig = "${CONFIG}/openvr_htcVive.xml" - -- Sets the scene that is to be loaded by OpenSpace. A scene file is a description - -- of all entities that will be visible during an instance of OpenSpace +-- Sets the scene that is to be loaded by OpenSpace. A scene file is a description +-- of all entities that will be visible during an instance of OpenSpace - Asset = "default", - -- Asset = "default_full", - -- Asset = "newhorizons", - -- Asset = "rosetta", - -- Asset = "osirisrex", - -- Asset = "voyager", +Asset = "default" +-- Asset = "default_full" +-- Asset = "newhorizons" +-- Asset = "rosetta" +-- Asset = "osirisrex" +-- Asset = "voyager" - -- These scripts are executed after the initialization of each scene, thus making - -- it possible to have global overrides to default values or execute other scripts - -- regardless of the scene that is loaded - GlobalCustomizationScripts = { - "${SCRIPTS}/customization.lua" +-- These scripts are executed after the initialization of each scene, thus making +-- it possible to have global overrides to default values or execute other scripts +-- regardless of the scene that is loaded +GlobalCustomizationScripts = { + "${SCRIPTS}/customization.lua" +} + +Paths = { + DATA = "${BASE}/data", + ASSETS = "${DATA}/assets", + FONTS = "${DATA}/fonts", + TASKS = "${DATA}/tasks", + SYNC = "${BASE}/sync", + SCREENSHOTS = "${BASE}/screenshots", + WEB = "${DATA}/web", + + CACHE = "${BASE}/cache", + CONFIG = "${BASE}/config", + DOCUMENTATION = "${BASE}/documentation", + LOGS = "${BASE}/logs", + MODULES = "${BASE}/modules", + SCRIPTS = "${BASE}/scripts", + SHADERS = "${BASE}/shaders" +} +Fonts = { + Mono = "${FONTS}/Bitstream-Vera-Sans-Mono/VeraMono.ttf", + Light = "${FONTS}/Roboto/Roboto-Regular.ttf", + Console = "${FONTS}/Inconsolata/Inconsolata-Regular.ttf", + Loading = "${FONTS}/Roboto/Roboto-Regular.ttf" +} +Logging = { + LogDir = "${LOGS}", + -- LogLevel = "Trace", + LogLevel = "Debug", + ImmediateFlush = true, + Logs = { + { Type = "html", File = "${LOGS}/log.html", Append = false } }, + CapabilitiesVerbosity = "Full" +} +ScriptLog = "${LOGS}/ScriptLog.txt" - Paths = { - DATA = "${BASE}/data", - ASSETS = "${DATA}/assets", - FONTS = "${DATA}/fonts", - TASKS = "${DATA}/tasks", - SYNC = "${BASE}/sync", - SCREENSHOTS = "${BASE}/screenshots", - WEB = "${DATA}/web", - - CACHE = "${BASE}/cache", - CONFIG = "${BASE}/config", - DOCUMENTATION = "${BASE}/documentation", - LOGS = "${BASE}/logs", - MODULES = "${BASE}/modules", - SCRIPTS = "${BASE}/scripts", - SHADERS = "${BASE}/shaders" - }, - Fonts = { - Mono = "${FONTS}/Bitstream-Vera-Sans-Mono/VeraMono.ttf", - Light = "${FONTS}/Roboto/Roboto-Regular.ttf", - Console = "${FONTS}/Inconsolata/Inconsolata-Regular.ttf", - Loading = "${FONTS}/Roboto/Roboto-Regular.ttf" - }, - Logging = { - LogDir = "${LOGS}", - -- LogLevel = "Trace", - LogLevel = "Debug", - ImmediateFlush = true, - Logs = { - { Type = "html", File = "${LOGS}/log.html", Append = false } - }, - CapabilitiesVerbosity = "Full" - }, - ScriptLog = "${LOGS}/ScriptLog.txt", - - Launcher = { - LogLevel = "None" - }, +Documentation = { LuaDocumentation = "${DOCUMENTATION}/LuaScripting.html", PropertyDocumentation = "${DOCUMENTATION}/Properties.html", ScenePropertyDocumentation = "${DOCUMENTATION}/SceneProperties.html", KeyboardShortcuts = "${DOCUMENTATION}/KeyboardMapping.html", Documentation = "${DOCUMENTATION}/Documentation.html", FactoryDocumentation = "${DOCUMENTATION}/FactoryDocumentation.html", - LicenseDocumentation = "${DOCUMENTATION}/License.html", - - UseMultithreadedInitialization = true, - LoadingScreen = { - ShowMessage = true, - ShowNodeNames = true, - ShowProgressbar = true - }, - CheckOpenGLState = false, - LogEachOpenGLCall = false, - - ShutdownCountdown = 3, - ScreenshotUseDate = true, - -- OnScreenTextScaling = "framebuffer", - -- PerSceneCache = true, - -- DisableRenderingOnMaster = true, - -- DisableSceneOnMaster = true, - ModuleConfigurations = { - Sync = { - SynchronizationRoot = "${SYNC}", - HttpSynchronizationRepositories = { - "data.openspaceproject.com/request" - } - } - }, - RenderingMethod = "Framebuffer", - OpenGLDebugContext = { - Activate = false, - FilterIdentifier = { - { Type = "Other", Source = "API", Identifier = 131185 }, - { Type = "Performance", Source = "API", Identifier = 131186 }, --Buffer performance warning: "copied/moved from VIDEO memory to HOST memory" - { Type = "Deprecated", Source = "API", Identifier = 7} -- API_ID_LINE_WIDTH deprecated behavior warning has been generated - }, --- FilterSeverity = { } - }, - --RenderingMethod = "ABuffer" -- alternative: "Framebuffer", - - ServerPasskey = "secret!", - ClientAddressWhitelist = "127.0.0.1 localhost", - WebHelperLocation = "${BASE}/bin/Release/openspace_web_helper", - -- CefWebGuiUrl = "file://${BASE_PATH}/gui/index.html#/onscreen/" - CefWebGuiUrl = "http://localhost:8080/#/onscreen/" } + +UseMultithreadedInitialization = true +LoadingScreen = { + ShowMessage = true, + ShowNodeNames = true, + ShowProgressbar = true +} +CheckOpenGLState = false +LogEachOpenGLCall = false + +ShutdownCountdown = 3 +ScreenshotUseDate = true +-- OnScreenTextScaling = "framebuffer" +-- PerSceneCache = true +-- DisableRenderingOnMaster = true +-- DisableSceneOnMaster = true +ModuleConfigurations = { + Sync = { + SynchronizationRoot = "${SYNC}", + HttpSynchronizationRepositories = { + "data.openspaceproject.com/request" + } + } +} +RenderingMethod = "Framebuffer" +OpenGLDebugContext = { + Activate = false, + FilterIdentifier = { + { Type = "Other", Source = "API", Identifier = 131185 }, + { Type = "Performance", Source = "API", Identifier = 131186 }, --Buffer performance warning: "copied/moved from VIDEO memory to HOST memory" + { Type = "Deprecated", Source = "API", Identifier = 7} -- API_ID_LINE_WIDTH deprecated behavior warning has been generated + }, +-- FilterSeverity = { } +} +--RenderingMethod = "ABuffer" -- alternative: "Framebuffer" + +ServerPasskey = "secret!" +ClientAddressWhitelist = { + "127.0.0.1", + "localhost" +} +WebHelperLocation = "${BASE}/bin/Release/openspace_web_helper" +-- CefWebGuiUrl = "file://${BASE_PATH}/gui/index.html#/onscreen/" +CefWebGuiUrl = "http://localhost:8080/#/onscreen/" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e1821936f3..a58f401cc2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -31,8 +31,10 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/documentation/documentationengine.cpp ${OPENSPACE_BASE_DIR}/src/documentation/documentationgenerator.cpp ${OPENSPACE_BASE_DIR}/src/documentation/verifier.cpp - ${OPENSPACE_BASE_DIR}/src/engine/configurationmanager.cpp - ${OPENSPACE_BASE_DIR}/src/engine/configurationmanager_doc.inl + ${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/logfactory.cpp ${OPENSPACE_BASE_DIR}/src/engine/moduleengine.cpp @@ -202,7 +204,7 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/documentation/documentationgenerator.h ${OPENSPACE_BASE_DIR}/include/openspace/documentation/verifier.h ${OPENSPACE_BASE_DIR}/include/openspace/documentation/verifier.inl - ${OPENSPACE_BASE_DIR}/include/openspace/engine/configurationmanager.h + ${OPENSPACE_BASE_DIR}/include/openspace/engine/configuration.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/downloadmanager.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/logfactory.h ${OPENSPACE_BASE_DIR}/include/openspace/engine/moduleengine.h diff --git a/src/documentation/core_registration.cpp b/src/documentation/core_registration.cpp index 0c1db348bc..01d5a297fe 100644 --- a/src/documentation/core_registration.cpp +++ b/src/documentation/core_registration.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -52,7 +51,6 @@ namespace openspace { void registerCoreClasses(documentation::DocumentationEngine& engine) { - engine.addDocumentation(ConfigurationManager::Documentation()); engine.addDocumentation(LogFactoryDocumentation()); engine.addDocumentation(Mission::Documentation()); engine.addDocumentation(Renderable::Documentation()); diff --git a/src/engine/configuration.cpp b/src/engine/configuration.cpp new file mode 100644 index 0000000000..f74e601bf5 --- /dev/null +++ b/src/engine/configuration.cpp @@ -0,0 +1,350 @@ +/***************************************************************************************** + * * + * 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 + +namespace { + constexpr const char* BasePathToken = "${BASE}"; + // We can't use ${SCRIPTS} here as that hasn't been defined by this point + constexpr const char* InitialConfigHelper = + "${BASE}/scripts/configuration_helper.lua"; + + // Variable names for the openspace.cfg file + // These are also used in the _doc include file + constexpr const char* KeySGCTConfig = "SGCTConfig"; + constexpr const char* KeyAsset = "Asset"; + constexpr const char* KeyGlobalCustomizationScripts = "GlobalCustomizationScripts"; + constexpr const char* KeyPaths = "Paths"; + constexpr const char* KeyPathsCACHE = "Paths.CACHE"; + constexpr const char* KeyFonts = "Fonts"; + constexpr const char* KeyLogging = "Logging"; + constexpr const char* KeyLogDir = "LogDir"; + constexpr const char* KeyPerformancePrefix = "PerformancePrefix"; + constexpr const char* KeyLogLevel = "LogLevel"; + constexpr const char* KeyImmediateFlush = "ImmediateFlush"; + constexpr const char* KeyLogs = "Logs"; + constexpr const char* KeyCapabilitiesVerbosity = "CapabilitiesVerbosity"; + constexpr const char* KeyLuaDocumentation = "LuaDocumentation"; + constexpr const char* KeyPropertyDocumentation = "PropertyDocumentation"; + constexpr const char* KeyScriptLog = "ScriptLog"; + constexpr const char* KeyKeyboardShortcuts = "KeyboardShortcuts"; + constexpr const char* KeyDocumentation = "Documentation"; + constexpr const char* KeyFactoryDocumentation = "FactoryDocumentation"; + constexpr const char* KeyRequireSocketAuthentication = "RequireSocketAuthentication"; + constexpr const char* KeyServerPasskey = "ServerPasskey"; + constexpr const char* KeyClientAddressWhitelist = "ClientAddressWhitelist"; + constexpr const char* KeyLicenseDocumentation = "LicenseDocumentation"; + constexpr const char* KeyShutdownCountdown = "ShutdownCountdown"; + constexpr const char* KeyPerSceneCache = "PerSceneCache"; + constexpr const char* KeyOnScreenTextScaling = "OnScreenTextScaling"; + constexpr const char* KeyRenderingMethod = "RenderingMethod"; + constexpr const char* KeyDisableRenderingOnMaster = "DisableRenderingOnMaster"; + constexpr const char* KeyDisableSceneOnMaster = "DisableSceneOnMaster"; + constexpr const char* KeyScreenshotUseDate = "ScreenshotUseDate"; + constexpr const char* KeyHttpProxy = "HttpProxy"; + constexpr const char* KeyAddress = "Address"; + constexpr const char* KeyPort = "Port"; + constexpr const char* KeyAuthentication = "Authentication"; + constexpr const char* KeyUser = "User"; + constexpr const char* KeyPassword = "Password"; + constexpr const char* KeyOpenGLDebugContext = "OpenGLDebugContext"; + constexpr const char* KeyActivate = "Activate"; + constexpr const char* KeySynchronous = "Synchronous"; + constexpr const char* KeyFilterIdentifier = "FilterIdentifier"; + constexpr const char* KeyIdentifier = "Identifier"; + constexpr const char* KeySource = "Source"; + constexpr const char* KeyType = "Type"; + constexpr const char* KeyFilterSeverity = "FilterSeverity"; + constexpr const char* KeyCheckOpenGLState = "CheckOpenGLState"; + constexpr const char* KeyLogEachOpenGLCall = "LogEachOpenGLCall"; + constexpr const char* KeyUseMultithreadedInitialization = + "UseMultithreadedInitialization"; + constexpr const char* KeyLoadingScreen = "LoadingScreen"; + constexpr const char* KeyShowMessage = "ShowMessage"; + constexpr const char* KeyShowNodeNames = "ShowNodeNames"; + constexpr const char* KeyShowProgressbar = "ShowProgressbar"; + constexpr const char* KeyModuleConfigurations = "ModuleConfigurations"; +} // 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"); + } + + 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; + } + 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; + } + 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; + } + 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; + } + } + 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); + } + 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); + } + 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; + } + } + 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); + } +} + +void parseLuaState(Configuration& configuration) { + using namespace ghoul::lua; + + // Shorten the rest of this function + Configuration& c = configuration; + LuaState& s = c.state; + + getValue(s, KeySGCTConfig, c.windowConfiguration); + getValue(s, KeyAsset, c.asset); + getValue(s, KeyGlobalCustomizationScripts, c.globalCustomizationScripts); + getValue(s, KeyPaths, c.pathTokens); + getValue(s, KeyFonts, c.fonts); + getValue(s, KeyScriptLog, c.scriptLog); + getValue(s, KeyUseMultithreadedInitialization, c.useMultithreadedInitialization); + getValue(s, KeyCheckOpenGLState, c.isCheckingOpenGLState); + getValue(s, KeyLogEachOpenGLCall, c.isLoggingOpenGLCalls); + getValue(s, KeyShutdownCountdown, c.shutdownCountdown); + getValue(s, KeyScreenshotUseDate, c.shouldUseScreenshotDate); + getValue(s, KeyOnScreenTextScaling, c.onScreenTextScaling); + getValue(s, KeyPerSceneCache, c.usePerSceneCache); + getValue(s, KeyDisableRenderingOnMaster, c.isRenderingOnMasterDisabled); + getValue(s, KeyDisableSceneOnMaster, c.isSceneTranslationOnMasterDisabled); + getValue(s, KeyRenderingMethod, c.renderingMethod); + getValue(s, KeyServerPasskey, c.serverPasskey); + getValue(s, KeyRequireSocketAuthentication, c.doesRequireSocketAuthentication); + getValue(s, KeyClientAddressWhitelist, c.clientAddressWhitelist); + getValue(s, "WebHelperLocation", c.webHelperLocation); + getValue(s, "CefWebGuiUrl", c.cefWebGuiUrl); + + getValue(s, KeyLogging, c.logging); + getValue(s, KeyDocumentation, c.documentation); + getValue(s, KeyLoadingScreen, c.loadingScreen); + getValue(s, KeyModuleConfigurations, c.moduleConfigurations); + getValue(s, KeyOpenGLDebugContext, c.openGLDebugContext); + getValue(s, KeyHttpProxy, c.httpProxy); +} + +std::string findConfiguration(const std::string& filename) { + using ghoul::filesystem::Directory; + + Directory directory = FileSys.currentDirectory(); + + while (true) { + std::string fullPath = FileSys.pathByAppendingComponent( + directory, + filename + ); + + if (FileSys.fileExists(fullPath)) { + // We have found the configuration file and can bail out + return fullPath; + } + + // Otherwise, we traverse the directory tree up + Directory nextDirectory = directory.parentDirectory( + ghoul::filesystem::Directory::AbsolutePath::Yes + ); + + if (directory.path() == nextDirectory.path()) { + // We have reached the root of the file system and did not find the file + throw ghoul::RuntimeError( + "Could not find configuration file '" + filename + "'", + "ConfigurationManager" + ); + } + directory = nextDirectory; + } +} + +Configuration loadConfigurationFromFile(const std::string& filename) { + ghoul_assert(!filename.empty(), "Filename must not be empty"); + ghoul_assert(FileSys.fileExists(filename), "File must exist"); + + Configuration result; + + // Register the base path as the directory where 'filename' lives + std::string basePath = ghoul::filesystem::File(filename).directoryName(); + FileSys.registerPathToken(BasePathToken, basePath); + + // If there is an initial config helper file, load it into the state + if (FileSys.fileExists(absPath(InitialConfigHelper))) { + ghoul::lua::runScriptFile(result.state, absPath(InitialConfigHelper)); + } + + // Load the configuration file into the state + ghoul::lua::runScriptFile(result.state, filename); + + parseLuaState(result); + + return result; +} + +} // namespace openspace diff --git a/src/engine/configurationmanager_doc.inl b/src/engine/configuration_doc.inl similarity index 74% rename from src/engine/configurationmanager_doc.inl rename to src/engine/configuration_doc.inl index a365448508..69b76c9381 100644 --- a/src/engine/configurationmanager_doc.inl +++ b/src/engine/configuration_doc.inl @@ -27,22 +27,20 @@ namespace openspace { -documentation::Documentation ConfigurationManager::Documentation() { - using namespace documentation; - - return { - "OpenSpace Configuration", - "openspace_configuraion", +using namespace documentation; +documentation::Documentation Configuration::Documentation = { + "OpenSpace Configuration", + "openspace_configuraion", + { { - { - ConfigurationManager::KeyConfigSgct, + KeySGCTConfig, new StringAnnotationVerifier("A valid SGCT configuration file"), Optional::No, "The SGCT configuration file that determines the window and view frustum " "settings that are being used when OpenSpace is started." }, { - ConfigurationManager::KeyConfigAsset, + KeyAsset, new StringAnnotationVerifier( "A valid scene file as described in the Scene documentation" ), @@ -53,7 +51,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "the Scene documentation." }, { - ConfigurationManager::KeyGlobalCustomizationScripts, + KeyGlobalCustomizationScripts, new StringListVerifier, Optional::Yes, "This value names a list of scripts that get executed after initialization " @@ -61,7 +59,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "such as a global rebinding of keys from the default." }, { - ConfigurationManager::KeyPaths, + KeyPaths, new StringListVerifier, Optional::No, "A list of paths that are automatically registered with the file system. " @@ -69,14 +67,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "in all other configuration files or scripts." }, { - ConfigurationManager::KeyCachePath, - new StringVerifier, - Optional::No, - "The path to be used as a cache folder. If per scene caching is enabled, the " - "name of the scene will be appended to this folder" - }, - { - ConfigurationManager::KeyFonts, + KeyFonts, new StringListVerifier("Font paths loadable by FreeType"), Optional::Yes, "A list of all fonts that will automatically be loaded on startup. Each " @@ -84,23 +75,23 @@ documentation::Documentation ConfigurationManager::Documentation() { "for a font." }, { - ConfigurationManager::KeyLogging, + KeyLogging, new TableVerifier({ { - ConfigurationManager::PartLogDir, + KeyLogDir, new StringVerifier, Optional::Yes, "The directory for logs. Default value is \"${BASE}\"" }, { - ConfigurationManager::PartLogPerformancePrefix, + KeyPerformancePrefix, new StringVerifier, Optional::Yes, "A string to prefix PerformanceMeasurement logfiles." "Default value is \"PM-\"" }, { - ConfigurationManager::PartLogLevel, + KeyLogLevel, new StringInListVerifier( // List from logmanager.cpp::levelFromString { "Trace", "Debug", "Info", "Warning", "Error", "Fatal", "None" } @@ -112,7 +103,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "severities is: Debug < Info < Warning < Error < Fatal < None." }, { - ConfigurationManager::PartImmediateFlush, + KeyImmediateFlush, new BoolVerifier, Optional::Yes, "Determines whether error messages will be displayed immediately " @@ -122,7 +113,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "logged." }, { - ConfigurationManager::PartLogs, + KeyLogs, new TableVerifier({ { "*", @@ -138,7 +129,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "be used additionally." }, { - ConfigurationManager::PartCapabilitiesVerbosity, + KeyCapabilitiesVerbosity, new StringInListVerifier( // List from OpenspaceEngine::initialize { "None", "Minimal", "Default", "Full" } @@ -154,22 +145,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "other information." }, { - ConfigurationManager::KeyLuaDocumentation, - new StringVerifier, - Optional::Yes, - "The filename that will be created on startup containing the documentation " - "of available Lua functions that can be executed in scene files or per " - "console. Any existing file will be silently overwritten." - }, - { - ConfigurationManager::KeyPropertyDocumentation, - new StringVerifier, - Optional::Yes, - "The file that will be created on startup containing a list of all " - "properties in the scene. Any existing file will be silently overwritten." - }, - { - ConfigurationManager::KeyScriptLog, + KeyScriptLog, new StringVerifier, Optional::Yes, "The file that will be created on startup containing the log of all Lua " @@ -177,78 +153,84 @@ documentation::Documentation ConfigurationManager::Documentation() { "the results from previous runs) will be silently overwritten." }, { - ConfigurationManager::KeyKeyboardShortcuts, - new StringVerifier, + KeyDocumentation, + new TableVerifier({ + { + KeyLuaDocumentation, + new StringVerifier, + Optional::Yes, + "The filename that will be created on startup containing the " + "documentation of available Lua functions that can be executed in " + "scene files or per console. Any existing file will be silently " + "overwritten." + }, + { + KeyPropertyDocumentation, + new StringVerifier, + Optional::Yes, + "The file that will be created on startup containing a list of all " + "properties in the scene. Any existing file will be silently " + "overwritten." + }, + { + KeyKeyboardShortcuts, + new StringVerifier, + Optional::Yes, + "The file that will be created on startup containing the list of all " + "keyboard bindings with their respective Lua scripts. For each key, " + "it mentions which scripts will be executed in the current session." + }, + { + KeyDocumentation, + new StringVerifier, + Optional::Yes, + "The file that will be created on startup containing this " + "documentation. Any previous file in this location will be silently " + "overwritten." + }, + { + KeyFactoryDocumentation, + new StringVerifier, + Optional::Yes, + "The file that will be created on startup containing the factory " + "documentation which shows the different types of objects that can " + "be created in the current application configuration. Any previous " + "file in this location will be silently overritten." + }, + { + KeyLicenseDocumentation, + new StringVerifier, + Optional::Yes, + "The file that will be created on startup containing the scene " + "license information. Any previous file in this location will be " + "silently overwritten." + }, + }), Optional::Yes, - "The file that will be created on startup containing the list of all " - "keyboard bindings with their respective Lua scripts. For each key, it " - "mentions which scripts will be executed in the current session." + "All documentations that are generated at application startup." }, { - ConfigurationManager::KeyDocumentation, - new StringVerifier, - Optional::Yes, - "The file that will be created on startup containing this documentation. Any " - "previous file in this location will be silently overwritten." - }, - { - ConfigurationManager::KeyFactoryDocumentation, - new StringVerifier, - Optional::Yes, - "The file that will be created on startup containing the factory " - "documentation which shows the different types of objects that can be " - "created in the current application configuration. Any previous file in this " - "location will be silently overritten." - }, - { - ConfigurationManager::KeyRequireSocketAuthentication, + KeyRequireSocketAuthentication, new BoolVerifier, Optional::Yes, "If socket connections should be authenticated or not before they are " "allowed to get or set information. Defaults to 'true'." }, { - ConfigurationManager::KeyServerPasskey, + KeyServerPasskey, new StringVerifier, Optional::Yes, "Passkey to limit server access. Used to authorize incoming connections." }, { - ConfigurationManager::KeyServerClientAddressWhitelist, - new StringVerifier, + KeyClientAddressWhitelist, + new StringListVerifier, Optional::Yes, - "String containing white listed client IP addresses that won't need to be " + "String containing white listed client IP addresses that won't need to be" "authorized with the server. Space separated" }, { - ConfigurationManager::KeySceneLicenseDocumentation, - new StringVerifier, - Optional::Yes, - "The file that will be created on startup containing the scene license " - "information. Any previous file in this location will be silently " - "overwritten." - }, - { - ConfigurationManager::KeyLauncher, - new TableVerifier({ - { - ConfigurationManager::PartLogLevel, - new StringInListVerifier( - // List from logmanager.cpp::levelFromString - { "Trace", "Debug", "Info", "Warning", "Error", "Fatal", "None" } - ), - Optional::Yes, - "The severity of log messages that will be displayed. Only " - "messages of the selected level or higher will be displayed. All " - "levels below will be silently discarded. The order of " - "severities is: Debug < Info < Warning < Error < Fatal < None." - }, - }), - Optional::Yes, - "Configurations for the Launcher & syncing application." - }, - { - ConfigurationManager::KeyShutdownCountdown, + KeyShutdownCountdown, new DoubleGreaterEqualVerifier(0.0), Optional::Yes, "The countdown that the application will wait between pressing ESC and " @@ -256,7 +238,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "shutdown is aborted." }, { - ConfigurationManager::KeyPerSceneCache, + KeyPerSceneCache, new BoolVerifier, Optional::Yes, "If this is set to 'true', the name of the scene will be appended to the " @@ -265,7 +247,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "the caches should be retained. This value defaults to 'false'." }, { - ConfigurationManager::KeyOnScreenTextScaling, + KeyOnScreenTextScaling, new StringInListVerifier({ // Values from RenderEngine:updateRenderer "window", "framebuffer" @@ -277,7 +259,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "rendering resolution ('framebuffer'). This value defaults to 'window'." }, { - ConfigurationManager::KeyRenderingMethod, + KeyRenderingMethod, new StringInListVerifier( // List from RenderEngine::setRendererFromString { "Framebuffer", "ABuffer" } @@ -287,7 +269,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "support for at least OpenGL 4.3" }, { - ConfigurationManager::KeyDisableMasterRendering, + KeyDisableRenderingOnMaster, new BoolVerifier, Optional::Yes, "Toggles whether the master in a multi-application setup should be rendering " @@ -295,7 +277,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "the master computer does not have the resources to render a scene." }, { - ConfigurationManager::KeyDisableSceneOnMaster, + KeyDisableSceneOnMaster, new BoolVerifier, Optional::Yes, "Toggles whether a potential scene transformation matrix, for example as " @@ -305,7 +287,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "default is false." }, { - ConfigurationManager::KeyScreenshotUseDate, + KeyScreenshotUseDate, new BoolVerifier, Optional::Yes, "Toggles whether screenshots generated by OpenSpace contain the date when " @@ -314,22 +296,28 @@ documentation::Documentation ConfigurationManager::Documentation() { "individual frames pass beyond local midnight." }, { - ConfigurationManager::KeyHttpProxy, + KeyHttpProxy, new TableVerifier({ { - ConfigurationManager::PartHttpProxyAddress, + KeyActivate, + new BoolVerifier, + Optional::Yes, + "Determines whether the proxy is being used" + }, + { + KeyAddress, new StringVerifier, Optional::No, "The address of the http proxy" }, { - ConfigurationManager::PartHttpProxyPort, - new StringVerifier, + KeyPort, + new IntVerifier, Optional::No, "The port of the http proxy" }, { - ConfigurationManager::PartHttpProxyAuthentication, + KeyAuthentication, new StringInListVerifier( { "basic", "ntlm", "digest", "any" } ), @@ -337,13 +325,13 @@ documentation::Documentation ConfigurationManager::Documentation() { "The authentication method of the http proxy" }, { - ConfigurationManager::PartHttpProxyUser, + KeyUser, new StringVerifier, Optional::Yes, "The user of the http proxy" }, { - ConfigurationManager::PartHttpProxyPassword, + KeyPassword, new StringVerifier, Optional::Yes, "The password of the http proxy" @@ -354,16 +342,16 @@ documentation::Documentation ConfigurationManager::Documentation() { "No proxy will be used if this is left out." }, { - ConfigurationManager::KeyOpenGLDebugContext, + KeyOpenGLDebugContext, new TableVerifier({ { - ConfigurationManager::PartActivate, + KeyActivate, new BoolVerifier, Optional::No, "Determines whether the OpenGL context should be a debug context" }, { - ConfigurationManager::PartSynchronous, + KeySynchronous, new BoolVerifier, Optional::Yes, "Determines whether the OpenGL debug callbacks are performed " @@ -372,18 +360,18 @@ documentation::Documentation ConfigurationManager::Documentation() { "triggered the message. The default value is ." }, { - ConfigurationManager::PartFilterIdentifier, + KeyFilterIdentifier, new TableVerifier({{ "*", new TableVerifier({ { - ConfigurationManager::PartFilterIdentifierIdentifier, + KeyIdentifier, new IntVerifier, Optional::No, "The identifier that is to be filtered" }, { - ConfigurationManager::PartFilterIdentifierSource, + KeySource, new StringInListVerifier({ // Taken from ghoul::debugcontext.cpp "API", "Window System", "Shader Compiler", @@ -393,7 +381,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "The source of the identifier to be filtered" }, { - ConfigurationManager::PartFilterIdentifierType, + KeyType, new StringInListVerifier({ // Taken from ghoul::debugcontext.cpp "Error", "Deprecated", "Undefined", "Portability", @@ -411,7 +399,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "A list of OpenGL debug messages identifiers that are filtered" }, { - ConfigurationManager::PartFilterSeverity, + KeyFilterSeverity, new TableVerifier({ { "*", @@ -430,7 +418,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "Determines the settings for the creation of an OpenGL debug context.", }, { - ConfigurationManager::KeyCheckOpenGLState, + KeyCheckOpenGLState, new BoolVerifier, Optional::Yes, "Determines whether the OpenGL state is checked after each OpenGL function " @@ -438,7 +426,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "OpenGL errors easier. This defaults to 'false'." }, { - ConfigurationManager::KeyLogEachOpenGLCall, + KeyLogEachOpenGLCall, new BoolVerifier, Optional::Yes, "Determines whether each OpenGL call that happens should be logged using the " @@ -447,7 +435,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "defaults to 'false'." }, { - ConfigurationManager::KeyUseMultithreadedInitialization, + KeyUseMultithreadedInitialization, new BoolVerifier, Optional::Yes, "This value determines whether the initialization of the scene graph should " @@ -456,17 +444,17 @@ documentation::Documentation ConfigurationManager::Documentation() { "debugging support." }, { - ConfigurationManager::KeyLoadingScreen, + KeyLoadingScreen, new TableVerifier({ { - ConfigurationManager::PartShowMessage, + KeyShowMessage, new BoolVerifier, Optional::Yes, "If this value is set to 'true', the loading screen will display a " "message information about the current phase the loading is in." }, { - ConfigurationManager::PartShowNodeNames, + KeyShowNodeNames, new BoolVerifier, Optional::Yes, "If this value is set to 'true', the loading screen will display a " @@ -474,7 +462,7 @@ documentation::Documentation ConfigurationManager::Documentation() { "loaded, initialized)." }, { - ConfigurationManager::PartShowProgressbar, + KeyShowProgressbar, new BoolVerifier, Optional::Yes, "If this value is set to 'true', the loading screen will contain a " @@ -486,14 +474,12 @@ documentation::Documentation ConfigurationManager::Documentation() { "displayed while the scene graph is created and initialized." }, { - ConfigurationManager::KeyModuleConfigurations, + KeyModuleConfigurations, new TableVerifier, Optional::Yes, "Configurations for each module" } - } - }; -} - + } +}; } // namespace openspace diff --git a/src/engine/configurationmanager.cpp b/src/engine/configurationmanager.cpp deleted file mode 100644 index 9db7940a23..0000000000 --- a/src/engine/configurationmanager.cpp +++ /dev/null @@ -1,144 +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 -#include -#include -#include -#include -#include -#include - -using std::string; - -#include "configurationmanager_doc.inl" - -namespace { - const char* _configurationFile = "openspace.cfg"; - const char* _keyBasePath = "BASE"; - // We can't use ${SCRIPTS} here as that hasn't been defined by this point - const char* _initialConfigHelper = "${BASE}/scripts/configuration_helper.lua"; -} // namespace - -namespace openspace { - -string ConfigurationManager::findConfiguration(const string& filename) { - using ghoul::filesystem::Directory; - - Directory directory = FileSys.currentDirectory(); - - while (true) { - std::string fullPath = FileSys.pathByAppendingComponent( - directory, - _configurationFile - ); - - if (FileSys.fileExists(fullPath)) { - // We have found the configuration file and can bail out - return fullPath; - } - - // Otherwise, we traverse the directory tree up - Directory nextDirectory = directory.parentDirectory( - ghoul::filesystem::Directory::AbsolutePath::Yes - ); - - if (directory.path() == nextDirectory.path()) { - // We have reached the root of the file system and did not find the file - throw ghoul::RuntimeError( - "Could not find configuration file '" + filename + "'", - "ConfigurationManager" - ); - } - directory = nextDirectory; - } -} - -void ConfigurationManager::loadFromFile(const string& filename) { - using ghoul::filesystem::FileSystem; - - ghoul_assert(!filename.empty(), "Filename must not be empty"); - ghoul_assert(FileSys.fileExists(filename), "File must exist"); - - // ${BASE} - string basePathToken = FileSystem::TokenOpeningBraces + string(_keyBasePath) + - FileSystem::TokenClosingBraces; - - // Retrieving the directory in which the configuration file lies - string basePath = ghoul::filesystem::File(filename).directoryName(); - FileSys.registerPathToken(basePathToken, basePath); - - ghoul::lua::LuaState state; - - if (FileSys.fileExists(absPath(_initialConfigHelper))) { - ghoul::lua::runScriptFile(state, absPath(_initialConfigHelper)); - } - - // Loading the configuration file into ourselves - ghoul::lua::loadDictionaryFromFile(filename, *this, state); - - // Perform testing against the documentation/specification - openspace::documentation::testSpecificationAndThrow( - ConfigurationManager::Documentation(), - *this, - "ConfigurationManager" - ); - - // Register all the paths - ghoul::Dictionary dictionary = value(KeyPaths); - - for (std::string key : dictionary.keys()) { - std::string p = dictionary.value(key); - std::string fullKey = - FileSystem::TokenOpeningBraces + key + FileSystem::TokenClosingBraces; - LDEBUGC("ConfigurationManager", - fmt::format("Registering path {}: {}", fullKey, p) - ); - - bool override = (basePathToken == fullKey); - if (override) { - LINFOC( - "ConfigurationManager", - fmt::format("Overriding base path with '{}'", p) - ); - } - - using Override = ghoul::filesystem::FileSystem::Override; - FileSys.registerPathToken( - std::move(fullKey), - std::move(p), - override ? Override::Yes : Override::No - ); - } - - // Remove the Paths dictionary from the configuration manager as those paths might - // change later and we don't want to be forced to keep our local copy up to date - removeKey(KeyPaths); -} - -} // namespace openspace diff --git a/src/engine/moduleengine.cpp b/src/engine/moduleengine.cpp index d43b403abd..547c11a30d 100644 --- a/src/engine/moduleengine.cpp +++ b/src/engine/moduleengine.cpp @@ -46,12 +46,15 @@ ModuleEngine::ModuleEngine() : properties::PropertyOwner({"Modules"}) {} -void ModuleEngine::initialize(const ghoul::Dictionary& moduleConfigurations) { +void ModuleEngine::initialize( + const std::map& moduleConfigurations) +{ for (OpenSpaceModule* m : AllModules()) { const std::string identifier = m->identifier(); + auto it = moduleConfigurations.find(identifier); ghoul::Dictionary configuration; - if (moduleConfigurations.hasKey(identifier)) { - moduleConfigurations.getValue(identifier, configuration); + if (it != moduleConfigurations.end()) { + configuration = it->second; } registerModule(std::unique_ptr(m), configuration); } diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index ddbea6a0e9..59daaf9043 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include #include @@ -111,7 +111,6 @@ using namespace ghoul::cmdparser; namespace { constexpr const char* _loggerCat = "OpenSpaceEngine"; - constexpr const char* SgctDefaultConfigFile = "${CONFIG}/single.xml"; constexpr const char* SgctConfigArgumentCommand = "-config"; @@ -150,7 +149,7 @@ OpenSpaceEngine* OpenSpaceEngine::_engine = nullptr; OpenSpaceEngine::OpenSpaceEngine(std::string programName, std::unique_ptr windowWrapper) - : _configurationManager(new ConfigurationManager) + : _configuration(new Configuration) , _scene(nullptr) , _dashboard(new Dashboard) , _downloadManager(nullptr) @@ -309,8 +308,7 @@ void OpenSpaceEngine::create(int argc, char** argv, std::string configurationFilePath = commandlineArgumentPlaceholders.configurationName; if (configurationFilePath.empty()) { LDEBUG("Finding configuration"); - configurationFilePath = - ConfigurationManager::findConfiguration(configurationFilePath); + configurationFilePath = findConfiguration(); } configurationFilePath = absPath(configurationFilePath); @@ -324,7 +322,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Loading configuration from disk LDEBUG("Loading configuration from disk"); try { - _engine->configurationManager().loadFromFile(configurationFilePath); + *_engine->_configuration = loadConfigurationFromFile(configurationFilePath); } catch (const documentation::SpecificationError& e) { LFATAL(fmt::format( @@ -346,19 +344,45 @@ void OpenSpaceEngine::create(int argc, char** argv, throw; } + + // 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) + { + std::string fullKey = + FileSystem::TokenOpeningBraces + path.first + FileSystem::TokenClosingBraces; + LDEBUGC( + "ConfigurationManager", + fmt::format("Registering path {}: {}", fullKey, path.second) + ); + + bool override = (fullKey == "${BASE}"); + if (override) { + LINFOC( + "ConfigurationManager", + 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 + ); + } + + const bool hasCacheCommandline = !commandlineArgumentPlaceholders.cacheFolder.empty(); - const bool hasCacheConfig = _engine->configurationManager().hasKeyAndValue( - ConfigurationManager::KeyPerSceneCache - ); + const bool hasCacheConfig = _engine->_configuration->usePerSceneCache; std::string cacheFolder = absPath("${CACHE}"); if (hasCacheCommandline || hasCacheConfig) { if (hasCacheCommandline) { cacheFolder = commandlineArgumentPlaceholders.cacheFolder; } if (hasCacheConfig) { - std::string scene = _engine->configurationManager().value( - ConfigurationManager::KeyConfigAsset - ); + std::string scene = _engine->_configuration->asset; cacheFolder += "-" + ghoul::filesystem::File(scene).baseName(); } @@ -385,18 +409,8 @@ void OpenSpaceEngine::create(int argc, char** argv, LINFOC("OpenSpace Version", std::string(OPENSPACE_VERSION_STRING_FULL)); LINFOC("Commit", std::string(OPENSPACE_GIT_FULL)); - ghoul::Dictionary moduleConfigurations; - if (_engine->configurationManager().hasKeyAndValue( - ConfigurationManager::KeyModuleConfigurations)) - { - _engine->configurationManager().getValue( - ConfigurationManager::KeyModuleConfigurations, - moduleConfigurations - ); - } - // Register modules - _engine->_moduleEngine->initialize(moduleConfigurations); + _engine->_moduleEngine->initialize(_engine->_configuration->moduleConfigurations); // After registering the modules, the documentations for the available classes // can be added as well @@ -406,6 +420,8 @@ void OpenSpaceEngine::create(int argc, char** argv, } } + DocEng.addDocumentation(Configuration::Documentation); + // Create the cachemanager try { FileSys.createCacheManager(cacheFolder, CacheVersion); @@ -420,10 +436,8 @@ void OpenSpaceEngine::create(int argc, char** argv, // Determining SGCT configuration file LDEBUG("Determining SGCT configuration file"); - std::string sgctConfigurationPath = SgctDefaultConfigFile; - _engine->configurationManager().getValue( - ConfigurationManager::KeyConfigSgct, sgctConfigurationPath); - + std::string sgctConfigurationPath = _engine->_configuration->windowConfiguration; + if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) { LDEBUG(fmt::format( "Overwriting SGCT configuration file with commandline argument: {}", @@ -509,27 +523,24 @@ void OpenSpaceEngine::initialize() { LDEBUG("Detecting capabilities"); SysCap.detectCapabilities(); - using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity; - Verbosity verbosity = Verbosity::Default; - if (configurationManager().hasKey(ConfigurationManager::KeyCapabilitiesVerbosity)) { - static const std::map VerbosityMap = { - { "None", Verbosity::None }, - { "Minimal", Verbosity::Minimal }, - { "Default", Verbosity::Default }, - { "Full", Verbosity::Full } - }; - std::string v = configurationManager().value( - ConfigurationManager::KeyCapabilitiesVerbosity - ); - ghoul_assert( - VerbosityMap.find(v) != VerbosityMap.end(), - "Missing check for syscaps verbosity in openspace.cfg documentation" - ); - verbosity = VerbosityMap.find(v)->second; - } + using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity; + static const std::map VerbosityMap = { + { "None", Verbosity::None }, + { "Minimal", Verbosity::Minimal }, + { "Default", Verbosity::Default }, + { "Full", Verbosity::Full } + }; + + std::string v = _engine->_configuration->logging.capabilitiesVerbosity; + ghoul_assert( + VerbosityMap.find(v) != VerbosityMap.end(), + "Missing check for syscaps verbosity in openspace.cfg documentation" + ); + Verbosity verbosity = VerbosityMap.find(v)->second; SysCap.logCapabilities(verbosity); + // Check the required OpenGL versions of the registered modules ghoul::systemcapabilities::Version version = _engine->_moduleEngine->requiredOpenGLVersion(); @@ -563,18 +574,11 @@ void OpenSpaceEngine::initialize() { scriptEngine().initialize(); writeStaticDocumentation(); - - if (configurationManager().hasKey(ConfigurationManager::KeyShutdownCountdown)) { - _shutdown.waitTime = static_cast(configurationManager().value( - ConfigurationManager::KeyShutdownCountdown - )); - } + + _shutdown.waitTime = _engine->_configuration->shutdownCountdown; if (!commandlineArgumentPlaceholders.sceneName.empty()) { - configurationManager().setValue( - ConfigurationManager::KeyConfigAsset, - commandlineArgumentPlaceholders.sceneName - ); + _engine->_configuration->asset = commandlineArgumentPlaceholders.sceneName; } // Initialize the NavigationHandler @@ -592,8 +596,7 @@ void OpenSpaceEngine::initialize() { func(); } - std::string assetPath = ""; - configurationManager().getValue(ConfigurationManager::KeyConfigAsset, assetPath); + std::string assetPath = _engine->_configuration->asset; _engine->_assetManager->initialize(); scheduleLoadSingleAsset(assetPath); @@ -606,26 +609,10 @@ void OpenSpaceEngine::scheduleLoadSingleAsset(std::string assetPath) { } std::unique_ptr OpenSpaceEngine::createLoadingScreen() { - bool showMessage = true; - constexpr const char* kMessage = ConfigurationManager::KeyLoadingScreenShowMessage; - if (configurationManager().hasKey(kMessage)) { - showMessage = configurationManager().value(kMessage); - } + bool showMessage = _configuration->loadingScreen.isShowingMessages; + bool showNodeNames = _configuration->loadingScreen.isShowingNodeNames; + bool showProgressbar = _configuration->loadingScreen.isShowingProgressbar; - bool showNodeNames = true; - constexpr const char* kNames = ConfigurationManager::KeyLoadingScreenShowNodeNames; - - if (configurationManager().hasKey(kNames)) { - showNodeNames = configurationManager().value(kNames); - } - - bool showProgressbar = true; - constexpr const char* kProgress = - ConfigurationManager::KeyLoadingScreenShowProgressbar; - - if (configurationManager().hasKey(kProgress)) { - showProgressbar = configurationManager().value(kProgress); - } return std::make_unique( LoadingScreen::ShowMessage(showMessage), LoadingScreen::ShowNodeNames(showNodeNames), @@ -656,12 +643,8 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { _rootPropertyOwner->removePropertySubOwner(_scene.get()); } - bool multiThreadedInitialization = configurationManager().hasKeyAndValue( - ConfigurationManager::KeyUseMultithreadedInitialization - ) && configurationManager().value( - ConfigurationManager::KeyUseMultithreadedInitialization - ); - + bool multiThreadedInitialization = _configuration->useMultithreadedInitialization; + std::unique_ptr sceneInitializer; if (multiThreadedInitialization) { unsigned int nAvailableThreads = std::thread::hardware_concurrency(); @@ -796,29 +779,18 @@ void OpenSpaceEngine::deinitialize() { void OpenSpaceEngine::writeStaticDocumentation() { // If a LuaDocumentationFile was specified, generate it now - if (configurationManager().hasKey(ConfigurationManager::KeyLuaDocumentation)) { - _scriptEngine->writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyLuaDocumentation - )) - ); + if (!_configuration->documentation.lua.empty()) { + _scriptEngine->writeDocumentation(absPath(_configuration->documentation.lua)); } // If a general documentation was specified, generate it now - if (configurationManager().hasKey(ConfigurationManager::KeyDocumentation)) { - DocEng.writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyDocumentation - )) - ); + if (!_configuration->documentation.documentation.empty()) { + DocEng.writeDocumentation(absPath(_configuration->documentation.documentation)); } - // If a factory documentation was specified, generate it now - if (configurationManager().hasKey(ConfigurationManager::KeyFactoryDocumentation)) { + if (!_configuration->documentation.factory.empty()) { FactoryManager::ref().writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyFactoryDocumentation - )) + absPath(_configuration->documentation.factory) ); } } @@ -857,49 +829,44 @@ void OpenSpaceEngine::runGlobalCustomizationScripts() { ghoul::lua::LuaState state; OsEng.scriptEngine().initializeLuaState(state); - std::string k = ConfigurationManager::KeyGlobalCustomizationScripts; - if (_configurationManager->hasKey(k)) { - ghoul::Dictionary dict = _configurationManager->value(k); - for (int i = 1; i <= static_cast(dict.size()); ++i) { - std::string script = absPath(dict.value(std::to_string(i))); - - if (FileSys.fileExists(script)) { - try { - LINFO(fmt::format("Running global customization script: {}", script)); - ghoul::lua::runScriptFile(state, script); - } catch (ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } - } - else { - LDEBUG(fmt::format("Ignoring non-existing script file: {}", script)); + for (const std::string& script : _configuration->globalCustomizationScripts) { + std::string s = absPath(script); + if (FileSys.fileExists(s)) { + try { + LINFO(fmt::format("Running global customization script: {}", s)); + ghoul::lua::runScriptFile(state, s); + } catch (const ghoul::RuntimeError& e) { + LERRORC(e.component, e.message); } } + else { + LDEBUG(fmt::format("Ignoring non-existing script file: {}", s)); + } } } void OpenSpaceEngine::loadFonts() { - ghoul::Dictionary fonts; - configurationManager().getValue(ConfigurationManager::KeyFonts, fonts); - _fontManager = std::make_unique(FontAtlasSize); - for (const std::string& key : fonts.keys()) { - std::string font = absPath(fonts.value(key)); + for (const std::pair& font : _configuration->fonts) { + std::string key = font.first; + std::string fontName = absPath(font.second); - if (!FileSys.fileExists(font)) { - LERROR(fmt::format("Could not find font '{}'", font)); + if (!FileSys.fileExists(fontName)) { + LERROR(fmt::format("Could not find font '{}' for key '{}'", fontName, key)); continue; } - LDEBUG(fmt::format("Registering font '{}' with key '{}'", font, key)); - bool success = _fontManager->registerFontPath(key, font); + LDEBUG(fmt::format("Registering font '{}' with key '{}'", fontName, key)); + bool success = _fontManager->registerFontPath(key, fontName); if (!success) { - LERROR(fmt::format("Error registering font '{}' with key '{}'", font, key)); + LERROR(fmt::format( + "Error registering font '{}' with key '{}'", fontName, key + )); } } - + try { bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); if (!initSuccess) { @@ -919,42 +886,28 @@ void OpenSpaceEngine::loadFonts() { } void OpenSpaceEngine::configureLogging(bool consoleLog) { - constexpr const char* KeyLogLevel = ConfigurationManager::KeyLoggingLogLevel; - constexpr const char* KeyLogImmediateFlush = - ConfigurationManager::KeyLoggingImmediateFlush; - constexpr const char* KeyLogs = ConfigurationManager::KeyLoggingLogs; + // We previously initialized the LogManager with a console log to provide some logging + // until we know which logs should be added + LogManager::deinitialize(); - if (configurationManager().hasKeyAndValue(KeyLogLevel)) { - std::string logLevel = "Info"; - configurationManager().getValue(KeyLogLevel, logLevel); + LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); + bool immediateFlush = _configuration->logging.forceImmediateFlush; - bool immediateFlush = false; - configurationManager().getValue(KeyLogImmediateFlush, immediateFlush); - - LogLevel level = ghoul::logging::levelFromString(logLevel); - LogManager::deinitialize(); - using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; - LogManager::initialize( - level, - immediateFlush ? ImmediateFlush::Yes : ImmediateFlush::No - ); - if (consoleLog) { - LogMgr.addLog(std::make_unique()); - } + using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; + LogManager::initialize( + level, + immediateFlush ? ImmediateFlush::Yes : ImmediateFlush::No + ); + if (consoleLog) { + LogMgr.addLog(std::make_unique()); } - if (configurationManager().hasKeyAndValue(KeyLogs)) { - ghoul::Dictionary logs = configurationManager().value(KeyLogs); - - for (size_t i = 1; i <= logs.size(); ++i) { - ghoul::Dictionary logInfo = logs.value(std::to_string(i)); - - try { - LogMgr.addLog(createLog(logInfo)); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } + for (const ghoul::Dictionary& log : _configuration->logging.logs) { + try { + LogMgr.addLog(createLog(log)); + } + catch (const ghoul::RuntimeError& e) { + LERRORC(e.component, e.message); } } @@ -980,40 +933,25 @@ void OpenSpaceEngine::configureLogging(bool consoleLog) { void OpenSpaceEngine::writeSceneDocumentation() { // Write keyboard documentation. - if (configurationManager().hasKey(ConfigurationManager::KeyKeyboardShortcuts)) { + if (!_configuration->documentation.keyboard.empty()) { keyBindingManager().writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyKeyboardShortcuts - )) + absPath(_configuration->documentation.keyboard) ); } - if (configurationManager().hasKey(ConfigurationManager::KeySceneLicenseDocumentation)) - { + if (!_configuration->documentation.license.empty()) { _scene->writeSceneLicenseDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeySceneLicenseDocumentation - )) + absPath(_configuration->documentation.license) ); } - // If a PropertyDocumentationFile was specified, generate it now. - if (configurationManager().hasKey( - ConfigurationManager::KeyScenePropertyDocumentation - )) - { - _scene->writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyScenePropertyDocumentation - )) - ); + if (!_configuration->documentation.sceneProperty.empty()) { + _scene->writeDocumentation(absPath(_configuration->documentation.sceneProperty)); } - if (configurationManager().hasKey(ConfigurationManager::KeyPropertyDocumentation)) { + if (!_configuration->documentation.property.empty()) { _rootPropertyOwner->writeDocumentation( - absPath(configurationManager().value( - ConfigurationManager::KeyPropertyDocumentation - )) + absPath(_configuration->documentation.property) ); } } @@ -1031,200 +969,149 @@ void OpenSpaceEngine::initializeGL() { } LTRACE("OpenSpaceEngine::initializeGL::Console::initialize(end)"); - if (_configurationManager->hasKey(ConfigurationManager::KeyOpenGLDebugContext)) { - LTRACE("OpenSpaceEngine::initializeGL::DebugContext(begin)"); - ghoul::Dictionary dict = _configurationManager->value( - ConfigurationManager::KeyOpenGLDebugContext - ); - bool debug = dict.value(ConfigurationManager::PartActivate); + 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 (OpenGLCap.openGLVersion() < minVersion) { - LINFO("OpenGL Debug context requested, but insufficient version available"); - debug = false; - } - - if (debug) { - using namespace ghoul::opengl::debug; - - bool synchronous = true; - if (dict.hasKey(ConfigurationManager::PartSynchronous)) { - synchronous = dict.value(ConfigurationManager::PartSynchronous); - } - - setDebugOutput(DebugOutput(debug), SynchronousOutput(synchronous)); - - if (dict.hasKey(ConfigurationManager::PartFilterIdentifier)) { - ghoul::Dictionary filterDict = dict.value( - ConfigurationManager::PartFilterIdentifier - ); - - for (size_t i = 1; i <= filterDict.size(); ++i) { - ghoul::Dictionary id = filterDict.value( - std::to_string(i) - ); - - const unsigned int identifier = static_cast( - id.value( - ConfigurationManager::PartFilterIdentifierIdentifier - ) - ); - - const std::string s = id.value( - ConfigurationManager::PartFilterIdentifierSource - ); - - const std::string t = id.value( - ConfigurationManager::PartFilterIdentifierType - ); - - setDebugMessageControl( - ghoul::from_string(s), - ghoul::from_string(t), - { identifier }, - Enabled::No - ); - } - } - - if (dict.hasKey(ConfigurationManager::PartFilterSeverity)) { - ghoul::Dictionary filterDict = dict.value( - ConfigurationManager::PartFilterIdentifier - ); - - for (size_t i = 1; i <= filterDict.size(); ++i) { - std::string severity = filterDict.value( - std::to_string(i) - ); - - setDebugMessageControl( - Source::DontCare, - Type::DontCare, - ghoul::from_string(severity), - Enabled::No - ); - } - } - - auto callback = [](Source source, Type type, Severity severity, - unsigned int id, std::string message) -> void - { - const std::string s = std::to_string(source); - const std::string t = std::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)"); + // 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 = std::to_string(source); + const std::string t = std::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 (_configurationManager->hasKey(ConfigurationManager::KeyCheckOpenGLState)) { - const bool val = _configurationManager->value( - ConfigurationManager::KeyCheckOpenGLState - ); - - if (val) { - using namespace glbinding; - 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.toString()) - ); - break; - case GL_INVALID_VALUE: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_VALUE", f.toString()) - ); - break; - case GL_INVALID_OPERATION: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_OPERATION", f.toString()) - ); - break; - case GL_INVALID_FRAMEBUFFER_OPERATION: - LERRORC( - "OpenGL Invalid State", - fmt::format( - "Function {}: GL_INVALID_FRAMEBUFFER_OPERATION", - f.toString() - ) - ); - break; - case GL_OUT_OF_MEMORY: - LERRORC( - "OpenGL Invalid State", - fmt::format("Function {}: GL_OUT_OF_MEMORY", f.toString()) - ); - break; - default: - LERRORC( - "OpenGL Invalid State", - fmt::format("Unknown error code: {0:x}", error) - ); - } - }); - } + 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.toString()) + ); + break; + case GL_INVALID_VALUE: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_INVALID_VALUE", f.toString()) + ); + break; + case GL_INVALID_OPERATION: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_INVALID_OPERATION", f.toString()) + ); + break; + case GL_INVALID_FRAMEBUFFER_OPERATION: + LERRORC( + "OpenGL Invalid State", + fmt::format( + "Function {}: GL_INVALID_FRAMEBUFFER_OPERATION", + f.toString() + ) + ); + break; + case GL_OUT_OF_MEMORY: + LERRORC( + "OpenGL Invalid State", + fmt::format("Function {}: GL_OUT_OF_MEMORY", f.toString()) + ); + break; + default: + LERRORC( + "OpenGL Invalid State", + fmt::format("Unknown error code: {0:x}", error) + ); + } + }); } - if (_configurationManager->hasKey(ConfigurationManager::KeyLogEachOpenGLCall)) { - const bool val = _configurationManager->value( - ConfigurationManager::KeyLogEachOpenGLCall - ); + if (_configuration->isLoggingOpenGLCalls) { + 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, AbstractValue* v) { + return a + ", " + v->asString(); + } + ); - if (val) { - 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, AbstractValue* v) { - return a + ", " + v->asString(); - } - ); + std::string returnValue = call.returnValue ? + " -> " + call.returnValue->asString() : + ""; - std::string returnValue = call.returnValue ? - " -> " + call.returnValue->asString() : - ""; - - LTRACEC( - "OpenGL", - call.function->name() + arguments + returnValue - ); - }); - } + LTRACEC( + "OpenGL", + call.function->name() + arguments + returnValue + ); + }); } LDEBUG("Initializing Rendering Engine"); @@ -1683,9 +1570,8 @@ void OpenSpaceEngine::registerModuleMouseScrollWheelCallback( _moduleCallbacks.mouseScrollWheel.push_back(std::move(function)); } -ConfigurationManager& OpenSpaceEngine::configurationManager() { - ghoul_assert(_configurationManager, "ConfigurationManager must not be nullptr"); - return *_configurationManager; +const Configuration& OpenSpaceEngine::configuration() const { + return *_configuration; } LuaConsole& OpenSpaceEngine::console() { diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 4b0254e367..4b717d7c6a 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include #include @@ -261,22 +261,9 @@ RenderEngine::RenderEngine() _doPerformanceMeasurements.onChange([this](){ if (_doPerformanceMeasurements) { if (!_performanceManager) { - std::string loggingDir = "${BASE}"; - constexpr const char* KeyDir = ConfigurationManager::LoggingDirectory; - if (OsEng.configurationManager().hasKey(KeyDir)) { - loggingDir = OsEng.configurationManager().value(KeyDir); - } - - std::string prefix = "PM-"; - constexpr const char* KeyPrefix = - ConfigurationManager::LoggingPerformancePrefix; - if (OsEng.configurationManager().hasKey(KeyPrefix)) { - prefix = OsEng.configurationManager().value(KeyPrefix); - } - _performanceManager = std::make_shared( - loggingDir, - prefix + OsEng.configuration().logging.directory, + OsEng.configuration().logging.performancePrefix ); } } @@ -352,14 +339,9 @@ void RenderEngine::setRendererFromString(const std::string& renderingMethod) { void RenderEngine::initialize() { _frameNumber = 0; - std::string renderingMethod = DefaultRenderingMethod; - // If the user specified a rendering method that he would like to use, use that - ConfigurationManager& confManager = OsEng.configurationManager(); - if (confManager.hasKeyAndValue(KeyRenderingMethod)) { - renderingMethod = confManager.value(KeyRenderingMethod); - } - else { + 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 @@ -370,17 +352,9 @@ void RenderEngine::initialize() { } } - if (confManager.hasKey(ConfigurationManager::KeyDisableMasterRendering)) { - _disableMasterRendering = confManager.value( - ConfigurationManager::KeyDisableMasterRendering - ); - } - - if (confManager.hasKey(ConfigurationManager::KeyDisableSceneOnMaster)) { - _disableSceneTranslationOnMaster = confManager.value( - ConfigurationManager::KeyDisableSceneOnMaster - ); - } + _disableMasterRendering = OsEng.configuration().isRenderingOnMasterDisabled; + _disableSceneTranslationOnMaster = + OsEng.configuration().isSceneTranslationOnMasterDisabled; _raycasterManager = std::make_unique(); _deferredcasterManager = std::make_unique(); @@ -531,16 +505,11 @@ glm::ivec2 RenderEngine::renderingResolution() const { } glm::ivec2 RenderEngine::fontResolution() const { - std::string value; - bool hasValue = OsEng.configurationManager().getValue( - ConfigurationManager::KeyOnScreenTextScaling, - value - ); - if (hasValue && value == "framebuffer") { + const std::string& value = OsEng.configuration().onScreenTextScaling; + if (value == "framebuffer") { return OsEng.windowWrapper().currentWindowResolution(); } else { - // The default is to use the window size return OsEng.windowWrapper().currentWindowSize(); } } diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index b4a4f25e7c..beddbec00e 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include #include diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index d7839e0749..afc31763f8 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include #include #include @@ -587,16 +587,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 - const bool hasFile = OsEng.configurationManager().hasKey( - ConfigurationManager::KeyScriptLog - ); - if (hasFile) { - OsEng.configurationManager().getValue( - ConfigurationManager::KeyScriptLog, - _logFilename - ); - - _logFilename = absPath(_logFilename); + if (!OsEng.configuration().scriptLog.empty()) { + _logFilename = absPath(OsEng.configuration().scriptLog); _logFileExists = true; LDEBUG(fmt::format( diff --git a/tests/main.cpp b/tests/main.cpp index af3fb23472..22dc7fc4ea 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -49,7 +49,6 @@ #define GHL_THROW_ON_ASSERT #endif // GHL_THROW_ON_ASSERTGHL_THROW_ON_ASSERT -#include #include #include #include From 64d84f3b1059fbe9dca09559965c836bce9c945c Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 19:00:00 -0400 Subject: [PATCH 45/79] Requested changes for merging. Part I. --- .../rendering/atmospheredeferredcaster.cpp | 63 +++++++++---------- modules/space/rendering/renderablestars.cpp | 4 +- .../rendering/renderableplanetprojection.cpp | 2 +- src/rendering/renderable.cpp | 2 +- 4 files changed, 32 insertions(+), 39 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 5e775e4885..eb29abd256 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -89,8 +89,8 @@ namespace { - const char* _loggerCat = "AtmosphereDeferredcaster"; - const char* GlslDeferredcastPath = + constexpr const char* _loggerCat = "AtmosphereDeferredcaster"; + constexpr const char* GlslDeferredcastPath = "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; constexpr const char* GlslDeferredcastFSPath = "${MODULES}/atmosphere/shaders/atmosphere_deferred_fs.glsl"; @@ -183,8 +183,7 @@ namespace openspace { } void AtmosphereDeferredcaster::preRaycast(const RenderData& renderData, - const DeferredcastData&, - ghoul::opengl::ProgramObject& program) + const DeferredcastData&, ghoul::opengl::ProgramObject& program) { // Atmosphere Frustum Culling glm::dvec3 tPlanetPosWorld = glm::dvec3( @@ -257,16 +256,12 @@ namespace openspace { // SGCT Projection to World Space glm::dmat4 dSgctProjectionToWorldTransformMatrix(dProjectionToTmpRotTransformMatrix); - double *mSource = (double*)glm::value_ptr(dSgctProjectionToWorldTransformMatrix); + double *mSource = reinterpret_cast(glm::value_ptr(dSgctProjectionToWorldTransformMatrix)); mSource[12] += renderData.camera.eyePositionVec3().x; mSource[13] += renderData.camera.eyePositionVec3().y; mSource[14] += renderData.camera.eyePositionVec3().z; - /* - mSource[12] += renderData.camera.positionVec3().x; - mSource[13] += renderData.camera.positionVec3().y; - mSource[14] += renderData.camera.positionVec3().z; - */ + mSource[15] = 1.0; @@ -311,7 +306,7 @@ namespace openspace { std::vector shadowDataArray; shadowDataArray.reserve(_shadowConfArray.size()); - for (const auto & shadowConf : _shadowConfArray) { + for (const ShadowConfiguration & shadowConf : _shadowConfArray) { // TO REMEMBER: all distances and lengths in world coordinates are in // meters!!! We need to move this to view space... // Getting source and caster: @@ -372,7 +367,7 @@ namespace openspace { const std::string uniformVarName("shadowDataArray["); unsigned int counter = 0; - for (const auto & sd : shadowDataArray) { + for (const ShadowRenderingStruct & sd : shadowDataArray) { std::stringstream ss; ss << uniformVarName << counter << "].isShadowing"; program.setUniform(ss.str(), sd.isShadowing); @@ -383,9 +378,9 @@ namespace openspace { ss.str(std::string()); ss << uniformVarName << counter << "].xu"; program.setUniform(ss.str(), sd.xu); - /*ss.str(std::string()); - ss << uniformVarName << counter << "].rs"; - program.setUniform(ss.str(), sd.rs);*/ + // ss.str(std::string()); + // ss << uniformVarName << counter << "].rs"; + // program.setUniform(ss.str(), sd.rs); ss.str(std::string()); ss << uniformVarName << counter << "].rc"; program.setUniform(ss.str(), sd.rc); @@ -416,8 +411,7 @@ namespace openspace { } void AtmosphereDeferredcaster::postRaycast(const RenderData&, - const DeferredcastData&, - ghoul::opengl::ProgramObject&) + const DeferredcastData&, ghoul::opengl::ProgramObject&) { // Deactivate the texture units _transmittanceTableTextureUnit.deactivate(); @@ -595,7 +589,8 @@ namespace openspace { _transmittanceProgramObject = ghoul::opengl::ProgramObject::Build( "transmittanceCalcProgram", absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_vs.glsl"), - absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl")); + absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl") + ); } using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; _transmittanceProgramObject->setIgnoreSubroutineUniformLocationError( @@ -1060,10 +1055,10 @@ namespace openspace { step3DTexture(_deltaJProgramObject, layer); renderQuadForCalc(quadCalcVAO, vertexSize); } - std::stringstream sst; if (_saveCalculationTextures) { - sst << "deltaJ_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + fmt::format("deltaJ_texture-scattering_order-{}.ppm", + scatteringOrder), _mu_s_samples * _nu_samples, _mu_samples); } _deltaJProgramObject->deactivate(); @@ -1111,9 +1106,9 @@ namespace openspace { loadAtmosphereDataIntoShaderProgram(_irradianceSupTermsProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaE_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + fmt::format("deltaE_texture-scattering_order-{}.ppm", + scatteringOrder), _delta_e_table_width, _delta_e_table_height); } _irradianceSupTermsProgramObject->deactivate(); @@ -1146,11 +1141,9 @@ namespace openspace { renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "deltaS_texture-scattering_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile( - GL_COLOR_ATTACHMENT0, - sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + fmt::format("deltaS_texture-scattering_order-{}.ppm", + scatteringOrder), _mu_s_samples * _nu_samples, _mu_samples ); @@ -1180,9 +1173,9 @@ namespace openspace { loadAtmosphereDataIntoShaderProgram(_irradianceFinalProgramObject); renderQuadForCalc(quadCalcVAO, vertexSize); if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "irradianceTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + fmt::format("irradianceTable_order-{}.ppm", + scatteringOrder), _delta_e_table_width, _delta_e_table_height); } _irradianceFinalProgramObject->deactivate(); @@ -1209,9 +1202,9 @@ namespace openspace { renderQuadForCalc(quadCalcVAO, vertexSize); } if (_saveCalculationTextures) { - sst.str(std::string()); - sst << "inscatteringTable_order-" << scatteringOrder << ".ppm"; - saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, sst.str(), + saveTextureToPPMFile(GL_COLOR_ATTACHMENT0, + fmt::format("inscatteringTable_order-{}.ppm", + scatteringOrder), _mu_s_samples * _nu_samples, _mu_samples); } _deltaSSupTermsProgramObject->deactivate(); diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 2e7801cc1a..823d11091d 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -691,8 +691,8 @@ bool RenderableStars::readSpeckFile() { break; } } - minLumValue = values[4] < minLumValue ? values[4] : minLumValue; - maxLumValue = values[4] > maxLumValue ? values[4] : maxLumValue; + minLumValue = std::min(values[4], minLumValue); + maxLumValue = std::max(values[4], minLumValue); if (!nullArray) { _fullData.insert(_fullData.end(), values.begin(), values.end()); } diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index 468a501b01..e449692ae9 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -575,7 +575,7 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _projectionComponent.generateMipMap(); } - _camScaling = glm::vec2(1, 0); // Unit scaling + _camScaling = glm::vec2(1.f, 0.f); // Unit scaling _up = data.camera.lookUpVectorCameraSpace(); if (_capture && _projectionComponent.doesPerformProjection()) { diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index d0d9bce9df..2fd4cca07a 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -187,7 +187,7 @@ void Renderable::setPscUniforms(ghoul::opengl::ProgramObject& program, program.setUniform("campos", camera.position().vec4()); program.setUniform("objpos", position.vec4()); program.setUniform("camrot", glm::mat4(camera.viewRotationMatrix())); - program.setUniform("scaling", glm::vec2(1, 0)); + program.setUniform("scaling", glm::vec2(1.f, 0.f)); } Renderable::RenderBin Renderable::renderBin() const { From c4ece52ca6cccbaf309ca27707da60434337398f Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 19:11:38 -0400 Subject: [PATCH 46/79] Requested changes for merging. Part II. --- .../rendering/atmospheredeferredcaster.cpp | 7 ++----- .../atmosphere/rendering/atmospheredeferredcaster.h | 3 +-- modules/space/rendering/renderablestars.cpp | 5 ++++- src/interaction/orbitalnavigator.cpp | 13 +++++++++---- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index eb29abd256..5693a6d72e 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -102,7 +102,6 @@ namespace { } // namespace namespace openspace { - AtmosphereDeferredcaster::AtmosphereDeferredcaster() : _transmittanceProgramObject(nullptr) , _irradianceProgramObject(nullptr) @@ -1275,8 +1274,6 @@ namespace openspace { LDEBUG("Ended precalculations for Atmosphere effects..."); } - void AtmosphereDeferredcaster::resetAtmosphereTextures() {} - void AtmosphereDeferredcaster::createRenderQuad(GLuint* vao, GLuint* vbo, GLfloat size) { glGenVertexArrays(1, vao); glGenBuffers(1, vbo); @@ -1404,10 +1401,10 @@ namespace openspace { void AtmosphereDeferredcaster::step3DTexture( std::unique_ptr& shaderProg, - int layer, bool doCalc) + int layer, bool doCalculation) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering - if (doCalc) { + if (doCalculation) { float earth2 = _atmospherePlanetRadius * _atmospherePlanetRadius; float atm2 = _atmosphereRadius * _atmosphereRadius; float diff = atm2 - earth2; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index 33184628f1..c53981fdb6 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -100,10 +100,9 @@ private: void deleteUnusedComputationTextures(); void executeCalculations(GLuint quadCalcVAO, GLenum drawBuffers[1], GLsizei vertexSize); - void resetAtmosphereTextures(); void createRenderQuad(GLuint* vao, GLuint* vbo, GLfloat size); void step3DTexture(std::unique_ptr& shaderProg, - int layer, bool doCalc = true); + int layer, bool doCalculation = true); void checkFrameBufferState(const std::string& codePosition) const; void loadAtmosphereDataIntoShaderProgram( std::unique_ptr & shaderProg diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 823d11091d..dfb5e1394a 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -699,8 +699,11 @@ bool RenderableStars::readSpeckFile() { } while (!file.eof()); // Normalize Luminosity: + int luminosityVarColumnPos = 4; for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { - _fullData[i + 4] = (_fullData[i + 4] - minLumValue) / (maxLumValue - minLumValue); + _fullData[i + luminosityVarColumnPos] = + (_fullData[i + luminosityVarColumnPos] - minLumValue) / + (maxLumValue - minLumValue); } return true; diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index 4bbac0188d..137a723720 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -345,8 +345,7 @@ void OrbitalNavigator::updateCameraStateFromMouseStates(Camera& camera, double d } glm::dvec3 OrbitalNavigator::cameraToSurfaceVector( - const glm::dvec3& camPos, - const glm::dvec3& centerPos, + const glm::dvec3& camPos, const glm::dvec3& centerPos, const SurfacePositionHandle& posHandle) { glm::dmat4 modelTransform = _focusNode->modelTransform(); @@ -491,16 +490,21 @@ glm::dquat OrbitalNavigator::interpolateLocalRotation(double deltaTime, else { return localCameraRotation; } + double t = _rotateToFocusNodeInterpolator.value(); _rotateToFocusNodeInterpolator.setDeltaTime(static_cast(deltaTime)); _rotateToFocusNodeInterpolator.step(); + glm::dquat result = glm::slerp( localCameraRotation, glm::dquat(glm::dvec3(0.0)), - glm::min(t * _rotateToFocusNodeInterpolator.deltaTimeScaled(), 1.0)); + glm::min(t * _rotateToFocusNodeInterpolator.deltaTimeScaled(), 1.0) + ); + if (angle(result) < 0.01) { _rotateToFocusNodeInterpolator.end(); } + return result; } @@ -520,7 +524,8 @@ double OrbitalNavigator::interpolateCameraToSurfaceDistance(double deltaTime, double result = glm::exp(glm::mix( glm::log(currentDistance), glm::log(targetDistance), - glm::min(t * _cameraToSurfaceDistanceInterpolator.deltaTimeScaled(), 1.0))); + glm::min(t * _cameraToSurfaceDistanceInterpolator.deltaTimeScaled(), 1.0)) + ); double ratio = currentDistance / targetDistance; if (glm::abs(ratio - 1.0) < 0.000001) { From 908ade32151283822324dbbb1d81621fe5335950 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 19:21:37 -0400 Subject: [PATCH 47/79] Requested changes for merging. Part III. --- .../rendering/atmospheredeferredcaster.cpp | 2 +- src/rendering/framebufferrenderer.cpp | 30 ++++++++----------- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 5693a6d72e..6d76231433 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -102,7 +102,7 @@ namespace { } // namespace namespace openspace { - AtmosphereDeferredcaster::AtmosphereDeferredcaster() + AtmosphereDeferredcaster::AtmosphereDeferredcaster() : _transmittanceProgramObject(nullptr) , _irradianceProgramObject(nullptr) , _irradianceSupTermsProgramObject(nullptr) diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index de8ed8eaaf..0e0fc36204 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -66,12 +66,11 @@ namespace { } // namespace namespace openspace { - void saveTextureToPPMFile(const GLenum color_buffer_attachment, - const std::string & fileName, - const int width, const int height); + void saveTextureToPPMFile(GLenum color_buffer_attachment, + const std::string & fileName, int width, int height); - void saveTextureToMemory(const GLenum color_buffer_attachment, - const int width, const int height, std::vector & memory); + void saveTextureToMemory(GLenum color_buffer_attachment, + int width, int height, std::vector & memory); FramebufferRenderer::FramebufferRenderer() @@ -1262,8 +1261,8 @@ namespace openspace { OsEng.renderEngine().setRendererData(dict); } - void saveTextureToPPMFile(const GLenum color_buffer_attachment, - const std::string & fileName, const int width, const int height) + void saveTextureToPPMFile(GLenum color_buffer_attachment, + const std::string & fileName, int width, int height) { std::fstream ppmFile; @@ -1295,7 +1294,6 @@ namespace openspace { ppmFile << width << " " << height << std::endl; ppmFile << "255" << std::endl; - std::cout << "\n\nFILE\n\n"; int k = 0; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { @@ -1312,30 +1310,26 @@ namespace openspace { } } - void saveTextureToMemory(const GLenum color_buffer_attachment, - const int width, const int height, std::vector & memory) { + void saveTextureToMemory(GLenum color_buffer_attachment, + int width, int height, std::vector & memory) { - if (!memory.empty()) { - memory.clear(); - } + memory.clear(); memory.resize(width * height * 3); - float *tempMemory = new float[width*height * 3]; + std::vector tempMemory(width*height * 3, 0.f); if (color_buffer_attachment != GL_DEPTH_ATTACHMENT) { glReadBuffer(color_buffer_attachment); - glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT, tempMemory); + glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT, &tempMemory[0]); } else { - glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, tempMemory); + glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, &tempMemory[0]); } for (auto i = 0; i < width*height * 3; ++i) { memory[i] = static_cast(tempMemory[i]); } - - delete[] tempMemory; } } // namespace openspace From cd95ebb213d5b77ddd50ea21143eaa6766768112 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 19:56:17 -0400 Subject: [PATCH 48/79] Requested changes for merging. Part IV. --- .../openspace/rendering/framebufferrenderer.h | 26 ++++---- src/rendering/framebufferrenderer.cpp | 66 ++++++++----------- 2 files changed, 40 insertions(+), 52 deletions(-) diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 8b219268f9..78bfc65b5f 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -54,6 +54,15 @@ class Scene; class FramebufferRenderer : public Renderer, public RaycasterListener, public DeferredcasterListener { +public: + typedef std::map< + VolumeRaycaster*, + std::unique_ptr + > RaycasterProgObjMap; + typedef std::map< + Deferredcaster*, + std::unique_ptr + > DeferredcasterProgObjMap; public: FramebufferRenderer(); virtual ~FramebufferRenderer(); @@ -97,21 +106,12 @@ public: private: std::map _raycastData; - std::map< - VolumeRaycaster*, std::unique_ptr - > _exitPrograms; - std::map< - VolumeRaycaster*, std::unique_ptr - > _raycastPrograms; - std::map< - VolumeRaycaster*, std::unique_ptr - > _insideRaycastPrograms; + RaycasterProgObjMap _exitPrograms; + RaycasterProgObjMap _raycastPrograms; + RaycasterProgObjMap _insideRaycastPrograms; std::map _deferredcastData; - std::map< - Deferredcaster*, - std::unique_ptr - > _deferredcastPrograms; + DeferredcasterProgObjMap _deferredcastPrograms; std::unique_ptr _hdrBackGroundProgram; std::unique_ptr _resolveProgram; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 0e0fc36204..f12de6e6f9 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -259,11 +259,9 @@ namespace openspace { _dirtyRaycastData = true; } - void FramebufferRenderer::deferredcastersChanged(Deferredcaster& deferredcaster, - isAttached isAttached) + void FramebufferRenderer::deferredcastersChanged(Deferredcaster& /*deferredcaster*/, + isAttached /*isAttached*/) { - (void)deferredcaster; - (void)isAttached; _dirtyDeferredcastData = true; } @@ -284,7 +282,7 @@ namespace openspace { _uniformCache.nAaSamples = _resolveProgram->uniformLocation("nAaSamples"); } - for (auto& program : _exitPrograms) { + for (RaycasterProgObjMap::value_type & program : _exitPrograms) { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); @@ -295,7 +293,7 @@ namespace openspace { } } - for (auto& program : _raycastPrograms) { + for (RaycasterProgObjMap::value_type & program : _raycastPrograms) { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); @@ -306,7 +304,7 @@ namespace openspace { } } - for (auto& program : _insideRaycastPrograms) { + for (RaycasterProgObjMap::value_type & program : _insideRaycastPrograms) { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); @@ -317,7 +315,7 @@ namespace openspace { } } - for (auto &program : _deferredcastPrograms) { + for (DeferredcasterProgObjMap::value_type &program : _deferredcastPrograms) { if (program.second && program.second->isDirty()) { try { program.second->rebuildFromFile(); @@ -433,7 +431,7 @@ namespace openspace { const std::vector& raycasters = OsEng.renderEngine().raycasterManager().raycasters(); int nextId = 0; - for (auto& raycaster : raycasters) { + for (VolumeRaycaster* raycaster : raycasters) { RaycastData data; data.id = nextId++; data.namespaceName = "HELPER"; @@ -503,7 +501,7 @@ namespace openspace { const std::vector& deferredcasters = OsEng.renderEngine().deferredcasterManager().deferredcasters(); int nextId = 0; - for (auto& caster : deferredcasters) { + for (Deferredcaster * caster : deferredcasters) { DeferredcastData data; data.id = nextId++; data.namespaceName = "HELPER"; @@ -518,7 +516,7 @@ namespace openspace { dict.setValue("id", data.id); std::string helperPath = caster->helperPath(); ghoul::Dictionary helpersDict; - if (helperPath != "") { + if (!helperPath.empty()) { helpersDict.setValue("0", helperPath); } dict.setValue("helperPaths", helpersDict); @@ -552,28 +550,23 @@ namespace openspace { } void FramebufferRenderer::updateHDRData() { - try { - _hdrBackGroundProgram = ghoul::opengl::ProgramObject::Build( - "HDR Background Control", - absPath("${SHADERS}/framebuffer/hdrBackground.vert"), - absPath("${SHADERS}/framebuffer/hdrBackground.frag") - ); - using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; - _hdrBackGroundProgram->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); - _hdrBackGroundProgram->setIgnoreUniformLocationError(IgnoreError::Yes); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } + _hdrBackGroundProgram = ghoul::opengl::ProgramObject::Build( + "HDR Background Control", + absPath("${SHADERS}/framebuffer/hdrBackground.vert"), + absPath("${SHADERS}/framebuffer/hdrBackground.frag") + ); + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; + _hdrBackGroundProgram->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + _hdrBackGroundProgram->setIgnoreUniformLocationError(IgnoreError::Yes); } void FramebufferRenderer::updateMSAASamplingPattern() { LDEBUG("Updating MSAA Sampling Pattern"); const int GRIDSIZE = 32; - GLfloat step = 2.0f / static_cast(GRIDSIZE); - GLfloat sizeX = -1.0f, - sizeY = 1.0f; + GLfloat step = 2.f / static_cast(GRIDSIZE); + GLfloat sizeX = -1.f, + sizeY = 1.f; const int NVERTEX = 4 * 6; // openPixelSizeVertexData @@ -613,7 +606,7 @@ namespace openspace { sizeX += step; } - sizeX = -1.0f; + sizeX = -1.f; sizeY -= step; } @@ -682,7 +675,7 @@ namespace openspace { GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, textureBuffers); - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClearColor(0.f, 0.f, 0.f, 1.f); glClear(GL_COLOR_BUFFER_BIT); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); @@ -846,16 +839,11 @@ namespace openspace { glViewport(0, 0, _nAaSamples, ONEPIXEL); std::unique_ptr nOneStripProgram = nullptr; - try { - nOneStripProgram = ghoul::opengl::ProgramObject::Build( - "OneStrip MSAA", - absPath("${SHADERS}/framebuffer/nOneStripMSAA.vert"), - absPath("${SHADERS}/framebuffer/nOneStripMSAA.frag") - ); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } + nOneStripProgram = ghoul::opengl::ProgramObject::Build( + "OneStrip MSAA", + absPath("${SHADERS}/framebuffer/nOneStripMSAA.vert"), + absPath("${SHADERS}/framebuffer/nOneStripMSAA.frag") + ); nOneStripProgram->activate(); From 5a63500cb0c748bff3c3e86b9c85ba508cae2efa Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 20:54:13 -0400 Subject: [PATCH 49/79] Requested changes for merging. Part V. --- .../atmosphere/rendering/atmospheredeferredcaster.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 6d76231433..6c4fd10880 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -524,28 +524,28 @@ namespace openspace { void AtmosphereDeferredcaster::setRayleighScatteringCoefficients( const glm::vec3& rayScattCoeff) { - _rayleighScatteringCoeff = rayScattCoeff; + _rayleighScatteringCoeff = std::move(rayScattCoeff); } void AtmosphereDeferredcaster::setOzoneExtinctionCoefficients( const glm::vec3& ozoneExtCoeff) { - _ozoneExtinctionCoeff = ozoneExtCoeff; + _ozoneExtinctionCoeff = std::move(ozoneExtCoeff); } void AtmosphereDeferredcaster::setMieScatteringCoefficients( const glm::vec3& mieScattCoeff) { - _mieScatteringCoeff = mieScattCoeff; + _mieScatteringCoeff = std::move(mieScattCoeff); } void AtmosphereDeferredcaster::setMieExtinctionCoefficients(const glm::vec3& mieExtCoeff) { - _mieExtinctionCoeff = mieExtCoeff; + _mieExtinctionCoeff = std::move(mieExtCoeff); } void AtmosphereDeferredcaster::setEllipsoidRadii(const glm::dvec3& radii) { - _ellipsoidRadii = radii; + _ellipsoidRadii = std::move(radii); } void AtmosphereDeferredcaster::setHardShadows(bool enabled) { From d42bd39fa242a4c6b06d3259a38ddd97c72c5edb Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 20:54:24 -0400 Subject: [PATCH 50/79] Fixed font rendering. --- include/openspace/rendering/loadingscreen.h | 2 ++ src/rendering/loadingscreen.cpp | 23 +++++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/include/openspace/rendering/loadingscreen.h b/include/openspace/rendering/loadingscreen.h index 899bcc6f71..24c8d347d4 100644 --- a/include/openspace/rendering/loadingscreen.h +++ b/include/openspace/rendering/loadingscreen.h @@ -38,6 +38,7 @@ namespace ghoul::fontrendering { class Font; + class FontRenderer; } // namespace ghoul::fontrendering namespace ghoul::opengl { @@ -101,6 +102,7 @@ private: std::unique_ptr _logoTexture; + std::unique_ptr _renderer; std::shared_ptr _loadingFont; std::shared_ptr _messageFont; std::shared_ptr _itemFont; diff --git a/src/rendering/loadingscreen.cpp b/src/rendering/loadingscreen.cpp index 37a2042e23..ea53eb3a0e 100644 --- a/src/rendering/loadingscreen.cpp +++ b/src/rendering/loadingscreen.cpp @@ -124,6 +124,8 @@ LoadingScreen::LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeName _uniformCache.useTexture = _program->uniformLocation("useTexture"); _uniformCache.color = _program->uniformLocation("color"); + _renderer = ghoul::fontrendering::FontRenderer::createDefault(); + _loadingFont = OsEng.fontManager().font( "Loading", LoadingFontSize, @@ -223,6 +225,8 @@ LoadingScreen::LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeName LoadingScreen::~LoadingScreen() { _logoTexture = nullptr; + _renderer = nullptr; + _loadingFont = nullptr; _messageFont = nullptr; _itemFont = nullptr; @@ -238,18 +242,21 @@ LoadingScreen::~LoadingScreen() { } void LoadingScreen::render() { + using FR = ghoul::fontrendering::FontRenderer; // 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::ivec2 res = - glm::vec2(OsEng.windowWrapper().currentWindowResolution()) / dpiScaling; + glm::vec2(OsEng.windowWrapper().currentDrawBufferResolution()) / dpiScaling; float screenAspectRatio = static_cast(res.x) / static_cast(res.y); float textureAspectRatio = static_cast(_logoTexture->dimensions().x) / static_cast(_logoTexture->dimensions().y); + _renderer->setFramebufferSize(res); + glm::vec2 size = { LogoSize.x, LogoSize.y * textureAspectRatio * screenAspectRatio @@ -411,8 +418,6 @@ void LoadingScreen::render() { // // "Loading" text // - using FR = ghoul::fontrendering::FontRenderer; - FR& renderer = FR::defaultRenderer(); std::string headline = @@ -421,7 +426,7 @@ void LoadingScreen::render() { "Loading..."; // We use "Loading" to center the text, but render "Loading..." to make it look more // pleasing - FR::BoundingBoxInformation bbox = renderer.boundingBox( + FR::BoundingBoxInformation bbox = _renderer->boundingBox( *_loadingFont, "%s", headline.substr(0, headline.size() - 2).c_str() @@ -433,7 +438,7 @@ void LoadingScreen::render() { ); glm::vec2 loadingUr = loadingLl + bbox.boundingBox; - renderer.render( + _renderer->render( *_loadingFont, loadingLl, glm::vec4(1.f, 1.f, 1.f, 1.f), @@ -446,7 +451,7 @@ void LoadingScreen::render() { if (_showMessage) { std::lock_guard guard(_messageMutex); - FR::BoundingBoxInformation bboxMessage = renderer.boundingBox( + FR::BoundingBoxInformation bboxMessage = _renderer->boundingBox( *_messageFont, "%s", _message.c_str() @@ -459,7 +464,7 @@ void LoadingScreen::render() { messageUr = messageLl + bboxMessage.boundingBox; - renderer.render( + _renderer->render( *_messageFont, messageLl, glm::vec4(1.f, 1.f, 1.f, 1.f), @@ -477,7 +482,7 @@ void LoadingScreen::render() { if (!item.hasLocation) { // Compute a new location - FR::BoundingBoxInformation b = renderer.boundingBox( + FR::BoundingBoxInformation b = _renderer->boundingBox( *_itemFont, "%s", (item.name + " 100%").c_str() @@ -600,7 +605,7 @@ void LoadingScreen::render() { "%"; } - renderer.render( + _renderer->render( *_itemFont, item.ll, color, From 87d10727120b381ac17de43a983f2fac86625d67 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 21:11:01 -0400 Subject: [PATCH 51/79] Requested changes for merging. Part V. --- .../rendering/atmospheredeferredcaster.cpp | 36 +++++--- .../rendering/atmospheredeferredcaster.h | 2 +- src/rendering/framebufferrenderer.cpp | 90 +++++++++---------- 3 files changed, 70 insertions(+), 58 deletions(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 6c4fd10880..a4a07807ca 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -199,7 +199,7 @@ namespace openspace { ) * renderData.camera.combinedViewMatrix(); if (!isAtmosphereInFrustum( - glm::value_ptr(MV), + MV, tPlanetPosWorld, (_atmosphereRadius + ATM_EPS)*KM_TO_M) ) @@ -1477,16 +1477,21 @@ namespace openspace { } } - bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const double* MVMatrix, + bool AtmosphereDeferredcaster::isAtmosphereInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position, double radius) const { // Frustum Planes - glm::dvec3 col1(MVMatrix[0], MVMatrix[4], MVMatrix[8]); - glm::dvec3 col2(MVMatrix[1], MVMatrix[5], MVMatrix[9]); - glm::dvec3 col3(MVMatrix[2], MVMatrix[6], MVMatrix[10]); - glm::dvec3 col4(MVMatrix[3], MVMatrix[7], MVMatrix[11]); + //glm::dvec3 col1(MVMatrix[0], MVMatrix[4], MVMatrix[8]); + //glm::dvec3 col2(MVMatrix[1], MVMatrix[5], MVMatrix[9]); + //glm::dvec3 col3(MVMatrix[2], MVMatrix[6], MVMatrix[10]); + //glm::dvec3 col4(MVMatrix[3], MVMatrix[7], MVMatrix[11]); + + glm::dvec3 col1(MVMatrix[0][0], MVMatrix[1][0], MVMatrix[2][0]); + glm::dvec3 col2(MVMatrix[0][1], MVMatrix[1][1], MVMatrix[2][1]); + glm::dvec3 col3(MVMatrix[0][2], MVMatrix[1][2], MVMatrix[2][2]); + glm::dvec3 col4(MVMatrix[0][3], MVMatrix[1][3], MVMatrix[2][3]); glm::dvec3 leftNormal = col4 + col1; glm::dvec3 rightNormal = col4 - col1; @@ -1496,12 +1501,19 @@ namespace openspace { glm::dvec3 farNormal = col4 - col3; // Plane Distances - double leftDistance = MVMatrix[15] + MVMatrix[12]; - double rightDistance = MVMatrix[15] - MVMatrix[12]; - double bottomDistance = MVMatrix[15] + MVMatrix[13]; - double topDistance = MVMatrix[15] - MVMatrix[13]; - double nearDistance = MVMatrix[15] + MVMatrix[14]; - double farDistance = MVMatrix[15] - MVMatrix[14]; + //double leftDistance = MVMatrix[15] + MVMatrix[12]; + //double rightDistance = MVMatrix[15] - MVMatrix[12]; + //double bottomDistance = MVMatrix[15] + MVMatrix[13]; + //double topDistance = MVMatrix[15] - MVMatrix[13]; + //double nearDistance = MVMatrix[15] + MVMatrix[14]; + //double farDistance = MVMatrix[15] - MVMatrix[14]; + + double leftDistance = MVMatrix[3][3] + MVMatrix[3][0]; + double rightDistance = MVMatrix[3][3] - MVMatrix[3][0]; + double bottomDistance = MVMatrix[3][3] + MVMatrix[3][1]; + double topDistance = MVMatrix[3][3] - MVMatrix[3][1]; + double nearDistance = MVMatrix[3][3] + MVMatrix[3][2]; + double farDistance = MVMatrix[3][3] - MVMatrix[3][2]; // Normalize Planes double invMag = 1.0 / glm::length(leftNormal); diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index c53981fdb6..78814104b6 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -110,7 +110,7 @@ private: void renderQuadForCalc(GLuint vao, GLsizei numberOfVertices); void saveTextureToPPMFile(GLenum color_buffer_attachment, const std::string& fileName, int width, int height) const; - bool isAtmosphereInFrustum(const double* MVMatrix, const glm::dvec3& position, + bool isAtmosphereInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position, double radius) const; const double DISTANCE_CULLING = 1e10; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index f12de6e6f9..96140bd733 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -576,33 +576,33 @@ namespace openspace { for (int x = 0; x < GRIDSIZE; ++x) { vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX] = sizeX; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 1] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 2] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 3] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 2] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 3] = 1.f; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 4] = sizeX + step; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 5] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 6] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 7] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 6] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 7] = 1.f; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 8] = sizeX; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 9] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 10] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 11] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 10] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 11] = 1.f; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 12] = sizeX; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 13] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 14] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 15] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 14] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 15] = 1.f; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 16] = sizeX + step; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 17] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 18] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 19] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 18] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 19] = 1.f; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 20] = sizeX + step; vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 21] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 22] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 23] = 1.0f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 22] = 0.f; + vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 23] = 1.f; sizeX += step; } @@ -718,53 +718,53 @@ namespace openspace { GLuint nOneStripVBO = 0; GLuint nOneStripTexture = 0; - sizeX = -1.0f; - step = 2.0f / static_cast(_nAaSamples); + sizeX = -1.f; + step = 2.f / static_cast(_nAaSamples); GLfloat * nOneStripVertexData = new GLfloat[_nAaSamples * (NVERTEX + 12)]; for (int x = 0; x < _nAaSamples; ++x) { nOneStripVertexData[x * (NVERTEX + 12)] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 1] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 2] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 3] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 4] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 5] = 0.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 1] = -1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 2] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 3] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 4] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 5] = 0.f; nOneStripVertexData[x * (NVERTEX + 12) + 6] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 7] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 8] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 9] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 10] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 11] = 1.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 7] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 8] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 9] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 10] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 11] = 1.f; nOneStripVertexData[x * (NVERTEX + 12) + 12] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 13] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 14] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 15] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 16] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 17] = 0.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 13] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 14] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 15] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 16] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 17] = 0.f; nOneStripVertexData[x * (NVERTEX + 12) + 18] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 19] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 20] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 21] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 22] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 23] = 0.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 19] = -1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 20] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 21] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 22] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 23] = 0.f; nOneStripVertexData[x * (NVERTEX + 12) + 24] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 25] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 26] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 27] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 28] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 29] = 1.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 25] = -1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 26] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 27] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 28] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 29] = 1.f; nOneStripVertexData[x * (NVERTEX + 12) + 30] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 31] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 32] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 33] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 34] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 35] = 1.0f; + nOneStripVertexData[x * (NVERTEX + 12) + 31] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 32] = 0.f; + nOneStripVertexData[x * (NVERTEX + 12) + 33] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 34] = 1.f; + nOneStripVertexData[x * (NVERTEX + 12) + 35] = 1.f; sizeX += step; } @@ -855,7 +855,7 @@ namespace openspace { // render strip glDrawBuffers(1, textureBuffers); - glClearColor(0.0f, 1.0f, 0.0f, 1.0f); + glClearColor(0.f, 1.f, 0.f, 1.f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(nOneStripVAO); glDisable(GL_DEPTH_TEST); From ce72e6c8ad2fc156c8747b016e02ba68157715fa Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 21:15:25 -0400 Subject: [PATCH 52/79] Requested changes for merging. Part VII. --- modules/atmosphere/rendering/atmospheredeferredcaster.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index a4a07807ca..36de406376 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -555,7 +555,7 @@ namespace openspace { void AtmosphereDeferredcaster::setShadowConfigArray( const std::vector& shadowConfigArray) { - _shadowConfArray = shadowConfigArray; + _shadowConfArray = std::move(shadowConfigArray); } void AtmosphereDeferredcaster::enableSunFollowing(bool enable) { From 49b08ed1c3be1a30a533acb49f6ca143f214461d Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 21:52:51 -0400 Subject: [PATCH 53/79] Enabled eclipses on Earth again. --- .../scene/solarsystem/planets/earth/earth.asset | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index 5ed01f4bfd..1e53f148a8 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -233,7 +233,21 @@ local Earth = { } } } - } + }, + ShadowGroup = { + Source1 = { + Name = "Sun", + -- All radius in meters + Radius = 696.3E6 + }, + --Source2 = { Name = "Monolith", Radius = 0.01E6, }, + Caster1 = { + Name = "Moon", + -- All radius in meters + Radius = 1.737E6 + } + --Caster2 = { Name = "Independency Day Ship", Radius = 0.0, } + } }, Tag = { "planet_solarSystem", "planet_terrestrial" }, GUI = { From d5af5aab5d94a1b1a950a767b8560190d7e362ca Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 22:47:17 -0400 Subject: [PATCH 54/79] Fixed interaction of trail points with ATM. (#602) * Fixed interaction of trail points with ATM. * Added fix from SunEarh day. --- modules/base/shaders/renderabletrail_fs.glsl | 23 +++++++++++++++----- modules/base/shaders/renderabletrail_vs.glsl | 4 +++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/modules/base/shaders/renderabletrail_fs.glsl b/modules/base/shaders/renderabletrail_fs.glsl index 979aa32445..df8778fe70 100644 --- a/modules/base/shaders/renderabletrail_fs.glsl +++ b/modules/base/shaders/renderabletrail_fs.glsl @@ -27,6 +27,7 @@ in vec4 vs_positionScreenSpace; in vec4 vs_gPosition; in float fade; +in float v_pointSize; uniform vec3 color; uniform int renderPhase; @@ -45,18 +46,30 @@ Fragment getFragment() { frag.depth = vs_positionScreenSpace.w; frag.blend = BLEND_MODE_ADDITIVE; + vec4 depthCorrection = vec4(0.0, 0.0, 100.0, 0.0); + if (renderPhase == RenderPhasePoints) { // Use the length of the vector (dot(circCoord, circCoord)) as factor in the // smoothstep to gradually decrease the alpha on the edges of the point vec2 circCoord = 2.0 * gl_PointCoord - 1.0; - frag.color.a *= 1.0 - smoothstep(1.0 - Delta, 1.0, dot(circCoord, circCoord)); - } + //float circleClipping = 1.0 - smoothstep(1.0 - Delta, 1.0, dot(circCoord, circCoord)); + float circleClipping = smoothstep(1.0, 1.0 - Delta, dot(circCoord, circCoord)); + float transparencyCorrection = frag.color.a * circleClipping; + if (transparencyCorrection < 0.9) { + discard; + } + + frag.color.a = transparencyCorrection; + } + // G-Buffer - frag.gPosition = vs_gPosition; + // JCC: The depthCorrection here is a temporary tweak + // to fix precision problems. + frag.gPosition = vs_gPosition + depthCorrection; + // There is no normal here - // TODO: Add the correct normal if necessary (JCC) - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + frag.gNormal = vec4(0.0, 0.0, -1.0, 1.0); return frag; } diff --git a/modules/base/shaders/renderabletrail_vs.glsl b/modules/base/shaders/renderabletrail_vs.glsl index 4c43ad45b1..b77c9f7dd8 100644 --- a/modules/base/shaders/renderabletrail_vs.glsl +++ b/modules/base/shaders/renderabletrail_vs.glsl @@ -31,6 +31,7 @@ layout(location = 0) in vec3 in_point_position; out vec4 vs_positionScreenSpace; out vec4 vs_gPosition; out float fade; +out float v_pointSize; uniform dmat4 modelViewTransform; uniform mat4 projectionTransform; @@ -75,5 +76,6 @@ void main() { vs_positionScreenSpace = z_normalization(projectionTransform * vs_gPosition); gl_PointSize = (stride == 1 || int(modId) % stride == 0) ? float(pointSize) : float(pointSize) / 2; - gl_Position = vs_positionScreenSpace; + v_pointSize = gl_PointSize; + gl_Position = vs_positionScreenSpace; } From 3960ee1f09772561b38fb6bdd56be4803256ac2a Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 20 Apr 2018 23:05:20 -0400 Subject: [PATCH 55/79] Requested changes for merging. Part VIII. --- src/interaction/orbitalnavigator.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index dc2287e04a..0b6240268b 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -363,9 +363,8 @@ void OrbitalNavigator::updateCameraStateFromStates(Camera& camera, double deltaT } } -glm::dvec3 OrbitalNavigator::cameraToSurfaceVector( - const glm::dvec3& camPos, const glm::dvec3& centerPos, - const SurfacePositionHandle& posHandle) +glm::dvec3 OrbitalNavigator::cameraToSurfaceVector(const glm::dvec3& camPos, + const glm::dvec3& centerPos, const SurfacePositionHandle& posHandle) { glm::dmat4 modelTransform = _focusNode->modelTransform(); glm::dvec3 posDiff = camPos - centerPos; From a9b981d71809459eae714e209ddc5985d8615892 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 20 Apr 2018 23:12:13 -0400 Subject: [PATCH 56/79] LLVM compile fixes Updated to new Ghoul commit --- ext/ghoul | 2 +- include/openspace/interaction/joystickinputstate.h | 4 ++-- modules/sync/torrentclient.h | 4 ++++ src/interaction/touchbar.mm | 3 +++ 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/ext/ghoul b/ext/ghoul index 9a7c0e600b..5cdf35fd66 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 9a7c0e600b21c2f39b025f2ab4742b4574ee382a +Subproject commit 5cdf35fd662f0f6f00351ddf706b2b87b312ee7f diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index baf75c43d5..e460dd266f 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -52,9 +52,9 @@ enum class JoystickAction : uint8_t { */ struct JoystickInputState { /// The maximum number of supported axes - static const int MaxAxes = 8; + static constexpr const int MaxAxes = 8; /// The maximum number of supported buttons - static const int MaxButtons = 32; + static constexpr const int MaxButtons = 32; /// Marks whether this joystick is connected. If this value is \c false, all other /// members of this struct are undefined diff --git a/modules/sync/torrentclient.h b/modules/sync/torrentclient.h index a84aca8f52..92f3422a39 100644 --- a/modules/sync/torrentclient.h +++ b/modules/sync/torrentclient.h @@ -41,6 +41,10 @@ #pragma warning (disable : 4996) #endif // _MSC_VER +// libtorrent defines a class with the name 'defer', which messes with out #define of the +// defer macro in ghoul/misc/defer.h +#undef defer + #include #include diff --git a/src/interaction/touchbar.mm b/src/interaction/touchbar.mm index 813d0a1aa6..f1dfcb4cc5 100644 --- a/src/interaction/touchbar.mm +++ b/src/interaction/touchbar.mm @@ -30,6 +30,9 @@ #include #include +// 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 #import #import #import From 8aa4c4fa42fb70730b685c75096a56d12fd99f1f Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 00:44:54 -0400 Subject: [PATCH 57/79] Update copyright headers --- modules/cefwebgui/shaders/gui_fs.glsl | 2 +- modules/cefwebgui/shaders/gui_vs.glsl | 2 +- modules/webbrowser/cmake/cef_support.cmake | 46 +++++++++---------- .../webbrowser/cmake/webbrowser_helpers.cmake | 46 +++++++++---------- .../webbrowser/shaders/screenspace_fs.glsl | 2 +- .../webbrowser/shaders/screenspace_vs.glsl | 2 +- modules/webgui/cmake/webgui_helpers.cmake | 46 +++++++++---------- 7 files changed, 73 insertions(+), 73 deletions(-) diff --git a/modules/cefwebgui/shaders/gui_fs.glsl b/modules/cefwebgui/shaders/gui_fs.glsl index 0a9946a42f..5862d118f2 100644 --- a/modules/cefwebgui/shaders/gui_fs.glsl +++ b/modules/cefwebgui/shaders/gui_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/cefwebgui/shaders/gui_vs.glsl b/modules/cefwebgui/shaders/gui_vs.glsl index 70cb0858a5..411a72b335 100644 --- a/modules/cefwebgui/shaders/gui_vs.glsl +++ b/modules/cefwebgui/shaders/gui_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/cmake/cef_support.cmake b/modules/webbrowser/cmake/cef_support.cmake index 843d3873b6..3d7eff4ebf 100644 --- a/modules/webbrowser/cmake/cef_support.cmake +++ b/modules/webbrowser/cmake/cef_support.cmake @@ -1,26 +1,26 @@ -######################################################################################### -# # -# OpenSpace # -# # -# Copyright (c) 2014-2017 # -# # -# 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. # -######################################################################################### +########################################################################################## +# # +# 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. # +########################################################################################## # This file consists of snippets taken from various CEF projects. diff --git a/modules/webbrowser/cmake/webbrowser_helpers.cmake b/modules/webbrowser/cmake/webbrowser_helpers.cmake index 3e0bbe2c9d..c4920841a2 100644 --- a/modules/webbrowser/cmake/webbrowser_helpers.cmake +++ b/modules/webbrowser/cmake/webbrowser_helpers.cmake @@ -1,26 +1,26 @@ -######################################################################################### -# # -# OpenSpace # -# # -# Copyright (c) 2014-2017 # -# # -# 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. # -######################################################################################### +########################################################################################## +# # +# 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. # +########################################################################################## function(set_cef_targets cef_root main_target) diff --git a/modules/webbrowser/shaders/screenspace_fs.glsl b/modules/webbrowser/shaders/screenspace_fs.glsl index d2a0660d3d..68c50f5544 100644 --- a/modules/webbrowser/shaders/screenspace_fs.glsl +++ b/modules/webbrowser/shaders/screenspace_fs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webbrowser/shaders/screenspace_vs.glsl b/modules/webbrowser/shaders/screenspace_vs.glsl index 9accc77e30..1d3388f0e8 100644 --- a/modules/webbrowser/shaders/screenspace_vs.glsl +++ b/modules/webbrowser/shaders/screenspace_vs.glsl @@ -2,7 +2,7 @@ * * * OpenSpace * * * - * Copyright (c) 2014-2017 * + * 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 * diff --git a/modules/webgui/cmake/webgui_helpers.cmake b/modules/webgui/cmake/webgui_helpers.cmake index a29de5cf34..eed90b8357 100644 --- a/modules/webgui/cmake/webgui_helpers.cmake +++ b/modules/webgui/cmake/webgui_helpers.cmake @@ -1,26 +1,26 @@ -######################################################################################### -# # -# OpenSpace # -# # -# Copyright (c) 2014-2017 # -# # -# 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. # -######################################################################################### +########################################################################################## +# # +# 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. # +########################################################################################## function(build_webgui_source target_name) set(NPM_COMMAND "npm" CACHE STRING "Location of NPM executable unless in PATH.") From 818ee225a5c5e74afe55ac3f9605c262e716bc51 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 07:00:43 -0400 Subject: [PATCH 58/79] Define a Cache path on default Cleanup OpenSpaceEngine Cleanup RenderEngine * ScreenSpaceRenderables are now owned by RenderEngine, rather than being shared_ptr Cleanup LogFactory --- apps/OpenSpace/main.cpp | 1 - apps/TaskRunner/main.cpp | 4 +- include/openspace/engine/configuration.h | 4 +- include/openspace/engine/openspaceengine.h | 13 +- include/openspace/rendering/renderengine.h | 44 ++-- include/openspace/util/screenlog.h | 17 +- modules/base/dashboard/dashboarditemangle.cpp | 2 +- .../base/dashboard/dashboarditemdistance.cpp | 2 +- .../base/rendering/screenspacedashboard.cpp | 10 +- modules/imgui/src/guijoystickcomponent.cpp | 4 +- modules/iswa/util/iswamanager_lua.inl | 4 +- src/engine/configuration.cpp | 1 - src/engine/logfactory.cpp | 124 ++++----- src/engine/openspaceengine.cpp | 208 +++++++-------- src/interaction/navigationhandler_lua.inl | 4 +- src/rendering/renderengine.cpp | 241 ++++++++---------- src/rendering/renderengine_lua.inl | 27 +- src/rendering/screenspacerenderable.cpp | 3 +- src/util/screenlog.cpp | 6 +- 19 files changed, 325 insertions(+), 394 deletions(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index 150b507a87..f66289d518 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -631,7 +631,6 @@ int main_main(int argc, char** argv) { std::pair glVersion = supportedOpenGLVersion(); // Create the OpenSpace engine and get arguments for the SGCT engine - // @CLEANUP: Replace the return valua with throwing an exception --abock std::vector sgctArguments; bool requestQuit = false; try { diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 34219a479f..28f8cc8af1 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -61,12 +61,12 @@ namespace { void initTextureReaders() { #ifdef GHOUL_USE_DEVIL ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_DEVIL #ifdef GHOUL_USE_FREEIMAGE ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_FREEIMAGE } diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index 1b2ef2760c..06916253fc 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -39,7 +39,9 @@ struct Configuration { std::string windowConfiguration = "${CONFIG}/single.xml"; std::string asset = "default"; std::vector globalCustomizationScripts; - std::map pathTokens; + std::map pathTokens = { + { "CACHE" , "CACHE = \"${BASE}/cache\"" } + }; std::map fonts; struct Logging { diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index efc6f9b511..e136e6c1b6 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -76,12 +76,12 @@ namespace scripting { struct ShutdownInformation { // Whether the application is currently in shutdown mode (i.e. counting down the // timer and closing it at '0' - bool inShutdown; + bool inShutdown = false; // Total amount of time the application will wait before actually shutting down - float waitTime; + float waitTime = 0.f; // Current state of the countdown; if it reaches '0', the application will // close - float timer; + float timer = 0.f; }; class OpenSpaceEngine { @@ -95,7 +95,7 @@ public: static OpenSpaceEngine& ref(); static bool isCreated(); - ~OpenSpaceEngine(); + ~OpenSpaceEngine() = default; // callbacks void initialize(); @@ -196,7 +196,6 @@ private: OpenSpaceEngine(std::string programName, std::unique_ptr windowWrapper); - std::unique_ptr createLoadingScreen(); void loadSingleAsset(const std::string& assetPath); void gatherCommandlineArguments(); void loadFonts(); @@ -241,7 +240,7 @@ private: properties::StringProperty sourceControlInformation; } _versionInformation; - bool _hasScheduledAssetLoading; + bool _hasScheduledAssetLoading = false; std::string _scheduledAssetPathToLoad; struct { @@ -269,7 +268,7 @@ private: // 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; + bool _isFirstRenderingFirstFrame = true; static OpenSpaceEngine* _engine; }; diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 5438b6d194..5520ca9e3e 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -36,7 +36,7 @@ namespace ghoul { class Dictionary; class SharedMemory; -} +} // ghoul namespace ghoul::fontrendering { class Font; } namespace ghoul::opengl { class ProgramObject; } @@ -77,8 +77,7 @@ public: Scene* scene(); void updateScene(); - Camera* camera() const; - Renderer* renderer() const; + const Renderer& renderer() const; RendererImplementation rendererImplementation() const; RaycasterManager& raycasterManager(); DeferredcasterManager& deferredcasterManager(); @@ -101,24 +100,19 @@ public: float globalBlackOutFactor(); void setGlobalBlackOutFactor(float factor); - void addScreenSpaceRenderable(std::shared_ptr s); - void removeScreenSpaceRenderable(std::shared_ptr s); + void addScreenSpaceRenderable(std::unique_ptr s); + void removeScreenSpaceRenderable(ScreenSpaceRenderable* s); void removeScreenSpaceRenderable(const std::string& name); - std::shared_ptr screenSpaceRenderable(const std::string& name); + ScreenSpaceRenderable* screenSpaceRenderable(const std::string& name); std::vector screenSpaceRenderables() const; std::unique_ptr buildRenderProgram( - std::string name, - std::string vsPath, - std::string fsPath, - const ghoul::Dictionary& dictionary = ghoul::Dictionary()); + const std::string& name, const std::string& vsPath, std::string fsPath, + ghoul::Dictionary dictionary = ghoul::Dictionary()); std::unique_ptr buildRenderProgram( - std::string name, - std::string vsPath, - std::string fsPath, - std::string csPath, - const ghoul::Dictionary& dictionary = ghoul::Dictionary()); + const std::string& name, const std::string& vsPath, std::string fsPath, + const std::string& csPath, ghoul::Dictionary dictionary = ghoul::Dictionary()); void removeRenderProgram(ghoul::opengl::ProgramObject* program); @@ -144,13 +138,13 @@ public: * Lets the renderer update the data to be brought into the rendererer programs * as a 'rendererData' variable in the dictionary. */ - void setRendererData(const ghoul::Dictionary& rendererData); + void setRendererData(ghoul::Dictionary rendererData); /** * Lets the renderer update the data to be brought into the post rendererer programs * as a 'resolveData' variable in the dictionary. */ - void setResolveData(const ghoul::Dictionary& resolveData); + void setResolveData(ghoul::Dictionary resolveData); /** * Returns the Lua library that contains all Lua functions available to affect the @@ -164,8 +158,6 @@ public: glm::ivec2 renderingResolution() const; glm::ivec2 fontResolution() const; - std::vector getSyncables(); - properties::PropertyOwner& screenSpaceOwner(); private: @@ -199,26 +191,26 @@ private: properties::BoolProperty _showCameraInfo; properties::TriggerProperty _takeScreenshot; - bool _shouldTakeScreenshot; + bool _shouldTakeScreenshot = false; properties::BoolProperty _applyWarping; properties::BoolProperty _showFrameNumber; properties::BoolProperty _disableMasterRendering; properties::BoolProperty _disableSceneTranslationOnMaster; - float _globalBlackOutFactor; - float _fadeDuration; - float _currentFadeTime; - int _fadeDirection; + float _globalBlackOutFactor = 1.f; + float _fadeDuration = 2.f; + float _currentFadeTime = 0.f; + int _fadeDirection = 0; properties::IntProperty _nAaSamples; properties::FloatProperty _hdrExposure; properties::FloatProperty _hdrBackground; properties::FloatProperty _gamma; - uint64_t _frameNumber; + uint64_t _frameNumber = 0; std::vector _programs; properties::PropertyOwner _screenSpaceOwner; - std::vector> _screenSpaceRenderables; + std::vector> _screenSpaceRenderables; std::shared_ptr _fontBig = nullptr; std::shared_ptr _fontInfo = nullptr; diff --git a/include/openspace/util/screenlog.h b/include/openspace/util/screenlog.h index 5296b42157..aed1c78dc8 100644 --- a/include/openspace/util/screenlog.h +++ b/include/openspace/util/screenlog.h @@ -70,10 +70,11 @@ public: * Constructor that creates a ScreenLog with the provided \p timeToLive, and the * minimum \p logLevel that is stored. Log message with a lower * ghoul::logging::LogLevel are automatically discarded. + * * \param timeToLive The time-to-live for the messages in this ScreenLog. Expired - * messages are removed whenever the #removeExpiredEntries method is called + * messages are removed whenever the #removeExpiredEntries method is called * \param logLevel The minimum ghoul::logging::LogLevel that messages must - * have in order to be stored in the ScreenLog + * have in order to be stored in the ScreenLog */ ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel = LogLevel::Info); @@ -85,6 +86,7 @@ public: /** * Overwritten ghoul::loggling::Log method that is called whenever a new log message * shall be stored. + * * \param level The ghoul::logging::LogLevel of the incoming log message * \param category The category of the log message * \param message The actual log message that was transmitted @@ -95,17 +97,19 @@ public: /** * This method removes all the stored LogEntry%s that have expired, calculated by * their timeStamp and the #_timeToLive value. + * * \post All entries retrieved by the #entries function have a timeStamp - * that is lower than the current time + #_timeToLive. The current time used is the - * time when this method was last called + * that is lower than the current time + #_timeToLive. The current time used is + * the time when this method was last called */ void removeExpiredEntries(); /** * Returns the list of all stored LogEntry%s. + * * \return The list of all stored LogEntry%s */ - std::vector entries() const; + const std::vector& entries() const; private: /// The list of all LogEntry%s stored by this ScreenLog @@ -118,7 +122,8 @@ private: /// The minimum LogLevel of messages LogLevel _logLevel; - /// A mutex to ensure thread-safety + /// A mutex to ensure thread-safety since the logging and the removal of expired + /// entires can occur on different threads mutable std::mutex _mutex; }; diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index 56843babde..a86684eddc 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -388,7 +388,7 @@ std::pair DashboardItemAngle::positionAndLabel( "focus" }; case Type::Camera: - return { OsEng.renderEngine().camera()->positionVec3(), "camera" }; + return { OsEng.renderEngine().scene()->camera()->positionVec3(), "camera" }; default: return { glm::dvec3(0.0), "Unknown" }; } diff --git a/modules/base/dashboard/dashboarditemdistance.cpp b/modules/base/dashboard/dashboarditemdistance.cpp index 30e4e8766f..00389c05df 100644 --- a/modules/base/dashboard/dashboarditemdistance.cpp +++ b/modules/base/dashboard/dashboarditemdistance.cpp @@ -406,7 +406,7 @@ std::pair DashboardItemDistance::positionAndLabel( "focus" }; case Type::Camera: - return { OsEng.renderEngine().camera()->positionVec3(), "camera" }; + return { OsEng.renderEngine().scene()->camera()->positionVec3(), "camera" }; default: return { glm::dvec3(0.0), "Unknown" }; } diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index 33730c82e2..b6a3ebf0f6 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -76,14 +76,13 @@ int addDashboardItemToScreenSpace(lua_State* L) { return 0; } - std::shared_ptr ssr = - OsEng.renderEngine().screenSpaceRenderable(name); + ScreenSpaceRenderable* ssr = OsEng.renderEngine().screenSpaceRenderable(name); if (!ssr) { return luaL_error(L, "Provided name is not a ScreenSpace item"); } - ScreenSpaceDashboard* dash = dynamic_cast(ssr.get()); + ScreenSpaceDashboard* dash = dynamic_cast(ssr); if (!dash) { return luaL_error( L, @@ -106,14 +105,13 @@ int removeDashboardItemsFromScreenSpace(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeDashboardItemsFromScreenSpace"); std::string name = ghoul::lua::checkStringAndPop(L); - std::shared_ptr ssr = - OsEng.renderEngine().screenSpaceRenderable(name); + ScreenSpaceRenderable* ssr = OsEng.renderEngine().screenSpaceRenderable(name); if (!ssr) { return luaL_error(L, "Provided name is not a ScreenSpace item"); } - ScreenSpaceDashboard* dash = dynamic_cast(ssr.get()); + ScreenSpaceDashboard* dash = dynamic_cast(ssr); if (!dash) { return luaL_error(L, "Provided name is a ScreenSpace item but not a dashboard"); } diff --git a/modules/imgui/src/guijoystickcomponent.cpp b/modules/imgui/src/guijoystickcomponent.cpp index 03c49fdbd6..999e3c6529 100644 --- a/modules/imgui/src/guijoystickcomponent.cpp +++ b/modules/imgui/src/guijoystickcomponent.cpp @@ -53,13 +53,13 @@ void GuiJoystickComponent::render() { const JoystickInputStates& states = OsEng.navigationHandler().inputState().joystickInputStates(); - for (int i = 0; i < states.size(); ++i) { + for (size_t i = 0; i < states.size(); ++i) { const JoystickInputState& state = states[i]; if (!state.isConnected) { continue; } - ImGui::Text("%s [%i]", state.name.c_str(), i); + ImGui::Text("%s [%i]", state.name.c_str(), static_cast(i)); ImGui::Text("%s", "Axes"); for (int j = 0; j < state.nAxes; ++j) { float f = state.axes[j]; diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index deb34946a2..bfd2c37ac2 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -89,10 +89,10 @@ int iswa_addScreenSpaceCygnet(lua_State* L) { d.setValue("Type", "ScreenSpaceCygnet"); d.setValue("UpdateInterval", static_cast(updateInterval)); - std::shared_ptr s( + std::unique_ptr s( ScreenSpaceRenderable::createFromDictionary(d) ); - OsEng.renderEngine().addScreenSpaceRenderable(s); + OsEng.renderEngine().addScreenSpaceRenderable(std::move(s)); } return 0; } diff --git a/src/engine/configuration.cpp b/src/engine/configuration.cpp index f74e601bf5..eea0537f59 100644 --- a/src/engine/configuration.cpp +++ b/src/engine/configuration.cpp @@ -43,7 +43,6 @@ namespace { constexpr const char* KeyAsset = "Asset"; constexpr const char* KeyGlobalCustomizationScripts = "GlobalCustomizationScripts"; constexpr const char* KeyPaths = "Paths"; - constexpr const char* KeyPathsCACHE = "Paths.CACHE"; constexpr const char* KeyFonts = "Fonts"; constexpr const char* KeyLogging = "Logging"; constexpr const char* KeyLogDir = "LogDir"; diff --git a/src/engine/logfactory.cpp b/src/engine/logfactory.cpp index f5feb51d41..042fc4d66b 100644 --- a/src/engine/logfactory.cpp +++ b/src/engine/logfactory.cpp @@ -26,30 +26,29 @@ #include #include - -#include -#include #include #include #include #include +#include +#include namespace { - const char* keyType = "Type"; - const char* keyFilename = "File"; - const char* keyAppend = "Append"; - const char* keyTimeStamping = "TimeStamping"; - const char* keyDateStamping = "DateStamping"; - const char* keyCategoryStamping = "CategoryStamping"; - const char* keyLogLevelStamping = "LogLevelStamping"; - const char* keyLogLevel = "LogLevel"; + constexpr const char* KeyType = "Type"; + constexpr const char* KeyFilename = "File"; + constexpr const char* KeyAppend = "Append"; + constexpr const char* KeyTimeStamping = "TimeStamping"; + constexpr const char* KeyDateStamping = "DateStamping"; + constexpr const char* KeyCategoryStamping = "CategoryStamping"; + constexpr const char* KeyLogLevelStamping = "LogLevelStamping"; + constexpr const char* KeyLogLevel = "LogLevel"; - const char* valueHtmlLog = "html"; - const char* valueTextLog = "Text"; + constexpr const char* ValueHtmlLog = "html"; + constexpr const char* ValueTextLog = "Text"; - const char* BootstrapPath = "${WEB}/common/bootstrap.min.css"; - const char* CssPath = "${WEB}/log/style.css"; - const char* JsPath = "${WEB}/log/script.js"; + constexpr const char* BootstrapPath = "${WEB}/common/bootstrap.min.css"; + constexpr const char* CssPath = "${WEB}/log/style.css"; + constexpr const char* JsPath = "${WEB}/log/script.js"; } // namespace namespace openspace { @@ -62,50 +61,50 @@ documentation::Documentation LogFactoryDocumentation() { "core_logfactory", { { - keyType, + KeyType, new StringInListVerifier({ // List from createLog - valueTextLog, valueHtmlLog + ValueTextLog, ValueHtmlLog }), Optional::No, "The type of the new log to be generated." }, { - keyFilename, + KeyFilename, new StringVerifier, Optional::No, "The filename to which the log will be written." }, { - keyAppend, + KeyAppend, new BoolVerifier, Optional::Yes, "Determines whether the file will be cleared at startup or if the " "contents will be appended to previous runs." }, { - keyTimeStamping, + KeyTimeStamping, new BoolVerifier, Optional::Yes, "Determines whether the log entires should be stamped with the time at " "which the message was logged." }, { - keyDateStamping, + KeyDateStamping, new BoolVerifier, Optional::Yes, "Determines whether the log entries should be stamped with the date at " "which the message was logged." }, { - keyCategoryStamping, + KeyCategoryStamping, new BoolVerifier, Optional::Yes, "Determines whether the log entries should be stamped with the " "category that creates the log message." }, { - keyLogLevelStamping, + KeyLogLevelStamping, new BoolVerifier, Optional::Yes, "Determines whether the log entries should be stamped with the log level " @@ -125,33 +124,33 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona ); // 'type' and 'filename' are required keys - std::string type = dictionary.value(keyType); - std::string filename = absPath(dictionary.value(keyFilename)); + std::string type = dictionary.value(KeyType); + std::string filename = absPath(dictionary.value(KeyFilename)); // the rest are optional bool append = true; - if (dictionary.hasKeyAndValue(keyAppend)) { - append = dictionary.value(keyAppend); + if (dictionary.hasKeyAndValue(KeyAppend)) { + append = dictionary.value(KeyAppend); } bool timeStamp = true; - if (dictionary.hasKeyAndValue(keyTimeStamping)) { - timeStamp = dictionary.value(keyTimeStamping); + if (dictionary.hasKeyAndValue(KeyTimeStamping)) { + timeStamp = dictionary.value(KeyTimeStamping); } bool dateStamp = true; - if (dictionary.hasKeyAndValue(keyDateStamping)) { - dateStamp = dictionary.value(keyDateStamping); + if (dictionary.hasKeyAndValue(KeyDateStamping)) { + dateStamp = dictionary.value(KeyDateStamping); } bool categoryStamp = true; - if (dictionary.hasKeyAndValue(keyCategoryStamping)) { - categoryStamp = dictionary.value(keyCategoryStamping); + if (dictionary.hasKeyAndValue(KeyCategoryStamping)) { + categoryStamp = dictionary.value(KeyCategoryStamping); } bool logLevelStamp = true; - if (dictionary.hasKeyAndValue(keyLogLevelStamping)) { - logLevelStamp = dictionary.value(keyLogLevelStamping); + if (dictionary.hasKeyAndValue(KeyLogLevelStamping)) { + logLevelStamp = dictionary.value(KeyLogLevelStamping); } std::string logLevel; - if (dictionary.hasKeyAndValue(keyLogLevel)) { - logLevel = dictionary.value(keyLogLevel); + if (dictionary.hasKeyAndValue(KeyLogLevel)) { + logLevel = dictionary.value(KeyLogLevel); } using Append = ghoul::logging::TextLog::Append; @@ -160,18 +159,18 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona using CategoryStamping = ghoul::logging::Log::CategoryStamping; using LogLevelStamping = ghoul::logging::Log::LogLevelStamping; - if (type == valueHtmlLog) { + if (type == ValueHtmlLog) { std::vector cssFiles{absPath(BootstrapPath), absPath(CssPath)}; std::vector jsFiles{absPath(JsPath)}; if (logLevel.empty()) { return std::make_unique( filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, + Append(append), + TimeStamping(timeStamp), + DateStamping(dateStamp), + CategoryStamping(categoryStamp), + LogLevelStamping(logLevelStamp), cssFiles, jsFiles ); @@ -179,35 +178,36 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona else { return std::make_unique( filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, - cssFiles, jsFiles, + Append(append), + TimeStamping(timeStamp), + DateStamping(dateStamp), + CategoryStamping(categoryStamp), + LogLevelStamping(logLevelStamp), + cssFiles, + jsFiles, ghoul::logging::levelFromString(logLevel) - ); + ); } } - else if (type == valueTextLog) { + else if (type == ValueTextLog) { if (logLevel.empty()) { return std::make_unique( filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No + Append(append), + TimeStamping(timeStamp), + DateStamping(dateStamp), + CategoryStamping(categoryStamp), + LogLevelStamping(logLevelStamp) ); } else { return std::make_unique( filename, - append ? Append::Yes : Append::No, - timeStamp ? TimeStamping::Yes : TimeStamping::No, - dateStamp ? DateStamping::Yes : DateStamping::No, - categoryStamp ? CategoryStamping::Yes : CategoryStamping::No, - logLevelStamp ? LogLevelStamping::Yes : LogLevelStamping::No, + Append(append), + TimeStamping(timeStamp), + DateStamping(dateStamp), + CategoryStamping(categoryStamp), + LogLevelStamping(logLevelStamp), ghoul::logging::levelFromString(logLevel) ); } diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 59daaf9043..2698336e56 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -39,17 +39,12 @@ #include #include #include - #include - #include #include #include #include #include -#include -#include - #include #include #include @@ -58,19 +53,18 @@ #include #include #include -#include - +#include +#include #include #include +#include #include #include #include #include #include #include - #include -#include #include #include #include @@ -80,12 +74,13 @@ #include #include #include +#include #include #include #include #include - #include +#include #if defined(_MSC_VER) && defined(OPENSPACE_ENABLE_VLD) #include @@ -100,8 +95,6 @@ #endif // __APPLE__ -#include - #include "openspaceengine_lua.inl" using namespace openspace::scripting; @@ -125,7 +118,6 @@ namespace { std::string cacheFolder; } commandlineArgumentPlaceholders; - static const openspace::properties::Property::PropertyInfo VersionInfo = { "VersionInfo", "Version Information", @@ -152,7 +144,7 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, : _configuration(new Configuration) , _scene(nullptr) , _dashboard(new Dashboard) - , _downloadManager(nullptr) + , _downloadManager(std::make_unique()) , _console(new LuaConsole) , _moduleEngine(new ModuleEngine) , _networkEngine(new NetworkEngine) @@ -175,10 +167,6 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, properties::StringProperty(VersionInfo, OPENSPACE_VERSION_STRING_FULL), properties::StringProperty(SourceControlInfo, OPENSPACE_GIT_FULL) } - , _hasScheduledAssetLoading(false) - , _scheduledAssetPathToLoad("") - , _shutdown({false, 0.f, 0.f}) - , _isFirstRenderingFirstFrame(true) { _rootPropertyOwner->addPropertySubOwner(_moduleEngine.get()); @@ -242,8 +230,6 @@ OpenSpaceEngine& OpenSpaceEngine::ref() { return *_engine; } -OpenSpaceEngine::~OpenSpaceEngine() {} - bool OpenSpaceEngine::isCreated() { return _engine != nullptr; } @@ -254,7 +240,6 @@ void OpenSpaceEngine::create(int argc, char** argv, bool& requestClose, bool consoleLog) { ghoul_assert(!_engine, "OpenSpaceEngine was already created"); - //ghoul_assert(windowWrapper != nullptr, "No Window Wrapper was provided"); requestClose = false; @@ -373,7 +358,6 @@ void OpenSpaceEngine::create(int argc, char** argv, ); } - const bool hasCacheCommandline = !commandlineArgumentPlaceholders.cacheFolder.empty(); const bool hasCacheConfig = _engine->_configuration->usePerSceneCache; std::string cacheFolder = absPath("${CACHE}"); @@ -468,14 +452,14 @@ void OpenSpaceEngine::create(int argc, char** argv, } void OpenSpaceEngine::destroy() { - if (_engine->parallelPeer().status() != - ParallelConnection::Status::Disconnected) - { + if (_engine->parallelPeer().status() != ParallelConnection::Status::Disconnected) { _engine->parallelPeer().disconnect(); } _engine->_syncEngine->removeSyncables(_engine->timeManager().getSyncables()); - _engine->_syncEngine->removeSyncables(_engine->_renderEngine->getSyncables()); + if (_engine->_scene && _engine->_scene->camera()) { + _engine->_syncEngine->removeSyncables(_engine->_scene->camera()->getSyncables()); + } _engine->_renderEngine->deinitializeGL(); @@ -505,7 +489,7 @@ void OpenSpaceEngine::initialize() { glbinding::Binding::useCurrentContext(); glbinding::Binding::initialize(); - // clear the screen so the user doesn't have to see old buffer contents from the + // 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)); @@ -523,21 +507,10 @@ void OpenSpaceEngine::initialize() { LDEBUG("Detecting capabilities"); SysCap.detectCapabilities(); - using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity; - static const std::map VerbosityMap = { - { "None", Verbosity::None }, - { "Minimal", Verbosity::Minimal }, - { "Default", Verbosity::Default }, - { "Full", Verbosity::Full } - }; - - std::string v = _engine->_configuration->logging.capabilitiesVerbosity; - ghoul_assert( - VerbosityMap.find(v) != VerbosityMap.end(), - "Missing check for syscaps verbosity in openspace.cfg documentation" + Verbosity verbosity = ghoul::from_string( + _engine->_configuration->logging.capabilitiesVerbosity ); - Verbosity verbosity = VerbosityMap.find(v)->second; SysCap.logCapabilities(verbosity); @@ -553,9 +526,6 @@ void OpenSpaceEngine::initialize() { ); } - _downloadManager = std::make_unique(); - - // Register Lua script functions LDEBUG("Registering Lua libraries"); registerCoreClasses(*_scriptEngine); @@ -570,7 +540,6 @@ void OpenSpaceEngine::initialize() { } } - // TODO: Maybe move all scenegraph and renderengine stuff to initializeGL scriptEngine().initialize(); writeStaticDocumentation(); @@ -589,16 +558,20 @@ void OpenSpaceEngine::initialize() { _renderEngine->initialize(); - _loadingScreen = _engine->createLoadingScreen(); + _loadingScreen = std::make_unique( + LoadingScreen::ShowMessage(_configuration->loadingScreen.isShowingMessages), + LoadingScreen::ShowNodeNames(_configuration->loadingScreen.isShowingNodeNames), + LoadingScreen::ShowProgressbar(_configuration->loadingScreen.isShowingProgressbar) + ); + _loadingScreen->render(); - for (const auto& func : _moduleCallbacks.initialize) { + for (const std::function& func : _moduleCallbacks.initialize) { func(); } - std::string assetPath = _engine->_configuration->asset; _engine->_assetManager->initialize(); - scheduleLoadSingleAsset(assetPath); + scheduleLoadSingleAsset(_engine->_configuration->asset); LTRACE("OpenSpaceEngine::initialize(end)"); } @@ -608,18 +581,6 @@ void OpenSpaceEngine::scheduleLoadSingleAsset(std::string assetPath) { _scheduledAssetPathToLoad = assetPath; } -std::unique_ptr OpenSpaceEngine::createLoadingScreen() { - bool showMessage = _configuration->loadingScreen.isShowingMessages; - bool showNodeNames = _configuration->loadingScreen.isShowingNodeNames; - bool showProgressbar = _configuration->loadingScreen.isShowingProgressbar; - - return std::make_unique( - LoadingScreen::ShowMessage(showMessage), - LoadingScreen::ShowNodeNames(showNodeNames), - LoadingScreen::ShowProgressbar(showProgressbar) - ); -} - void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { LTRACE("OpenSpaceEngine::loadSingleAsset(begin)"); @@ -630,12 +591,14 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { windowWrapper().setBarrier(true); }; - if (assetPath == "") { + if (assetPath.empty()) { return; } if (_scene) { _syncEngine->removeSyncables(_timeManager->getSyncables()); - _syncEngine->removeSyncables(_renderEngine->getSyncables()); + if (_scene && _scene->camera()) { + _syncEngine->removeSyncables(_scene->camera()->getSyncables()); + } _renderEngine->setScene(nullptr); _renderEngine->setCamera(nullptr); _navigationHandler->setCamera(nullptr); @@ -643,10 +606,8 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { _rootPropertyOwner->removePropertySubOwner(_scene.get()); } - bool multiThreadedInitialization = _configuration->useMultithreadedInitialization; - std::unique_ptr sceneInitializer; - if (multiThreadedInitialization) { + if (_configuration->useMultithreadedInitialization) { unsigned int nAvailableThreads = std::thread::hardware_concurrency(); unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads - 1; sceneInitializer = std::make_unique(nThreads); @@ -681,11 +642,11 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { _assetManager->rootAsset()->subTreeAssets(); std::unordered_set> resourceSyncs; - for (const auto& a : allAssets) { + for (const std::shared_ptr& a : allAssets) { std::vector> syncs = a->ownSynchronizations(); - for (const auto& s : syncs) { + for (const std::shared_ptr& s : syncs) { if (s->state() == ResourceSynchronization::State::Syncing) { resourceSyncs.insert(s); _loadingScreen->updateItem( @@ -722,7 +683,7 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { (*it)->name(), (*it)->name(), LoadingScreen::ItemStatus::Finished, - 1.0f + 1.f ); it = resourceSyncs.erase(it); } @@ -740,11 +701,13 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { _loadingScreen->finalize(); _renderEngine->updateScene(); - _renderEngine->setGlobalBlackOutFactor(0.0); - _renderEngine->startFading(1, 3.0); + _renderEngine->setGlobalBlackOutFactor(0.f); + _renderEngine->startFading(1, 3.f); _syncEngine->addSyncables(_timeManager->getSyncables()); - _syncEngine->addSyncables(_renderEngine->getSyncables()); + if (_scene && _scene->camera()) { + _syncEngine->addSyncables(_scene->camera()->getSyncables()); + } #ifdef __APPLE__ showTouchbar(); @@ -760,11 +723,11 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { void OpenSpaceEngine::deinitialize() { LTRACE("OpenSpaceEngine::deinitialize(begin)"); - for (const auto& func : _engine->_moduleCallbacks.deinitializeGL) { + for (const std::function& func : _engine->_moduleCallbacks.deinitializeGL) { func(); } - for (const auto& func : _engine->_moduleCallbacks.deinitialize) { + for (const std::function& func : _engine->_moduleCallbacks.deinitialize) { func(); } @@ -824,7 +787,6 @@ void OpenSpaceEngine::gatherCommandlineArguments() { } void OpenSpaceEngine::runGlobalCustomizationScripts() { - // @CLEANUP: Move this into the scene loading? ---abock LINFO("Running Global initialization scripts"); ghoul::lua::LuaState state; OsEng.scriptEngine().initializeLuaState(state); @@ -896,7 +858,7 @@ void OpenSpaceEngine::configureLogging(bool consoleLog) { using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; LogManager::initialize( level, - immediateFlush ? ImmediateFlush::Yes : ImmediateFlush::No + ImmediateFlush(immediateFlush) ); if (consoleLog) { LogMgr.addLog(std::make_unique()); @@ -906,8 +868,15 @@ void OpenSpaceEngine::configureLogging(bool consoleLog) { try { LogMgr.addLog(createLog(log)); } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); + catch (const documentation::SpecificationError& e) { + LERROR("Failed loading of log"); + for (const documentation::TestResult::Offense& o : e.result.offenses) { + LERRORC(o.offender, std::to_string(o.reason)); + } + for (const documentation::TestResult::Warning& w : e.result.warnings) { + LWARNINGC(w.offender, std::to_string(w.reason)); + } + throw; } } @@ -918,9 +887,7 @@ void OpenSpaceEngine::configureLogging(bool consoleLog) { #endif // WIN32 #ifndef GHOUL_LOGGING_ENABLE_TRACE - std::string logLevel = "Info"; - configurationManager().getValue(KeyLogLevel, logLevel); - LogLevel level = ghoul::logging::levelFromString(logLevel); + LogLevel level = ghoul::logging::levelFromString(_configuration->logging.level); if (level == ghoul::logging::LogLevel::Trace) { LWARNING( @@ -996,8 +963,7 @@ void OpenSpaceEngine::initializeGL() { } - for (const std::string& sev : _configuration->openGLDebugContext.severityFilters) - { + for (const std::string& sev : _configuration->openGLDebugContext.severityFilters){ setDebugMessageControl( Source::DontCare, Type::DontCare, @@ -1041,6 +1007,7 @@ void OpenSpaceEngine::initializeGL() { // state from KeyCheckOpenGLState if (_configuration->isCheckingOpenGLState) { using namespace glbinding; + // Infinite loop -- welcome to the danger zone setCallbackMaskExcept(CallbackMask::After, { "glGetError" }); setAfterCallback([](const FunctionCall& f) { @@ -1092,6 +1059,7 @@ void OpenSpaceEngine::initializeGL() { if (_configuration->isLoggingOpenGLCalls) { using namespace glbinding; + setCallbackMask(CallbackMask::After | CallbackMask::ParametersAndReturnValue); glbinding::setAfterCallback([](const glbinding::FunctionCall& call) { std::string arguments = std::accumulate( @@ -1119,7 +1087,7 @@ void OpenSpaceEngine::initializeGL() { _moduleEngine->initializeGL(); - for (const auto& func : _moduleCallbacks.initializeGL) { + for (const std::function& func : _moduleCallbacks.initializeGL) { func(); } @@ -1136,7 +1104,7 @@ void OpenSpaceEngine::preSynchronization() { perf = std::make_unique( "OpenSpaceEngine::preSynchronization", OsEng.renderEngine().performanceManager() - ); + ); } FileSys.triggerFilesystemEvents(); @@ -1145,7 +1113,7 @@ void OpenSpaceEngine::preSynchronization() { LINFO(fmt::format("Loading asset: {}", _scheduledAssetPathToLoad)); loadSingleAsset(_scheduledAssetPathToLoad); _hasScheduledAssetLoading = false; - _scheduledAssetPathToLoad = ""; + _scheduledAssetPathToLoad.clear(); } if (_isFirstRenderingFirstFrame) { @@ -1165,22 +1133,23 @@ void OpenSpaceEngine::preSynchronization() { ); for (Iter it = scheduledScripts.first; it != scheduledScripts.second; ++it) { _scriptEngine->queueScript( - *it, ScriptEngine::RemoteScripting::Yes + *it, + ScriptEngine::RemoteScripting::Yes ); } _renderEngine->updateScene(); //_navigationHandler->updateCamera(dt); - Camera* camera = _renderEngine->camera(); + Camera* camera = _scene->camera(); if (camera) { _navigationHandler->updateCamera(dt); - _renderEngine->camera()->invalidateCache(); + camera->invalidateCache(); } _parallelPeer->preSynchronization(); } - for (const auto& func : _moduleCallbacks.preSync) { + for (const std::function& func : _moduleCallbacks.preSync) { func(); } LTRACE("OpenSpaceEngine::preSynchronization(end)"); @@ -1220,10 +1189,10 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { _renderEngine->updateShaderPrograms(); if (!master) { - _renderEngine->camera()->invalidateCache(); + _scene->camera()->invalidateCache(); } - for (const auto& func : _moduleCallbacks.postSyncPreDraw) { + for (const std::function& func : _moduleCallbacks.postSyncPreDraw) { func(); } @@ -1249,8 +1218,7 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { LTRACE("OpenSpaceEngine::postSynchronizationPreDraw(end)"); } -void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, - const glm::mat4& viewMatrix, +void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix) { LTRACE("OpenSpaceEngine::render(begin)"); @@ -1271,7 +1239,7 @@ void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, _renderEngine->render(sceneMatrix, viewMatrix, projectionMatrix); - for (const auto& func : _moduleCallbacks.render) { + for (const std::function& func : _moduleCallbacks.render) { func(); } @@ -1297,7 +1265,7 @@ void OpenSpaceEngine::drawOverlays() { _console->render(); } - for (const auto& func : _moduleCallbacks.draw2D) { + for (const std::function& func : _moduleCallbacks.draw2D) { func(); } @@ -1317,7 +1285,7 @@ void OpenSpaceEngine::postDraw() { _renderEngine->postDraw(); - for (const auto& func : _moduleCallbacks.postDraw) { + for (const std::function& func : _moduleCallbacks.postDraw) { func(); } @@ -1326,20 +1294,20 @@ void OpenSpaceEngine::postDraw() { _isFirstRenderingFirstFrame = false; } - LTRACE("OpenSpaceEngine::postDraw(end)"); } void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction action) { - for (const auto& func : _moduleCallbacks.keyboard) { - const bool consumed = func(key, mod, action); - if (consumed) { + using F = std::function; + for (const F& func : _moduleCallbacks.keyboard) { + const bool isConsumed = func(key, mod, action); + if (isConsumed) { return; } } - const bool consoleConsumed = _console->keyboardCallback(key, mod, action); - if (consoleConsumed) { + const bool isConsoleConsumed = _console->keyboardCallback(key, mod, action); + if (isConsoleConsumed) { return; } @@ -1348,9 +1316,10 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio } void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier) { - for (const auto& func : _moduleCallbacks.character) { - bool consumed = func(codepoint, modifier); - if (consumed) { + using F = std::function; + for (const F& func : _moduleCallbacks.character) { + bool isConsumed = func(codepoint, modifier); + if (isConsumed) { return; } } @@ -1359,9 +1328,10 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier) } void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action) { - for (const auto& func : _moduleCallbacks.mouseButton) { - bool consumed = func(button, action); - if (consumed) { + using F = std::function; + for (const F& func : _moduleCallbacks.mouseButton) { + bool isConsumed = func(button, action); + if (isConsumed) { // If the mouse was released, we still want to forward it to the navigation // handler in order to reliably terminate a rotation or zoom. Accidentally // moving the cursor over a UI window is easy to miss and leads to weird @@ -1379,7 +1349,8 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action } void OpenSpaceEngine::mousePositionCallback(double x, double y) { - for (const auto& func : _moduleCallbacks.mousePosition) { + using F = std::function; + for (const F& func : _moduleCallbacks.mousePosition) { func(x, y); } @@ -1387,9 +1358,10 @@ void OpenSpaceEngine::mousePositionCallback(double x, double y) { } void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY) { - for (const auto& func : _moduleCallbacks.mouseScrollWheel) { - bool consumed = func(posX, posY); - if (consumed) { + using F = std::function; + for (const F& func : _moduleCallbacks.mouseScrollWheel) { + bool isConsumed = func(posX, posY); + if (isConsumed) { return; } } @@ -1571,6 +1543,7 @@ void OpenSpaceEngine::registerModuleMouseScrollWheelCallback( } const Configuration& OpenSpaceEngine::configuration() const { + ghoul_assert(_configuration, "Configuration must not be nullptr"); return *_configuration; } @@ -1645,19 +1618,12 @@ interaction::KeyBindingManager& OpenSpaceEngine::keyBindingManager() { } properties::PropertyOwner& OpenSpaceEngine::rootPropertyOwner() { - ghoul_assert( - _rootPropertyOwner, - "Root Property Namespace must not be nullptr" - ); + 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" - ); - + ghoul_assert(_virtualPropertyManager, "Virtual Property Manager must not be nullptr"); return *_virtualPropertyManager; } diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index 5a640be04e..ab8eccee66 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -184,7 +184,7 @@ int bindJoystickButton(lua_State* L) { } int clearJoystickButton(lua_State* L) { - int n = ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); + ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); int button = static_cast(lua_tonumber(L, 1)); @@ -195,7 +195,7 @@ int clearJoystickButton(lua_State* L) { } int joystickButton(lua_State* L) { - int n = ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); + ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::bindJoystickButton"); int button = static_cast(lua_tonumber(L, 1)); diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 4b717d7c6a..bdc25c82fc 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -86,9 +86,7 @@ namespace { constexpr const char* _loggerCat = "RenderEngine"; - constexpr const char* KeyRenderingMethod = "RenderingMethod"; constexpr const std::chrono::seconds ScreenLogTimeToLive(15); - constexpr const char* DefaultRenderingMethod = "ABuffer"; constexpr const char* RenderFsPath = "${SHADERS}/render.frag"; constexpr const char* KeyFontMono = "Mono"; @@ -242,20 +240,14 @@ RenderEngine::RenderEngine() , _showVersionInfo(ShowVersionInfo, true) , _showCameraInfo(ShowCameraInfo, true) , _takeScreenshot(TakeScreenshotInfo) - , _shouldTakeScreenshot(false) , _applyWarping(ApplyWarpingInfo, false) , _showFrameNumber(ShowFrameNumberInfo, false) , _disableMasterRendering(DisableMasterInfo, false) , _disableSceneTranslationOnMaster(DisableTranslationInfo, false) - , _globalBlackOutFactor(1.f) - , _fadeDuration(2.f) - , _currentFadeTime(0.f) - , _fadeDirection(0) , _nAaSamples(AaSamplesInfo, 4, 1, 16) , _hdrExposure(HDRExposureInfo, 0.4f, 0.01f, 10.0f) , _hdrBackground(BackgroundExposureInfo, 2.8f, 0.01f, 10.0f) , _gamma(GammaInfo, 2.2f, 0.01f, 10.0f) - , _frameNumber(0) , _screenSpaceOwner({ "ScreenSpace" }) { _doPerformanceMeasurements.onChange([this](){ @@ -284,26 +276,29 @@ RenderEngine::RenderEngine() _renderer->setNAaSamples(_nAaSamples); } }); + addProperty(_nAaSamples); + _hdrExposure.onChange([this]() { if (_renderer) { _renderer->setHDRExposure(_hdrExposure); } }); + addProperty(_hdrExposure); + _hdrBackground.onChange([this]() { if (_renderer) { _renderer->setHDRBackground(_hdrBackground); } }); + addProperty(_hdrBackground); + _gamma.onChange([this]() { if (_renderer) { _renderer->setGamma(_gamma); } }); - - addProperty(_nAaSamples); - addProperty(_hdrExposure); - addProperty(_hdrBackground); addProperty(_gamma); + addProperty(_applyWarping); _takeScreenshot.onChange([this](){ @@ -324,14 +319,14 @@ void RenderEngine::setRendererFromString(const std::string& renderingMethod) { std::unique_ptr newRenderer = nullptr; switch (_rendererImplementation) { - case RendererImplementation::Framebuffer: - newRenderer = std::make_unique(); - break; - case RendererImplementation::ABuffer: - newRenderer = std::make_unique(); - break; - case RendererImplementation::Invalid: - LFATAL(fmt::format("Rendering method '{}' not available", renderingMethod)); + case RendererImplementation::Framebuffer: + newRenderer = std::make_unique(); + break; + case RendererImplementation::ABuffer: + newRenderer = std::make_unique(); + break; + case RendererImplementation::Invalid: + LFATAL(fmt::format("Rendering method '{}' not available", renderingMethod)); } setRenderer(std::move(newRenderer)); @@ -352,9 +347,11 @@ void RenderEngine::initialize() { } } - _disableMasterRendering = OsEng.configuration().isRenderingOnMasterDisabled; + // 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; _raycasterManager = std::make_unique(); _deferredcasterManager = std::make_unique(); @@ -365,30 +362,30 @@ void RenderEngine::initialize() { #ifdef GHOUL_USE_DEVIL ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_DEVIL #ifdef GHOUL_USE_FREEIMAGE ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_FREEIMAGE #ifdef GHOUL_USE_SOIL ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); ghoul::io::TextureWriter::ref().addWriter( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_SOIL #ifdef GHOUL_USE_STB_IMAGE ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); #endif // GHOUL_USE_STB_IMAGE ghoul::io::TextureReader::ref().addReader( - std::make_shared() + std::make_unique() ); MissionManager::initialize(); @@ -403,26 +400,21 @@ void RenderEngine::initializeGL() { // development OsEng.windowWrapper().setNearFarClippingPlane(0.001f, 1000.f); - try { - const float fontSizeBig = 50.f; - _fontBig = OsEng.fontManager().font(KeyFontMono, fontSizeBig); - const float fontSizeTime = 15.f; - _fontDate = OsEng.fontManager().font(KeyFontMono, fontSizeTime); - const float fontSizeMono = 10.f; - _fontInfo = OsEng.fontManager().font(KeyFontMono, fontSizeMono); - const float fontSizeLight = 8.f; - _fontLog = OsEng.fontManager().font(KeyFontLight, fontSizeLight); - } catch (const ghoul::fontrendering::Font::FreeTypeException& e) { - LERROR(e.what()); - throw; - } + constexpr const float fontSizeBig = 50.f; + _fontBig = OsEng.fontManager().font(KeyFontMono, fontSizeBig); + constexpr const float fontSizeTime = 15.f; + _fontDate = OsEng.fontManager().font(KeyFontMono, fontSizeTime); + constexpr const float fontSizeMono = 10.f; + _fontInfo = OsEng.fontManager().font(KeyFontMono, fontSizeMono); + constexpr const float fontSizeLight = 8.f; + _fontLog = OsEng.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::shared_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : _screenSpaceRenderables) { ssr->initializeGL(); } @@ -431,7 +423,7 @@ void RenderEngine::initializeGL() { } void RenderEngine::deinitialize() { - for (std::shared_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : _screenSpaceRenderables) { ssr->deinitialize(); } @@ -439,7 +431,7 @@ void RenderEngine::deinitialize() { } void RenderEngine::deinitializeGL() { - for (std::shared_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : _screenSpaceRenderables) { ssr->deinitializeGL(); } } @@ -453,7 +445,7 @@ void RenderEngine::updateScene() { const Time& currentTime = OsEng.timeManager().time(); _scene->update({ - { glm::dvec3(0), glm::dmat3(1), 1.0 }, + { glm::dvec3(0.0), glm::dmat3(11.), 1.0 }, currentTime, _performanceManager != nullptr }); @@ -490,7 +482,7 @@ void RenderEngine::updateRenderer() { } void RenderEngine::updateScreenSpaceRenderables() { - for (std::shared_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : _screenSpaceRenderables) { ssr->update(); } } @@ -516,18 +508,18 @@ glm::ivec2 RenderEngine::fontResolution() const { void RenderEngine::updateFade() { // Temporary fade funtionality - const float fadedIn = 1.0; - const float fadedOut = 0.0; + constexpr const float FadedIn = 1.0; + constexpr const float FadedOut = 0.0; // Don't restart the fade if you've already done it in that direction - const bool isFadedIn = (_fadeDirection > 0 && _globalBlackOutFactor == fadedIn); - const bool isFadedOut = (_fadeDirection < 0 && _globalBlackOutFactor == fadedOut); + const bool isFadedIn = (_fadeDirection > 0 && _globalBlackOutFactor == FadedIn); + const bool isFadedOut = (_fadeDirection < 0 && _globalBlackOutFactor == FadedOut); if (isFadedIn || isFadedOut) { _fadeDirection = 0; } if (_fadeDirection != 0) { if (_currentFadeTime > _fadeDuration) { - _globalBlackOutFactor = _fadeDirection > 0 ? fadedIn : fadedOut; + _globalBlackOutFactor = _fadeDirection > 0 ? FadedIn : FadedOut; _fadeDirection = 0; } else { @@ -547,13 +539,13 @@ void RenderEngine::updateFade() { } _currentFadeTime += static_cast( OsEng.windowWrapper().averageDeltaTime() - ); + ); } } } void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, - const glm::mat4& projectionMatrix) + const glm::mat4& projectionMatrix) { LTRACE("RenderEngine::render(begin)"); WindowWrapper& wrapper = OsEng.windowWrapper(); @@ -584,7 +576,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat ++_frameNumber; - for (std::shared_ptr& ssr : _screenSpaceRenderables) { + for (std::unique_ptr& ssr : _screenSpaceRenderables) { if (ssr->isEnabled() && ssr->isReady()) { ssr->render(); } @@ -612,7 +604,7 @@ void RenderEngine::renderOverlays(const ShutdownInformation& info) { } void RenderEngine::renderShutdownInformation(float timer, float fullTime) { - timer = timer < 0.f ? 0.f : timer; + timer = std::max(timer, 0.f); auto size = ghoul::fontrendering::FontRenderer::defaultRenderer().boundingBox( *_fontDate, @@ -650,7 +642,7 @@ void RenderEngine::renderDashboard() { perf = std::make_unique( "Main Dashboard::render", OsEng.renderEngine().performanceManager() - ); + ); } glm::vec2 penPosition = glm::vec2( 10.f, @@ -716,12 +708,8 @@ void RenderEngine::setCamera(Camera* camera) { } } -Camera* RenderEngine::camera() const { - return _camera; -} - -Renderer* RenderEngine::renderer() const { - return _renderer.get(); +const Renderer& RenderEngine::renderer() const { + return *_renderer; } RenderEngine::RendererImplementation RenderEngine::rendererImplementation() const { @@ -743,27 +731,29 @@ void RenderEngine::startFading(int direction, float fadeDuration) { } /** -* Build a program object for rendering with the used renderer -*/ + * Build a program object for rendering with the used renderer + */ std::unique_ptr RenderEngine::buildRenderProgram( - std::string name, std::string vsPath, - std::string fsPath, const ghoul::Dictionary& data) + const std::string& name, + const std::string& vsPath, + std::string fsPath, + ghoul::Dictionary data) { - ghoul::Dictionary dict = data; + ghoul::Dictionary dict = std::move(data); // set path to the current renderer's main fragment shader dict.setValue("rendererData", _rendererData); // parameterize the main fragment shader program with specific contents. // fsPath should point to a shader file defining a Fragment getFragment() function // instead of a void main() setting glFragColor, glFragDepth, etc. - dict.setValue("fragmentPath", fsPath); + dict.setValue("fragmentPath", std::move(fsPath)); using namespace ghoul::opengl; std::unique_ptr program = ProgramObject::Build( name, vsPath, absPath(RenderFsPath), - dict + std::move(dict) ); if (program) { @@ -776,17 +766,19 @@ std::unique_ptr RenderEngine::buildRenderProgram( * Build a program object for rendering with the used renderer */ std::unique_ptr RenderEngine::buildRenderProgram( - std::string name, std::string vsPath, - std::string fsPath, std::string csPath, - const ghoul::Dictionary& data) + const std::string& name, + const std::string& vsPath, + std::string fsPath, + const std::string& csPath, + ghoul::Dictionary data) { - ghoul::Dictionary dict = data; + ghoul::Dictionary dict = std::move(data); dict.setValue("rendererData", _rendererData); // parameterize the main fragment shader program with specific contents. // fsPath should point to a shader file defining a Fragment getFragment() function // instead of a void main() setting glFragColor, glFragDepth, etc. - dict.setValue("fragmentPath", fsPath); + dict.setValue("fragmentPath", std::move(fsPath)); using namespace ghoul::opengl; std::unique_ptr program = ProgramObject::Build( @@ -794,7 +786,7 @@ std::unique_ptr RenderEngine::buildRenderProgram( vsPath, absPath(RenderFsPath), csPath, - dict + std::move(dict) ); if (program) { @@ -824,8 +816,8 @@ void RenderEngine::removeRenderProgram(ghoul::opengl::ProgramObject* program) { * Called from the renderer, whenever it needs to update * the dictionary of all rendering programs. */ -void RenderEngine::setRendererData(const ghoul::Dictionary& data) { - _rendererData = data; +void RenderEngine::setRendererData(ghoul::Dictionary data) { + _rendererData = std::move(data); for (ghoul::opengl::ProgramObject* program : _programs) { ghoul::Dictionary dict = program->dictionary(); dict.setValue("rendererData", _rendererData); @@ -838,8 +830,8 @@ void RenderEngine::setRendererData(const ghoul::Dictionary& data) { * Called from the renderer, whenever it needs to update * the dictionary of all post rendering programs. */ -void RenderEngine::setResolveData(const ghoul::Dictionary& data) { - _resolveData = data; +void RenderEngine::setResolveData(ghoul::Dictionary data) { + _resolveData = std::move(data); for (ghoul::opengl::ProgramObject* program : _programs) { ghoul::Dictionary dict = program->dictionary(); dict.setValue("resolveData", _resolveData); @@ -848,22 +840,22 @@ void RenderEngine::setResolveData(const ghoul::Dictionary& data) { } /** -* Set raycasting uniforms on the program object, and setup raycasting. -*/ + * Set raycasting uniforms on the program object, and setup raycasting. + */ void RenderEngine::preRaycast(ghoul::opengl::ProgramObject& programObject) { _renderer->preRaycast(programObject); } /** -* Tear down raycasting for the specified program object. -*/ + * Tear down raycasting for the specified program object. + */ void RenderEngine::postRaycast(ghoul::opengl::ProgramObject& programObject) { _renderer->postRaycast(programObject); } /** -* Set renderer -*/ + * Set renderer + */ void RenderEngine::setRenderer(std::unique_ptr renderer) { if (_renderer) { _renderer->deinitialize(); @@ -938,7 +930,7 @@ std::shared_ptr RenderEngine::performanceManage return _performanceManager; } -void RenderEngine::addScreenSpaceRenderable(std::shared_ptr s) { +void RenderEngine::addScreenSpaceRenderable(std::unique_ptr s) { s->initialize(); s->initializeGL(); @@ -947,41 +939,41 @@ void RenderEngine::addScreenSpaceRenderable(std::shared_ptr s) { - auto it = std::find( +void RenderEngine::removeScreenSpaceRenderable(ScreenSpaceRenderable* s) { + auto it = std::find_if( _screenSpaceRenderables.begin(), _screenSpaceRenderables.end(), - s + [s](const std::unique_ptr& r) { return r.get() == s; } ); if (it != _screenSpaceRenderables.end()) { s->deinitialize(); - _screenSpaceOwner.removePropertySubOwner(s.get()); + _screenSpaceOwner.removePropertySubOwner(s); _screenSpaceRenderables.erase(it); } } void RenderEngine::removeScreenSpaceRenderable(const std::string& name) { - std::shared_ptr s = screenSpaceRenderable(name); + ScreenSpaceRenderable* s = screenSpaceRenderable(name); if (s) { removeScreenSpaceRenderable(s); } } -std::shared_ptr RenderEngine::screenSpaceRenderable( +ScreenSpaceRenderable* RenderEngine::screenSpaceRenderable( const std::string& identifier) { auto it = std::find_if( _screenSpaceRenderables.begin(), _screenSpaceRenderables.end(), - [&identifier](const std::shared_ptr& s) { + [&identifier](const std::unique_ptr& s) { return s->identifier() == identifier; } ); if (it != _screenSpaceRenderables.end()) { - return *it; + return it->get(); } else { return nullptr; @@ -994,7 +986,7 @@ std::vector RenderEngine::screenSpaceRenderables() const _screenSpaceRenderables.begin(), _screenSpaceRenderables.end(), res.begin(), - [](std::shared_ptr p) { return p.get(); } + [](const std::unique_ptr& p) { return p.get(); } ); return res; } @@ -1020,8 +1012,8 @@ void RenderEngine::renderCameraInformation() { return; } - const glm::vec4 enabled = glm::vec4(0.2f, 0.75f, 0.2f, 1.f); - const glm::vec4 disabled = glm::vec4(0.55f, 0.2f, 0.2f, 1.f); + const glm::vec4 EnabledColor = glm::vec4(0.2f, 0.75f, 0.2f, 1.f); + const glm::vec4 DisabledColor = glm::vec4(0.55f, 0.2f, 0.2f, 1.f); using FR = ghoul::fontrendering::FontRenderer; @@ -1033,19 +1025,19 @@ void RenderEngine::renderCameraInformation() { float penPosY = fontResolution().y - rotationBox.boundingBox.y; - const float ySeparation = 5.f; - const float xSeparation = 5.f; + constexpr const float YSeparation = 5.f; + constexpr const float XSeparation = 5.f; interaction::OrbitalNavigator nav = OsEng.navigationHandler().orbitalNavigator(); FR::defaultRenderer().render( *_fontInfo, - glm::vec2(fontResolution().x - rotationBox.boundingBox.x - xSeparation, penPosY), - nav.hasRotationalFriction() ? enabled : disabled, + glm::vec2(fontResolution().x - rotationBox.boundingBox.x - XSeparation, penPosY), + nav.hasRotationalFriction() ? EnabledColor : DisabledColor, "%s", "Rotation" ); - penPosY -= rotationBox.boundingBox.y + ySeparation; + penPosY -= rotationBox.boundingBox.y + YSeparation; FR::BoundingBoxInformation zoomBox = FR::defaultRenderer().boundingBox( *_fontInfo, @@ -1055,12 +1047,12 @@ void RenderEngine::renderCameraInformation() { FR::defaultRenderer().render( *_fontInfo, - glm::vec2(fontResolution().x - zoomBox.boundingBox.x - xSeparation, penPosY), - nav.hasZoomFriction() ? enabled : disabled, + glm::vec2(fontResolution().x - zoomBox.boundingBox.x - XSeparation, penPosY), + nav.hasZoomFriction() ? EnabledColor : DisabledColor, "%s", "Zoom" ); - penPosY -= zoomBox.boundingBox.y + ySeparation; + penPosY -= zoomBox.boundingBox.y + YSeparation; FR::BoundingBoxInformation rollBox = FR::defaultRenderer().boundingBox( *_fontInfo, @@ -1070,8 +1062,8 @@ void RenderEngine::renderCameraInformation() { FR::defaultRenderer().render( *_fontInfo, - glm::vec2(fontResolution().x - rollBox.boundingBox.x - xSeparation, penPosY), - nav.hasRollFriction() ? enabled : disabled, + glm::vec2(fontResolution().x - rollBox.boundingBox.x - XSeparation, penPosY), + nav.hasRollFriction() ? EnabledColor : DisabledColor, "%s", "Roll" ); @@ -1134,15 +1126,15 @@ void RenderEngine::renderScreenLog() { _log->removeExpiredEntries(); - const int max = 10; - const int categoryLength = 20; - const int messageLength = 140; - std::chrono::seconds fade(5); + constexpr const int MaxNumberMessages = 10; + constexpr const int CategoryLength = 20; + constexpr const int MessageLength = 140; + constexpr const std::chrono::seconds FadeTime(5); - const std::vector entries = _log->entries(); + const std::vector& entries = _log->entries(); auto lastEntries = - entries.size() > max ? - std::make_pair(entries.rbegin(), entries.rbegin() + max) : + entries.size() > MaxNumberMessages ? + std::make_pair(entries.rbegin(), entries.rbegin() + MaxNumberMessages) : std::make_pair(entries.rbegin(), entries.rend()); size_t nr = 1; @@ -1152,22 +1144,22 @@ void RenderEngine::renderScreenLog() { std::chrono::duration diff = now - e->timeStamp; - float alpha = 1; - std::chrono::duration ttf = ScreenLogTimeToLive - fade; + float alpha = 1.f; + std::chrono::duration ttf = ScreenLogTimeToLive - FadeTime; if (diff > ttf) { auto d = (diff - ttf).count(); - auto t = static_cast(d) / static_cast(fade.count()); + auto t = static_cast(d) / static_cast(FadeTime.count()); float p = 0.8f - t; alpha = (p <= 0.f) ? 0.f : pow(p, 0.4f); } // Since all log entries are ordered, once one exceeds alpha, all have - if (alpha <= 0.0) { + if (alpha <= 0.f) { break; } const std::string lvl = "(" + ghoul::logging::stringFromLevel(e->level) + ")"; - const std::string& message = e->message.substr(0, messageLength); + const std::string& message = e->message.substr(0, MessageLength); nr += std::count(message.begin(), message.end(), '\n'); const glm::vec4 white(0.9f, 0.9f, 0.9f, alpha); @@ -1178,7 +1170,7 @@ void RenderEngine::renderScreenLog() { white, "%-14s %s%s", e->timeString.c_str(), - e->category.substr(0, categoryLength).c_str(), + e->category.substr(0, CategoryLength).c_str(), e->category.length() > 20 ? "..." : ""); glm::vec4 color(glm::uninitialize); @@ -1208,7 +1200,8 @@ void RenderEngine::renderScreenLog() { lvl.c_str() ); - RenderFont(*_fontLog, + RenderFont( + *_fontLog, glm::vec2(10 + 53 * _fontLog->pointSize(), _fontLog->pointSize() * nr * 2), white, "%s", @@ -1218,14 +1211,6 @@ void RenderEngine::renderScreenLog() { } } -std::vector RenderEngine::getSyncables() { - if (_camera) { - return _camera->getSyncables(); - } else { - return {}; - } -} - properties::PropertyOwner& RenderEngine::screenSpaceOwner() { return _screenSpaceOwner; } diff --git a/src/rendering/renderengine_lua.inl b/src/rendering/renderengine_lua.inl index ee437b9799..f5a3715d56 100644 --- a/src/rendering/renderengine_lua.inl +++ b/src/rendering/renderengine_lua.inl @@ -70,7 +70,8 @@ int toggleFade(lua_State* L) { int fadeIn(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::fadeIn"); - double t = luaL_checknumber(L, -1); + double t = luaL_checknumber(L, 1); + lua_pop(L, 1); OsEng.renderEngine().startFading(1, static_cast(t)); @@ -85,7 +86,8 @@ int fadeIn(lua_State* L) { int fadeOut(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::fadeOut"); - double t = luaL_checknumber(L, -1); + double t = luaL_checknumber(L, 1); + lua_pop(L, 1); OsEng.renderEngine().startFading(-1, static_cast(t)); @@ -108,10 +110,10 @@ int addScreenSpaceRenderable(lua_State* L) { return 0; } - std::shared_ptr s( + std::unique_ptr s( ScreenSpaceRenderable::createFromDictionary(d) ); - OsEng.renderEngine().addScreenSpaceRenderable(s); + OsEng.renderEngine().addScreenSpaceRenderable(std::move(s)); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; @@ -123,22 +125,7 @@ int removeScreenSpaceRenderable(lua_State* L) { using ghoul::lua::errorLocation; std::string name = ghoul::lua::checkStringAndPop(L); - - std::shared_ptr s = OsEng.renderEngine().screenSpaceRenderable( - name - ); - if (!s) { - LERRORC( - "removeScreenSpaceRenderable", - fmt::format( - "{}: Could not find ScreenSpaceRenderable '{}'", errorLocation(L), name - ) - ); - ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); - return 0; - } - - OsEng.renderEngine().removeScreenSpaceRenderable(s); + OsEng.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 ac3f8cee77..e29fc2dd7a 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -540,7 +541,7 @@ void ScreenSpaceRenderable::draw(glm::mat4 modelTransform) { _shader->setUniform( _uniformCache.viewProj, - OsEng.renderEngine().camera()->viewProjectionMatrix() + OsEng.renderEngine().scene()->camera()->viewProjectionMatrix() ); ghoul::opengl::TextureUnit unit; diff --git a/src/util/screenlog.cpp b/src/util/screenlog.cpp index e0ce4c8e2e..b0d312d99f 100644 --- a/src/util/screenlog.cpp +++ b/src/util/screenlog.cpp @@ -40,12 +40,11 @@ ScreenLog::~ScreenLog() {} void ScreenLog::removeExpiredEntries() { std::lock_guard guard(_mutex); auto t = std::chrono::steady_clock::now(); - auto ttl = _timeToLive; auto rit = std::remove_if( _entries.begin(), _entries.end(), - [&t, &ttl](const LogEntry& e) { return (t - e.timeStamp) > ttl; } + [&t, ttl = _timeToLive](const LogEntry& e) { return (t - e.timeStamp) > ttl; } ); _entries.erase(rit, _entries.end() ); @@ -64,8 +63,7 @@ void ScreenLog::log(LogLevel level, const string& category, const string& messag } } -std::vector ScreenLog::entries() const { - std::lock_guard guard(_mutex); +const std::vector& ScreenLog::entries() const { return _entries; } From d0368a2edde9a4ee754301c95406092e676b8ff7 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 08:26:59 -0400 Subject: [PATCH 59/79] Fix warnings and coding style issues --- apps/OpenSpace/main.cpp | 2 +- include/openspace/engine/configuration.h | 4 +- .../interaction/camerainteractionstates.h | 8 +- .../openspace/interaction/inputdevicestates.h | 8 +- .../interaction/joystickcamerastates.h | 9 ++- .../interaction/joystickinputstate.h | 2 +- .../openspace/interaction/navigationhandler.h | 6 +- .../openspace/interaction/orbitalnavigator.h | 2 +- modules/touch/src/touchinteraction.cpp | 74 +++++++++++++------ src/engine/openspaceengine.cpp | 8 +- src/interaction/joystickcamerastates.cpp | 7 +- src/interaction/mousecamerastates.cpp | 4 +- src/interaction/navigationhandler.cpp | 13 ++-- src/interaction/navigationhandler_lua.inl | 4 +- src/interaction/orbitalnavigator.cpp | 2 +- 15 files changed, 95 insertions(+), 58 deletions(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index f66289d518..fc05459112 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -315,7 +315,7 @@ void mainInitFunc() { std::string screenshotPath = "${SCREENSHOTS}"; std::string screenshotNames = "OpenSpace"; - + if (OsEng.configuration().shouldUseScreenshotDate) { std::time_t now = std::time(nullptr); std::tm* nowTime = std::localtime(&now); diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index 06916253fc..05c8a035e0 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -85,14 +85,14 @@ struct Configuration { std::string onScreenTextScaling = "window"; bool usePerSceneCache = false; - + bool isRenderingOnMasterDisabled = false; bool isSceneTranslationOnMasterDisabled = false; std::map moduleConfigurations; std::string renderingMethod = "Framebuffer"; - + struct OpenGLDebugContext { bool isActive = false; bool isSynchronous = true; diff --git a/include/openspace/interaction/camerainteractionstates.h b/include/openspace/interaction/camerainteractionstates.h index abf4abff56..d0364f9652 100644 --- a/include/openspace/interaction/camerainteractionstates.h +++ b/include/openspace/interaction/camerainteractionstates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___INPUTDEVICESTATES___H__ -#define __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#ifndef __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#define __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ #include #include @@ -43,7 +43,7 @@ public: virtual ~CameraInteractionStates() = default; virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; - + void setRotationalFriction(double friction); void setHorizontalFriction(double friction); void setVerticalFriction(double friction); @@ -78,4 +78,4 @@ protected: } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#endif // __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ diff --git a/include/openspace/interaction/inputdevicestates.h b/include/openspace/interaction/inputdevicestates.h index 11db6993a0..41f5c6e4f1 100644 --- a/include/openspace/interaction/inputdevicestates.h +++ b/include/openspace/interaction/inputdevicestates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ -#define __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#ifndef __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#define __OPENSPACE_CORE___INPUTDEVICESTATES___H__ #include #include @@ -43,7 +43,7 @@ public: virtual ~CameraInteractionStates() = default; virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; - + void setRotationalFriction(double friction); void setHorizontalFriction(double friction); void setVerticalFriction(double friction); @@ -78,4 +78,4 @@ protected: } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#endif // __OPENSPACE_CORE___INPUTDEVICESTATES___H__ diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index 89e19488ee..97d155b279 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___JOYSTICKSTATE___H__ -#define __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#ifndef __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ +#define __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ #include @@ -115,8 +115,9 @@ std::string to_string(const openspace::interaction::JoystickCameraStates::AxisTy namespace ghoul { template <> -openspace::interaction::JoystickCameraStates::AxisType from_string(const std::string& string); +openspace::interaction::JoystickCameraStates::AxisType +from_string(const std::string& string); } // namespace ghoul -#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#endif // __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index e460dd266f..112b39f30e 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -123,4 +123,4 @@ openspace::interaction::JoystickAction from_string(const std::string& str); } // namespace ghoul -#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#endif // __OPENSPACE_CORE___JOYSTICKINPUTSTATE___H__ diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index e906700333..bec01c674f 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -86,8 +86,10 @@ public: void setJoystickAxisMapping( int axis, JoystickCameraStates::AxisType mapping, - JoystickCameraStates::AxisInvert shouldInvert = JoystickCameraStates::AxisInvert::No, - JoystickCameraStates::AxisNormalize shouldNormalize = JoystickCameraStates::AxisNormalize::No + JoystickCameraStates::AxisInvert shouldInvert = + JoystickCameraStates::AxisInvert::No, + JoystickCameraStates::AxisNormalize shouldNormalize = + JoystickCameraStates::AxisNormalize::No ); JoystickCameraStates::AxisInformation joystickAxisMapping(int axis) const; diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index b31965b517..b7c898a3c3 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -86,7 +86,7 @@ private: properties::FloatProperty _followFocusNodeRotationDistance; properties::FloatProperty _minimumAllowedDistance; - + properties::FloatProperty _mouseSensitivity; properties::FloatProperty _joystickSensitivity; diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 9246f28462..484eb05976 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -146,15 +146,19 @@ namespace { "" // @TODO Missing documentation }; - static const openspace::properties::Property::PropertyInfo ZoomSensitivityDistanceThresholdInfo = { + static const openspace::properties::Property::PropertyInfo + ZoomSensitivityDistanceThresholdInfo = { "ZoomSensitivityDistanceThreshold", - "Threshold of distance to target node for whether or not to use exponential zooming", + "Threshold of distance to target node for whether or not to use exponential " + "zooming", "" // @TODO Missing documentation }; - static const openspace::properties::Property::PropertyInfo ZoomBoundarySphereMultiplierInfo = { + static const openspace::properties::Property::PropertyInfo + ZoomBoundarySphereMultiplierInfo = { "ZoomBoundarySphereMultiplier", - "Multiplies a node's boundary sphere by this in order to limit zoom & prevent surface collision", + "Multiplies a node's boundary sphere by this in order to limit zoom & prevent " + "surface collision", "" // @TODO Missing documentation }; @@ -226,7 +230,12 @@ TouchInteraction::TouchInteraction() , _orbitSpeedThreshold(OrbitSpinningThreshold, 0.005f, 0.f, 0.01f) , _spinSensitivity(SpinningSensitivityInfo, 1.f, 0.f, 2.f) , _zoomSensitivity(ZoomSensitivityInfo, 1.025f, 1.0f, 1.1f) - , _zoomSensitivityDistanceThreshold(ZoomSensitivityDistanceThresholdInfo, 0.05, 0.01, 0.25) + , _zoomSensitivityDistanceThreshold( + ZoomSensitivityDistanceThresholdInfo, + 0.05, + 0.01, + 0.25 + ) , _zoomBoundarySphereMultiplier(ZoomBoundarySphereMultiplierInfo, 1.001, 1.0, 1.01) , _inputStillThreshold(InputSensitivityInfo, 0.0005f, 0.f, 0.001f) // used to void wrongly interpreted roll interactions @@ -252,8 +261,8 @@ TouchInteraction::TouchInteraction() 0.f, 1.f ) - , _ignoreGui( - { "Ignore GUI", "Disable GUI touch interaction", "" }, // @TODO Missing documentation + , _ignoreGui( // @TODO Missing documentation + { "Ignore GUI", "Disable GUI touch interaction", "" }, false ) , _vel{ glm::dvec2(0.0), 0.0, 0.0, glm::dvec2(0.0) } @@ -582,9 +591,15 @@ void TouchInteraction::directControl(const std::vector& list) { [&sb](const TuioCursor& c) { return c.getSessionID() == sb.id; } ); if (c != list.end()) { - screenPoints.push_back(glm::dvec2(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5))); // normalized -1 to 1 coordinates on screen + // normalized -1 to 1 coordinates on screen + screenPoints.push_back( + glm::dvec2(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5)) + ); } else { - OsEng.moduleEngine().module()->touchInput = { 1, glm::dvec2(0.0, 0.0), 1 }; + OsEng.moduleEngine().module()->touchInput = { + 1, + glm::dvec2(0.0, 0.0), 1 + }; resetAfterInput(); return; } @@ -891,7 +906,10 @@ int TouchInteraction::interpretInteraction(const std::vector& list, } ); - double normalizedCentroidDistance = glm::distance(_centroid, lastCentroid) / list.size(); + double normalizedCentroidDistance = glm::distance( + _centroid, + lastCentroid + ) / list.size(); #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.normalizedCentroidDistance = normalizedCentroidDistance; _debugProperties.rollOn = rollOn; @@ -935,17 +953,22 @@ void TouchInteraction::computeVelocities(const std::vector& list, #ifdef TOUCH_DEBUG_PROPERTIES const std::map interactionNames = { - {ROT, "Rotation"}, - {PINCH, "Pinch"}, - {PAN, "Pan"}, - {ROLL, "Roll"}, - {PICK, "Pick"} + { ROT, "Rotation" }, + { PINCH, "Pinch" }, + { PAN, "Pan" }, + { ROLL, "Roll" }, + { PICK, "Pick" } }; _debugProperties.interpretedInteraction = interactionNames.at(action); if (pinchConsecCt > 0 && action != PINCH) { - if( pinchConsecCt > 3 ) - LINFO("PINCH_gesture_ended_with " << pinchConsecZoomFactor << " drag_distance_and " << pinchConsecCt << " counts."); + if (pinchConsecCt > 3) { + LDEBUG(fmt::format( + "PINCH gesture ended with {} drag distance and {} counts", + pinchConsecZoomFactor, + pinchConsecCt + )); + } pinchConsecCt = 0; pinchConsecZoomFactor = 0.0; } @@ -988,13 +1011,16 @@ void TouchInteraction::computeVelocities(const std::vector& list, glm::dvec3 centerPos = _focusNode->worldPosition(); glm::dvec3 currDistanceToFocusNode = camPos - centerPos; - double distanceFromFocusSurface = length(currDistanceToFocusNode) - _focusNode->boundingSphere(); + double distanceFromFocusSurface = + length(currDistanceToFocusNode) - _focusNode->boundingSphere(); double zoomFactor = (distance - lastDistance); #ifdef TOUCH_DEBUG_PROPERTIES pinchConsecCt++; pinchConsecZoomFactor += zoomFactor; #endif - if ((length(currDistanceToFocusNode) / distanceFromFocusSurface) > _zoomSensitivityDistanceThreshold) { + if ((length(currDistanceToFocusNode) / distanceFromFocusSurface) > + _zoomSensitivityDistanceThreshold) + { zoomFactor *= pow( distanceFromFocusSurface, static_cast(_zoomSensitivity) @@ -1184,10 +1210,14 @@ void TouchInteraction::step(double dt) { #ifdef TOUCH_DEBUG_PROPERTIES //Show velocity status every N frames - /*if (++stepVelUpdate >= 60) { + if (++stepVelUpdate >= 60) { stepVelUpdate = 0; - LINFO("DistToFocusNode " << length(centerToCamera) << " stepZoomVelUpdate " << _vel.zoom); - }*/ + LINFO(fmt::format( + "DistToFocusNode {} stepZoomVelUpdate {}", + length(centerToCamera), + _vel.zoom + )); + } #endif _tap = false; diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 2698336e56..7d2a606e84 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -421,7 +421,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Determining SGCT configuration file LDEBUG("Determining SGCT configuration file"); std::string sgctConfigurationPath = _engine->_configuration->windowConfiguration; - + if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) { LDEBUG(fmt::format( "Overwriting SGCT configuration file with commandline argument: {}", @@ -543,7 +543,7 @@ void OpenSpaceEngine::initialize() { scriptEngine().initialize(); writeStaticDocumentation(); - + _shutdown.waitTime = _engine->_configuration->shutdownCountdown; if (!commandlineArgumentPlaceholders.sceneName.empty()) { @@ -597,7 +597,7 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { if (_scene) { _syncEngine->removeSyncables(_timeManager->getSyncables()); if (_scene && _scene->camera()) { - _syncEngine->removeSyncables(_scene->camera()->getSyncables()); + _syncEngine->removeSyncables(_scene->camera()->getSyncables()); } _renderEngine->setScene(nullptr); _renderEngine->setCamera(nullptr); @@ -828,7 +828,7 @@ void OpenSpaceEngine::loadFonts() { )); } } - + try { bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); if (!initSuccess) { diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 6309dfff5b..a25516bb9e 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -57,7 +57,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, value = 0.f; hasValue = false; } - + if (t.normalize) { value = (value + 1.f) / 2.f; } @@ -148,8 +148,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, else { _localRotationState.velocity.decelerate(deltaTime); } - - + for (int i = 0; i < JoystickInputState::MaxButtons; ++i) { auto itRange = _buttonMapping.equal_range(i); for (auto it = itRange.first; it != itRange.second; ++it) { @@ -251,7 +250,7 @@ openspace::interaction::JoystickCameraStates::AxisType from_string( const std::string& string) { using T = openspace::interaction::JoystickCameraStates::AxisType; - + static const std::map Map = { { "None", T::None }, { "Orbit X", T::OrbitX }, diff --git a/src/interaction/mousecamerastates.cpp b/src/interaction/mousecamerastates.cpp index c79edcf343..a58334d420 100644 --- a/src/interaction/mousecamerastates.cpp +++ b/src/interaction/mousecamerastates.cpp @@ -32,7 +32,9 @@ MouseCameraStates::MouseCameraStates(double sensitivity, double velocityScaleFac : CameraInteractionStates(sensitivity, velocityScaleFactor) {} -void MouseCameraStates::updateStateFromInput(const InputState& inputState, double deltaTime) { +void MouseCameraStates::updateStateFromInput(const InputState& inputState, + double deltaTime) +{ glm::dvec2 mousePosition = inputState.mousePosition(); bool button1Pressed = inputState.isMouseButtonPressed(MouseButton::Button1); diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 2fff65ded4..f72289daa5 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -297,9 +297,10 @@ void NavigationHandler::restoreCameraStateFromFile(const std::string& filepath) } } -void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, - JoystickCameraStates::AxisInvert shouldInvert, - JoystickCameraStates::AxisNormalize shouldNormalize) +void NavigationHandler::setJoystickAxisMapping(int axis, + JoystickCameraStates::AxisType mapping, + JoystickCameraStates::AxisInvert shouldInvert, + JoystickCameraStates::AxisNormalize shouldNormalize) { _orbitalNavigator->joystickStates().setAxisMapping( axis, @@ -309,7 +310,9 @@ void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::A ); } -JoystickCameraStates::AxisInformation NavigationHandler::joystickAxisMapping(int axis) const { +JoystickCameraStates::AxisInformation +NavigationHandler::joystickAxisMapping(int axis) const +{ return _orbitalNavigator->joystickStates().axisMapping(axis); } @@ -323,7 +326,7 @@ float NavigationHandler::joystickAxisDeadzone(int axis) const { void NavigationHandler::bindJoystickButtonCommand(int button, std::string command, JoystickAction action, - JoystickCameraStates::ButtonCommandRemote remote) + JoystickCameraStates::ButtonCommandRemote remote) { _orbitalNavigator->joystickStates().bindButtonCommand( button, diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index ab8eccee66..5219ac35d0 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -101,7 +101,7 @@ int bindJoystickAxis(lua_State* L) { if (n > 2) { shouldInvert = lua_toboolean(L, 3); } - + bool shouldNormalize = false; if (n > 3) { shouldNormalize = lua_toboolean(L, 4); @@ -178,7 +178,7 @@ int bindJoystickButton(lua_State* L) { action, interaction::JoystickCameraStates::ButtonCommandRemote(isRemote) ); - + lua_settop(L, 0); return 0; } diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index b0e1fd439b..4d95321ab1 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -456,7 +456,7 @@ glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, -_mouseStates.globalRotationVelocity().y * deltaTime, -_mouseStates.globalRotationVelocity().x * deltaTime, 0) * speedScale); - + glm::dquat joystickRotationDiffCamSpace = glm::dquat(glm::dvec3( -_joystickStates.globalRotationVelocity().y * deltaTime, -_joystickStates.globalRotationVelocity().x * deltaTime, From db66084ad8e95d02cf3c74c56b14983138e4c798 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 08:26:59 -0400 Subject: [PATCH 60/79] Fix warnings and coding style issues --- apps/OpenSpace/main.cpp | 2 +- ext/ghoul | 2 +- include/openspace/engine/configuration.h | 4 +- .../interaction/camerainteractionstates.h | 8 +- .../openspace/interaction/inputdevicestates.h | 8 +- .../interaction/joystickcamerastates.h | 9 ++- .../interaction/joystickinputstate.h | 2 +- .../openspace/interaction/navigationhandler.h | 6 +- .../openspace/interaction/orbitalnavigator.h | 2 +- modules/touch/src/touchinteraction.cpp | 74 +++++++++++++------ src/engine/openspaceengine.cpp | 8 +- src/interaction/joystickcamerastates.cpp | 7 +- src/interaction/mousecamerastates.cpp | 4 +- src/interaction/navigationhandler.cpp | 13 ++-- src/interaction/navigationhandler_lua.inl | 4 +- src/interaction/orbitalnavigator.cpp | 2 +- 16 files changed, 96 insertions(+), 59 deletions(-) diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index f66289d518..fc05459112 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -315,7 +315,7 @@ void mainInitFunc() { std::string screenshotPath = "${SCREENSHOTS}"; std::string screenshotNames = "OpenSpace"; - + if (OsEng.configuration().shouldUseScreenshotDate) { std::time_t now = std::time(nullptr); std::tm* nowTime = std::localtime(&now); diff --git a/ext/ghoul b/ext/ghoul index 5cdf35fd66..e6a0f5094a 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 5cdf35fd662f0f6f00351ddf706b2b87b312ee7f +Subproject commit e6a0f5094ad8b4e588c6beb8e2b003b6830a5a77 diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index 06916253fc..05c8a035e0 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -85,14 +85,14 @@ struct Configuration { std::string onScreenTextScaling = "window"; bool usePerSceneCache = false; - + bool isRenderingOnMasterDisabled = false; bool isSceneTranslationOnMasterDisabled = false; std::map moduleConfigurations; std::string renderingMethod = "Framebuffer"; - + struct OpenGLDebugContext { bool isActive = false; bool isSynchronous = true; diff --git a/include/openspace/interaction/camerainteractionstates.h b/include/openspace/interaction/camerainteractionstates.h index abf4abff56..d0364f9652 100644 --- a/include/openspace/interaction/camerainteractionstates.h +++ b/include/openspace/interaction/camerainteractionstates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___INPUTDEVICESTATES___H__ -#define __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#ifndef __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#define __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ #include #include @@ -43,7 +43,7 @@ public: virtual ~CameraInteractionStates() = default; virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; - + void setRotationalFriction(double friction); void setHorizontalFriction(double friction); void setVerticalFriction(double friction); @@ -78,4 +78,4 @@ protected: } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#endif // __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ diff --git a/include/openspace/interaction/inputdevicestates.h b/include/openspace/interaction/inputdevicestates.h index 11db6993a0..41f5c6e4f1 100644 --- a/include/openspace/interaction/inputdevicestates.h +++ b/include/openspace/interaction/inputdevicestates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ -#define __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#ifndef __OPENSPACE_CORE___INPUTDEVICESTATES___H__ +#define __OPENSPACE_CORE___INPUTDEVICESTATES___H__ #include #include @@ -43,7 +43,7 @@ public: virtual ~CameraInteractionStates() = default; virtual void updateStateFromInput(const InputState& inputState, double deltaTime) = 0; - + void setRotationalFriction(double friction); void setHorizontalFriction(double friction); void setVerticalFriction(double friction); @@ -78,4 +78,4 @@ protected: } // namespace openspace::interaction -#endif // __OPENSPACE_CORE___CAMERAINTERACTIONSTATES___H__ +#endif // __OPENSPACE_CORE___INPUTDEVICESTATES___H__ diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index 89e19488ee..97d155b279 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___JOYSTICKSTATE___H__ -#define __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#ifndef __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ +#define __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ #include @@ -115,8 +115,9 @@ std::string to_string(const openspace::interaction::JoystickCameraStates::AxisTy namespace ghoul { template <> -openspace::interaction::JoystickCameraStates::AxisType from_string(const std::string& string); +openspace::interaction::JoystickCameraStates::AxisType +from_string(const std::string& string); } // namespace ghoul -#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#endif // __OPENSPACE_CORE___JOYSTICKCAMERASTATES___H__ diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index e460dd266f..112b39f30e 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -123,4 +123,4 @@ openspace::interaction::JoystickAction from_string(const std::string& str); } // namespace ghoul -#endif // __OPENSPACE_CORE___JOYSTICKSTATE___H__ +#endif // __OPENSPACE_CORE___JOYSTICKINPUTSTATE___H__ diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index e906700333..bec01c674f 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -86,8 +86,10 @@ public: void setJoystickAxisMapping( int axis, JoystickCameraStates::AxisType mapping, - JoystickCameraStates::AxisInvert shouldInvert = JoystickCameraStates::AxisInvert::No, - JoystickCameraStates::AxisNormalize shouldNormalize = JoystickCameraStates::AxisNormalize::No + JoystickCameraStates::AxisInvert shouldInvert = + JoystickCameraStates::AxisInvert::No, + JoystickCameraStates::AxisNormalize shouldNormalize = + JoystickCameraStates::AxisNormalize::No ); JoystickCameraStates::AxisInformation joystickAxisMapping(int axis) const; diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index b31965b517..b7c898a3c3 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -86,7 +86,7 @@ private: properties::FloatProperty _followFocusNodeRotationDistance; properties::FloatProperty _minimumAllowedDistance; - + properties::FloatProperty _mouseSensitivity; properties::FloatProperty _joystickSensitivity; diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 9246f28462..484eb05976 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -146,15 +146,19 @@ namespace { "" // @TODO Missing documentation }; - static const openspace::properties::Property::PropertyInfo ZoomSensitivityDistanceThresholdInfo = { + static const openspace::properties::Property::PropertyInfo + ZoomSensitivityDistanceThresholdInfo = { "ZoomSensitivityDistanceThreshold", - "Threshold of distance to target node for whether or not to use exponential zooming", + "Threshold of distance to target node for whether or not to use exponential " + "zooming", "" // @TODO Missing documentation }; - static const openspace::properties::Property::PropertyInfo ZoomBoundarySphereMultiplierInfo = { + static const openspace::properties::Property::PropertyInfo + ZoomBoundarySphereMultiplierInfo = { "ZoomBoundarySphereMultiplier", - "Multiplies a node's boundary sphere by this in order to limit zoom & prevent surface collision", + "Multiplies a node's boundary sphere by this in order to limit zoom & prevent " + "surface collision", "" // @TODO Missing documentation }; @@ -226,7 +230,12 @@ TouchInteraction::TouchInteraction() , _orbitSpeedThreshold(OrbitSpinningThreshold, 0.005f, 0.f, 0.01f) , _spinSensitivity(SpinningSensitivityInfo, 1.f, 0.f, 2.f) , _zoomSensitivity(ZoomSensitivityInfo, 1.025f, 1.0f, 1.1f) - , _zoomSensitivityDistanceThreshold(ZoomSensitivityDistanceThresholdInfo, 0.05, 0.01, 0.25) + , _zoomSensitivityDistanceThreshold( + ZoomSensitivityDistanceThresholdInfo, + 0.05, + 0.01, + 0.25 + ) , _zoomBoundarySphereMultiplier(ZoomBoundarySphereMultiplierInfo, 1.001, 1.0, 1.01) , _inputStillThreshold(InputSensitivityInfo, 0.0005f, 0.f, 0.001f) // used to void wrongly interpreted roll interactions @@ -252,8 +261,8 @@ TouchInteraction::TouchInteraction() 0.f, 1.f ) - , _ignoreGui( - { "Ignore GUI", "Disable GUI touch interaction", "" }, // @TODO Missing documentation + , _ignoreGui( // @TODO Missing documentation + { "Ignore GUI", "Disable GUI touch interaction", "" }, false ) , _vel{ glm::dvec2(0.0), 0.0, 0.0, glm::dvec2(0.0) } @@ -582,9 +591,15 @@ void TouchInteraction::directControl(const std::vector& list) { [&sb](const TuioCursor& c) { return c.getSessionID() == sb.id; } ); if (c != list.end()) { - screenPoints.push_back(glm::dvec2(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5))); // normalized -1 to 1 coordinates on screen + // normalized -1 to 1 coordinates on screen + screenPoints.push_back( + glm::dvec2(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5)) + ); } else { - OsEng.moduleEngine().module()->touchInput = { 1, glm::dvec2(0.0, 0.0), 1 }; + OsEng.moduleEngine().module()->touchInput = { + 1, + glm::dvec2(0.0, 0.0), 1 + }; resetAfterInput(); return; } @@ -891,7 +906,10 @@ int TouchInteraction::interpretInteraction(const std::vector& list, } ); - double normalizedCentroidDistance = glm::distance(_centroid, lastCentroid) / list.size(); + double normalizedCentroidDistance = glm::distance( + _centroid, + lastCentroid + ) / list.size(); #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.normalizedCentroidDistance = normalizedCentroidDistance; _debugProperties.rollOn = rollOn; @@ -935,17 +953,22 @@ void TouchInteraction::computeVelocities(const std::vector& list, #ifdef TOUCH_DEBUG_PROPERTIES const std::map interactionNames = { - {ROT, "Rotation"}, - {PINCH, "Pinch"}, - {PAN, "Pan"}, - {ROLL, "Roll"}, - {PICK, "Pick"} + { ROT, "Rotation" }, + { PINCH, "Pinch" }, + { PAN, "Pan" }, + { ROLL, "Roll" }, + { PICK, "Pick" } }; _debugProperties.interpretedInteraction = interactionNames.at(action); if (pinchConsecCt > 0 && action != PINCH) { - if( pinchConsecCt > 3 ) - LINFO("PINCH_gesture_ended_with " << pinchConsecZoomFactor << " drag_distance_and " << pinchConsecCt << " counts."); + if (pinchConsecCt > 3) { + LDEBUG(fmt::format( + "PINCH gesture ended with {} drag distance and {} counts", + pinchConsecZoomFactor, + pinchConsecCt + )); + } pinchConsecCt = 0; pinchConsecZoomFactor = 0.0; } @@ -988,13 +1011,16 @@ void TouchInteraction::computeVelocities(const std::vector& list, glm::dvec3 centerPos = _focusNode->worldPosition(); glm::dvec3 currDistanceToFocusNode = camPos - centerPos; - double distanceFromFocusSurface = length(currDistanceToFocusNode) - _focusNode->boundingSphere(); + double distanceFromFocusSurface = + length(currDistanceToFocusNode) - _focusNode->boundingSphere(); double zoomFactor = (distance - lastDistance); #ifdef TOUCH_DEBUG_PROPERTIES pinchConsecCt++; pinchConsecZoomFactor += zoomFactor; #endif - if ((length(currDistanceToFocusNode) / distanceFromFocusSurface) > _zoomSensitivityDistanceThreshold) { + if ((length(currDistanceToFocusNode) / distanceFromFocusSurface) > + _zoomSensitivityDistanceThreshold) + { zoomFactor *= pow( distanceFromFocusSurface, static_cast(_zoomSensitivity) @@ -1184,10 +1210,14 @@ void TouchInteraction::step(double dt) { #ifdef TOUCH_DEBUG_PROPERTIES //Show velocity status every N frames - /*if (++stepVelUpdate >= 60) { + if (++stepVelUpdate >= 60) { stepVelUpdate = 0; - LINFO("DistToFocusNode " << length(centerToCamera) << " stepZoomVelUpdate " << _vel.zoom); - }*/ + LINFO(fmt::format( + "DistToFocusNode {} stepZoomVelUpdate {}", + length(centerToCamera), + _vel.zoom + )); + } #endif _tap = false; diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 2698336e56..7d2a606e84 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -421,7 +421,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Determining SGCT configuration file LDEBUG("Determining SGCT configuration file"); std::string sgctConfigurationPath = _engine->_configuration->windowConfiguration; - + if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) { LDEBUG(fmt::format( "Overwriting SGCT configuration file with commandline argument: {}", @@ -543,7 +543,7 @@ void OpenSpaceEngine::initialize() { scriptEngine().initialize(); writeStaticDocumentation(); - + _shutdown.waitTime = _engine->_configuration->shutdownCountdown; if (!commandlineArgumentPlaceholders.sceneName.empty()) { @@ -597,7 +597,7 @@ void OpenSpaceEngine::loadSingleAsset(const std::string& assetPath) { if (_scene) { _syncEngine->removeSyncables(_timeManager->getSyncables()); if (_scene && _scene->camera()) { - _syncEngine->removeSyncables(_scene->camera()->getSyncables()); + _syncEngine->removeSyncables(_scene->camera()->getSyncables()); } _renderEngine->setScene(nullptr); _renderEngine->setCamera(nullptr); @@ -828,7 +828,7 @@ void OpenSpaceEngine::loadFonts() { )); } } - + try { bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); if (!initSuccess) { diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 6309dfff5b..a25516bb9e 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -57,7 +57,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, value = 0.f; hasValue = false; } - + if (t.normalize) { value = (value + 1.f) / 2.f; } @@ -148,8 +148,7 @@ void JoystickCameraStates::updateStateFromInput(const InputState& inputState, else { _localRotationState.velocity.decelerate(deltaTime); } - - + for (int i = 0; i < JoystickInputState::MaxButtons; ++i) { auto itRange = _buttonMapping.equal_range(i); for (auto it = itRange.first; it != itRange.second; ++it) { @@ -251,7 +250,7 @@ openspace::interaction::JoystickCameraStates::AxisType from_string( const std::string& string) { using T = openspace::interaction::JoystickCameraStates::AxisType; - + static const std::map Map = { { "None", T::None }, { "Orbit X", T::OrbitX }, diff --git a/src/interaction/mousecamerastates.cpp b/src/interaction/mousecamerastates.cpp index c79edcf343..a58334d420 100644 --- a/src/interaction/mousecamerastates.cpp +++ b/src/interaction/mousecamerastates.cpp @@ -32,7 +32,9 @@ MouseCameraStates::MouseCameraStates(double sensitivity, double velocityScaleFac : CameraInteractionStates(sensitivity, velocityScaleFactor) {} -void MouseCameraStates::updateStateFromInput(const InputState& inputState, double deltaTime) { +void MouseCameraStates::updateStateFromInput(const InputState& inputState, + double deltaTime) +{ glm::dvec2 mousePosition = inputState.mousePosition(); bool button1Pressed = inputState.isMouseButtonPressed(MouseButton::Button1); diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 2fff65ded4..f72289daa5 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -297,9 +297,10 @@ void NavigationHandler::restoreCameraStateFromFile(const std::string& filepath) } } -void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::AxisType mapping, - JoystickCameraStates::AxisInvert shouldInvert, - JoystickCameraStates::AxisNormalize shouldNormalize) +void NavigationHandler::setJoystickAxisMapping(int axis, + JoystickCameraStates::AxisType mapping, + JoystickCameraStates::AxisInvert shouldInvert, + JoystickCameraStates::AxisNormalize shouldNormalize) { _orbitalNavigator->joystickStates().setAxisMapping( axis, @@ -309,7 +310,9 @@ void NavigationHandler::setJoystickAxisMapping(int axis, JoystickCameraStates::A ); } -JoystickCameraStates::AxisInformation NavigationHandler::joystickAxisMapping(int axis) const { +JoystickCameraStates::AxisInformation +NavigationHandler::joystickAxisMapping(int axis) const +{ return _orbitalNavigator->joystickStates().axisMapping(axis); } @@ -323,7 +326,7 @@ float NavigationHandler::joystickAxisDeadzone(int axis) const { void NavigationHandler::bindJoystickButtonCommand(int button, std::string command, JoystickAction action, - JoystickCameraStates::ButtonCommandRemote remote) + JoystickCameraStates::ButtonCommandRemote remote) { _orbitalNavigator->joystickStates().bindButtonCommand( button, diff --git a/src/interaction/navigationhandler_lua.inl b/src/interaction/navigationhandler_lua.inl index ab8eccee66..5219ac35d0 100644 --- a/src/interaction/navigationhandler_lua.inl +++ b/src/interaction/navigationhandler_lua.inl @@ -101,7 +101,7 @@ int bindJoystickAxis(lua_State* L) { if (n > 2) { shouldInvert = lua_toboolean(L, 3); } - + bool shouldNormalize = false; if (n > 3) { shouldNormalize = lua_toboolean(L, 4); @@ -178,7 +178,7 @@ int bindJoystickButton(lua_State* L) { action, interaction::JoystickCameraStates::ButtonCommandRemote(isRemote) ); - + lua_settop(L, 0); return 0; } diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index b0e1fd439b..4d95321ab1 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -456,7 +456,7 @@ glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, -_mouseStates.globalRotationVelocity().y * deltaTime, -_mouseStates.globalRotationVelocity().x * deltaTime, 0) * speedScale); - + glm::dquat joystickRotationDiffCamSpace = glm::dquat(glm::dvec3( -_joystickStates.globalRotationVelocity().y * deltaTime, -_joystickStates.globalRotationVelocity().x * deltaTime, From 5e1f26cc6b4cf10cd3f8673fd8d14884e18da788 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 09:54:05 -0400 Subject: [PATCH 61/79] Issue/372 (#606) * Add commandline argument that applies a Lua script to the configuration --- ext/ghoul | 2 +- include/openspace/engine/configuration.h | 2 ++ include/openspace/engine/openspaceengine.h | 3 ++ src/engine/openspaceengine.cpp | 34 +++++++++++++++++++--- 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/ext/ghoul b/ext/ghoul index e6a0f5094a..c25721693b 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit e6a0f5094ad8b4e588c6beb8e2b003b6830a5a77 +Subproject commit c25721693b499284c4dcf6c746ba85aa44655f27 diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index 05c8a035e0..c6471e08e3 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -131,6 +131,8 @@ std::string findConfiguration(const std::string& filename = "openspace.cfg"); Configuration loadConfigurationFromFile(const std::string& filename); +void parseLuaState(Configuration& configuration); + } // namespace openspace #endif // __OPENSPACE_CORE___CONFIGURATION___H__ diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index e136e6c1b6..c93deb2e71 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -121,6 +121,9 @@ public: 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 diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 7d2a606e84..f385b57bf3 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -116,6 +116,7 @@ namespace { std::string sgctConfigurationName; std::string sceneName; std::string cacheFolder; + std::string configurationOverwrite; } commandlineArgumentPlaceholders; static const openspace::properties::Property::PropertyInfo VersionInfo = { @@ -308,6 +309,18 @@ void OpenSpaceEngine::create(int argc, char** argv, 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( @@ -421,6 +434,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // Determining SGCT configuration file LDEBUG("Determining SGCT configuration file"); std::string sgctConfigurationPath = _engine->_configuration->windowConfiguration; + LDEBUG(fmt::format("SGCT Configuration file: {}", sgctConfigurationPath)); if (!commandlineArgumentPlaceholders.sgctConfigurationName.empty()) { LDEBUG(fmt::format( @@ -762,27 +776,39 @@ void OpenSpaceEngine::gatherCommandlineArguments() { commandlineArgumentPlaceholders.configurationName = ""; _commandlineParser->addCommand(std::make_unique>( commandlineArgumentPlaceholders.configurationName, "--config", "-c", - "Provides the path to the OpenSpace configuration file" + "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" + "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" + "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" + "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." )); } From f7e5ba8fffe7fb3f8d89d9fb3d5df0a7b2361417 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 14:32:17 +0000 Subject: [PATCH 62/79] Closes #604 Remove identifier from VirtualPropertyManager Add VirtualPropertyManager to the query of allProperties --- src/engine/openspaceengine.cpp | 4 ++++ src/engine/virtualpropertymanager.cpp | 6 +++++- src/query/query.cpp | 11 +++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index f385b57bf3..8332259a6f 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -178,6 +178,10 @@ OpenSpaceEngine::OpenSpaceEngine(std::string programName, _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()); } diff --git a/src/engine/virtualpropertymanager.cpp b/src/engine/virtualpropertymanager.cpp index 516b334c02..c275ae5836 100644 --- a/src/engine/virtualpropertymanager.cpp +++ b/src/engine/virtualpropertymanager.cpp @@ -28,8 +28,12 @@ namespace openspace { +// The VirtualPropertyManager cannot have an identifier (and thus cannot be part of +// another PropertyOwner) as otherwise the regex-as-name trick would no longer work. I +// don't particular like this implementation, but it's what we got for now; I'm open to +// replacing it with a better mechanism VirtualPropertyManager::VirtualPropertyManager() - : properties::PropertyOwner({ "VirtualPropertyManager" }) + : properties::PropertyOwner({ "" }) {} void VirtualPropertyManager::addProperty(std::unique_ptr prop) { diff --git a/src/query/query.cpp b/src/query/query.cpp index 61e51c4ed6..1f189324e3 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -70,6 +70,17 @@ std::vector allProperties() { 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(); + + properties.insert( + properties.end(), + p2.begin(), + p2.end() + ); + return properties; } From 7068637c9d1fe42746e13d0dac5cf05b783e2e46 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 21 Apr 2018 19:04:47 +0000 Subject: [PATCH 63/79] Make it possible to click on the friction markers in the image to toggle the friction (closes issue #576) --- include/openspace/engine/openspaceengine.h | 2 + include/openspace/rendering/renderengine.h | 8 +++ src/engine/openspaceengine.cpp | 11 ++++ src/rendering/renderengine.cpp | 64 ++++++++++++++++++++++ 4 files changed, 85 insertions(+) diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index c93deb2e71..140c857b73 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -273,6 +273,8 @@ private: // disable the synchronization; otherwise a hardware sync will kill us after 1 minute bool _isFirstRenderingFirstFrame = true; + glm::dvec2 _mousePosition; + static OpenSpaceEngine* _engine; }; diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 5520ca9e3e..804cc9d386 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -90,6 +90,8 @@ public: void render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix); + bool mouseActivationCallback(const glm::dvec2& mousePosition) const; + void renderOverlays(const ShutdownInformation& shutdownInfo); void postDraw(); @@ -216,6 +218,12 @@ private: std::shared_ptr _fontInfo = nullptr; std::shared_ptr _fontDate = nullptr; std::shared_ptr _fontLog = nullptr; + + struct { + glm::ivec4 rotation; + glm::ivec4 zoom; + glm::ivec4 roll; + } _cameraButtonLocations; }; } // namespace openspace diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index 8332259a6f..7403e05ce0 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -1375,6 +1375,15 @@ 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); + + if (isConsumed) { + return; + } + } + _navigationHandler->mouseButtonCallback(button, action); } @@ -1384,6 +1393,8 @@ void OpenSpaceEngine::mousePositionCallback(double x, double y) { func(x, y); } + _mousePosition = { x, y }; + _navigationHandler->mousePositionCallback(x, y); } diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index bdc25c82fc..6bb1b2ba6d 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -584,6 +584,52 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat LTRACE("RenderEngine::render(end)"); } +bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) const { + auto intersects = [](const glm::dvec2& mousePos, const glm::ivec4& bbox) { + return mousePos.x >= bbox.x && mousePos.x <= bbox.x + bbox.z && + mousePos.y <= bbox.y && mousePos.y >= bbox.y - bbox.w; + }; + + + if (intersects(mousePosition, _cameraButtonLocations.rotation)) { + constexpr const char* ToggleRotationFrictionScript = R"( + local f = 'NavigationHandler.OrbitalNavigator.Friction.RotationalFriction'; + openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; + + OsEng.scriptEngine().queueScript( + ToggleRotationFrictionScript, + scripting::ScriptEngine::RemoteScripting::Yes + ); + return true; + } + + if (intersects(mousePosition, _cameraButtonLocations.zoom)) { + constexpr const char* ToggleZoomFrictionScript = R"( + local f = 'NavigationHandler.OrbitalNavigator.Friction.ZoomFriction'; + openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; + + OsEng.scriptEngine().queueScript( + ToggleZoomFrictionScript, + scripting::ScriptEngine::RemoteScripting::Yes + ); + return true; + } + + if (intersects(mousePosition, _cameraButtonLocations.roll)) { + constexpr const char* ToggleRollFrictionScript = R"( + local f = 'NavigationHandler.OrbitalNavigator.Friction.RollFriction'; + openspace.setPropertyValue(f, not openspace.getPropertyValue(f));)"; + + OsEng.scriptEngine().queueScript( + ToggleRollFrictionScript, + scripting::ScriptEngine::RemoteScripting::Yes + ); + return true; + } + + return false; +} + void RenderEngine::renderOverlays(const ShutdownInformation& info) { const bool isMaster = OsEng.windowWrapper().isMaster(); if (isMaster || _showOverlayOnSlaves) { @@ -1030,6 +1076,12 @@ void RenderEngine::renderCameraInformation() { interaction::OrbitalNavigator nav = OsEng.navigationHandler().orbitalNavigator(); + _cameraButtonLocations.rotation = { + fontResolution().x - rotationBox.boundingBox.x - XSeparation, + fontResolution().y - penPosY, + rotationBox.boundingBox.x, + rotationBox.boundingBox.y + }; FR::defaultRenderer().render( *_fontInfo, glm::vec2(fontResolution().x - rotationBox.boundingBox.x - XSeparation, penPosY), @@ -1045,6 +1097,12 @@ void RenderEngine::renderCameraInformation() { "Zoom" ); + _cameraButtonLocations.zoom = { + fontResolution().x - zoomBox.boundingBox.x - XSeparation, + fontResolution().y - penPosY, + zoomBox.boundingBox.x, + zoomBox.boundingBox.y + }; FR::defaultRenderer().render( *_fontInfo, glm::vec2(fontResolution().x - zoomBox.boundingBox.x - XSeparation, penPosY), @@ -1060,6 +1118,12 @@ void RenderEngine::renderCameraInformation() { "Roll" ); + _cameraButtonLocations.roll = { + fontResolution().x - rollBox.boundingBox.x - XSeparation, + fontResolution().y - penPosY, + rollBox.boundingBox.x, + rollBox.boundingBox.y + }; FR::defaultRenderer().render( *_fontInfo, glm::vec2(fontResolution().x - rollBox.boundingBox.x - XSeparation, penPosY), From fc71ad1a8368754d1ccf996202e03cf4ee527a5c Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sat, 21 Apr 2018 15:17:41 -0400 Subject: [PATCH 64/79] Copied changes from previous branch and added new size control system. --- .../rendering/renderablebillboardscloud.cpp | 2544 +++++++++-------- .../rendering/renderablebillboardscloud.h | 278 +- .../digitaluniverse/shaders/billboard_fs.glsl | 9 +- .../digitaluniverse/shaders/billboard_gs.glsl | 187 +- openspace.cfg | 2 +- 5 files changed, 1506 insertions(+), 1514 deletions(-) diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index 39503c6f0a..144008ab71 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -1,26 +1,26 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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 @@ -30,6 +30,7 @@ #include #include #include + #include #include #include @@ -39,8 +40,10 @@ #include #include #include + #include #include + #include #include #include @@ -48,8 +51,8 @@ #include namespace { - constexpr const char* _loggerCat = "RenderableBillboardsCloud"; - constexpr const char* ProgramObjectName = "RenderableBillboardsCloud"; + constexpr const char* _loggerCat = "RenderableBillboardsCloud"; + constexpr const char* ProgramObjectName = "RenderableBillboardsCloud"; constexpr const char* RenderToPolygonProgram = "RenderableBillboardsCloud_Polygon"; constexpr const char* KeyFile = "File"; @@ -204,15 +207,26 @@ namespace { "object." }; + static const openspace::properties::Property::PropertyInfo CorrectionSizeEndDistanceInfo = { + "CorrectionSizeEndDistanceInfo", + "Distance in 10^X meters where correction size stops acting.", + "Distance in 10^X meters where correction size stops acting." + }; + + static const openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { + "CorrectionSizeFactorInfo", + "Control variable for distance size.", + "" + }; } // namespace namespace openspace { -documentation::Documentation RenderableBillboardsCloud::Documentation() { - using namespace documentation; - return { - "RenderableBillboardsCloud", - "digitaluniverse_RenderableBillboardsCloud", + documentation::Documentation RenderableBillboardsCloud::Documentation() { + using namespace documentation; + return { + "RenderableBillboardsCloud", + "digitaluniverse_RenderableBillboardsCloud", { { "Type", @@ -339,295 +353,323 @@ documentation::Documentation RenderableBillboardsCloud::Documentation() { new DoubleVerifier, Optional::Yes, BillboardMinSizeInfo.description + }, + { + CorrectionSizeEndDistanceInfo.identifier, + new DoubleVerifier, + Optional::Yes, + CorrectionSizeEndDistanceInfo.description + }, + { + CorrectionSizeFactorInfo.identifier, + new DoubleVerifier, + Optional::Yes, + CorrectionSizeFactorInfo.description } } - }; -} - - -RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) - , _hasSpeckFile(false) - , _dataIsDirty(true) - , _textColorIsDirty(true) - , _hasSpriteTexture(false) - , _spriteTextureIsDirty(true) - , _hasColorMapFile(false) - , _hasPolygon(false) - , _hasLabel(false) - , _labelDataIsDirty(true) - , _polygonSides(0) - , _pTexture(0) - , _alphaValue(TransparencyInfo, 1.f, 0.f, 1.f) - , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 600.f) - , _pointColor( - ColorInfo, - glm::vec3(1.f, 0.4f, 0.2f), - glm::vec3(0.f, 0.f, 0.f), - glm::vec3(1.0f, 1.0f, 1.0f) - ) - , _spriteTexturePath(SpriteTextureInfo) - , _textColor( - TextColorInfo, - glm::vec4(1.0f, 1.0, 1.0f, 1.f), - glm::vec4(0.f), - glm::vec4(1.f) - ) - , _textSize(TextSizeInfo, 8.0, 0.5, 24.0) - , _textMinSize(LabelMinSizeInfo, 8.0, 0.5, 24.0) - , _textMaxSize(LabelMaxSizeInfo, 500.0, 0.0, 1000.0) - , _drawElements(DrawElementsInfo, true) - , _drawLabels(DrawLabelInfo, false) - , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) - , _fadeInDistance( - FadeInDistancesInfo, - glm::vec2(0.0f), - glm::vec2(0.0), - glm::vec2(100.0) - ) - , _disableFadeInDistance(DisableFadeInInfo, true) - , _billboardMaxSize(BillboardMaxSizeInfo, 400.0, 0.0, 1000.0) - , _billboardMinSize(BillboardMinSizeInfo, 0.0, 0.0, 100.0) - , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) - , _polygonTexture(nullptr) - , _spriteTexture(nullptr) - , _program(nullptr) - , _renderToPolygonProgram(nullptr) - , _font(nullptr) - , _speckFile("") - , _colorMapFile("") - , _labelFile("") - , _colorOptionString("") - , _unit(Parsec) - , _nValuesPerAstronomicalObject(0) - , _transformationMatrix(glm::dmat4(1.0)) - , _vao(0) - , _vbo(0) - , _polygonVao(0) - , _polygonVbo(0) -{ - using File = ghoul::filesystem::File; - - documentation::testSpecificationAndThrow( - Documentation(), - dictionary, - "RenderableBillboardsCloud" - ); - - if (dictionary.hasKey(KeyFile)) { - _speckFile = absPath(dictionary.value(KeyFile)); - _hasSpeckFile = true; - _drawElements.onChange([&]() { - _hasSpeckFile = _hasSpeckFile == true? false : true; }); - addProperty(_drawElements); + }; } - // DEBUG: - _renderOption.addOption(0, "Camera View Direction"); - _renderOption.addOption(1, "Camera Position Normal"); - _renderOption.addOption(2, "Screen center Position Normal"); - addProperty(_renderOption); - if (dictionary.hasKey(keyUnit)) { - std::string unit = dictionary.value(keyUnit); - if (unit == MeterUnit) { - _unit = Meter; - } - else if (unit == KilometerUnit) { - _unit = Kilometer; - } - else if (unit == ParsecUnit) { - _unit = Parsec; - } - else if (unit == KiloparsecUnit) { - _unit = Kiloparsec; - } - else if (unit == MegaparsecUnit) { - _unit = Megaparsec; - } - else if (unit == GigaparsecUnit) { - _unit = Gigaparsec; - } - else if (unit == GigalightyearUnit) { - _unit = GigalightYears; - } - else { - LWARNING( - "No unit given for RenderableBillboardsCloud. Using meters as units." - ); - _unit = Meter; - } - } + RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) + , _hasSpeckFile(false) + , _dataIsDirty(true) + , _textColorIsDirty(true) + , _hasSpriteTexture(false) + , _spriteTextureIsDirty(true) + , _hasColorMapFile(false) + , _hasPolygon(false) + , _hasLabel(false) + , _labelDataIsDirty(true) + , _polygonSides(0) + , _pTexture(0) + , _alphaValue(TransparencyInfo, 1.f, 0.f, 1.f) + , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 600.f) + , _pointColor( + ColorInfo, + glm::vec3(1.f, 0.4f, 0.2f), + glm::vec3(0.f, 0.f, 0.f), + glm::vec3(1.0f, 1.0f, 1.0f) + ) + , _spriteTexturePath(SpriteTextureInfo) + , _textColor( + TextColorInfo, + glm::vec4(1.0f, 1.0, 1.0f, 1.f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _textSize(TextSizeInfo, 8.0, 0.5, 24.0) + , _textMinSize(LabelMinSizeInfo, 8.0, 0.5, 24.0) + , _textMaxSize(LabelMaxSizeInfo, 500.0, 0.0, 1000.0) + , _drawElements(DrawElementsInfo, true) + , _drawLabels(DrawLabelInfo, false) + , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _fadeInDistance( + FadeInDistancesInfo, + glm::vec2(0.0f), + glm::vec2(0.0), + glm::vec2(100.0) + ) + , _disableFadeInDistance(DisableFadeInInfo, true) + , _billboardMaxSize(BillboardMaxSizeInfo, 400.0, 0.0, 1000.0) + , _billboardMinSize(BillboardMinSizeInfo, 0.0, 0.0, 100.0) + , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17, 0.0, 30) + , _correctionSizeFactor(CorrectionSizeFactorInfo, 8, 0.0, 15) + , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _polygonTexture(nullptr) + , _spriteTexture(nullptr) + , _program(nullptr) + , _font(nullptr) + , _speckFile("") + , _colorMapFile("") + , _labelFile("") + , _colorOptionString("") + , _unit(Parsec) + , _nValuesPerAstronomicalObject(0) + , _transformationMatrix(glm::dmat4(1.0)) + , _vao(0) + , _vbo(0) + , _polygonVao(0) + , _polygonVbo(0) + { + using File = ghoul::filesystem::File; - if (dictionary.hasKey(SpriteTextureInfo.identifier)) { - _spriteTexturePath = absPath(dictionary.value( - SpriteTextureInfo.identifier - )); - _spriteTextureFile = std::make_unique(_spriteTexturePath); - - _spriteTexturePath.onChange([&] { _spriteTextureIsDirty = true; }); - _spriteTextureFile->setCallback( - [&](const File&) { _spriteTextureIsDirty = true; } + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableBillboardsCloud" ); - addProperty(_spriteTexturePath); + if (dictionary.hasKey(KeyFile)) { + _speckFile = absPath(dictionary.value(KeyFile)); + _hasSpeckFile = true; + _drawElements.onChange([&]() { + _hasSpeckFile = _hasSpeckFile == true ? false : true; }); + addProperty(_drawElements); + } - _hasSpriteTexture = true; - } + // DEBUG: + _renderOption.addOption(0, "Camera View Direction"); + _renderOption.addOption(1, "Camera Position Normal"); + _renderOption.set(1); + addProperty(_renderOption); - if (dictionary.hasKey(ColorMapInfo.identifier)) { - _colorMapFile = absPath(dictionary.value( - ColorMapInfo.identifier - )); - _hasColorMapFile = true; - - if (dictionary.hasKey(ColorOptionInfo.identifier)) { - ghoul::Dictionary colorOptionDataDic = dictionary.value( - ColorOptionInfo.identifier + if (dictionary.hasKey(keyUnit)) { + std::string unit = dictionary.value(keyUnit); + if (unit == MeterUnit) { + _unit = Meter; + } + else if (unit == KilometerUnit) { + _unit = Kilometer; + } + else if (unit == ParsecUnit) { + _unit = Parsec; + } + else if (unit == KiloparsecUnit) { + _unit = Kiloparsec; + } + else if (unit == MegaparsecUnit) { + _unit = Megaparsec; + } + else if (unit == GigaparsecUnit) { + _unit = Gigaparsec; + } + else if (unit == GigalightyearUnit) { + _unit = GigalightYears; + } + else { + LWARNING( + "No unit given for RenderableBillboardsCloud. Using meters as units." ); - for (int i = 0; i < static_cast(colorOptionDataDic.size()); ++i) { - std::string colorMapInUseName( - colorOptionDataDic.value(std::to_string(i + 1))); - _colorOption.addOption(i, colorMapInUseName); - _optionConversionMap.insert({i, colorMapInUseName}); - _colorOptionString = colorMapInUseName; + _unit = Meter; } } - _colorOption.onChange( - [&] { - _dataIsDirty = true; - _colorOptionString = _optionConversionMap[_colorOption.value()]; - }); - addProperty(_colorOption); - if (dictionary.hasKey(ColorRangeInfo.identifier)) { - ghoul::Dictionary rangeDataDict = dictionary.value( - ColorRangeInfo.identifier + if (dictionary.hasKey(SpriteTextureInfo.identifier)) { + _spriteTexturePath = absPath(dictionary.value( + SpriteTextureInfo.identifier + )); + _spriteTextureFile = std::make_unique(_spriteTexturePath); + + _spriteTexturePath.onChange([&] { _spriteTextureIsDirty = true; }); + _spriteTextureFile->setCallback( + [&](const File&) { _spriteTextureIsDirty = true; } ); - for (size_t i = 0; i < rangeDataDict.size(); ++i) { - _colorRangeData.push_back( - rangeDataDict.value(std::to_string(i + 1))); + addProperty(_spriteTexturePath); + + + _hasSpriteTexture = true; + } + + if (dictionary.hasKey(ColorMapInfo.identifier)) { + _colorMapFile = absPath(dictionary.value( + ColorMapInfo.identifier + )); + _hasColorMapFile = true; + + if (dictionary.hasKey(ColorOptionInfo.identifier)) { + ghoul::Dictionary colorOptionDataDic = dictionary.value( + ColorOptionInfo.identifier + ); + for (int i = 0; i < static_cast(colorOptionDataDic.size()); ++i) { + std::string colorMapInUseName( + colorOptionDataDic.value(std::to_string(i + 1))); + _colorOption.addOption(i, colorMapInUseName); + _optionConversionMap.insert({ i, colorMapInUseName }); + _colorOptionString = colorMapInUseName; + } } + _colorOption.onChange( + [&] { + _dataIsDirty = true; + _colorOptionString = _optionConversionMap[_colorOption.value()]; + }); + addProperty(_colorOption); + + if (dictionary.hasKey(ColorRangeInfo.identifier)) { + ghoul::Dictionary rangeDataDict = dictionary.value( + ColorRangeInfo.identifier + ); + for (size_t i = 0; i < rangeDataDict.size(); ++i) { + _colorRangeData.push_back( + rangeDataDict.value(std::to_string(i + 1))); + } + } + + } + else if (dictionary.hasKey(keyColor)) { + _pointColor = dictionary.value(keyColor); + addProperty(_pointColor); } - } else if (dictionary.hasKey(keyColor)) { - _pointColor = dictionary.value(keyColor); - addProperty(_pointColor); - } - - if (dictionary.hasKey(TransparencyInfo.identifier)) { - _alphaValue = static_cast( - dictionary.value(TransparencyInfo.identifier) - ); - } - addProperty(_alphaValue); - - if (dictionary.hasKey(ScaleFactorInfo.identifier)) { - _scaleFactor = static_cast( - dictionary.value(ScaleFactorInfo.identifier) - ); - } - addProperty(_scaleFactor); - - if (dictionary.hasKey(PolygonSidesInfo.identifier)) { - _polygonSides = static_cast( - dictionary.value(PolygonSidesInfo.identifier) - ); - _hasPolygon = true; - } - - if (dictionary.hasKey(LabelFileInfo.identifier)) { - if (dictionary.hasKey(DrawLabelInfo.identifier)) { - _drawLabels = dictionary.value(DrawLabelInfo.identifier); + if (dictionary.hasKey(TransparencyInfo.identifier)) { + _alphaValue = static_cast( + dictionary.value(TransparencyInfo.identifier) + ); } - addProperty(_drawLabels); + addProperty(_alphaValue); - _labelFile = absPath(dictionary.value( - LabelFileInfo.identifier - )); - _hasLabel = true; + if (dictionary.hasKey(ScaleFactorInfo.identifier)) { + _scaleFactor = static_cast( + dictionary.value(ScaleFactorInfo.identifier) + ); + } + addProperty(_scaleFactor); - if (dictionary.hasKey(TextColorInfo.identifier)) { - _textColor = dictionary.value(TextColorInfo.identifier); + if (dictionary.hasKey(PolygonSidesInfo.identifier)) { + _polygonSides = static_cast( + dictionary.value(PolygonSidesInfo.identifier) + ); + _hasPolygon = true; + } + + if (dictionary.hasKey(LabelFileInfo.identifier)) { + if (dictionary.hasKey(DrawLabelInfo.identifier)) { + _drawLabels = dictionary.value(DrawLabelInfo.identifier); + } + addProperty(_drawLabels); + + _labelFile = absPath(dictionary.value( + LabelFileInfo.identifier + )); _hasLabel = true; + + if (dictionary.hasKey(TextColorInfo.identifier)) { + _textColor = dictionary.value(TextColorInfo.identifier); + _hasLabel = true; + } + _textColor.setViewOption(properties::Property::ViewOptions::Color); + addProperty(_textColor); + _textColor.onChange([&]() { _textColorIsDirty = true; }); + + + if (dictionary.hasKey(TextSizeInfo.identifier)) { + _textSize = dictionary.value(TextSizeInfo.identifier); + } + addProperty(_textSize); + + if (dictionary.hasKey(LabelMinSizeInfo.identifier)) { + _textMinSize = static_cast( + dictionary.value(LabelMinSizeInfo.identifier) + ); + } + addProperty(_textMinSize); + + if (dictionary.hasKey(LabelMaxSizeInfo.identifier)) { + _textMaxSize = static_cast( + dictionary.value(LabelMaxSizeInfo.identifier) + ); + } + addProperty(_textMaxSize); } - _textColor.setViewOption(properties::Property::ViewOptions::Color); - addProperty(_textColor); - _textColor.onChange([&]() { _textColorIsDirty = true; }); - - if (dictionary.hasKey(TextSizeInfo.identifier)) { - _textSize = dictionary.value(TextSizeInfo.identifier); + if (dictionary.hasKey(TransformationMatrixInfo.identifier)) { + _transformationMatrix = dictionary.value( + TransformationMatrixInfo.identifier + ); } - addProperty(_textSize); - if (dictionary.hasKey(LabelMinSizeInfo.identifier)) { - _textMinSize = static_cast( - dictionary.value(LabelMinSizeInfo.identifier) - ); + if (dictionary.hasKey(FadeInDistancesInfo.identifier)) { + glm::vec2 fadeInValue = dictionary.value( + FadeInDistancesInfo.identifier + ); + _fadeInDistance.set(fadeInValue); + _disableFadeInDistance.set(false); + addProperty(_fadeInDistance); + addProperty(_disableFadeInDistance); } - addProperty(_textMinSize); - if (dictionary.hasKey(LabelMaxSizeInfo.identifier)) { - _textMaxSize = static_cast( - dictionary.value(LabelMaxSizeInfo.identifier) - ); + if (dictionary.hasKey(BillboardMaxSizeInfo.identifier)) { + _billboardMaxSize = static_cast( + dictionary.value(BillboardMaxSizeInfo.identifier) + ); } - addProperty(_textMaxSize); - } - - if (dictionary.hasKey(TransformationMatrixInfo.identifier)) { - _transformationMatrix = dictionary.value( - TransformationMatrixInfo.identifier - ); - } - - if (dictionary.hasKey(FadeInDistancesInfo.identifier)) { - glm::vec2 fadeInValue = dictionary.value( - FadeInDistancesInfo.identifier - ); - _fadeInDistance.set(fadeInValue); - _disableFadeInDistance.set(false); - addProperty(_fadeInDistance); - addProperty(_disableFadeInDistance); - } - - if (dictionary.hasKey(BillboardMaxSizeInfo.identifier)) { - _billboardMaxSize = static_cast( - dictionary.value(BillboardMaxSizeInfo.identifier) - ); addProperty(_billboardMaxSize); - } - if (dictionary.hasKey(BillboardMinSizeInfo.identifier)) { - _billboardMinSize = static_cast( - dictionary.value(BillboardMinSizeInfo.identifier) - ); + if (dictionary.hasKey(BillboardMinSizeInfo.identifier)) { + _billboardMinSize = static_cast( + dictionary.value(BillboardMinSizeInfo.identifier) + ); + } addProperty(_billboardMinSize); - } -} -bool RenderableBillboardsCloud::isReady() const { - return ((_program != nullptr) && (!_fullData.empty())) || (!_labelData.empty()); -} + if (dictionary.hasKey(CorrectionSizeEndDistanceInfo.identifier)) { + _correctionSizeEndDistance = static_cast( + dictionary.value(CorrectionSizeEndDistanceInfo.identifier) + ); + } + addProperty(_correctionSizeEndDistance); -void RenderableBillboardsCloud::initialize() { - bool success = loadData(); - if (!success) { - throw ghoul::RuntimeError("Error loading data"); + if (dictionary.hasKey(CorrectionSizeFactorInfo.identifier)) { + _correctionSizeFactor = static_cast( + dictionary.value(CorrectionSizeFactorInfo.identifier) + ); + } + addProperty(_correctionSizeFactor); } - if (!_colorOptionString.empty()) { - // Following DU behavior here. The last colormap variable - // entry is the one selected by default. - _colorOption.setValue(static_cast(_colorRangeData.size() - 1)); + bool RenderableBillboardsCloud::isReady() const { + return ((_program != nullptr) && (!_fullData.empty())) || (!_labelData.empty()); } -} -void RenderableBillboardsCloud::initializeGL() { - _program = DigitalUniverseModule::ProgramObjectManager.requestProgramObject( - ProgramObjectName, - []() -> std::unique_ptr { + void RenderableBillboardsCloud::initialize() { + bool success = loadData(); + if (!success) { + throw ghoul::RuntimeError("Error loading data"); + } + + if (!_colorOptionString.empty()) { + // Following DU behavior here. The last colormap variable + // entry is the one selected by default. + _colorOption.setValue(static_cast(_colorRangeData.size() - 1)); + } + } + + void RenderableBillboardsCloud::initializeGL() { + _program = DigitalUniverseModule::ProgramObjectManager.requestProgramObject( + ProgramObjectName, + []() -> std::unique_ptr { return OsEng.renderEngine().buildRenderProgram( ProgramObjectName, absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_vs.glsl"), @@ -635,1098 +677,1062 @@ void RenderableBillboardsCloud::initializeGL() { absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboard_gs.glsl") ); } - ); - - _renderToPolygonProgram = - DigitalUniverseModule::ProgramObjectManager.requestProgramObject( - RenderToPolygonProgram, - []() -> std::unique_ptr { - return ghoul::opengl::ProgramObject::Build( - RenderToPolygonProgram, - absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), - absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), - absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") - ); - } ); - - _uniformCache.modelViewProjection = _program->uniformLocation( - "modelViewProjectionTransform" - ); - _uniformCache.cameraPos = _program->uniformLocation("cameraPosition"); - _uniformCache.cameraLookup = _program->uniformLocation("cameraLookUp"); - _uniformCache.renderOption = _program->uniformLocation("renderOption"); - _uniformCache.centerSceenInWorldPos = _program->uniformLocation( - "centerScreenInWorldPosition" - ); - _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); - _uniformCache.maxBillboardSize = _program->uniformLocation("maxBillboardSize"); - _uniformCache.color = _program->uniformLocation("color"); - _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); - _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); - _uniformCache.up = _program->uniformLocation("up"); - _uniformCache.right = _program->uniformLocation("right"); - _uniformCache.fadeInValue = _program->uniformLocation("fadeInValue"); - _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.spriteTexture = _program->uniformLocation("spriteTexture"); - _uniformCache.polygonTexture = _program->uniformLocation("polygonTexture"); - _uniformCache.hasPolygon = _program->uniformLocation("hasPolygon"); - _uniformCache.hasColormap = _program->uniformLocation("hasColorMap"); - - if (_hasPolygon) { - createPolygonTexture(); - } - - if (_hasLabel) { - if (_font == nullptr) { - size_t _fontSize = 50; - _font = OsEng.fontManager().font( - "Mono", - static_cast(_fontSize), - ghoul::fontrendering::FontManager::Outline::Yes, - ghoul::fontrendering::FontManager::LoadGlyphs::No + _renderToPolygonProgram = + DigitalUniverseModule::ProgramObjectManager.requestProgramObject( + RenderToPolygonProgram, + []() -> std::unique_ptr { + return ghoul::opengl::ProgramObject::Build( + RenderToPolygonProgram, + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") ); } + ); + + _uniformCache.modelViewMatrix = _program->uniformLocation( + "modelViewMatrix" + ); + + _uniformCache.projectionMatrix = _program->uniformLocation( + "projectionMatrix" + ); + + _uniformCache.cameraViewProjectionMatrix = _program->uniformLocation( + "cameraViewProjectionMatrix" + ); + + _uniformCache.modelMatrix = _program->uniformLocation( + "modelMatrix" + ); + + _uniformCache.cameraPos = _program->uniformLocation("cameraPosition"); + _uniformCache.cameraLookup = _program->uniformLocation("cameraLookUp"); + _uniformCache.renderOption = _program->uniformLocation("renderOption"); + _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.maxBillboardSize = _program->uniformLocation("maxBillboardSize"); + _uniformCache.color = _program->uniformLocation("color"); + _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); + _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); + _uniformCache.up = _program->uniformLocation("up"); + _uniformCache.right = _program->uniformLocation("right"); + _uniformCache.fadeInValue = _program->uniformLocation("fadeInValue"); + _uniformCache.screenSize = _program->uniformLocation("screenSize"); + _uniformCache.spriteTexture = _program->uniformLocation("spriteTexture"); + _uniformCache.polygonTexture = _program->uniformLocation("polygonTexture"); + _uniformCache.hasPolygon = _program->uniformLocation("hasPolygon"); + _uniformCache.hasColormap = _program->uniformLocation("hasColorMap"); + + if (_hasPolygon) { + createPolygonTexture(); + } + + if (_hasLabel) { + if (_font == nullptr) { + size_t _fontSize = 50; + _font = OsEng.fontManager().font( + "Mono", + static_cast(_fontSize), + ghoul::fontrendering::FontManager::Outline::Yes, + ghoul::fontrendering::FontManager::LoadGlyphs::No + ); + } + } } -} -void RenderableBillboardsCloud::deinitializeGL() { - glDeleteBuffers(1, &_vbo); - _vbo = 0; - glDeleteVertexArrays(1, &_vao); - _vao = 0; + void RenderableBillboardsCloud::deinitializeGL() { + glDeleteBuffers(1, &_vbo); + _vbo = 0; + glDeleteVertexArrays(1, &_vao); + _vao = 0; - DigitalUniverseModule::ProgramObjectManager.releaseProgramObject( - ProgramObjectName, - [](ghoul::opengl::ProgramObject* p) { + DigitalUniverseModule::ProgramObjectManager.releaseProgramObject( + ProgramObjectName, + [](ghoul::opengl::ProgramObject* p) { OsEng.renderEngine().removeRenderProgram(p); } - ); - _program = nullptr; - - DigitalUniverseModule::ProgramObjectManager.releaseProgramObject( - RenderToPolygonProgram - ); - _renderToPolygonProgram = nullptr; - - if (_hasSpriteTexture) { - _spriteTexture = nullptr; - } - - if (_hasPolygon) { - _polygonTexture = nullptr; - glDeleteTextures(1, &_pTexture); - } -} - -void RenderableBillboardsCloud::renderBillboards(const RenderData& data, - const glm::dmat4& modelViewMatrix, - const glm::dmat4& worldToModelTransform, - const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, - float fadeInVariable) -{ - glDepthMask(false); - - // Saving current OpenGL state - GLboolean blendEnabled = glIsEnabledi(GL_BLEND, 0); - GLenum blendEquationRGB; - GLenum blendEquationAlpha; - GLenum blendDestAlpha; - GLenum blendDestRGB; - GLenum blendSrcAlpha; - GLenum blendSrcRGB; - - glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); - glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); - glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); - glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); - glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); - glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); - - glEnablei(GL_BLEND, 0); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - _program->activate(); - - glm::dmat4 projMatrix = glm::dmat4(data.camera.projectionMatrix()); - _program->setUniform( - "screenSize", - glm::vec2(OsEng.renderEngine().renderingResolution()) - ); - - _program->setUniform(_uniformCache.modelViewProjection, projMatrix * modelViewMatrix); - _program->setUniform( - _uniformCache.cameraPos, - glm::dvec3(worldToModelTransform * glm::dvec4(data.camera.positionVec3(), 1.0)) - ); - _program->setUniform( - _uniformCache.cameraLookup, - glm::dvec3(worldToModelTransform * - glm::dvec4(data.camera.lookUpVectorWorldSpace(), 1.0) - ) - ); - - _program->setUniform(_uniformCache.renderOption, _renderOption.value()); - glm::dvec4 centerScreenWorld = glm::inverse(data.camera.combinedViewMatrix()) * - glm::dvec4(0.0, 0.0, 0.0, 1.0); - - _program->setUniform(_uniformCache.centerSceenInWorldPos, centerScreenWorld); - - _program->setUniform(_uniformCache.minBillboardSize, _billboardMinSize); // in pixels - _program->setUniform(_uniformCache.maxBillboardSize, _billboardMaxSize); // in pixels - _program->setUniform(_uniformCache.color, _pointColor); - _program->setUniform(_uniformCache.alphaValue, _alphaValue); - _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); - - _program->setUniform(_uniformCache.up, orthoUp); - _program->setUniform(_uniformCache.right, orthoRight); - - _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); - - GLint viewport[4]; - glGetIntegerv(GL_VIEWPORT, viewport); - _program->setUniform(_uniformCache.screenSize, glm::vec2(viewport[2], viewport[3])); - - - ghoul::opengl::TextureUnit spriteTextureUnit; - if (_hasSpriteTexture) { - spriteTextureUnit.activate(); - _spriteTexture->bind(); - _program->setUniform(_uniformCache.spriteTexture, spriteTextureUnit); - } - - ghoul::opengl::TextureUnit polygonTextureUnit; - if (_hasPolygon) { - polygonTextureUnit.activate(); - glBindTexture(GL_TEXTURE_2D, _pTexture); - _program->setUniform(_uniformCache.polygonTexture, polygonTextureUnit); - _program->setUniform(_uniformCache.hasPolygon, _hasPolygon); - } - - _program->setUniform(_uniformCache.hasColormap, _hasColorMapFile); - - glBindVertexArray(_vao); - const GLsizei nAstronomicalObjects = static_cast(_fullData.size() / - _nValuesPerAstronomicalObject); - glDrawArrays(GL_POINTS, 0, nAstronomicalObjects); - - glBindVertexArray(0); - _program->deactivate(); - - // Restores blending state - glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); - glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); - - if (!blendEnabled) { - glDisablei(GL_BLEND, 0); - } - - glDepthMask(true); - -} - -void RenderableBillboardsCloud::renderLabels(const RenderData& data, - const glm::dmat4& modelViewProjectionMatrix, - const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, - float fadeInVariable) -{ - float scale = 0.0; - switch (_unit) { - case Meter: - scale = 1.0; - break; - case Kilometer: - scale = 1e3; - break; - case Parsec: - scale = PARSEC; - break; - case Kiloparsec: - scale = 1e3 * PARSEC; - break; - case Megaparsec: - scale = 1e6 * PARSEC; - break; - case Gigaparsec: - scale = 1e9 * PARSEC; - break; - case GigalightYears: - scale = 306391534.73091 * PARSEC; - break; - } - - glm::vec4 textColor = _textColor; - textColor.a *= fadeInVariable; - for (const std::pair& pair : _labelData) { - //glm::vec3 scaledPos(_transformationMatrix * glm::dvec4(pair.first, 1.0)); - glm::vec3 scaledPos(pair.first); - scaledPos *= scale; - ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( - *_font, - scaledPos, - textColor, - pow(10.0, _textSize.value()), - _textMinSize, - _textMaxSize, - modelViewProjectionMatrix, - orthoRight, - orthoUp, - data.camera.positionVec3(), - data.camera.lookUpVectorWorldSpace(), - _renderOption.value(), - "%s", - pair.second.c_str() ); - } -} + _program = nullptr; -void RenderableBillboardsCloud::render(const RenderData& data, RendererTasks&) { - - float scale = 0.0; - switch (_unit) { - case Meter: - scale = 1.0; - break; - case Kilometer: - scale = 1e3; - break; - case Parsec: - scale = PARSEC; - break; - case Kiloparsec: - scale = 1e3 * PARSEC; - break; - case Megaparsec: - scale = 1e6 * PARSEC; - break; - case Gigaparsec: - scale = 1e9 * PARSEC; - break; - case GigalightYears: - scale = 306391534.73091 * PARSEC; - break; - } - - float fadeInVariable = 1.0f; - if (!_disableFadeInDistance) { - float distCamera = glm::length(data.camera.positionVec3()); - - /* - // Linear Fading - float funcValue = static_cast( - (1.0 / double(_fadeInDistance*scale))*(distCamera) + DigitalUniverseModule::ProgramObjectManager.releaseProgramObject( + RenderToPolygonProgram ); - fadeInVariable *= funcValue > 1.0 ? 1.0 : funcValue; + _renderToPolygonProgram = nullptr; - if (funcValue < 0.01) { - return; + if (_hasSpriteTexture) { + _spriteTexture = nullptr; } - */ - glm::vec2 fadeRange = _fadeInDistance; - float a = 1.0f / ((fadeRange.y - fadeRange.x) * scale); - float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); - float funcValue = a * distCamera + b; - fadeInVariable *= funcValue > 1.0 ? 1.0 : funcValue; - - if (funcValue < 0.01) { - return; + if (_hasPolygon) { + _polygonTexture = nullptr; + glDeleteTextures(1, &_pTexture); } } + void RenderableBillboardsCloud::renderBillboards(const RenderData& data, + const glm::dmat4& modelMatrix, + const glm::dvec3& orthoRight, + const glm::dvec3& orthoUp, + float fadeInVariable) + { + glDepthMask(false); - glm::dmat4 modelMatrix = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation - glm::dmat4(data.modelTransform.rotation) * // Spice rotation - glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); + // Saving current OpenGL state + GLboolean blendEnabled = glIsEnabledi(GL_BLEND, 0); + GLenum blendEquationRGB; + GLenum blendEquationAlpha; + GLenum blendDestAlpha; + GLenum blendDestRGB; + GLenum blendSrcAlpha; + GLenum blendSrcRGB; - glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; - glm::mat4 projectionMatrix = data.camera.projectionMatrix(); + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); - glm::dmat4 modelViewProjectionMatrix = glm::dmat4(projectionMatrix) * - modelViewMatrix; + glEnablei(GL_BLEND, 0); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glm::dmat4 worldToModelTransform = glm::inverse(modelMatrix); + _program->activate(); - /*glm::dmat4 internalCameraMatrix = data.camera.viewRotationMatrix() * - glm::inverse(glm::translate(glm::dmat4(1.0), data.camera.positionVec3())); - glm::dmat4 invInternalCameraMatrix = glm::inverse(internalCameraMatrix); - glm::vec3 lookup = worldToModelTransform * invInternalCameraMatrix * glm::dvec4(data.camera.lookUpVectorWorldSpace(), 0.0); - glm::vec3 viewDirection = worldToModelTransform * invInternalCameraMatrix * glm::dvec4(data.camera.viewDirectionWorldSpace(), 0.0); - - - glm::vec3 right = glm::cross(viewDirection, lookup); - glm::vec3 up = glm::cross(right, viewDirection); - - - glm::vec3 orthoRight = glm::normalize(right); - glm::vec3 orthoUp = glm::normalize(up);*/ - - /* - glm::dmat4 internalCameraMatrix = data.camera.viewRotationMatrix() * - glm::inverse(glm::translate(glm::dmat4(1.0), data.camera.positionVec3())); - glm::dmat4 invInternalCameraMatrix = glm::inverse(internalCameraMatrix); - glm::dvec4 lookup = worldToModelTransform * glm::dvec4(data.camera.lookUpVectorWorldSpace(), 0.0); - glm::dvec4 viewDirection = worldToModelTransform * glm::dvec4(data.camera.viewDirectionWorldSpace(), 0.0); - glm::vec3 right = glm::cross(glm::vec3(viewDirection), glm::vec3(lookup)); - glm::vec3 up = glm::cross(right, glm::vec3(viewDirection)); - - glm::vec3 orthoRight = glm::normalize(right); - glm::vec3 orthoUp = glm::normalize(up); - */ - - - // Almost Working - glm::dmat4 invMVPParts = worldToModelTransform * glm::inverse(data.camera.combinedViewMatrix()) * - glm::inverse(glm::dmat4(projectionMatrix)); - glm::dvec3 orthoRight = glm::dvec3(glm::normalize(glm::dvec3(invMVPParts * glm::dvec4(1.0, 0.0, 0.0, 0.0)))); - glm::dvec3 orthoUp = glm::dvec3(glm::normalize(glm::dvec3(invMVPParts * glm::dvec4(0.0, 1.0, 0.0, 0.0)))); - - if (_hasSpeckFile) { - renderBillboards( - data, - modelViewMatrix, - worldToModelTransform, - orthoRight, - orthoUp, - fadeInVariable + glm::dmat4 projMatrix = glm::dmat4(data.camera.projectionMatrix()); + _program->setUniform( + "screenSize", + glm::vec2(OsEng.renderEngine().renderingResolution()) ); - } - if (_drawLabels && _hasLabel) { - renderLabels( - data, - modelViewProjectionMatrix, - orthoRight, - orthoUp, - fadeInVariable - ); - } -} + _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); + _program->setUniform(_uniformCache.cameraLookup, data.camera.lookUpVectorWorldSpace()); + _program->setUniform(_uniformCache.renderOption, _renderOption.value()); + _program->setUniform(_uniformCache.modelViewMatrix, data.camera.combinedViewMatrix() * modelMatrix); + _program->setUniform(_uniformCache.projectionMatrix, glm::dmat4(data.camera.projectionMatrix())); + _program->setUniform(_uniformCache.modelMatrix, modelMatrix); + _program->setUniform(_uniformCache.cameraViewProjectionMatrix, + glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix()); + _program->setUniform(_uniformCache.minBillboardSize, _billboardMinSize); // in pixels + _program->setUniform(_uniformCache.maxBillboardSize, _billboardMaxSize); // in pixels + _program->setUniform(_uniformCache.color, _pointColor); + _program->setUniform(_uniformCache.alphaValue, _alphaValue); + _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); + _program->setUniform(_uniformCache.up, orthoUp); + _program->setUniform(_uniformCache.right, orthoRight); + _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); -void RenderableBillboardsCloud::update(const UpdateData&) { - if (_dataIsDirty && _hasSpeckFile) { - LDEBUG("Regenerating data"); + _program->setUniform("correctionSizeEndDistance", _correctionSizeEndDistance); + _program->setUniform("correctionSizeFactor", _correctionSizeFactor); - createDataSlice(); + GLint viewport[4]; + glGetIntegerv(GL_VIEWPORT, viewport); + _program->setUniform(_uniformCache.screenSize, glm::vec2(viewport[2], viewport[3])); - int size = static_cast(_slicedData.size()); - - if (_vao == 0) { - glGenVertexArrays(1, &_vao); - LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); + ghoul::opengl::TextureUnit spriteTextureUnit; + if (_hasSpriteTexture) { + spriteTextureUnit.activate(); + _spriteTexture->bind(); + _program->setUniform(_uniformCache.spriteTexture, spriteTextureUnit); } - if (_vbo == 0) { - glGenBuffers(1, &_vbo); - LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); + + ghoul::opengl::TextureUnit polygonTextureUnit; + if (_hasPolygon) { + polygonTextureUnit.activate(); + glBindTexture(GL_TEXTURE_2D, _pTexture); + _program->setUniform(_uniformCache.polygonTexture, polygonTextureUnit); + _program->setUniform(_uniformCache.hasPolygon, _hasPolygon); } + _program->setUniform(_uniformCache.hasColormap, _hasColorMapFile); + glBindVertexArray(_vao); - glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferData( - GL_ARRAY_BUFFER, - size * sizeof(float), - &_slicedData[0], - GL_STATIC_DRAW - ); - GLint positionAttrib = _program->attributeLocation("in_position"); - - if (_hasColorMapFile) { - /*const size_t nAstronomicalObjects = _fullData.size() / - _nValuesPerAstronomicalObject; - const size_t nValues = _slicedData.size() / nAstronomicalObjects; - GLsizei stride = static_cast(sizeof(float) * nValues);*/ - - glEnableVertexAttribArray(positionAttrib); - glVertexAttribPointer( - positionAttrib, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(float)*8, - nullptr - ); - - GLint colorMapAttrib = _program->attributeLocation("in_colormap"); - glEnableVertexAttribArray(colorMapAttrib); - glVertexAttribPointer( - colorMapAttrib, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(float) * 8, - reinterpret_cast(sizeof(float)*4) - ); - } - else { - glEnableVertexAttribArray(positionAttrib); - glVertexAttribPointer( - positionAttrib, - 4, - GL_FLOAT, - GL_FALSE, - 0, - nullptr - ); - } + const GLsizei nAstronomicalObjects = static_cast(_fullData.size() / + _nValuesPerAstronomicalObject); + glDrawArrays(GL_POINTS, 0, nAstronomicalObjects); glBindVertexArray(0); + _program->deactivate(); + + // Restores blending state + glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); + + if (!blendEnabled) { + glDisablei(GL_BLEND, 0); + } + + glDepthMask(true); - _dataIsDirty = false; } - if (_hasSpriteTexture && _spriteTextureIsDirty) { - LDEBUG("Reloading Sprite Texture"); - _spriteTexture = nullptr; - if (_spriteTexturePath.value() != "") { - _spriteTexture = ghoul::io::TextureReader::ref().loadTexture( - absPath(_spriteTexturePath) + void RenderableBillboardsCloud::renderLabels(const RenderData& data, + const glm::dmat4& modelViewProjectionMatrix, + const glm::dvec3& orthoRight, + const glm::dvec3& orthoUp, + float fadeInVariable) + { + float scale = 0.0; + switch (_unit) { + case Meter: + scale = 1.0; + break; + case Kilometer: + scale = 1e3; + break; + case Parsec: + scale = PARSEC; + break; + case Kiloparsec: + scale = 1e3 * PARSEC; + break; + case Megaparsec: + scale = 1e6 * PARSEC; + break; + case Gigaparsec: + scale = 1e9 * PARSEC; + break; + case GigalightYears: + scale = 306391534.73091 * PARSEC; + break; + } + + glm::vec4 textColor = _textColor; + textColor.a *= fadeInVariable; + for (const std::pair& pair : _labelData) { + //glm::vec3 scaledPos(_transformationMatrix * glm::dvec4(pair.first, 1.0)); + glm::vec3 scaledPos(pair.first); + scaledPos *= scale; + ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( + *_font, + scaledPos, + textColor, + pow(10.0, _textSize.value()), + _textMinSize, + _textMaxSize, + modelViewProjectionMatrix, + orthoRight, + orthoUp, + data.camera.positionVec3(), + data.camera.lookUpVectorWorldSpace(), + _renderOption.value(), + "%s", + pair.second.c_str() ); - if (_spriteTexture) { - LINFO(fmt::format( - "Loaded texture from '{}'", - absPath(_spriteTexturePath) - )); - _spriteTexture->uploadTexture(); + } + } + + void RenderableBillboardsCloud::render(const RenderData& data, RendererTasks&) { + + float scale = 0.0; + switch (_unit) { + case Meter: + scale = 1.0; + break; + case Kilometer: + scale = 1e3; + break; + case Parsec: + scale = PARSEC; + break; + case Kiloparsec: + scale = 1e3 * PARSEC; + break; + case Megaparsec: + scale = 1e6 * PARSEC; + break; + case Gigaparsec: + scale = 1e9 * PARSEC; + break; + case GigalightYears: + scale = 306391534.73091 * PARSEC; + break; + } + + float fadeInVariable = 1.0f; + if (!_disableFadeInDistance) { + float distCamera = glm::length(data.camera.positionVec3()); + glm::vec2 fadeRange = _fadeInDistance; + float a = 1.0f / ((fadeRange.y - fadeRange.x) * scale); + float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); + float funcValue = a * distCamera + b; + fadeInVariable *= funcValue > 1.0 ? 1.0 : funcValue; + + if (funcValue < 0.01) { + return; } - _spriteTexture->setFilter( - ghoul::opengl::Texture::FilterMode::AnisotropicMipMap + } + + + glm::dmat4 modelMatrix = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation + glm::dmat4(data.modelTransform.rotation) * // Spice rotation + glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); + + glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; + glm::mat4 projectionMatrix = data.camera.projectionMatrix(); + + glm::dmat4 modelViewProjectionMatrix = glm::dmat4(projectionMatrix) * + modelViewMatrix; + + glm::dvec3 cameraViewDirectionWorld = glm::normalize(data.camera.viewDirectionWorldSpace()); + glm::dvec3 cameraUpDirectionWorld = glm::normalize(data.camera.lookUpVectorWorldSpace()); + glm::dvec3 orthoRight = glm::dvec3(glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld)); + if (orthoRight == glm::dvec3(0.0)) { + glm::dvec3 otherVector(cameraUpDirectionWorld.y, cameraUpDirectionWorld.x, cameraUpDirectionWorld.z); + orthoRight = glm::dvec3(glm::cross(otherVector, cameraViewDirectionWorld)); + } + glm::dvec3 orthoUp = cameraUpDirectionWorld; + + if (_hasSpeckFile) { + renderBillboards( + data, + modelMatrix, + orthoRight, + orthoUp, + fadeInVariable ); + } - _spriteTextureFile = std::make_unique( - _spriteTexturePath); - _spriteTextureFile->setCallback( - [&](const ghoul::filesystem::File&) { _spriteTextureIsDirty = true; } + if (_drawLabels && _hasLabel) { + renderLabels( + data, + modelViewProjectionMatrix, + orthoRight, + orthoUp, + fadeInVariable + ); + } + } + + void RenderableBillboardsCloud::update(const UpdateData&) { + if (_dataIsDirty && _hasSpeckFile) { + LDEBUG("Regenerating data"); + + createDataSlice(); + + int size = static_cast(_slicedData.size()); + + if (_vao == 0) { + glGenVertexArrays(1, &_vao); + LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); + } + if (_vbo == 0) { + glGenBuffers(1, &_vbo); + LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); + } + + glBindVertexArray(_vao); + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + glBufferData( + GL_ARRAY_BUFFER, + size * sizeof(float), + &_slicedData[0], + GL_STATIC_DRAW + ); + GLint positionAttrib = _program->attributeLocation("in_position"); + + if (_hasColorMapFile) { + /*const size_t nAstronomicalObjects = _fullData.size() / + _nValuesPerAstronomicalObject; + const size_t nValues = _slicedData.size() / nAstronomicalObjects; + GLsizei stride = static_cast(sizeof(float) * nValues);*/ + + glEnableVertexAttribArray(positionAttrib); + glVertexAttribPointer( + positionAttrib, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(float) * 8, + nullptr ); - } - _spriteTextureIsDirty = false; - } - if (_hasLabel && _labelDataIsDirty) { - - _labelDataIsDirty = false; - } -} - -bool RenderableBillboardsCloud::loadData() { - bool success = true; - - success &= loadSpeckData(); - - if (_hasColorMapFile) { - if (!_hasSpeckFile) { - success = true; - } - success &= readColorMapFile(); - } - - success &= loadLabelData(); - - return success; -} - -bool RenderableBillboardsCloud::loadSpeckData() { - bool success = true; - if (_hasSpeckFile) { - std::string _file = _speckFile; - // I disabled the cache as it didn't work on Mac --- abock - - std::string cachedFile = FileSys.cacheManager()->cachedFilename( - ghoul::filesystem::File(_file), - "RenderableDUMeshes|" + identifier(), - ghoul::filesystem::CacheManager::Persistent::Yes - ); - - bool hasCachedFile = FileSys.fileExists(cachedFile); - if (hasCachedFile) { - LINFO(fmt::format( - "Cached file '{}' used for Speck file '{}'", - cachedFile, - _file - )); - - success = loadCachedFile(cachedFile); - if (success) { - return true; + GLint colorMapAttrib = _program->attributeLocation("in_colormap"); + glEnableVertexAttribArray(colorMapAttrib); + glVertexAttribPointer( + colorMapAttrib, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(float) * 8, + reinterpret_cast(sizeof(float) * 4) + ); } else { - FileSys.cacheManager()->removeCacheFile(_file); - // Intentional fall-through to the 'else' to generate the cache - // file for the next run + glEnableVertexAttribArray(positionAttrib); + glVertexAttribPointer( + positionAttrib, + 4, + GL_FLOAT, + GL_FALSE, + 0, + nullptr + ); } - } - else { - LINFO(fmt::format("Cache for Speck file '{}' not found", _file)); - } - LINFO(fmt::format("Loading Speck file '{}'", _file)); - success = readSpeckFile(); - if (!success) { - return false; + glBindVertexArray(0); + + _dataIsDirty = false; } - success &= saveCachedFile(cachedFile); + if (_hasSpriteTexture && _spriteTextureIsDirty) { + LDEBUG("Reloading Sprite Texture"); + _spriteTexture = nullptr; + if (_spriteTexturePath.value() != "") { + _spriteTexture = ghoul::io::TextureReader::ref().loadTexture( + absPath(_spriteTexturePath) + ); + if (_spriteTexture) { + LINFO(fmt::format( + "Loaded texture from '{}'", + absPath(_spriteTexturePath) + )); + _spriteTexture->uploadTexture(); + } + _spriteTexture->setFilter( + ghoul::opengl::Texture::FilterMode::AnisotropicMipMap + ); + + _spriteTextureFile = std::make_unique( + _spriteTexturePath); + _spriteTextureFile->setCallback( + [&](const ghoul::filesystem::File&) { _spriteTextureIsDirty = true; } + ); + } + _spriteTextureIsDirty = false; + } + + if (_hasLabel && _labelDataIsDirty) { + + _labelDataIsDirty = false; + } } - return success; -} -bool RenderableBillboardsCloud::loadLabelData() { - bool success = true; - std::string labelFile = _labelFile; - if (!labelFile.empty()) { - // I disabled the cache as it didn't work on Mac --- abock - std::string cachedFile = FileSys.cacheManager()->cachedFilename( - ghoul::filesystem::File(labelFile), - ghoul::filesystem::CacheManager::Persistent::Yes - ); - if (!_hasSpeckFile && !_hasColorMapFile) { - success = true; - } - bool hasCachedFile = FileSys.fileExists(cachedFile); - if (hasCachedFile) { - LINFO(fmt::format( - "Cached file '{}' used for Label file '{}'", - cachedFile, - labelFile - )); + bool RenderableBillboardsCloud::loadData() { + bool success = true; - success &= loadCachedFile(cachedFile); - if (!success) { - FileSys.cacheManager()->removeCacheFile(labelFile); - // Intentional fall-through to the 'else' to generate the cache - // file for the next run + success &= loadSpeckData(); + + if (_hasColorMapFile) { + if (!_hasSpeckFile) { + success = true; } + success &= readColorMapFile(); } - else { - LINFO(fmt::format("Cache for Label file '{}' not found", labelFile)); - LINFO(fmt::format("Loading Label file '{}'", labelFile)); - success &= readLabelFile(); + success &= loadLabelData(); + + return success; + } + + bool RenderableBillboardsCloud::loadSpeckData() { + bool success = true; + if (_hasSpeckFile) { + std::string _file = _speckFile; + // I disabled the cache as it didn't work on Mac --- abock + + std::string cachedFile = FileSys.cacheManager()->cachedFilename( + ghoul::filesystem::File(_file), + "RenderableDUMeshes|" + identifier(), + ghoul::filesystem::CacheManager::Persistent::Yes + ); + + bool hasCachedFile = FileSys.fileExists(cachedFile); + if (hasCachedFile) { + LINFO(fmt::format( + "Cached file '{}' used for Speck file '{}'", + cachedFile, + _file + )); + + success = loadCachedFile(cachedFile); + if (success) { + return true; + } + else { + FileSys.cacheManager()->removeCacheFile(_file); + // Intentional fall-through to the 'else' to generate the cache + // file for the next run + } + } + else { + LINFO(fmt::format("Cache for Speck file '{}' not found", _file)); + } + LINFO(fmt::format("Loading Speck file '{}'", _file)); + + success = readSpeckFile(); if (!success) { return false; } + + success &= saveCachedFile(cachedFile); } + return success; } - return success; -} + bool RenderableBillboardsCloud::loadLabelData() { + bool success = true; + std::string labelFile = _labelFile; + if (!labelFile.empty()) { + // I disabled the cache as it didn't work on Mac --- abock + std::string cachedFile = FileSys.cacheManager()->cachedFilename( + ghoul::filesystem::File(labelFile), + ghoul::filesystem::CacheManager::Persistent::Yes + ); + if (!_hasSpeckFile && !_hasColorMapFile) { + success = true; + } + bool hasCachedFile = FileSys.fileExists(cachedFile); + if (hasCachedFile) { + LINFO(fmt::format( + "Cached file '{}' used for Label file '{}'", + cachedFile, + labelFile + )); + success &= loadCachedFile(cachedFile); + if (!success) { + FileSys.cacheManager()->removeCacheFile(labelFile); + // Intentional fall-through to the 'else' to generate the cache + // file for the next run + } + } + else { + LINFO(fmt::format("Cache for Label file '{}' not found", labelFile)); + LINFO(fmt::format("Loading Label file '{}'", labelFile)); -bool RenderableBillboardsCloud::readSpeckFile() { - std::string _file = _speckFile; - std::ifstream file(_file); - if (!file.good()) { - LERROR(fmt::format("Failed to open Speck file '{}'", _file)); - return false; + success &= readLabelFile(); + if (!success) { + return false; + } + } + } + + return success; } - _nValuesPerAstronomicalObject = 0; - // The beginning of the speck file has a header that either contains comments - // (signaled by a preceding '#') or information about the structure of the file - // (signaled by the keywords 'datavar', 'texturevar', and 'texture') - std::string line = ""; - while (true) { - std::streampos position = file.tellg(); - std::getline(file, line); - - // Guard against wrong line endings (copying files from Windows to Mac) causes - // lines to have a final \r - if (!line.empty() && line.back() == '\r') { - line = line.substr(0, line.length() -1); - } - - if (line.empty() || line[0] == '#') { - continue; - } - - if (line.substr(0, 7) != "datavar" && - line.substr(0, 10) != "texturevar" && - line.substr(0, 7) != "texture" && - line.substr(0, 10) != "polyorivar" && - line.substr(0, 10) != "maxcomment") - { - // we read a line that doesn't belong to the header, so we have to jump back - // before the beginning of the current line - file.seekg(position); - break; - } - - if (line.substr(0, 7) == "datavar") { - // datavar lines are structured as follows: - // datavar # description - // where # is the index of the data variable; so if we repeatedly overwrite - // the 'nValues' variable with the latest index, we will end up with the total - // number of values (+3 since X Y Z are not counted in the Speck file index) - std::stringstream str(line); - - std::string dummy; - str >> dummy; // command - str >> _nValuesPerAstronomicalObject; // variable index - dummy.clear(); - str >> dummy; // variable name - - _variableDataPositionMap.insert({ dummy, _nValuesPerAstronomicalObject }); - - // We want the number, but the index is 0 based - _nValuesPerAstronomicalObject += 1; - } - } - - _nValuesPerAstronomicalObject += 3; // X Y Z are not counted in the Speck file indices - - do { - std::vector values(_nValuesPerAstronomicalObject); - - std::getline(file, line); - - // Guard against wrong line endings (copying files from Windows to Mac) causes - // lines to have a final \r - if (!line.empty() && line.back() == '\r') { - line = line.substr(0, line.length() -1); - } - - if (line.empty()) { - continue; - } - - std::stringstream str(line); - - for (int i = 0; i < _nValuesPerAstronomicalObject; ++i) { - str >> values[i]; - } - - _fullData.insert(_fullData.end(), values.begin(), values.end()); - } while (!file.eof()); - - return true; -} - -bool RenderableBillboardsCloud::readColorMapFile() { - std::string _file = _colorMapFile; - std::ifstream file(_file); - if (!file.good()) { - LERROR(fmt::format("Failed to open Color Map file '{}'", _file)); - return false; - } - - std::size_t numberOfColors = 0; - - // The beginning of the speck file has a header that either contains comments - // (signaled by a preceding '#') or information about the structure of the file - // (signaled by the keywords 'datavar', 'texturevar', and 'texture') - std::string line = ""; - while (true) { - // std::streampos position = file.tellg(); - std::getline(file, line); - - if (line[0] == '#' || line.empty()) { - continue; - } - - // Initial number of colors - std::locale loc; - if (std::isdigit(line[0], loc)) { - std::string::size_type sz; - numberOfColors = std::stoi(line, &sz); - break; - } - else if (file.eof()) { + bool RenderableBillboardsCloud::readSpeckFile() { + std::string _file = _speckFile; + std::ifstream file(_file); + if (!file.good()) { + LERROR(fmt::format("Failed to open Speck file '{}'", _file)); return false; } - } - for (size_t i = 0; i < numberOfColors; ++i) { - std::getline(file, line); - std::stringstream str(line); + _nValuesPerAstronomicalObject = 0; - glm::vec4 color; - for (int j = 0; j < 4; ++j) { - str >> color[j]; - } + // The beginning of the speck file has a header that either contains comments + // (signaled by a preceding '#') or information about the structure of the file + // (signaled by the keywords 'datavar', 'texturevar', and 'texture') + std::string line = ""; + while (true) { + std::streampos position = file.tellg(); + std::getline(file, line); - _colorMapData.push_back(color); - } + // Guard against wrong line endings (copying files from Windows to Mac) causes + // lines to have a final \r + if (!line.empty() && line.back() == '\r') { + line = line.substr(0, line.length() - 1); + } - return true; -} + if (line.empty() || line[0] == '#') { + continue; + } -bool RenderableBillboardsCloud::readLabelFile() { - std::string _file = _labelFile; - std::ifstream file(_file); - if (!file.good()) { - LERROR(fmt::format("Failed to open Label file '{}'", _file)); - return false; - } - - // The beginning of the speck file has a header that either contains comments - // (signaled by a preceding '#') or information about the structure of the file - // (signaled by the keywords 'datavar', 'texturevar', and 'texture') - std::string line = ""; - while (true) { - std::streampos position = file.tellg(); - std::getline(file, line); - - // Guard against wrong line endings (copying files from Windows to Mac) causes - // lines to have a final \r - if (!line.empty() && line.back() == '\r') { - line = line.substr(0, line.length() -1); - } - - if (line.empty() || line[0] == '#') { - continue; - } - - if (line.substr(0, 9) != "textcolor") { - // we read a line that doesn't belong to the header, so we have to jump back - // before the beginning of the current line - file.seekg(position); - continue; - } - - if (line.substr(0, 9) == "textcolor") { - // textcolor lines are structured as follows: - // textcolor # description - // where # is color text defined in configuration file - std::stringstream str(line); - - // TODO: handle cases of labels with different colors - break; - } - } - - - do { - std::vector values(_nValuesPerAstronomicalObject); - - std::getline(file, line); - - // Guard against wrong line endings (copying files from Windows to Mac) causes - // lines to have a final \r - if (!line.empty() && line.back() == '\r') { - line = line.substr(0, line.length() -1); - } - - if (line.empty()) { - continue; - } - - std::stringstream str(line); - - glm::vec3 position; - for (auto j = 0; j < 3; ++j) { - str >> position[j]; - } - - std::string dummy; - str >> dummy; // text keyword - - std::string label; - str >> label; - dummy.clear(); - - while (str >> dummy) { - if (dummy == "#") { + if (line.substr(0, 7) != "datavar" && + line.substr(0, 10) != "texturevar" && + line.substr(0, 7) != "texture" && + line.substr(0, 10) != "polyorivar" && + line.substr(0, 10) != "maxcomment") + { + // we read a line that doesn't belong to the header, so we have to jump back + // before the beginning of the current line + file.seekg(position); break; } - label += " " + dummy; + if (line.substr(0, 7) == "datavar") { + // datavar lines are structured as follows: + // datavar # description + // where # is the index of the data variable; so if we repeatedly overwrite + // the 'nValues' variable with the latest index, we will end up with the total + // number of values (+3 since X Y Z are not counted in the Speck file index) + std::stringstream str(line); + + std::string dummy; + str >> dummy; // command + str >> _nValuesPerAstronomicalObject; // variable index + dummy.clear(); + str >> dummy; // variable name + + _variableDataPositionMap.insert({ dummy, _nValuesPerAstronomicalObject }); + + // We want the number, but the index is 0 based + _nValuesPerAstronomicalObject += 1; + } + } + + _nValuesPerAstronomicalObject += 3; // X Y Z are not counted in the Speck file indices + + do { + std::vector values(_nValuesPerAstronomicalObject); + + std::getline(file, line); + + // Guard against wrong line endings (copying files from Windows to Mac) causes + // lines to have a final \r + if (!line.empty() && line.back() == '\r') { + line = line.substr(0, line.length() - 1); + } + + if (line.empty()) { + continue; + } + + std::stringstream str(line); + + for (int i = 0; i < _nValuesPerAstronomicalObject; ++i) { + str >> values[i]; + } + + _fullData.insert(_fullData.end(), values.begin(), values.end()); + } while (!file.eof()); + + return true; + } + + bool RenderableBillboardsCloud::readColorMapFile() { + std::string _file = _colorMapFile; + std::ifstream file(_file); + if (!file.good()) { + LERROR(fmt::format("Failed to open Color Map file '{}'", _file)); + return false; + } + + std::size_t numberOfColors = 0; + + // The beginning of the speck file has a header that either contains comments + // (signaled by a preceding '#') or information about the structure of the file + // (signaled by the keywords 'datavar', 'texturevar', and 'texture') + std::string line = ""; + while (true) { + // std::streampos position = file.tellg(); + std::getline(file, line); + + if (line[0] == '#' || line.empty()) { + continue; + } + + // Initial number of colors + std::locale loc; + if (std::isdigit(line[0], loc)) { + std::string::size_type sz; + numberOfColors = std::stoi(line, &sz); + break; + } + else if (file.eof()) { + return false; + } + } + + for (size_t i = 0; i < numberOfColors; ++i) { + std::getline(file, line); + std::stringstream str(line); + + glm::vec4 color; + for (int j = 0; j < 4; ++j) { + str >> color[j]; + } + + _colorMapData.push_back(color); + } + + return true; + } + + bool RenderableBillboardsCloud::readLabelFile() { + std::string _file = _labelFile; + std::ifstream file(_file); + if (!file.good()) { + LERROR(fmt::format("Failed to open Label file '{}'", _file)); + return false; + } + + // The beginning of the speck file has a header that either contains comments + // (signaled by a preceding '#') or information about the structure of the file + // (signaled by the keywords 'datavar', 'texturevar', and 'texture') + std::string line = ""; + while (true) { + std::streampos position = file.tellg(); + std::getline(file, line); + + // Guard against wrong line endings (copying files from Windows to Mac) causes + // lines to have a final \r + if (!line.empty() && line.back() == '\r') { + line = line.substr(0, line.length() - 1); + } + + if (line.empty() || line[0] == '#') { + continue; + } + + if (line.substr(0, 9) != "textcolor") { + // we read a line that doesn't belong to the header, so we have to jump back + // before the beginning of the current line + file.seekg(position); + continue; + } + + if (line.substr(0, 9) == "textcolor") { + // textcolor lines are structured as follows: + // textcolor # description + // where # is color text defined in configuration file + std::stringstream str(line); + + // TODO: handle cases of labels with different colors + break; + } + } + + + do { + std::vector values(_nValuesPerAstronomicalObject); + + std::getline(file, line); + + // Guard against wrong line endings (copying files from Windows to Mac) causes + // lines to have a final \r + if (!line.empty() && line.back() == '\r') { + line = line.substr(0, line.length() - 1); + } + + if (line.empty()) { + continue; + } + + std::stringstream str(line); + + glm::vec3 position; + for (auto j = 0; j < 3; ++j) { + str >> position[j]; + } + + std::string dummy; + str >> dummy; // text keyword + + std::string label; + str >> label; dummy.clear(); - } - glm::vec3 transformedPos = glm::vec3( - _transformationMatrix * glm::dvec4(position, 1.0) - ); - _labelData.push_back(std::make_pair(transformedPos, label)); - } while (!file.eof()); - - return true; -} - -bool RenderableBillboardsCloud::loadCachedFile(const std::string& file) { - std::ifstream fileStream(file, std::ifstream::binary); - if (fileStream.good()) { - int8_t version = 0; - fileStream.read(reinterpret_cast(&version), sizeof(int8_t)); - if (version != CurrentCacheVersion) { - LINFO("The format of the cached file has changed: deleting old cache"); - fileStream.close(); - FileSys.deleteFile(file); - return false; - } - - int32_t nValues = 0; - fileStream.read(reinterpret_cast(&nValues), sizeof(int32_t)); - fileStream.read( - reinterpret_cast(&_nValuesPerAstronomicalObject), - sizeof(int32_t) - ); - - _fullData.resize(nValues); - fileStream.read(reinterpret_cast(&_fullData[0]), - nValues * sizeof(_fullData[0])); - - if (_hasColorMapFile) { - int32_t nItems = 0; - fileStream.read(reinterpret_cast(&nItems), sizeof(int32_t)); - - for (int i = 0; i < nItems; ++i) { - int32_t keySize = 0; - fileStream.read(reinterpret_cast(&keySize), sizeof(int32_t)); - std::string key; - for (int c = 0; c < keySize; ++c) { - char t; - fileStream.read(&t, sizeof(char)); - key.append(1, t); - } - int32_t value = 0; - fileStream.read(reinterpret_cast(&value), sizeof(int32_t)); - - _variableDataPositionMap.insert({ key, value }); - } - } - - bool success = fileStream.good(); - return success; - } - else { - LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); - return false; - } -} - -bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { - std::ofstream fileStream(file, std::ofstream::binary); - if (fileStream.good()) { - fileStream.write(reinterpret_cast(&CurrentCacheVersion), - sizeof(int8_t)); - - int32_t nValues = static_cast(_fullData.size()); - if (nValues == 0) { - LERROR("Error writing cache: No values were loaded"); - return false; - } - fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); - - int32_t nValuesPerAstronomicalObject = static_cast( - _nValuesPerAstronomicalObject - ); - fileStream.write( - reinterpret_cast(&nValuesPerAstronomicalObject), - sizeof(int32_t) - ); - - size_t nBytes = nValues * sizeof(_fullData[0]); - fileStream.write(reinterpret_cast(&_fullData[0]), nBytes); - - if (_hasColorMapFile) { - int32_t nItems = static_cast(_variableDataPositionMap.size()); - fileStream.write(reinterpret_cast(&nItems), sizeof(int32_t)); - - for (auto pair : _variableDataPositionMap) { - int32_t keySize = static_cast(pair.first.size()); - fileStream.write( - reinterpret_cast(&keySize), - sizeof(int32_t) - ); - for (size_t c = 0; c < pair.first.size(); ++c) { - char keyChar = static_cast(pair.first[c]); - fileStream.write(&keyChar, sizeof(char)); - } - int32_t value = static_cast(pair.second); - fileStream.write(reinterpret_cast(&value), sizeof(int32_t)); - } - } - - bool success = fileStream.good(); - return success; - } - else { - LERROR(fmt::format("Error opening file '{}' for save cache file", file)); - return false; - } -} - -void RenderableBillboardsCloud::createDataSlice() { - _slicedData.clear(); - if (_hasColorMapFile) { - _slicedData.reserve(8 * (_fullData.size() / _nValuesPerAstronomicalObject)); - } - else { - _slicedData.reserve(4 * (_fullData.size()/_nValuesPerAstronomicalObject)); - } - - // Generate the color bins for the colomap - int colorMapInUse = 0; - std::vector colorBins; - if (_hasColorMapFile) { - colorMapInUse = _variableDataPositionMap[_colorOptionString]; - glm::vec2 currentColorRange = _colorRangeData[_colorOption.value()]; - float colorMapBinSize = (currentColorRange.y - currentColorRange.x) / - static_cast(_colorMapData.size()); - float bin = colorMapBinSize; - for (size_t i = 0; i < _colorMapData.size(); ++i) { - colorBins.push_back(bin); - bin += colorMapBinSize; - } - } - - float biggestCoord = -1.0f; - for (size_t i = 0; i < _fullData.size(); i += _nValuesPerAstronomicalObject) { - glm::dvec4 transformedPos = _transformationMatrix * glm::dvec4( - _fullData[i + 0], - _fullData[i + 1], - _fullData[i + 2], - 1.0 - ); - glm::vec4 position(glm::vec3(transformedPos), static_cast(_unit)); - - if (_hasColorMapFile) { - for (auto j = 0; j < 4; ++j) { - _slicedData.push_back(position[j]); - biggestCoord = biggestCoord < position[j] ? position[j] : biggestCoord; - } - // Finds from which bin to get the color. - // Note: the first color in the colormap file - // is the outliers color. - glm::vec4 itemColor; - float variableColor = _fullData[i + 3 + colorMapInUse]; - int c = static_cast(colorBins.size() - 1); - while (variableColor < colorBins[c]) { - --c; - if (c == 0) + while (str >> dummy) { + if (dummy == "#") { break; + } + + label += " " + dummy; + dummy.clear(); } - int colorIndex = - c == static_cast(colorBins.size() - 1) ? - 0 : - c + 1; + glm::vec3 transformedPos = glm::vec3( + _transformationMatrix * glm::dvec4(position, 1.0) + ); + _labelData.push_back(std::make_pair(transformedPos, label)); + } while (!file.eof()); - for (auto j = 0; j < 4; ++j) { - _slicedData.push_back(_colorMapData[colorIndex][j]); + return true; + } + + bool RenderableBillboardsCloud::loadCachedFile(const std::string& file) { + std::ifstream fileStream(file, std::ifstream::binary); + if (fileStream.good()) { + int8_t version = 0; + fileStream.read(reinterpret_cast(&version), sizeof(int8_t)); + if (version != CurrentCacheVersion) { + LINFO("The format of the cached file has changed: deleting old cache"); + fileStream.close(); + FileSys.deleteFile(file); + return false; } + + int32_t nValues = 0; + fileStream.read(reinterpret_cast(&nValues), sizeof(int32_t)); + fileStream.read( + reinterpret_cast(&_nValuesPerAstronomicalObject), + sizeof(int32_t) + ); + + _fullData.resize(nValues); + fileStream.read(reinterpret_cast(&_fullData[0]), + nValues * sizeof(_fullData[0])); + + if (_hasColorMapFile) { + int32_t nItems = 0; + fileStream.read(reinterpret_cast(&nItems), sizeof(int32_t)); + + for (int i = 0; i < nItems; ++i) { + int32_t keySize = 0; + fileStream.read(reinterpret_cast(&keySize), sizeof(int32_t)); + std::string key; + for (int c = 0; c < keySize; ++c) { + char t; + fileStream.read(&t, sizeof(char)); + key.append(1, t); + } + int32_t value = 0; + fileStream.read(reinterpret_cast(&value), sizeof(int32_t)); + + _variableDataPositionMap.insert({ key, value }); + } + } + + bool success = fileStream.good(); + return success; } else { - for (auto j = 0; j < 4; ++j) { - _slicedData.push_back(position[j]); - } + LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); + return false; } } - _fadeInDistance.setMaxValue(glm::vec2(10.0f * biggestCoord)); -} -void RenderableBillboardsCloud::createPolygonTexture() { - LDEBUG("Creating Polygon Texture"); + bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { + std::ofstream fileStream(file, std::ofstream::binary); + if (fileStream.good()) { + fileStream.write(reinterpret_cast(&CurrentCacheVersion), + sizeof(int8_t)); - glGenTextures(1, &_pTexture); - glBindTexture(GL_TEXTURE_2D, _pTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, - 256, 0, GL_RGBA, GL_BYTE, nullptr); + int32_t nValues = static_cast(_fullData.size()); + if (nValues == 0) { + LERROR("Error writing cache: No values were loaded"); + return false; + } + fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); - renderToTexture( - std::bind( - &openspace::RenderableBillboardsCloud::loadPolygonGeometryForRendering, - this - ), - std::bind( - &openspace::RenderableBillboardsCloud::renderPolygonGeometry, - this, - std::placeholders::_1 - ), - _pTexture, - 256, - 256 - ); -} + int32_t nValuesPerAstronomicalObject = static_cast( + _nValuesPerAstronomicalObject + ); + fileStream.write( + reinterpret_cast(&nValuesPerAstronomicalObject), + sizeof(int32_t) + ); -void RenderableBillboardsCloud::renderToTexture( - std::function geometryLoadingFunction, - std::function renderFunction, - GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight) -{ - LDEBUG("Rendering to Texture"); + size_t nBytes = nValues * sizeof(_fullData[0]); + fileStream.write(reinterpret_cast(&_fullData[0]), nBytes); - // Saves initial Application's OpenGL State - GLint defaultFBO; - GLint viewport[4]; - glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - glGetIntegerv(GL_VIEWPORT, viewport); + if (_hasColorMapFile) { + int32_t nItems = static_cast(_variableDataPositionMap.size()); + fileStream.write(reinterpret_cast(&nItems), sizeof(int32_t)); - GLuint textureFBO; - glGenFramebuffers(1, &textureFBO); - glBindFramebuffer(GL_FRAMEBUFFER, textureFBO); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); + for (auto pair : _variableDataPositionMap) { + int32_t keySize = static_cast(pair.first.size()); + fileStream.write( + reinterpret_cast(&keySize), + sizeof(int32_t) + ); + for (size_t c = 0; c < pair.first.size(); ++c) { + char keyChar = static_cast(pair.first[c]); + fileStream.write(&keyChar, sizeof(char)); + } + int32_t value = static_cast(pair.second); + fileStream.write(reinterpret_cast(&value), sizeof(int32_t)); + } + } - glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); - - glViewport(0, 0, textureWidth, textureHeight); - - geometryLoadingFunction(); - renderFunction(_polygonVao); - - // Restores Applications' OpenGL State - glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); - - if (_polygonVbo) { - glDeleteBuffers(1, &_polygonVbo); + bool success = fileStream.good(); + return success; + } + else { + LERROR(fmt::format("Error opening file '{}' for save cache file", file)); + return false; + } } - if (_polygonVao) { - glDeleteVertexArrays(1, &_polygonVao); + void RenderableBillboardsCloud::createDataSlice() { + _slicedData.clear(); + if (_hasColorMapFile) { + _slicedData.reserve(8 * (_fullData.size() / _nValuesPerAstronomicalObject)); + } + else { + _slicedData.reserve(4 * (_fullData.size() / _nValuesPerAstronomicalObject)); + } + + // Generate the color bins for the colomap + int colorMapInUse = 0; + std::vector colorBins; + if (_hasColorMapFile) { + colorMapInUse = _variableDataPositionMap[_colorOptionString]; + glm::vec2 currentColorRange = _colorRangeData[_colorOption.value()]; + float colorMapBinSize = (currentColorRange.y - currentColorRange.x) / + static_cast(_colorMapData.size()); + float bin = colorMapBinSize; + for (size_t i = 0; i < _colorMapData.size(); ++i) { + colorBins.push_back(bin); + bin += colorMapBinSize; + } + } + + float biggestCoord = -1.0f; + for (size_t i = 0; i < _fullData.size(); i += _nValuesPerAstronomicalObject) { + glm::dvec4 transformedPos = _transformationMatrix * glm::dvec4( + _fullData[i + 0], + _fullData[i + 1], + _fullData[i + 2], + 1.0 + ); + glm::vec4 position(glm::vec3(transformedPos), static_cast(_unit)); + + if (_hasColorMapFile) { + for (auto j = 0; j < 4; ++j) { + _slicedData.push_back(position[j]); + biggestCoord = biggestCoord < position[j] ? position[j] : biggestCoord; + } + // Finds from which bin to get the color. + // Note: the first color in the colormap file + // is the outliers color. + glm::vec4 itemColor; + float variableColor = _fullData[i + 3 + colorMapInUse]; + int c = static_cast(colorBins.size() - 1); + while (variableColor < colorBins[c]) { + --c; + if (c == 0) + break; + } + + int colorIndex = + c == static_cast(colorBins.size() - 1) ? + 0 : + c + 1; + + for (auto j = 0; j < 4; ++j) { + _slicedData.push_back(_colorMapData[colorIndex][j]); + } + } + else { + for (auto j = 0; j < 4; ++j) { + _slicedData.push_back(position[j]); + } + } + } + _fadeInDistance.setMaxValue(glm::vec2(10.0f * biggestCoord)); } - glDeleteFramebuffers(1, &textureFBO); -} -void RenderableBillboardsCloud::loadPolygonGeometryForRendering() { - glGenVertexArrays(1, &_polygonVao); - glGenBuffers(1, &_polygonVbo); - glBindVertexArray(_polygonVao); - glBindBuffer(GL_ARRAY_BUFFER, _polygonVbo); + void RenderableBillboardsCloud::createPolygonTexture() { + LDEBUG("Creating Polygon Texture"); - const GLfloat vertex_data[] = { - // x y z w - 0.0f, 0.0f, 0.0f, 1.0f, - }; + glGenTextures(1, &_pTexture); + glBindTexture(GL_TEXTURE_2D, _pTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, + 256, 0, GL_RGBA, GL_BYTE, nullptr); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 4, - nullptr - ); - glEnableVertexAttribArray(0); - glBindVertexArray(0); -} + renderToTexture( + std::bind( + &openspace::RenderableBillboardsCloud::loadPolygonGeometryForRendering, + this + ), + std::bind( + &openspace::RenderableBillboardsCloud::renderPolygonGeometry, + this, + std::placeholders::_1 + ), + _pTexture, + 256, + 256 + ); + } -void RenderableBillboardsCloud::renderPolygonGeometry(GLuint vao) { - _renderToPolygonProgram->activate(); - static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glClearBufferfv(GL_COLOR, 0, black); + void RenderableBillboardsCloud::renderToTexture( + std::function geometryLoadingFunction, + std::function renderFunction, + GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight) + { + LDEBUG("Rendering to Texture"); - _renderToPolygonProgram->setUniform("sides", _polygonSides); - _renderToPolygonProgram->setUniform("polygonColor", _pointColor); + // Saves initial Application's OpenGL State + GLint defaultFBO; + GLint viewport[4]; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); + glGetIntegerv(GL_VIEWPORT, viewport); - glBindVertexArray(vao); - glDrawArrays(GL_POINTS, 0, 1); - glBindVertexArray(0); + GLuint textureFBO; + glGenFramebuffers(1, &textureFBO); + glBindFramebuffer(GL_FRAMEBUFFER, textureFBO); + GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, drawBuffers); - _renderToPolygonProgram->deactivate(); -} + glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); + + glViewport(0, 0, textureWidth, textureHeight); + + geometryLoadingFunction(); + renderFunction(_polygonVao); + + // Restores Applications' OpenGL State + glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + + if (_polygonVbo) { + glDeleteBuffers(1, &_polygonVbo); + } + + if (_polygonVao) { + glDeleteVertexArrays(1, &_polygonVao); + } + glDeleteFramebuffers(1, &textureFBO); + } + + void RenderableBillboardsCloud::loadPolygonGeometryForRendering() { + glGenVertexArrays(1, &_polygonVao); + glGenBuffers(1, &_polygonVbo); + glBindVertexArray(_polygonVao); + glBindBuffer(GL_ARRAY_BUFFER, _polygonVbo); + + const GLfloat vertex_data[] = { + // x y z w + 0.0f, 0.0f, 0.0f, 1.0f, + }; + + glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 4, + nullptr + ); + glEnableVertexAttribArray(0); + glBindVertexArray(0); + } + + void RenderableBillboardsCloud::renderPolygonGeometry(GLuint vao) { + std::unique_ptr program = + ghoul::opengl::ProgramObject::Build("RenderableBillboardsCloud_Polygon", + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_vs.glsl"), + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_fs.glsl"), + absPath("${MODULE_DIGITALUNIVERSE}/shaders/billboardpolygon_gs.glsl") + ); + + program->activate(); + static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + glClearBufferfv(GL_COLOR, 0, black); + + program->setUniform("sides", _polygonSides); + program->setUniform("polygonColor", _pointColor); + + glBindVertexArray(vao); + glDrawArrays(GL_POINTS, 0, 1); + glBindVertexArray(0); + + program->deactivate(); + } } // namespace openspace diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.h b/modules/digitaluniverse/rendering/renderablebillboardscloud.h index 7a9db171a1..be3f2576f0 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.h +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.h @@ -1,26 +1,26 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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_MODULE_DIGITALUNIVERSE___RENDERABLEBILLBOARDSCLOUD___H__ #define __OPENSPACE_MODULE_DIGITALUNIVERSE___RENDERABLEBILLBOARDSCLOUD___H__ @@ -51,132 +51,134 @@ namespace ghoul::opengl { namespace openspace { -namespace documentation { struct Documentation; } + namespace documentation { struct Documentation; } -class RenderableBillboardsCloud : public Renderable { -public: - explicit RenderableBillboardsCloud(const ghoul::Dictionary& dictionary); - ~RenderableBillboardsCloud() = default; + class RenderableBillboardsCloud : public Renderable { + public: + explicit RenderableBillboardsCloud(const ghoul::Dictionary& dictionary); + ~RenderableBillboardsCloud() = default; - void initialize() override; - void initializeGL() override; - void deinitializeGL() override; + void initialize() override; + void initializeGL() override; + void deinitializeGL() override; - bool isReady() const override; + bool isReady() const override; - void render(const RenderData& data, RendererTasks& rendererTask) override; - void update(const UpdateData& data) override; + void render(const RenderData& data, RendererTasks& rendererTask) override; + void update(const UpdateData& data) override; - static documentation::Documentation Documentation(); + static documentation::Documentation Documentation(); -private: + private: - enum Unit { - Meter = 0, - Kilometer = 1, - Parsec = 2, - Kiloparsec = 3, - Megaparsec = 4, - Gigaparsec = 5, + enum Unit { + Meter = 0, + Kilometer = 1, + Parsec = 2, + Kiloparsec = 3, + Megaparsec = 4, + Gigaparsec = 5, - GigalightYears = 6 + GigalightYears = 6 + }; + + void createDataSlice(); + void createPolygonTexture(); + void renderToTexture(std::function geometryLoadingFunction, + std::function renderFunction, + GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight); + void loadPolygonGeometryForRendering(); + void renderPolygonGeometry(GLuint vao); + void renderBillboards(const RenderData& data, const glm::dmat4& modelMatrix, + const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); + void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, + const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); + + bool loadData(); + bool loadSpeckData(); + bool loadLabelData(); + bool readSpeckFile(); + bool readColorMapFile(); + bool readLabelFile(); + bool loadCachedFile(const std::string& file); + bool saveCachedFile(const std::string& file) const; + + bool _hasSpeckFile; + bool _dataIsDirty; + bool _textColorIsDirty; + bool _hasSpriteTexture; + bool _spriteTextureIsDirty; + bool _hasColorMapFile; + bool _hasPolygon; + bool _hasLabel; + bool _labelDataIsDirty; + + int _polygonSides; + + GLuint _pTexture; + + properties::FloatProperty _alphaValue; + properties::FloatProperty _scaleFactor; + properties::Vec3Property _pointColor; + properties::StringProperty _spriteTexturePath; + properties::Vec4Property _textColor; + properties::FloatProperty _textSize; + properties::FloatProperty _textMinSize; + properties::FloatProperty _textMaxSize; + properties::BoolProperty _drawElements; + properties::BoolProperty _drawLabels; + properties::OptionProperty _colorOption; + properties::Vec2Property _fadeInDistance; + properties::BoolProperty _disableFadeInDistance; + properties::FloatProperty _billboardMaxSize; + properties::FloatProperty _billboardMinSize; + properties::FloatProperty _correctionSizeEndDistance; + properties::FloatProperty _correctionSizeFactor; + + // DEBUG: + properties::OptionProperty _renderOption; + + + std::unique_ptr _polygonTexture; + std::unique_ptr _spriteTexture; + std::unique_ptr _spriteTextureFile; + //std::unique_ptr _program; + ghoul::opengl::ProgramObject* _program; + ghoul::opengl::ProgramObject* _renderToPolygonProgram; + UniformCache(modelViewMatrix, projectionMatrix, cameraViewProjectionMatrix, + modelMatrix, cameraPos, cameraLookup, renderOption, + minBillboardSize, maxBillboardSize, color, sides, alphaValue, + scaleFactor, up, right, fadeInValue, screenSize, + spriteTexture, polygonTexture, hasPolygon, hasColormap) _uniformCache; + std::shared_ptr _font; + + std::string _speckFile; + std::string _colorMapFile; + std::string _labelFile; + std::string _colorOptionString; + + Unit _unit; + + std::vector _slicedData; + std::vector _fullData; + std::vector _colorMapData; + std::vector> _labelData; + std::unordered_map _variableDataPositionMap; + std::unordered_map _optionConversionMap; + std::vector _colorRangeData; + + int _nValuesPerAstronomicalObject; + + glm::dmat4 _transformationMatrix; + + GLuint _vao; + GLuint _vbo; + + // For polygons + GLuint _polygonVao; + GLuint _polygonVbo; }; - void createDataSlice(); - void createPolygonTexture(); - void renderToTexture(std::function geometryLoadingFunction, - std::function renderFunction, - GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight); - void loadPolygonGeometryForRendering(); - void renderPolygonGeometry(GLuint vao); - void renderBillboards(const RenderData& data, const glm::dmat4& modelViewMatrix, - const glm::dmat4& worldToModelTransform, const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, float fadeInVariable); - void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, - const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); - - bool loadData(); - bool loadSpeckData(); - bool loadLabelData(); - bool readSpeckFile(); - bool readColorMapFile(); - bool readLabelFile(); - bool loadCachedFile(const std::string& file); - bool saveCachedFile(const std::string& file) const; - - bool _hasSpeckFile; - bool _dataIsDirty; - bool _textColorIsDirty; - bool _hasSpriteTexture; - bool _spriteTextureIsDirty; - bool _hasColorMapFile; - bool _hasPolygon; - bool _hasLabel; - bool _labelDataIsDirty; - - int _polygonSides; - - GLuint _pTexture; - - properties::FloatProperty _alphaValue; - properties::FloatProperty _scaleFactor; - properties::Vec3Property _pointColor; - properties::StringProperty _spriteTexturePath; - properties::Vec4Property _textColor; - properties::FloatProperty _textSize; - properties::FloatProperty _textMinSize; - properties::FloatProperty _textMaxSize; - properties::BoolProperty _drawElements; - properties::BoolProperty _drawLabels; - properties::OptionProperty _colorOption; - properties::Vec2Property _fadeInDistance; - properties::BoolProperty _disableFadeInDistance; - properties::FloatProperty _billboardMaxSize; - properties::FloatProperty _billboardMinSize; - - // DEBUG: - properties::OptionProperty _renderOption; - - - std::unique_ptr _polygonTexture; - std::unique_ptr _spriteTexture; - std::unique_ptr _spriteTextureFile; - ghoul::opengl::ProgramObject* _program; - ghoul::opengl::ProgramObject* _renderToPolygonProgram; - - UniformCache(modelViewProjection, cameraPos, cameraLookup, - renderOption, centerSceenInWorldPos, minBillboardSize, maxBillboardSize, - color, sides, alphaValue, scaleFactor, up, right, fadeInValue, screenSize, - spriteTexture, polygonTexture, hasPolygon, hasColormap) _uniformCache; - std::shared_ptr _font; - - std::string _speckFile; - std::string _colorMapFile; - std::string _labelFile; - std::string _colorOptionString; - - Unit _unit; - - std::vector _slicedData; - std::vector _fullData; - std::vector _colorMapData; - std::vector> _labelData; - std::unordered_map _variableDataPositionMap; - std::unordered_map _optionConversionMap; - std::vector _colorRangeData; - - int _nValuesPerAstronomicalObject; - - glm::dmat4 _transformationMatrix; - - GLuint _vao; - GLuint _vbo; - - // For polygons - GLuint _polygonVao; - GLuint _polygonVbo; -}; - } // namespace openspace diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 809c628a82..ccc7e29982 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -53,17 +53,18 @@ Fragment getFragment() { } fullColor.a *= fadeInValue * ta; - - if (fullColor.a == 0.f) { + + if (fullColor.a == 0.f || + fullColor.rgb == vec3(0.0)) { discard; } Fragment frag; frag.color = fullColor; frag.depth = vs_screenSpaceDepth; - frag.gPosition = vec4(1e32, 1e32, 1e32, 1.0); + frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); return frag; -} +} \ No newline at end of file diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index af5b7acc9f..3cf72c0edf 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -27,21 +27,26 @@ #include "PowerScaling/powerScalingMath.hglsl" layout(points) in; -layout(triangle_strip, max_vertices = 6) out; +layout(triangle_strip, max_vertices = 4) out; -//uniform dmat4 transformMatrix; -uniform dmat4 modelViewProjectionTransform; uniform float scaleFactor; -uniform dvec3 up; +uniform dvec3 up; uniform dvec3 right; -uniform dvec3 cameraPosition; -uniform dvec3 cameraLookUp; -uniform dvec4 centerScreenInWorldPosition; +uniform dvec3 cameraPosition; // in world space (no SGCT View was considered) +uniform dvec3 cameraLookUp; // in world space (no SGCT View was considered) uniform int renderOption; uniform vec2 screenSize; uniform float maxBillboardSize; uniform float minBillboardSize; +uniform dmat4 modelViewMatrix; +uniform dmat4 projectionMatrix; +uniform dmat4 cameraViewProjectionMatrix; +uniform dmat4 modelMatrix; + +uniform float correctionSizeFactor; +uniform float correctionSizeEndDistance; + in vec4 colorMap[]; out vec4 gs_colorMap; @@ -60,30 +65,9 @@ const vec2 corners[4] = vec2[4]( void main() { - ta = 1.0f; - vec4 pos = gl_in[0].gl_Position; + ta = 1.0f; + vec4 pos = gl_in[0].gl_Position; // in object space gs_colorMap = colorMap[0]; - - double scaleMultiply = exp(scaleFactor/10); - dvec3 scaledRight = dvec3(0.0); - dvec3 scaledUp = dvec3(0.0); - - if (renderOption == 0) { - scaledRight = scaleMultiply * right/2.0f; - scaledUp = scaleMultiply * up/2.0f; - } else if (renderOption == 1) { - dvec3 normal = normalize(cameraPosition - dvec3(pos.xyz)); - dvec3 newRight = normalize(cross(cameraLookUp, normal)); - dvec3 newUp = cross(normal, newRight); - scaledRight = scaleMultiply * newRight/2.0f; - scaledUp = scaleMultiply * newUp/2.0f; - } else if (renderOption == 2) { - dvec3 normal = normalize(centerScreenInWorldPosition.xyz - dvec3(pos.xyz)); - dvec3 newRight = normalize(cross(cameraLookUp, normal)); - dvec3 newUp = cross(normal, newRight); - scaledRight = scaleMultiply * newRight/2.0f; - scaledUp = scaleMultiply * newUp/2.0f; - } double unit = PARSEC; @@ -101,91 +85,90 @@ void main() { } else if (pos.w == 6.f) { unit = 306391534.73091 * PARSEC; } - - //dvec4 dpos = transformMatrix * dvec4(dvec3(pos.xyz) * unit, 1.0); - dvec4 dpos = dvec4(dvec3(pos.xyz) * unit, 1.0); - // texCoord = corners[0]; - vec4 initialPosition = z_normalization(vec4(modelViewProjectionTransform * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - vs_screenSpaceDepth = initialPosition.w; + dvec4 dpos = dvec4(dvec3(pos.xyz) * unit, 1.0); + dpos = modelMatrix * dpos; + + double scaleMultiply = exp(scaleFactor * 0.10); + dvec3 scaledRight = dvec3(0.0); + dvec3 scaledUp = dvec3(0.0); + vec4 initialPosition, secondPosition, thirdPosition, crossCorner; + + if (renderOption == 0) { + scaledRight = scaleMultiply * right * 0.5f; + scaledUp = scaleMultiply * up * 0.5f; + } else if (renderOption == 1) { + dvec3 normal = normalize(cameraPosition - dpos.xyz); + dvec3 newRight = normalize(cross(cameraLookUp, normal)); + dvec3 newUp = cross(normal, newRight); + + double distCamera = length(cameraPosition - dpos.xyz); + float expVar = float(-distCamera) / pow(10.f, correctionSizeEndDistance); + double factorVar = double(pow(10, correctionSizeFactor)); + scaleMultiply *= 1.0 / (1.0 + factorVar * double(exp(expVar))); + + scaledRight = scaleMultiply * newRight * 0.5f; + scaledUp = scaleMultiply * newUp * 0.5f; + } - // texCoord = corners[1]; - vec4 secondPosition = z_normalization(vec4(modelViewProjectionTransform * - dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - - //texCoord = corners[2]; - vec4 crossCorner = z_normalization(vec4(modelViewProjectionTransform * + initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + vs_screenSpaceDepth = initialPosition.w; + crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - // texCoord = corners[3]; - vec4 thirdPosition = z_normalization(vec4(modelViewProjectionTransform * - dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); + // Testing size for rectangular viewport: + vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; + vec2 topRight = crossCorner.xy/crossCorner.w; + vec2 bottomLeft = initialPosition.xy/initialPosition.w; - // Testing size: - vec4 topRight = secondPosition/secondPosition.w; - topRight = ((topRight + vec4(1.0)) / vec4(2.0)) * vec4(screenSize.x, screenSize.y, 1.0, 1.0); - vec4 bottomLeft = initialPosition/initialPosition.w; - bottomLeft = ((bottomLeft + vec4(1.0)) / vec4(2.0)) * vec4(screenSize.x, screenSize.y, 1.0, 1.0); + // width and height + vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); + + bool rectangularViewPort = false; + if (rectangularViewPort && ((sizes.y > maxBillboardSize) || + (sizes.x > maxBillboardSize))) { + //Set maximum size as Carter's instructions + float correctionScale = sizes.y > maxBillboardSize ? maxBillboardSize / sizes.y : + maxBillboardSize / sizes.x; + + scaledRight *= correctionScale; + scaledUp *= correctionScale; + + } else { + if (sizes.x < 2.0f * minBillboardSize) { + float maxVar = 2.0f * minBillboardSize; + float minVar = minBillboardSize; + float var = (sizes.y + sizes.x); + ta = ( (var - minVar)/(maxVar - minVar) ); + if (ta == 0.0f) + return; + } + } - float height = abs(topRight.y - bottomLeft.y); - float width = abs(topRight.x - bottomLeft.x); - float var = (height + width); - - if ((height > maxBillboardSize) || - (width > maxBillboardSize)) { - - // Set maximum size as Carter's instructions - float correctionScale = height > maxBillboardSize ? maxBillboardSize / (topRight.y - bottomLeft.y) : - maxBillboardSize / (topRight.x - bottomLeft.x); - - scaledRight = correctionScale * scaleMultiply * right/2.0f; - scaledUp = correctionScale * scaleMultiply * up/2.0f; - initialPosition = z_normalization(vec4(modelViewProjectionTransform * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - vs_screenSpaceDepth = initialPosition.w; - secondPosition = z_normalization(vec4(modelViewProjectionTransform * + initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - crossCorner = z_normalization(vec4(modelViewProjectionTransform * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - thirdPosition = z_normalization(vec4(modelViewProjectionTransform * + crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + thirdPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); - // Fade-out - // float maxVar = 2.0f * maxBillboardSize; - // float minVar = maxBillboardSize; - // ta = 1.0f - ( (var - minVar)/(maxVar - minVar) ); - // if (ta == 0.0f) - // return; - } - else if (width < 2.0f * minBillboardSize) { - //return; - float maxVar = 2.0f * minBillboardSize; - float minVar = minBillboardSize; - ta = ( (var - minVar)/(maxVar - minVar) ); - if (ta == 0.0f) - return; - } - + // Build primitive + texCoord = corners[3]; + gl_Position = thirdPosition; + EmitVertex(); texCoord = corners[0]; gl_Position = initialPosition; EmitVertex(); + texCoord = corners[2]; + gl_Position = crossCorner; + EmitVertex(); texCoord = corners[1]; gl_Position = secondPosition; EmitVertex(); - texCoord = corners[2]; - gl_Position = crossCorner; - EmitVertex(); - EndPrimitive(); // First Triangle - texCoord = corners[0]; - gl_Position = initialPosition; - EmitVertex(); - texCoord = corners[2]; - gl_Position = crossCorner; - EmitVertex(); - texCoord = corners[3]; - gl_Position = thirdPosition; - EmitVertex(); - EndPrimitive(); // Second Triangle -} + EndPrimitive(); + +} \ No newline at end of file diff --git a/openspace.cfg b/openspace.cfg index d2c01f1da4..76279a8449 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -15,7 +15,7 @@ SGCTConfig = sgct.config.single{} -- SGCTConfig = sgct.config.single{1920, 1080, border=false, windowPos={0,0}, shared=true, name="WV_OBS_SPOUT1"} -- A 1k fisheye rendering --- SGCTConfig = sgct.config.fisheye{1024, 1024} +SGCTConfig = sgct.config.fisheye{1024, 1024} -- A 4k fisheye rendering in a 1024x1024 window -- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} From fca8e7f46b3a2d5c6d695bad21219f2e173ff1ab Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sat, 21 Apr 2018 16:38:24 -0400 Subject: [PATCH 65/79] Refined new size control and added possibility to change control size system. --- .../rendering/renderablebillboardscloud.cpp | 66 ++++++++++------ .../rendering/renderablebillboardscloud.h | 14 ++-- .../digitaluniverse/shaders/billboard_gs.glsl | 78 ++++++++++--------- 3 files changed, 95 insertions(+), 63 deletions(-) diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index 144008ab71..54ba7d2eab 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -208,16 +208,21 @@ namespace { }; static const openspace::properties::Property::PropertyInfo CorrectionSizeEndDistanceInfo = { - "CorrectionSizeEndDistanceInfo", + "CorrectionSizeEndDistance", "Distance in 10^X meters where correction size stops acting.", "Distance in 10^X meters where correction size stops acting." }; static const openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { - "CorrectionSizeFactorInfo", + "CorrectionSizeFactor", "Control variable for distance size.", "" }; + static const openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { + "EnablePixelSizeControl", + "Enable pixel size control.", + "Enable pixel size control for rectangular projections." + }; } // namespace namespace openspace { @@ -365,6 +370,12 @@ namespace openspace { new DoubleVerifier, Optional::Yes, CorrectionSizeFactorInfo.description + }, + { + PixelSizeControlInfo.identifier, + new BoolVerifier, + Optional::Yes, + PixelSizeControlInfo.description } } }; @@ -404,6 +415,7 @@ namespace openspace { , _textMaxSize(LabelMaxSizeInfo, 500.0, 0.0, 1000.0) , _drawElements(DrawElementsInfo, true) , _drawLabels(DrawLabelInfo, false) + , _pixelSizeControl(PixelSizeControlInfo, false) , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _fadeInDistance( FadeInDistancesInfo, @@ -414,8 +426,8 @@ namespace openspace { , _disableFadeInDistance(DisableFadeInInfo, true) , _billboardMaxSize(BillboardMaxSizeInfo, 400.0, 0.0, 1000.0) , _billboardMinSize(BillboardMinSizeInfo, 0.0, 0.0, 100.0) - , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17, 0.0, 30) - , _correctionSizeFactor(CorrectionSizeFactorInfo, 8, 0.0, 15) + , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17.0, 12.0, 25.0) + , _correctionSizeFactor(CorrectionSizeFactorInfo, 8, 0.0, 20.0) , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) , _polygonTexture(nullptr) , _spriteTexture(nullptr) @@ -647,6 +659,11 @@ namespace openspace { ); } addProperty(_correctionSizeFactor); + + if (dictionary.hasKey(PixelSizeControlInfo.identifier)) { + _pixelSizeControl = dictionary.value(PixelSizeControlInfo.identifier); + } + addProperty(_pixelSizeControl); } bool RenderableBillboardsCloud::isReady() const { @@ -708,22 +725,25 @@ namespace openspace { "modelMatrix" ); - _uniformCache.cameraPos = _program->uniformLocation("cameraPosition"); - _uniformCache.cameraLookup = _program->uniformLocation("cameraLookUp"); - _uniformCache.renderOption = _program->uniformLocation("renderOption"); - _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); - _uniformCache.maxBillboardSize = _program->uniformLocation("maxBillboardSize"); - _uniformCache.color = _program->uniformLocation("color"); - _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); - _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); - _uniformCache.up = _program->uniformLocation("up"); - _uniformCache.right = _program->uniformLocation("right"); - _uniformCache.fadeInValue = _program->uniformLocation("fadeInValue"); - _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.spriteTexture = _program->uniformLocation("spriteTexture"); - _uniformCache.polygonTexture = _program->uniformLocation("polygonTexture"); - _uniformCache.hasPolygon = _program->uniformLocation("hasPolygon"); - _uniformCache.hasColormap = _program->uniformLocation("hasColorMap"); + _uniformCache.cameraPos = _program->uniformLocation("cameraPosition"); + _uniformCache.cameraLookup = _program->uniformLocation("cameraLookUp"); + _uniformCache.renderOption = _program->uniformLocation("renderOption"); + _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.maxBillboardSize = _program->uniformLocation("maxBillboardSize"); + _uniformCache.correctionSizeEndDistance = _program->uniformLocation("correctionSizeEndDistance"); + _uniformCache.correctionSizeFactor = _program->uniformLocation("correctionSizeFactor"); + _uniformCache.color = _program->uniformLocation("color"); + _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); + _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); + _uniformCache.up = _program->uniformLocation("up"); + _uniformCache.right = _program->uniformLocation("right"); + _uniformCache.fadeInValue = _program->uniformLocation("fadeInValue"); + _uniformCache.screenSize = _program->uniformLocation("screenSize"); + _uniformCache.spriteTexture = _program->uniformLocation("spriteTexture"); + _uniformCache.polygonTexture = _program->uniformLocation("polygonTexture"); + _uniformCache.hasPolygon = _program->uniformLocation("hasPolygon"); + _uniformCache.hasColormap = _program->uniformLocation("hasColorMap"); + _uniformCache.enabledRectSizeControl = _program->uniformLocation("enabledRectSizeControl"); if (_hasPolygon) { createPolygonTexture(); @@ -824,8 +844,10 @@ namespace openspace { _program->setUniform(_uniformCache.right, orthoRight); _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); - _program->setUniform("correctionSizeEndDistance", _correctionSizeEndDistance); - _program->setUniform("correctionSizeFactor", _correctionSizeFactor); + _program->setUniform(_uniformCache.correctionSizeEndDistance, _correctionSizeEndDistance); + _program->setUniform(_uniformCache.correctionSizeFactor, _correctionSizeFactor); + + _program->setUniform(_uniformCache.enabledRectSizeControl, _pixelSizeControl); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.h b/modules/digitaluniverse/rendering/renderablebillboardscloud.h index be3f2576f0..3b9dd38c3c 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.h +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.h @@ -127,6 +127,7 @@ namespace openspace { properties::FloatProperty _textMaxSize; properties::BoolProperty _drawElements; properties::BoolProperty _drawLabels; + properties::BoolProperty _pixelSizeControl; properties::OptionProperty _colorOption; properties::Vec2Property _fadeInDistance; properties::BoolProperty _disableFadeInDistance; @@ -145,11 +146,14 @@ namespace openspace { //std::unique_ptr _program; ghoul::opengl::ProgramObject* _program; ghoul::opengl::ProgramObject* _renderToPolygonProgram; - UniformCache(modelViewMatrix, projectionMatrix, cameraViewProjectionMatrix, - modelMatrix, cameraPos, cameraLookup, renderOption, - minBillboardSize, maxBillboardSize, color, sides, alphaValue, - scaleFactor, up, right, fadeInValue, screenSize, - spriteTexture, polygonTexture, hasPolygon, hasColormap) _uniformCache; + UniformCache( + modelViewMatrix, projectionMatrix, cameraViewProjectionMatrix, + modelMatrix, cameraPos, cameraLookup, renderOption, minBillboardSize, + maxBillboardSize, correctionSizeEndDistance, correctionSizeFactor, + color, sides, alphaValue, scaleFactor, up, right, fadeInValue, screenSize, + spriteTexture, polygonTexture, hasPolygon, hasColormap, + enabledRectSizeControl + ) _uniformCache; std::shared_ptr _font; std::string _speckFile; diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index 3cf72c0edf..e7f2311dae 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -47,6 +47,8 @@ uniform dmat4 modelMatrix; uniform float correctionSizeFactor; uniform float correctionSizeEndDistance; +uniform bool enabledRectSizeControl; + in vec4 colorMap[]; out vec4 gs_colorMap; @@ -102,50 +104,54 @@ void main() { dvec3 newRight = normalize(cross(cameraLookUp, normal)); dvec3 newUp = cross(normal, newRight); - double distCamera = length(cameraPosition - dpos.xyz); - float expVar = float(-distCamera) / pow(10.f, correctionSizeEndDistance); - double factorVar = double(pow(10, correctionSizeFactor)); - scaleMultiply *= 1.0 / (1.0 + factorVar * double(exp(expVar))); - + if (!enabledRectSizeControl) { + double distCamera = length(cameraPosition - dpos.xyz); + float expVar = float(-distCamera) / pow(10.f, correctionSizeEndDistance); + double factorVar = double(pow(10, correctionSizeFactor)); + scaleMultiply *= 1.0 / (1.0 + factorVar * double(exp(expVar))); + } + scaledRight = scaleMultiply * newRight * 0.5f; scaledUp = scaleMultiply * newUp * 0.5f; } - initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * + if (enabledRectSizeControl) { + initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - vs_screenSpaceDepth = initialPosition.w; - crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - - // Testing size for rectangular viewport: - vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; - vec2 topRight = crossCorner.xy/crossCorner.w; - vec2 bottomLeft = initialPosition.xy/initialPosition.w; - - // width and height - vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); - - bool rectangularViewPort = false; - if (rectangularViewPort && ((sizes.y > maxBillboardSize) || - (sizes.x > maxBillboardSize))) { - //Set maximum size as Carter's instructions - float correctionScale = sizes.y > maxBillboardSize ? maxBillboardSize / sizes.y : - maxBillboardSize / sizes.x; + vs_screenSpaceDepth = initialPosition.w; + crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - scaledRight *= correctionScale; - scaledUp *= correctionScale; - - } else { - if (sizes.x < 2.0f * minBillboardSize) { - float maxVar = 2.0f * minBillboardSize; - float minVar = minBillboardSize; - float var = (sizes.y + sizes.x); - ta = ( (var - minVar)/(maxVar - minVar) ); - if (ta == 0.0f) - return; + // Testing size for rectangular viewport: + vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; + vec2 topRight = crossCorner.xy/crossCorner.w; + vec2 bottomLeft = initialPosition.xy/initialPosition.w; + + // width and height + vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); + + bool rectangularViewPort = false; + if (rectangularViewPort && ((sizes.y > maxBillboardSize) || + (sizes.x > maxBillboardSize))) { + //Set maximum size as Carter's instructions + float correctionScale = sizes.y > maxBillboardSize ? maxBillboardSize / sizes.y : + maxBillboardSize / sizes.x; + + scaledRight *= correctionScale; + scaledUp *= correctionScale; + + } else { + if (sizes.x < 2.0f * minBillboardSize) { + float maxVar = 2.0f * minBillboardSize; + float minVar = minBillboardSize; + float var = (sizes.y + sizes.x); + ta = ( (var - minVar)/(maxVar - minVar) ); + if (ta == 0.0f) + return; + } } } - + initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * From 7ca335a32403793aa75078cd0f79c797fc2442cd Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sat, 21 Apr 2018 16:38:54 -0400 Subject: [PATCH 66/79] New size control configurations for a few assets. --- data/assets/scene/digitaluniverse/2mass.asset | 2 ++ data/assets/scene/digitaluniverse/dwarfs.asset | 2 ++ data/assets/scene/digitaluniverse/exoplanets.asset | 2 ++ data/assets/scene/digitaluniverse/kepler.asset | 2 ++ data/assets/scene/digitaluniverse/sdss.asset | 2 ++ data/assets/scene/digitaluniverse/supernovaremnants.asset | 2 ++ data/assets/scene/digitaluniverse/tully.asset | 2 ++ openspace.cfg | 6 +++--- 8 files changed, 17 insertions(+), 3 deletions(-) diff --git a/data/assets/scene/digitaluniverse/2mass.asset b/data/assets/scene/digitaluniverse/2mass.asset index 3247753ba5..ab68580372 100644 --- a/data/assets/scene/digitaluniverse/2mass.asset +++ b/data/assets/scene/digitaluniverse/2mass.asset @@ -29,6 +29,8 @@ local object = { ColorOption = { "redshift", "prox5Mpc" }, ColorRange = { { 0.0, 0.075 }, { 1.0, 50.0 } }, Unit = "Mpc", + CorrectionSizeEndDistance = 20.6, + CorrectionSizeFactor = 15.0, ScaleFactor = 508.0 }, GUI = { diff --git a/data/assets/scene/digitaluniverse/dwarfs.asset b/data/assets/scene/digitaluniverse/dwarfs.asset index d0e4bf6e18..8bec8ceaf7 100644 --- a/data/assets/scene/digitaluniverse/dwarfs.asset +++ b/data/assets/scene/digitaluniverse/dwarfs.asset @@ -30,6 +30,8 @@ local object = { TextSize = 14.6, TextMinSize = 10.0, ScaleFactor = 360, + CorrectionSizeEndDistance = 16.1, + CorrectionSizeFactor = 7.75, Unit = "pc" }, GUI = { diff --git a/data/assets/scene/digitaluniverse/exoplanets.asset b/data/assets/scene/digitaluniverse/exoplanets.asset index a482e8674d..4e47c7bb9f 100644 --- a/data/assets/scene/digitaluniverse/exoplanets.asset +++ b/data/assets/scene/digitaluniverse/exoplanets.asset @@ -32,6 +32,8 @@ local object = { TextSize = 14.8, TextMaxSize = 200.0, TextMinSize = 10.0, + CorrectionSizeEndDistance = 15.23, + CorrectionSizeFactor = 13.3, Unit = "pc" }, GUI = { diff --git a/data/assets/scene/digitaluniverse/kepler.asset b/data/assets/scene/digitaluniverse/kepler.asset index a6c9d28cdc..e541ec7a87 100644 --- a/data/assets/scene/digitaluniverse/kepler.asset +++ b/data/assets/scene/digitaluniverse/kepler.asset @@ -26,6 +26,8 @@ local object = { ScaleFactor = 395.0, File = speck .. "/kepler.speck", Texture = textures .. "/halo.png", + CorrectionSizeEndDistance = 15.86, + CorrectionSizeFactor = 8.59, Unit = "pc" }, GUI = { diff --git a/data/assets/scene/digitaluniverse/sdss.asset b/data/assets/scene/digitaluniverse/sdss.asset index bf3df4dba7..03829710cc 100644 --- a/data/assets/scene/digitaluniverse/sdss.asset +++ b/data/assets/scene/digitaluniverse/sdss.asset @@ -34,6 +34,8 @@ local object = { FadeInDistances = { 220.0, 650.0 }, BillboardMaxSize = 50.0, BillboardMinSize = 0.0, + CorrectionSizeEndDistance = 20.65, + CorrectionSizeFactor = 10.41, TextSize = 14.8, TextMinSize = 10.0, TextMaxSize = 50.0 diff --git a/data/assets/scene/digitaluniverse/supernovaremnants.asset b/data/assets/scene/digitaluniverse/supernovaremnants.asset index a010f4e6fa..783a7a48ea 100644 --- a/data/assets/scene/digitaluniverse/supernovaremnants.asset +++ b/data/assets/scene/digitaluniverse/supernovaremnants.asset @@ -31,6 +31,8 @@ local object = { ScaleFactor = 440.08, TextSize = 17.5, TextMinSize = 8.0, + CorrectionSizeEndDistance = 17.5, + CorrectionSizeFactor = 13.96, Unit = "pc" }, GUI = { diff --git a/data/assets/scene/digitaluniverse/tully.asset b/data/assets/scene/digitaluniverse/tully.asset index b1ae788a5d..e3f5213edb 100644 --- a/data/assets/scene/digitaluniverse/tully.asset +++ b/data/assets/scene/digitaluniverse/tully.asset @@ -45,6 +45,8 @@ local tullyPoints = { -- Max size in pixels BillboardMaxSize = 50.0, BillboardMinSize = 0.0, + CorrectionSizeEndDistance = 20.55, + CorrectionSizeFactor = 10.45, }, GUI = { Name = "Tully Galaxies", diff --git a/openspace.cfg b/openspace.cfg index 76279a8449..05511d9627 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -15,7 +15,7 @@ SGCTConfig = sgct.config.single{} -- SGCTConfig = sgct.config.single{1920, 1080, border=false, windowPos={0,0}, shared=true, name="WV_OBS_SPOUT1"} -- A 1k fisheye rendering -SGCTConfig = sgct.config.fisheye{1024, 1024} +-- SGCTConfig = sgct.config.fisheye{1024, 1024} -- A 4k fisheye rendering in a 1024x1024 window -- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} @@ -25,8 +25,8 @@ SGCTConfig = sgct.config.fisheye{1024, 1024} -- SGCTConfig = "${CONFIG}/spout_output.xml" ---SGCTConfig = "${CONFIG}/openvr_oculusRiftCv1.xml" ---SGCTConfig = "${CONFIG}/openvr_htcVive.xml" +-- SGCTConfig = "${CONFIG}/openvr_oculusRiftCv1.xml" +-- SGCTConfig = "${CONFIG}/openvr_htcVive.xml" -- Sets the scene that is to be loaded by OpenSpace. A scene file is a description -- of all entities that will be visible during an instance of OpenSpace From a5108db4057ad3d3b40cfaf0e785a84f4cb86479 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sat, 21 Apr 2018 16:45:19 -0400 Subject: [PATCH 67/79] Removed unused transformations. --- .../rendering/renderablebillboardscloud.cpp | 10 ---------- .../rendering/renderablebillboardscloud.h | 11 +++++------ modules/digitaluniverse/shaders/billboard_gs.glsl | 10 ++++------ 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index 54ba7d2eab..3e5441d5af 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -709,14 +709,6 @@ namespace openspace { } ); - _uniformCache.modelViewMatrix = _program->uniformLocation( - "modelViewMatrix" - ); - - _uniformCache.projectionMatrix = _program->uniformLocation( - "projectionMatrix" - ); - _uniformCache.cameraViewProjectionMatrix = _program->uniformLocation( "cameraViewProjectionMatrix" ); @@ -830,8 +822,6 @@ namespace openspace { _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); _program->setUniform(_uniformCache.cameraLookup, data.camera.lookUpVectorWorldSpace()); _program->setUniform(_uniformCache.renderOption, _renderOption.value()); - _program->setUniform(_uniformCache.modelViewMatrix, data.camera.combinedViewMatrix() * modelMatrix); - _program->setUniform(_uniformCache.projectionMatrix, glm::dmat4(data.camera.projectionMatrix())); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform(_uniformCache.cameraViewProjectionMatrix, glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix()); diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.h b/modules/digitaluniverse/rendering/renderablebillboardscloud.h index 3b9dd38c3c..5d74509ef3 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.h +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.h @@ -147,12 +147,11 @@ namespace openspace { ghoul::opengl::ProgramObject* _program; ghoul::opengl::ProgramObject* _renderToPolygonProgram; UniformCache( - modelViewMatrix, projectionMatrix, cameraViewProjectionMatrix, - modelMatrix, cameraPos, cameraLookup, renderOption, minBillboardSize, - maxBillboardSize, correctionSizeEndDistance, correctionSizeFactor, - color, sides, alphaValue, scaleFactor, up, right, fadeInValue, screenSize, - spriteTexture, polygonTexture, hasPolygon, hasColormap, - enabledRectSizeControl + cameraViewProjectionMatrix, modelMatrix, cameraPos, cameraLookup, + renderOption, minBillboardSize, maxBillboardSize, correctionSizeEndDistance, + correctionSizeFactor, color, sides, alphaValue, scaleFactor, up, right, + fadeInValue, screenSize, spriteTexture, polygonTexture, hasPolygon, + hasColormap, enabledRectSizeControl ) _uniformCache; std::shared_ptr _font; diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index e7f2311dae..0b0dd8a514 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -39,8 +39,6 @@ uniform vec2 screenSize; uniform float maxBillboardSize; uniform float minBillboardSize; -uniform dmat4 modelViewMatrix; -uniform dmat4 projectionMatrix; uniform dmat4 cameraViewProjectionMatrix; uniform dmat4 modelMatrix; @@ -130,12 +128,12 @@ void main() { // width and height vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); - bool rectangularViewPort = false; - if (rectangularViewPort && ((sizes.y > maxBillboardSize) || + if (enabledRectSizeControl && ((sizes.y > maxBillboardSize) || (sizes.x > maxBillboardSize))) { //Set maximum size as Carter's instructions - float correctionScale = sizes.y > maxBillboardSize ? maxBillboardSize / sizes.y : - maxBillboardSize / sizes.x; + float correctionScale = + sizes.y > maxBillboardSize ? maxBillboardSize / sizes.y : + maxBillboardSize / sizes.x; scaledRight *= correctionScale; scaledUp *= correctionScale; From a881eef15634b993b1f5f278bea89e5cbbdbc6b6 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sun, 22 Apr 2018 09:15:42 +0000 Subject: [PATCH 68/79] Cleanup in Renderers --- include/openspace/rendering/abufferrenderer.h | 9 +- .../openspace/rendering/framebufferrenderer.h | 9 +- include/openspace/rendering/renderer.h | 5 +- modules/base/shaders/texture_clean_fs.glsl | 31 -- modules/base/shaders/texture_clean_vs.glsl | 31 -- shaders/blending.glsl | 17 +- shaders/floatoperations.glsl | 22 +- shaders/framebuffer/hdrBackground.frag | 6 +- shaders/framebuffer/nOneStripMSAA.frag | 2 +- shaders/framebuffer/nOneStripMSAA.vert | 4 +- shaders/framebuffer/pixelSizeMSAA.frag | 4 +- shaders/framebuffer/raycastframebuffer.frag | 3 - shaders/hdr.glsl | 57 ++-- src/rendering/abufferrenderer.cpp | 269 ++++++++---------- src/rendering/framebufferrenderer.cpp | 234 +++++++-------- src/rendering/renderengine.cpp | 15 +- 16 files changed, 287 insertions(+), 431 deletions(-) delete mode 100644 modules/base/shaders/texture_clean_fs.glsl delete mode 100644 modules/base/shaders/texture_clean_vs.glsl diff --git a/include/openspace/rendering/abufferrenderer.h b/include/openspace/rendering/abufferrenderer.h index 4dd87d6448..6ea55bace4 100644 --- a/include/openspace/rendering/abufferrenderer.h +++ b/include/openspace/rendering/abufferrenderer.h @@ -45,7 +45,7 @@ namespace ghoul::filesystem { class File; } namespace ghoul::opengl { class ProgramObject; class Texture; -} // namespace opengl +} // namespace ghoul::opengl namespace openspace { @@ -61,8 +61,6 @@ public: void initialize() override; void deinitialize() override; - void setCamera(Camera* camera) override; - void setScene(Scene* scene) override; void setResolution(glm::ivec2 res) override; void setNAaSamples(int nAaSamples) override; void setHDRExposure(float hdrExposure) override; @@ -79,7 +77,8 @@ public: void postRaycast(const RaycasterTask& raycasterTask); void update() override; - void render(float blackoutFactor, bool doPerformanceMeasurements) override; + void render(Scene* scene, Camera* camera, float blackoutFactor, + bool doPerformanceMeasurements) override; /** * Update render data @@ -97,8 +96,6 @@ private: void saveTextureToMemory(const GLenum color_buffer_attachment, const int width, const int height, std::vector & memory) const; - Camera* _camera; - Scene* _scene; glm::ivec2 _resolution; bool _dirtyResolution; diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 66fc0801f0..066adb731f 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -44,7 +44,7 @@ namespace ghoul::filesystem { class File; } namespace ghoul::opengl { class ProgramObject; class Texture; -} +} // namespace ghoul::opengl namespace openspace { @@ -67,8 +67,6 @@ public: void updateHDRData(); void updateMSAASamplingPattern(); - void setCamera(Camera* camera) override; - void setScene(Scene* scene) override; void setResolution(glm::ivec2 res) override; void setNAaSamples(int nAaSamples) override; void setHDRExposure(float hdrExposure) override; @@ -81,7 +79,8 @@ public: std::vector mSSAPattern() const override; void update() override; - void render(float blackoutFactor, bool doPerformanceMeasurements) override; + void render(Scene* scene, Camera* camera, float blackoutFactor, + bool doPerformanceMeasurements) override; /** * Update render data @@ -132,8 +131,6 @@ private: bool _dirtyRaycastData; bool _dirtyResolution; - Camera* _camera; - Scene* _scene; glm::vec2 _resolution; int _nAaSamples; float _hdrExposure; diff --git a/include/openspace/rendering/renderer.h b/include/openspace/rendering/renderer.h index 9a12b23b44..7814bd7136 100644 --- a/include/openspace/rendering/renderer.h +++ b/include/openspace/rendering/renderer.h @@ -52,8 +52,6 @@ public: virtual void initialize() = 0; virtual void deinitialize() = 0; - virtual void setCamera(Camera* camera) = 0; - virtual void setScene(Scene* scene) = 0; virtual void setResolution(glm::ivec2 res) = 0; virtual void setNAaSamples(int nAaSamples) = 0; virtual void setHDRExposure(float hdrExposure) = 0; @@ -77,7 +75,8 @@ public: virtual void update() = 0; - virtual void render(float blackoutFactor, bool doPerformanceMeasurements) = 0; + virtual void render(Scene* scene, Camera* camera, float blackoutFactor, + bool doPerformanceMeasurements) = 0; /** * Update render data * Responsible for calling renderEngine::setRenderData diff --git a/modules/base/shaders/texture_clean_fs.glsl b/modules/base/shaders/texture_clean_fs.glsl deleted file mode 100644 index 64f579ff6b..0000000000 --- a/modules/base/shaders/texture_clean_fs.glsl +++ /dev/null @@ -1,31 +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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -out vec4 renderTableColor; - -void main() { - renderTableColor = vec4(0.0); -} diff --git a/modules/base/shaders/texture_clean_vs.glsl b/modules/base/shaders/texture_clean_vs.glsl deleted file mode 100644 index e266156549..0000000000 --- a/modules/base/shaders/texture_clean_vs.glsl +++ /dev/null @@ -1,31 +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. * - ****************************************************************************************/ - -#version __CONTEXT__ - -layout(location = 0) in vec3 in_position; - -void main() { - gl_Position = vec4(in_position, 1.0); -} diff --git a/shaders/blending.glsl b/shaders/blending.glsl index 377ac28668..75e65203ad 100644 --- a/shaders/blending.glsl +++ b/shaders/blending.glsl @@ -25,15 +25,14 @@ #ifndef _BLENDING_GLSL_ #define _BLENDING_GLSL_ - /** * Blend in src behind dst using normal blending * dst is premultiplied * src is expressed in straight RGBA */ void normalBlend(inout vec4 dst, vec4 src) { - dst.rgb = dst.rgb + (1.0 - dst.a) * src.a * src.rgb; - dst.a = dst.a + (1.0 - dst.a) * src.a; + dst.rgb = dst.rgb + (1.f - dst.a) * src.a * src.rgb; + dst.a = dst.a + (1.f - dst.a) * src.a; } /** @@ -42,7 +41,7 @@ void normalBlend(inout vec4 dst, vec4 src) { * src is expressed in straight RGBA */ void additiveBlend(inout vec4 dst, vec4 src) { - dst.rgb = dst.rgb + (1.0 - dst.a) * src.a * src.rgb;// dst.rgb = dst.rgb + src.a * src.rgb; + dst.rgb = dst.rgb + (1.f - dst.a) * src.a * src.rgb;// dst.rgb = dst.rgb + src.a * src.rgb; //dst.a = dst.a + src.a; } @@ -55,7 +54,7 @@ void additiveBlend(inout vec4 dst, vec4 src) { * stepSize = 1: alpha becomes src.a */ void normalBlendStep(inout vec4 dst, vec4 src, float stepSize) { - src.a = 1.0 - pow(1.0 - src.a, stepSize); + src.a = 1.f - pow(1.f - src.a, stepSize); normalBlend(dst, src); } @@ -77,8 +76,8 @@ void additiveBlendStep(inout vec4 dst, vec4 src, float stepSize) { * src is expressed in straight RGBA */ void blend(inout vec4 dst, vec4 src) { - dst.rgb = dst.rgb + (1.0 - dst.a) * src.a * src.rgb; - dst.a = dst.a + (1.0 - dst.a) * src.a; + dst.rgb = dst.rgb + (1.f - dst.a) * src.a * src.rgb; + dst.a = dst.a + (1.f - dst.a) * src.a; } /** @@ -89,8 +88,8 @@ void blend(inout vec4 dst, vec4 src) { * stepSize = 1: alpha becomes src.a */ void blendStep(inout vec4 dst, vec4 src, float stepSize) { - src.a = 1.0 - pow(1.0 - src.a, stepSize); + src.a = 1.0 - pow(1.f - src.a, stepSize); blend(dst, src); } -#endif +#endif // _BLENDING_GLSL_ diff --git a/shaders/floatoperations.glsl b/shaders/floatoperations.glsl index 798fe9db71..adf5dfa635 100644 --- a/shaders/floatoperations.glsl +++ b/shaders/floatoperations.glsl @@ -25,7 +25,6 @@ #ifndef _FLOATOPERATIONS_GLSL_ #define _FLOATOPERATIONS_GLSL_ - /** * Convert a positive floating point distance [0, 10^27] * (size of observable universe) @@ -51,43 +50,44 @@ float denormalizeFloat(float inpt) { /** * Compute the length of a vector. - * Supporting huge vectors, where the square of any of the components is too large to represent as a float. + * Supporting huge vectors, where the square of any of the components is too large to be + * represented as a float. */ float safeLength(vec4 v) { float m = max(max(max(abs(v.x), abs(v.y)), abs(v.z)), abs(v.w)); - if (m > 0.0) { + if (m > 0.f) { return length(v / m) * m; } else { - return 0; + return 0.f; } } float safeLength(vec3 v) { float m = max(max(abs(v.x), abs(v.y)), abs(v.z)); - if (m > 0.0) { + if (m > 0.f) { return length(v / m) * m; } else { - return 0; + return 0.f; } } float safeLength(vec2 v) { float m = max(abs(v.x), abs(v.y)); - if (m > 0.0) { + if (m > 0.f) { return length(v / m) * m; } else { - return 0; + return 0.f; } } /** * Normalize a vector - * Supporting huge vectors, where the square of any of the components is too large to represent as a float. + * Supporting huge vectors, where the square of any of the components is too large to be + * represent as a float. */ vec3 safeNormalize(vec3 v) { float m = max(max(abs(v.x), abs(v.y)), abs(v.z)); return normalize(v / m); } - -#endif +#endif // _FLOATOPERATIONS_GLSL_ diff --git a/shaders/framebuffer/hdrBackground.frag b/shaders/framebuffer/hdrBackground.frag index 453038312f..a68147ef73 100644 --- a/shaders/framebuffer/hdrBackground.frag +++ b/shaders/framebuffer/hdrBackground.frag @@ -36,11 +36,11 @@ uniform sampler2DMS mainColorTexture; void main() { vec4 color = vec4(0.0); for (int i = 0; i < nAaSamples; i++) { - color += texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); + color += texelFetch(mainColorTexture, ivec2(gl_FragCoord), i); } color /= nAaSamples; - //color.rgb *= blackoutFactor; + // color.rgb *= blackoutFactor; - finalColor = vec4(HDR(color.rgb * backgroundConstant, backgroundExposure), 1.0); + finalColor = vec4(HDR(color.rgb * backgroundConstant, backgroundExposure), 1.0); } diff --git a/shaders/framebuffer/nOneStripMSAA.frag b/shaders/framebuffer/nOneStripMSAA.frag index e49ee51cc1..3db536607e 100644 --- a/shaders/framebuffer/nOneStripMSAA.frag +++ b/shaders/framebuffer/nOneStripMSAA.frag @@ -27,7 +27,7 @@ layout (location = 0) out vec4 finalColor; in vec2 vTexCoord; -flat in vec3 vPosition; +// flat in vec3 vPosition; uniform int currentSample; uniform sampler2DMS pixelSizeTexture; diff --git a/shaders/framebuffer/nOneStripMSAA.vert b/shaders/framebuffer/nOneStripMSAA.vert index 4a5619acb9..0a337bb74d 100644 --- a/shaders/framebuffer/nOneStripMSAA.vert +++ b/shaders/framebuffer/nOneStripMSAA.vert @@ -28,11 +28,11 @@ layout(location = 0) in vec4 position; layout(location = 1) in vec2 texCoord; out vec2 vTexCoord; -flat out vec3 vPosition; +// flat out vec3 vPosition; void main() { vTexCoord = texCoord; - vPosition = position.xyz; + // vPosition = position.xyz; gl_Position = position; } diff --git a/shaders/framebuffer/pixelSizeMSAA.frag b/shaders/framebuffer/pixelSizeMSAA.frag index 4397682d33..99a7aa0dc6 100644 --- a/shaders/framebuffer/pixelSizeMSAA.frag +++ b/shaders/framebuffer/pixelSizeMSAA.frag @@ -28,6 +28,6 @@ layout (location = 0) out vec4 finalColor; flat in vec3 vPosition; -void main() { - finalColor = vec4(0.5 * vPosition + 0.5, 1.0); +void main() { + finalColor = vec4(0.5 * vPosition + 0.5, 1.0); } diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index 458f7da1b8..d9ec1f038c 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -113,8 +113,6 @@ void main() { for (steps = 0; (accumulatedAlpha.r < ALPHA_LIMIT || accumulatedAlpha.g < ALPHA_LIMIT || accumulatedAlpha.b < ALPHA_LIMIT) && steps < RAYCAST_MAX_STEPS; ++steps) { - - while (sampleIndex < nAaSamples && currentDepth + nextStepSize * jitterFactor > raycastDepths[sampleIndex]) { sampleIndex++; aaOpacity -= opacityDecay; @@ -132,7 +130,6 @@ void main() { vec3 jitteredPosition = position + direction*jitteredStepSize; position += direction * currentStepSize; - sample#{id}(jitteredPosition, direction, accumulatedColor, accumulatedAlpha, nextStepSize); float sampleDistance = aaOpacity * (jitteredStepSize + previousJitterDistance); diff --git a/shaders/hdr.glsl b/shaders/hdr.glsl index 2e1a5c22d5..cb282bed8f 100644 --- a/shaders/hdr.glsl +++ b/shaders/hdr.glsl @@ -22,10 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -//uniform float exposure; uniform float gamma; -vec3 exponentialToneMapping(vec3 color, const float exposure) { +vec3 exponentialToneMapping(vec3 color, float exposure) { color *= exposure; color.r = color.r < 1.413 ? pow(color.r * 0.38317, 1.0 / gamma) : 1.0 - exp(-color.r); @@ -35,62 +34,58 @@ vec3 exponentialToneMapping(vec3 color, const float exposure) { return color; } -vec3 linearToneMapping(vec3 color, const float exposure) { +vec3 linearToneMapping(vec3 color, float exposure) { float tExposure = 0.08f; - color = clamp(tExposure * color, 0.0f, 1.0f); - color = pow(color, vec3(1.0f / gamma)); + color = clamp(tExposure * color, 0.f, 1.f); + color = pow(color, vec3(1.f / gamma)); return color; } -vec3 simpleReinhardToneMapping(vec3 color, const float exposure) { +vec3 simpleReinhardToneMapping(vec3 color, float exposure) { float tExposure = 1.5f; - color *= tExposure/(1.0f + color / tExposure); - color = pow(color, vec3(1. / gamma)); + color *= tExposure/(1.f + color / tExposure); + color = pow(color, vec3(1.f / gamma)); return color; } -vec3 lumaBasedReinhardToneMapping(vec3 color, const float exposure) -{ +vec3 lumaBasedReinhardToneMapping(vec3 color, float exposure) { float luma = dot(color, vec3(0.2126f, 0.7152f, 0.0722f)); - float toneMappedLuma = luma / (1.0f + luma); + float toneMappedLuma = luma / (1.f + luma); color *= toneMappedLuma / luma; - color = pow(color, vec3(1.0f / gamma)); + color = pow(color, vec3(1.f / gamma)); return color; } -vec3 whitePreservingLumaBasedReinhardToneMapping(vec3 color, const float exposure) -{ - float white = 4.0f; +vec3 whitePreservingLumaBasedReinhardToneMapping(vec3 color, float exposure) { + float white = 4.f; //float luma = dot(color, vec3(0.2126f, 0.7152f, 0.0722f)); float luma = dot(color, vec3(0.4126f, 0.9152f, 0.2722f)); - float toneMappedLuma = luma * (1.0f + luma / (white * white)) / (1.0f + luma); + float toneMappedLuma = luma * (1.f + luma / (white * white)) / (1.f + luma); color *= toneMappedLuma / luma; - color = pow(color, vec3(1.0f / gamma)); + color = pow(color, vec3(1.f / gamma)); return color; } -vec3 RomBinDaHouseToneMapping(vec3 color, const float exposure) -{ - color = exp( -1.0f / ( 2.72f * color + 0.15f ) ); - color = pow(color, vec3(1.7 / gamma)); +vec3 RomBinDaHouseToneMapping(vec3 color, float exposure) { + color = exp( -1.f / ( 2.72f * color + 0.15f ) ); + color = pow(color, vec3(1.7f / gamma)); return color; } -vec3 filmicToneMapping(vec3 color, const float exposure) +vec3 filmicToneMapping(vec3 color, float exposure) { - color = max(vec3(0.0f), color - vec3(0.04f)); - color = (color * (6.2f * color + 0.5f)) / (color * (6.2f * color + 20.0f) + 0.06f); + color = max(vec3(0.f), color - vec3(0.04f)); + color = (color * (6.2f * color + 0.5f)) / (color * (6.2f * color + 20.f) + 0.06f); return color; } -vec3 Uncharted2ToneMapping(vec3 color, const float exposure) -{ +vec3 Uncharted2ToneMapping(vec3 color, float exposure) { float A = 0.15f; - float B = 0.50f; - float C = 0.10f; - float D = 0.20f; + float B = 0.5f; + float C = 0.1f; + float D = 0.2f; float E = 0.02f; - float F = 0.30f; + float F = 0.3f; float W = 11.2f; float tExposure = 0.4f; color *= tExposure; @@ -101,7 +96,7 @@ vec3 Uncharted2ToneMapping(vec3 color, const float exposure) return color; } -vec3 jToneMapping(const vec3 color, const float exposure) { +vec3 jToneMapping(vec3 color, float exposure) { return 1.0 - exp(-exposure * color); } diff --git a/src/rendering/abufferrenderer.cpp b/src/rendering/abufferrenderer.cpp index 0545a6a664..a870716ca4 100644 --- a/src/rendering/abufferrenderer.cpp +++ b/src/rendering/abufferrenderer.cpp @@ -59,9 +59,7 @@ namespace { namespace openspace { ABufferRenderer::ABufferRenderer() - : _camera(nullptr) - , _scene(nullptr) - , _resolution(glm::ivec2(0)) + : _resolution(glm::ivec2(0)) , _dirtyResolution(true) , _dirtyRendererData(true) , _dirtyRaycastData(true) @@ -76,15 +74,15 @@ ABufferRenderer::~ABufferRenderer() {} void ABufferRenderer::initialize() { LINFO("Initializing ABufferRenderer"); - const GLfloat size = 1.0f; + const GLfloat size = 1.f; const GLfloat vertex_data[] = { // x y s t - -size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f, - -size, size, 0.0f, 1.0f, - -size, -size, 0.0f, 1.0f, - size, -size, 0.0f, 1.0f, - size, size, 0.0f, 1.0f, + -size, -size, 0.f, 1.f, + size, size, 0.f, 1.f, + -size, size, 0.f, 1.f, + -size, -size, 0.f, 1.f, + size, -size, 0.f, 1.f, + size, size, 0.f, 1.f, }; @@ -95,14 +93,7 @@ void ABufferRenderer::initialize() { glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 4, - nullptr - ); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, nullptr); glEnableVertexAttribArray(0); glGenTextures(1, &_anchorPointerTexture); @@ -230,8 +221,9 @@ void ABufferRenderer::update() { LERRORC(error.component, error.message); } } - - for (auto &program : _boundsPrograms) { + using K = VolumeRaycaster* const; + using V = std::unique_ptr; + for (std::pair& program : _boundsPrograms) { if (program.second->isDirty()) { try { program.second->rebuildFromFile(); @@ -243,57 +235,59 @@ void ABufferRenderer::update() { } void ABufferRenderer::updateMSAASamplingPattern() { + // @CLEANUP(abock): This should probably be merged with the same code from the + // framebuffer renderer? LINFO("Updating MSAA Sampling Pattern"); - const int GRIDSIZE = 32; - GLfloat step = 2.0f / static_cast(GRIDSIZE); - GLfloat sizeX = -1.0f, - sizeY = 1.0f; + constexpr const int GridSize = 32; + GLfloat step = 2.f / static_cast(GridSize); + GLfloat sizeX = -1.0f; + GLfloat sizeY = 1.0f; - const int NVERTEX = 4 * 6; + constexpr const int NVertex = 4 * 6; // openPixelSizeVertexData - GLfloat vertexData[GRIDSIZE * GRIDSIZE * NVERTEX]; + GLfloat vertexData[GridSize * GridSize * NVertex]; - for (int y = 0; y < GRIDSIZE; ++y) { - for (int x = 0; x < GRIDSIZE; ++x) { - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 1] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 2] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 3] = 1.0f; + for (int y = 0; y < GridSize; ++y) { + for (int x = 0; x < GridSize; ++x) { + vertexData[y * GridSize * NVertex + x * NVertex] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 1] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 2] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 3] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 4] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 5] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 6] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 7] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 4] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 5] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 6] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 7] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 8] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 9] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 10] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 11] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 8] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 9] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 10] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 11] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 12] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 13] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 14] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 15] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 12] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 13] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 14] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 15] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 16] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 17] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 18] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 19] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 16] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 17] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 18] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 19] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 20] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 21] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 22] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 23] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 20] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 21] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 22] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 23] = 1.f; sizeX += step; } - sizeX = -1.0f; + sizeX = -1.f; sizeY -= step; } - GLuint pixelSizeQuadVAO = 0, - pixelSizeQuadVBO = 0; + GLuint pixelSizeQuadVAO = 0; + GLuint pixelSizeQuadVBO = 0; glGenVertexArrays(1, &pixelSizeQuadVAO); glBindVertexArray(pixelSizeQuadVAO); @@ -303,20 +297,13 @@ void ABufferRenderer::updateMSAASamplingPattern() { glBufferData( GL_ARRAY_BUFFER, - sizeof(GLfloat) * GRIDSIZE * GRIDSIZE * NVERTEX, + sizeof(GLfloat) * GridSize * GridSize * NVertex, vertexData, GL_STATIC_DRAW ); // Position - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - 0, - nullptr - ); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(0); // Saves current state @@ -366,17 +353,12 @@ void ABufferRenderer::updateMSAASamplingPattern() { return; } - std::unique_ptr pixelSizeProgram = nullptr; - try { - pixelSizeProgram = ghoul::opengl::ProgramObject::Build( + std::unique_ptr pixelSizeProgram = + ghoul::opengl::ProgramObject::Build( "OnePixel MSAA", "${SHADERS}/framebuffer/pixelSizeMSAA.vert", "${SHADERS}/framebuffer/pixelSizeMSAA.frag" ); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } pixelSizeProgram->activate(); @@ -385,7 +367,7 @@ void ABufferRenderer::updateMSAASamplingPattern() { glBindVertexArray(pixelSizeQuadVAO); glDisable(GL_DEPTH_TEST); glDepthMask(false); - glDrawArrays(GL_TRIANGLES, 0, GRIDSIZE * GRIDSIZE * 6); + glDrawArrays(GL_TRIANGLES, 0, GridSize * GridSize * 6); glBindVertexArray(0); glDepthMask(true); glEnable(GL_DEPTH_TEST); @@ -394,58 +376,58 @@ void ABufferRenderer::updateMSAASamplingPattern() { pixelSizeProgram->deactivate(); // Now we render the Nx1 quad strip - GLuint nOneStripFramebuffer = 0, - nOneStripVAO = 0, - nOneStripVBO = 0, - nOneStripTexture = 0; + GLuint nOneStripFramebuffer = 0; + GLuint nOneStripVAO = 0; + GLuint nOneStripVBO = 0; + GLuint nOneStripTexture = 0; - sizeX = -1.0f; - step = 2.0f / static_cast(_nAaSamples); + sizeX = -1.f; + step = 2.f / static_cast(_nAaSamples); - GLfloat * nOneStripVertexData = new GLfloat[_nAaSamples * (NVERTEX + 12)]; + std::vector nOneStripVertexData(_nAaSamples * (NVertex + 12)); for (int x = 0; x < _nAaSamples; ++x) { - nOneStripVertexData[x * (NVERTEX + 12)] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 1] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 2] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 3] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 4] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 5] = 0.0f; + nOneStripVertexData[x * (NVertex + 12)] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 1] = -1.0f; + nOneStripVertexData[x * (NVertex + 12) + 2] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 3] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 4] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 5] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 6] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 7] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 8] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 9] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 10] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 11] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 6] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 7] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 8] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 9] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 10] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 11] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 12] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 13] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 14] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 15] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 16] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 17] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 12] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 13] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 14] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 15] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 16] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 17] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 18] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 19] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 20] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 21] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 22] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 23] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 18] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 19] = -1.0f; + nOneStripVertexData[x * (NVertex + 12) + 20] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 21] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 22] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 23] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 24] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 25] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 26] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 27] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 28] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 29] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 24] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 25] = -1.0f; + nOneStripVertexData[x * (NVertex + 12) + 26] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 27] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 28] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 29] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 30] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 31] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 32] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 33] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 34] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 35] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 30] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 31] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 32] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 33] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 34] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 35] = 1.0f; sizeX += step; } @@ -456,8 +438,8 @@ void ABufferRenderer::updateMSAASamplingPattern() { glBindBuffer(GL_ARRAY_BUFFER, nOneStripVBO); glBufferData( GL_ARRAY_BUFFER, - sizeof(GLfloat) * _nAaSamples * (NVERTEX + 12), - nOneStripVertexData, + sizeof(GLfloat) * _nAaSamples * (NVertex + 12), + nOneStripVertexData.data(), GL_STATIC_DRAW ); @@ -482,7 +464,6 @@ void ABufferRenderer::updateMSAASamplingPattern() { reinterpret_cast(sizeof(GLfloat) * 4) ); glEnableVertexAttribArray(1); - delete[] nOneStripVertexData; // fbo texture buffer glGenTextures(1, &nOneStripTexture); @@ -519,17 +500,12 @@ void ABufferRenderer::updateMSAASamplingPattern() { glViewport(0, 0, _nAaSamples, ONEPIXEL); - std::unique_ptr nOneStripProgram = nullptr; - try { - nOneStripProgram = ghoul::opengl::ProgramObject::Build( + std::unique_ptr nOneStripProgram = + ghoul::opengl::ProgramObject::Build( "OneStrip MSAA", "${SHADERS}/framebuffer/nOneStripMSAA.vert", "${SHADERS}/framebuffer/nOneStripMSAA.frag" ); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } nOneStripProgram->activate(); @@ -541,7 +517,7 @@ void ABufferRenderer::updateMSAASamplingPattern() { // render strip glDrawBuffers(1, textureBuffers); - glClearColor(0.0f, 1.0f, 0.0f, 1.0f); + glClearColor(0.f, 1.f, 0.f, 1.f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(nOneStripVAO); glDisable(GL_DEPTH_TEST); @@ -584,10 +560,12 @@ void ABufferRenderer::updateMSAASamplingPattern() { glDeleteVertexArrays(1, &nOneStripVAO); } -void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurements) { +void ABufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, + bool doPerformanceMeasurements) +{ PerfMeasure("ABufferRenderer::render"); - if (!_scene || !_camera) { + if (!scene || !camera) { return; } @@ -626,7 +604,7 @@ void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurement Time time = OsEng.timeManager().time(); RenderData data { - *_camera, + *camera, psc(), time, doPerformanceMeasurements, @@ -634,7 +612,7 @@ void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurement {} }; RendererTasks tasks; - _scene->render(data, tasks); + scene->render(data, tasks); _blackoutFactor = blackoutFactor; glBindFramebuffer(GL_FRAMEBUFFER, defaultFbo); @@ -670,8 +648,8 @@ void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurement float logDistance = std::log(glm::length(cameraPos / maxComponent) * maxComponent) / std::log(10.f); - const float minLogDist = 15; - const float maxLogDist = 20; + const float minLogDist = 15.f; + const float maxLogDist = 20.f; float t = (logDistance - minLogDist) / (maxLogDist - minLogDist); t = glm::clamp(t, 0.0f, 1.0f); @@ -703,7 +681,6 @@ void ABufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurement _mainDepthTextureUnit = nullptr; } - void ABufferRenderer::preRaycast(const RaycasterTask& raycasterTask) { VolumeRaycaster& raycaster = *raycasterTask.raycaster; const RaycastData& raycastData = _raycastData[&raycaster]; @@ -733,17 +710,9 @@ void ABufferRenderer::postRaycast(const RaycasterTask& raycasterTask) { raycaster.postRaycast(raycastData, *_resolveProgram); } -void ABufferRenderer::setScene(Scene* scene) { - _scene = scene; -} - -void ABufferRenderer::setCamera(Camera* camera) { - _camera = camera; -} - void ABufferRenderer::setResolution(glm::ivec2 res) { if (res != _resolution) { - _resolution = res; + _resolution = std::move(res); _dirtyResolution = true; } } @@ -893,8 +862,6 @@ void ABufferRenderer::updateResolution() { _dirtyResolution = false; } - - void ABufferRenderer::updateResolveDictionary() { ghoul::Dictionary dict; ghoul::Dictionary raycastersDict; @@ -1026,29 +993,27 @@ void ABufferRenderer::updateRendererData() { } void ABufferRenderer::saveTextureToMemory(const GLenum color_buffer_attachment, - const int width, const int height, std::vector & memory) const { + const int width, const int height, std::vector& memory) const { if (!memory.empty()) { memory.clear(); } memory.reserve(width * height * 3); - float * tempMemory = new float[width * height * 3]; + std::vector tmpMemory(width * height * 3); if (color_buffer_attachment != GL_DEPTH_ATTACHMENT) { glReadBuffer(color_buffer_attachment); - glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT, tempMemory); + glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT, tmpMemory.data()); } else { - glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, tempMemory); + glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, tmpMemory.data()); } for (auto i = 0; i < width*height * 3; ++i) { - memory[i] = static_cast(tempMemory[i]); + memory[i] = static_cast(tmpMemory[i]); } - - delete[] tempMemory; } -} +} // namespace openspace diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index aedd04ed1a..2227ecddb9 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -75,9 +75,7 @@ void saveTextureToMemory(const GLenum color_buffer_attachment, FramebufferRenderer::FramebufferRenderer() - : _camera(nullptr) - , _scene(nullptr) - , _resolution(glm::vec2(0)) + : _resolution(glm::vec2(0)) , _hdrExposure(0.4f) , _hdrBackground(2.8f) , _gamma(2.2f) @@ -577,50 +575,54 @@ void FramebufferRenderer::updateHDRData() { void FramebufferRenderer::updateMSAASamplingPattern() { LDEBUG("Updating MSAA Sampling Pattern"); - const int GRIDSIZE = 32; - GLfloat step = 2.0f / static_cast(GRIDSIZE); - GLfloat sizeX = -1.0f, - sizeY = 1.0f; + constexpr const int GridSize = 32; + GLfloat step = 2.f / static_cast(GridSize); + GLfloat sizeX = -1.f; + GLfloat sizeY = 1.0; - const int NVERTEX = 4 * 6; + constexpr const int NVertex = 4 * 6; // openPixelSizeVertexData - GLfloat vertexData[GRIDSIZE * GRIDSIZE * NVERTEX]; + GLfloat vertexData[GridSize * GridSize * NVertex]; - for (int y = 0; y < GRIDSIZE; ++y) { - for (int x = 0; x < GRIDSIZE; ++x) { - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 1] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 2] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 3] = 1.0f; + // @CLEANUP(abock): Is this necessary? I was mucking about with the shader and it + // didn't make any visual difference. If it is necessary, the z and w + // components can be removed for sure since they are always 0, 1 and + // not used in the shader either + for (int y = 0; y < GridSize; ++y) { + for (int x = 0; x < GridSize; ++x) { + vertexData[y * GridSize * NVertex + x * NVertex] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 1] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 2] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 3] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 4] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 5] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 6] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 7] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 4] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 5] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 6] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 7] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 8] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 9] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 10] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 11] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 8] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 9] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 10] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 11] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 12] = sizeX; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 13] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 14] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 15] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 12] = sizeX; + vertexData[y * GridSize * NVertex + x * NVertex + 13] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 14] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 15] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 16] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 17] = sizeY - step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 18] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 19] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 16] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 17] = sizeY - step; + vertexData[y * GridSize * NVertex + x * NVertex + 18] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 19] = 1.f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 20] = sizeX + step; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 21] = sizeY; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 22] = 0.0f; - vertexData[y * GRIDSIZE * NVERTEX + x * NVERTEX + 23] = 1.0f; + vertexData[y * GridSize * NVertex + x * NVertex + 20] = sizeX + step; + vertexData[y * GridSize * NVertex + x * NVertex + 21] = sizeY; + vertexData[y * GridSize * NVertex + x * NVertex + 22] = 0.f; + vertexData[y * GridSize * NVertex + x * NVertex + 23] = 1.f; sizeX += step; } - sizeX = -1.0f; + sizeX = -1.f; sizeY -= step; } @@ -635,20 +637,13 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glBufferData( GL_ARRAY_BUFFER, - sizeof(GLfloat) * GRIDSIZE * GRIDSIZE * NVERTEX, + sizeof(GLfloat) * GridSize * GridSize * NVertex, vertexData, GL_STATIC_DRAW ); // Position - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - 0, - nullptr - ); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(0); // Saves current state @@ -689,7 +684,7 @@ void FramebufferRenderer::updateMSAASamplingPattern() { GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, textureBuffers); - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClearColor(0.f, 0.f, 0.f, 1.f); glClear(GL_COLOR_BUFFER_BIT); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); @@ -698,17 +693,12 @@ void FramebufferRenderer::updateMSAASamplingPattern() { return; } - std::unique_ptr pixelSizeProgram = nullptr; - try { - pixelSizeProgram = ghoul::opengl::ProgramObject::Build( + std::unique_ptr pixelSizeProgram = + ghoul::opengl::ProgramObject::Build( "OnePixel MSAA", absPath("${SHADERS}/framebuffer/pixelSizeMSAA.vert"), absPath("${SHADERS}/framebuffer/pixelSizeMSAA.frag") ); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } pixelSizeProgram->activate(); @@ -717,7 +707,7 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glBindVertexArray(pixelSizeQuadVAO); glDisable(GL_DEPTH_TEST); glDepthMask(false); - glDrawArrays(GL_TRIANGLES, 0, GRIDSIZE * GRIDSIZE * 6); + glDrawArrays(GL_TRIANGLES, 0, GridSize * GridSize * 6); glBindVertexArray(0); glDepthMask(true); glEnable(GL_DEPTH_TEST); @@ -731,53 +721,53 @@ void FramebufferRenderer::updateMSAASamplingPattern() { GLuint nOneStripVBO = 0; GLuint nOneStripTexture = 0; - sizeX = -1.0f; - step = 2.0f / static_cast(_nAaSamples); + sizeX = -1.f; + step = 2.f / static_cast(_nAaSamples); - GLfloat * nOneStripVertexData = new GLfloat[_nAaSamples * (NVERTEX + 12)]; + std::vectornOneStripVertexData(_nAaSamples * (NVertex + 12)); for (int x = 0; x < _nAaSamples; ++x) { - nOneStripVertexData[x * (NVERTEX + 12)] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 1] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 2] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 3] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 4] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 5] = 0.0f; + nOneStripVertexData[x * (NVertex + 12)] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 1] = -1.f; + nOneStripVertexData[x * (NVertex + 12) + 2] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 3] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 4] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 5] = 0.f; - nOneStripVertexData[x * (NVERTEX + 12) + 6] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 7] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 8] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 9] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 10] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 11] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 6] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 7] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 8] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 9] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 10] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 11] = 1.f; - nOneStripVertexData[x * (NVERTEX + 12) + 12] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 13] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 14] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 15] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 16] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 17] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 12] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 13] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 14] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 15] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 16] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 17] = 0.f; - nOneStripVertexData[x * (NVERTEX + 12) + 18] = sizeX; - nOneStripVertexData[x * (NVERTEX + 12) + 19] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 20] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 21] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 22] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 23] = 0.0f; + nOneStripVertexData[x * (NVertex + 12) + 18] = sizeX; + nOneStripVertexData[x * (NVertex + 12) + 19] = -1.f; + nOneStripVertexData[x * (NVertex + 12) + 20] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 21] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 22] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 23] = 0.f; - nOneStripVertexData[x * (NVERTEX + 12) + 24] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 25] = -1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 26] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 27] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 28] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 29] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 24] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 25] = -1.f; + nOneStripVertexData[x * (NVertex + 12) + 26] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 27] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 28] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 29] = 1.f; - nOneStripVertexData[x * (NVERTEX + 12) + 30] = sizeX + step; - nOneStripVertexData[x * (NVERTEX + 12) + 31] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 32] = 0.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 33] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 34] = 1.0f; - nOneStripVertexData[x * (NVERTEX + 12) + 35] = 1.0f; + nOneStripVertexData[x * (NVertex + 12) + 30] = sizeX + step; + nOneStripVertexData[x * (NVertex + 12) + 31] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 32] = 0.f; + nOneStripVertexData[x * (NVertex + 12) + 33] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 34] = 1.f; + nOneStripVertexData[x * (NVertex + 12) + 35] = 1.f; sizeX += step; } @@ -788,20 +778,13 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glBindBuffer(GL_ARRAY_BUFFER, nOneStripVBO); glBufferData( GL_ARRAY_BUFFER, - sizeof(GLfloat) * _nAaSamples * (NVERTEX + 12), - nOneStripVertexData, + sizeof(GLfloat) * _nAaSamples * (NVertex + 12), + nOneStripVertexData.data(), GL_STATIC_DRAW ); // position - glVertexAttribPointer( - 0, - 4, - GL_FLOAT, - GL_FALSE, - sizeof(GLfloat) * 6, - nullptr - ); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glEnableVertexAttribArray(0); // texture coords @@ -814,7 +797,6 @@ void FramebufferRenderer::updateMSAASamplingPattern() { reinterpret_cast(sizeof(GLfloat) * 4) ); glEnableVertexAttribArray(1); - delete[] nOneStripVertexData; // fbo texture buffer glGenTextures(1, &nOneStripTexture); @@ -851,17 +833,12 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glViewport(0, 0, _nAaSamples, ONEPIXEL); - std::unique_ptr nOneStripProgram = nullptr; - try { - nOneStripProgram = ghoul::opengl::ProgramObject::Build( + std::unique_ptr nOneStripProgram = + ghoul::opengl::ProgramObject::Build( "OneStrip MSAA", absPath("${SHADERS}/framebuffer/nOneStripMSAA.vert"), absPath("${SHADERS}/framebuffer/nOneStripMSAA.frag") ); - } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); - } nOneStripProgram->activate(); @@ -915,7 +892,9 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glDeleteVertexArrays(1, &nOneStripVAO); } -void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasurements) { +void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, + bool doPerformanceMeasurements) +{ std::unique_ptr perf; if (doPerformanceMeasurements) { perf = std::make_unique( @@ -924,7 +903,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure ); } - if (!_scene || !_camera) { + if (!scene || !camera) { return; } @@ -933,7 +912,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure Time time = OsEng.timeManager().time(); - RenderData data = { *_camera, psc(), time, doPerformanceMeasurements, 0, {} }; + RenderData data = { *camera, psc(), time, doPerformanceMeasurements, 0, {} }; RendererTasks tasks; // Capture standard fbo @@ -965,7 +944,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure } data.renderBinMask = static_cast(Renderable::RenderBin::Background); - _scene->render(data, tasks); + scene->render(data, tasks); } { std::unique_ptr perfInternal; @@ -977,7 +956,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure } data.renderBinMask = static_cast(Renderable::RenderBin::Opaque); - _scene->render(data, tasks); + scene->render(data, tasks); } { std::unique_ptr perfInternal; @@ -989,7 +968,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure } data.renderBinMask = static_cast(Renderable::RenderBin::Transparent); - _scene->render(data, tasks); + scene->render(data, tasks); } { std::unique_ptr perfInternal; @@ -1001,7 +980,7 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure } data.renderBinMask = static_cast(Renderable::RenderBin::Overlay); - _scene->render(data, tasks); + scene->render(data, tasks); } { @@ -1125,18 +1104,17 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure bool firstPaint = true; for (const DeferredcasterTask& deferredcasterTask : tasks.deferredcasterTasks) { - Deferredcaster* deferredcaster = deferredcasterTask.deferredcaster; ghoul::opengl::ProgramObject* deferredcastProgram = nullptr; if (deferredcastProgram != _deferredcastPrograms[deferredcaster].get() - || deferredcastProgram == nullptr) { + || deferredcastProgram == nullptr) + { deferredcastProgram = _deferredcastPrograms[deferredcaster].get(); } if (deferredcastProgram) { - deferredcastProgram->activate(); // adding G-Buffer @@ -1188,9 +1166,11 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure glDepthMask(true); glEnable(GL_DEPTH_TEST); - deferredcaster->postRaycast(deferredcasterTask.renderData, + deferredcaster->postRaycast( + deferredcasterTask.renderData, _deferredcastData[deferredcaster], - *deferredcastProgram); + *deferredcastProgram + ); deferredcastProgram->deactivate(); @@ -1225,14 +1205,6 @@ void FramebufferRenderer::render(float blackoutFactor, bool doPerformanceMeasure } } -void FramebufferRenderer::setScene(Scene* scene) { - _scene = scene; -} - -void FramebufferRenderer::setCamera(Camera* camera) { - _camera = camera; -} - void FramebufferRenderer::setResolution(glm::ivec2 res) { _resolution = res; _dirtyResolution = true; diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 6bb1b2ba6d..807eeae613 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -562,7 +562,12 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat bool masterEnabled = wrapper.isMaster() ? !_disableMasterRendering : true; if (masterEnabled && !wrapper.isGuiWindow() && _globalBlackOutFactor > 0.f) { - _renderer->render(_globalBlackOutFactor, _performanceManager != nullptr); + _renderer->render( + _scene, + _camera, + _globalBlackOutFactor, + _performanceManager != nullptr + ); } if (_showFrameNumber) { @@ -742,16 +747,10 @@ DeferredcasterManager& RenderEngine::deferredcasterManager() { void RenderEngine::setScene(Scene* scene) { _scene = scene; - if (_renderer) { - _renderer->setScene(scene); - } } void RenderEngine::setCamera(Camera* camera) { _camera = camera; - if (_renderer) { - _renderer->setCamera(camera); - } } const Renderer& RenderEngine::renderer() const { @@ -912,8 +911,6 @@ void RenderEngine::setRenderer(std::unique_ptr renderer) { _renderer->setNAaSamples(_nAaSamples); _renderer->setHDRExposure(_hdrExposure); _renderer->initialize(); - _renderer->setCamera(_camera); - _renderer->setScene(_scene); } scripting::LuaLibrary RenderEngine::luaLibrary() { From 7285a66c89ea8e8aa18fde5ddcd7d3f7a57b321a Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sun, 22 Apr 2018 09:52:21 -0400 Subject: [PATCH 69/79] Changes from comments. --- modules/digitaluniverse/shaders/billboard_fs.glsl | 2 ++ modules/digitaluniverse/shaders/billboard_gs.glsl | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index ccc7e29982..8772121d17 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -62,6 +62,8 @@ Fragment getFragment() { Fragment frag; frag.color = fullColor; frag.depth = vs_screenSpaceDepth; + // Setting the position of the billboards to not interact + // with the ATM. frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index 0b0dd8a514..a252051069 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -30,7 +30,7 @@ layout(points) in; layout(triangle_strip, max_vertices = 4) out; uniform float scaleFactor; -uniform dvec3 up; +uniform dvec3 up; uniform dvec3 right; uniform dvec3 cameraPosition; // in world space (no SGCT View was considered) uniform dvec3 cameraLookUp; // in world space (no SGCT View was considered) @@ -83,6 +83,7 @@ void main() { } else if (pos.w == 5.f) { unit = 1E9 * PARSEC; } else if (pos.w == 6.f) { + // Convertion factor from Parsecs to GigalightYears unit = 306391534.73091 * PARSEC; } @@ -152,6 +153,7 @@ void main() { initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + vs_screenSpaceDepth = initialPosition.w; secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * @@ -173,6 +175,5 @@ void main() { texCoord = corners[1]; gl_Position = secondPosition; EmitVertex(); - EndPrimitive(); - + EndPrimitive(); } \ No newline at end of file From d6571a131dd390879814cc49e2001e2113c5ba56 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 1 May 2018 14:30:18 -0400 Subject: [PATCH 70/79] Enable the disabling of hash generation in URL synchronization --- data/assets/examples/urlsynchronization.asset | 8 ++++ modules/sync/syncs/urlsynchronization.cpp | 39 +++++++++++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/data/assets/examples/urlsynchronization.asset b/data/assets/examples/urlsynchronization.asset index 630eb4762b..9f0a0eafca 100644 --- a/data/assets/examples/urlsynchronization.asset +++ b/data/assets/examples/urlsynchronization.asset @@ -40,3 +40,11 @@ asset.syncedResource({ Type = "UrlSynchronization", Url = "http://ipv4.download.thinkbroadband.com/5MB.zip" }) + +asset.syncedResource({ + Name = "Example No Hash", + Type = "UrlSynchronization", + Identifier = "no_hash", + Url = "http://wms.itn.liu.se/Mercury/Messenger_Mosaic/Messenger_Mosaic.wms", + UseHash = false +}) diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index 365aa0523b..8206b2e53a 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -41,6 +41,7 @@ namespace { constexpr const char* KeyUrl = "Url"; constexpr const char* KeyIdentifier = "Identifier"; constexpr const char* KeyOverride = "Override"; + constexpr const char* KeyUseHash = "UseHash"; constexpr const char* TempSuffix = ".tmp"; } // namespace @@ -66,7 +67,8 @@ documentation::Documentation UrlSynchronization::Documentation() { Optional::Yes, "This optional identifier will be part of the used folder structure and, " "if provided, can be used to manually find the downloaded folder in the " - "synchronization folder." + "synchronization folder. If this value is not specified, 'UseHash' has " + "to be set to 'true'." }, { KeyOverride, @@ -77,6 +79,16 @@ documentation::Documentation UrlSynchronization::Documentation() { "be downloaded, thus overwriting the local files. This is useful for " "files that are updated regularly remotely and should be fetch at every " "startup." + }, + { + KeyUseHash, + new BoolVerifier, + Optional::Yes, + "If this value is set to 'true' (the default), the hash of the URL is " + "appended to the directory name to produce a unique directory under all " + "circumstances. If this is not desired, the URLSynchronization use the " + "bare directory name alone if this value is 'false'. If this value is " + "'false', the identifier has to be specified." } } }; @@ -104,16 +116,37 @@ UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dict, } } + bool useHash = true; + if (dict.hasValue(KeyUseHash)) { + useHash = dict.value(KeyUseHash); + } + // We just merge all of the URLs together to generate a hash, it's not as stable to // reordering URLs, but every other solution would be more error prone std::string urlConcat = std::accumulate(_urls.begin(), _urls.end(), std::string()); size_t hash = std::hash{}(urlConcat); if (dict.hasValue(KeyIdentifier)) { std::string ident = dict.value(KeyIdentifier); - _identifier = ident + "(" + std::to_string(hash) + ")"; + if (useHash) { + _identifier = std::move(ident) + "(" + std::to_string(hash) + ")"; + } + else { + _identifier = std::move(ident); + } } else { - _identifier = std::to_string(hash); + if (useHash) { + _identifier = std::to_string(hash); + } + else { + documentation::TestResult res; + res.success = false; + res.offenses.push_back({ + std::string(KeyIdentifier) + "|" + KeyUseHash, + documentation::TestResult::Offense::Reason::MissingKey + }); + throw documentation::SpecificationError(std::move(res), "UrlSynchronization"); + } } if (dict.hasValue(KeyOverride)) { From 0f33639ca21b8210e9827d82b7e4969d596806e8 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 1 May 2018 17:16:28 -0400 Subject: [PATCH 71/79] Add LiU WMS files Make use of Sweden-based WMS files Set correct name for automatically loaded Info files --- .../solarsystem/planets/earth/earth.asset | 18 +++- .../earth/map_service_configs/LiU/Bmng.wms | 20 +++++ .../earth/map_service_configs/LiU/Gebco.wms | 20 +++++ .../map_service_configs/LiU/Clem_Uvvis.wms | 20 +++++ .../moon/map_service_configs/LiU/Kaguya.wms | 20 +++++ .../LiU/Lola_Clr_Shade.wms | 20 +++++ .../moon/map_service_configs/LiU/Lola_DEM.wms | 21 +++++ .../map_service_configs/LiU/Lola_Shade.wms | 20 +++++ .../map_service_configs/LiU/Uvvis_Hybrid.wms | 20 +++++ .../moon/map_service_configs/LiU/WAC.wms | 20 +++++ .../moon/map_service_configs/OnMoonColor.wms | 68 --------------- .../solarsystem/planets/earth/moon/moon.asset | 83 +++++++++++++++---- .../mars/map_service_configs/LiU/Color.wms | 20 +++++ .../mars/map_service_configs/LiU/MDIM.wms | 20 +++++ .../mars/map_service_configs/LiU/Mola_CTX.wms | 20 +++++ .../LiU/Mola_Elevation.wms | 25 ------ .../map_service_configs/LiU/Mola_HRSC.wms | 20 +++++ .../LiU/Mola_PseudoColor.wms | 20 +++++ .../map_service_configs/LiU/Themis_IR_Day.wms | 20 +++++ .../LiU/Themis_IR_Night.wms | 20 +++++ .../map_service_configs/Utah/Mars_Color.wms | 2 +- .../Utah/Themis_IR_Night.wms | 4 +- .../scene/solarsystem/planets/mars/mars.asset | 78 ++++++++++++----- .../LiU/Messenger_MDIS.wms | 20 +++++ .../LiU/Messenger_Mosaic.wms | 20 +++++ .../solarsystem/planets/mercury/mercury.asset | 18 ++-- .../solarsystem/planets/mercury/trail.asset | 2 +- .../globebrowsing/scripts/layer_support.lua | 2 + 28 files changed, 515 insertions(+), 146 deletions(-) create mode 100644 data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Bmng.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Gebco.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Clem_Uvvis.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Kaguya.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Clr_Shade.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_DEM.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Shade.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Uvvis_Hybrid.wms create mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/WAC.wms delete mode 100644 data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/OnMoonColor.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Color.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/MDIM.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_CTX.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_HRSC.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_PseudoColor.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Day.wms create mode 100644 data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Night.wms create mode 100644 data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_MDIS.wms create mode 100644 data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_Mosaic.wms diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index 5ed01f4bfd..ab86b85445 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -110,9 +110,15 @@ local Earth = { ) }, { - Identifier = "BMNG", + Name = "BMNH [Utah]", + Identifier = "BMNG_Utah", FilePath = mapServiceConfigsPath .. "/Utah/Bmng.wms" }, + { + Name = "BMNH [Sweden]", + Identifier = "BMNG_Sweden", + FilePath = mapServiceConfigsPath .. "/LiU/Bmng.wms" + }, { Identifier = "AMSR2_GCOM_W1_Sea_Ice_Concentration_Temporal", Name = "AMSR2 GCOM W1 Sea Ice Concentration (Temporal)", @@ -188,9 +194,15 @@ local Earth = { Enabled = true }, { - Identifier = "GEBCO", + Name = "Gebco [Utah]", + Identifier = "Gebco_Utah", FilePath = mapServiceConfigsPath .. "/Utah/Gebco.wms" - } + }, + { + Name = "Gebco [Sweden]", + Identifier = "Gebco_Sweden", + FilePath = mapServiceConfigsPath .. "/LiU/Gebco.wms" + }, }, Overlays = { { diff --git a/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Bmng.wms b/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Bmng.wms new file mode 100644 index 0000000000..e118500f8b --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Bmng.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Earth/Bmng/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 86400 + 43200 + 8 + top + + EPSG:4326 + 240 + 240 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Gebco.wms b/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Gebco.wms new file mode 100644 index 0000000000..eb202dbd2d --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/map_service_configs/LiU/Gebco.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Earth/Gebco/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 43200 + 21600 + 6 + top + + EPSG:4326 + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Clem_Uvvis.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Clem_Uvvis.wms new file mode 100644 index 0000000000..7df84ff7cb --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Clem_Uvvis.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/Clem_Uvvis/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Kaguya.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Kaguya.wms new file mode 100644 index 0000000000..f9c4b8ebcc --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Kaguya.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/Kaguya/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 1474560 + 737280 + 11 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Clr_Shade.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Clr_Shade.wms new file mode 100644 index 0000000000..fe510f9b0b --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Clr_Shade.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/Lola_Clr_Shade/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_DEM.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_DEM.wms new file mode 100644 index 0000000000..4bd6ed5421 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_DEM.wms @@ -0,0 +1,21 @@ + + + http://wms.itn.liu.se/Moon/Lola_DEM/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + Int16 + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Shade.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Shade.wms new file mode 100644 index 0000000000..7dd5f9f173 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Lola_Shade.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/Lola_Shade/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Uvvis_Hybrid.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Uvvis_Hybrid.wms new file mode 100644 index 0000000000..46203c927e --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/Uvvis_Hybrid.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/Uvvis_Hybrid/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 184320 + 92160 + 8 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/WAC.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/WAC.wms new file mode 100644 index 0000000000..20a8109b55 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/LiU/WAC.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Moon/WAC/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 109164 + 54582 + 8 + top + + GEOGCS["GCS_Moon_2000",DATUM["D_Moon_2000",SPHEROID["Moon_2000_IAU_IAG",1737400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/OnMoonColor.wms b/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/OnMoonColor.wms deleted file mode 100644 index a8895878f8..0000000000 --- a/data/assets/scene/solarsystem/planets/earth/moon/map_service_configs/OnMoonColor.wms +++ /dev/null @@ -1,68 +0,0 @@ - - - http://onmoon.lmmp.nasa.gov/wms.cgi? - LRO WAC Mosaic, LMMP - - - - - -180.0 - 90 - 180.0 - -90 - 20 - 2 - 1 - top - - 512 - 512 - true - 400 - true - 5 - diff --git a/data/assets/scene/solarsystem/planets/earth/moon/moon.asset b/data/assets/scene/solarsystem/planets/earth/moon/moon.asset index 44692f8ca3..57ed5eddad 100644 --- a/data/assets/scene/solarsystem/planets/earth/moon/moon.asset +++ b/data/assets/scene/solarsystem/planets/earth/moon/moon.asset @@ -30,38 +30,85 @@ local Moon = { SegmentsPerPatch = 64, Layers = { ColorLayers = { - -- Utah based servers - { - Identifier = "ClemUvvis", - Name = "Clem Uvvis", - FilePath = mapServiceConfigs .. "/Utah/ClemUvvis.wms" - }, - { - Identifier = "Kaguya", - FilePath = mapServiceConfigs .. "/Utah/Kaguya.wms" - }, { Identifier = "WAC_Utah", - Name = "WAC Utah", + Name = "WAC [Utah]", FilePath = mapServiceConfigs .. "/Utah/Wac.wms", Enabled = true }, - -- LMMP based servers { - Identifier = "OnMoon", - FilePath = mapServiceConfigs .. "/OnMoonColor.wms" - } + Identifier = "WAC_Sweden", + Name = "WAC [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/WAC.wms" + }, + { + Identifier = "ClemUvvis_Utah", + Name = "Clem Uvvis [Utah]", + FilePath = mapServiceConfigs .. "/Utah/ClemUvvis.wms" + }, + { + Identifier = "ClemUvvis_Sweden", + Name = "Clem Uvvis [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Clem_Uvvis.wms" + }, + { + Identifier = "UvvisHybrid_Utah", + Name = "Uvvis Hybrid [Utah]", + FilePath = mapServiceConfigs .. "/Utah/UvvisHybrid.wms" + }, + { + Identifier = "UvvisHybrid_Sweden", + Name = "Uvvis Hybrid [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Uvvis_Hybrid.wms" + }, + { + Identifier = "Kaguya_Utah", + Name = "Kaguya [Utah]", + FilePath = mapServiceConfigs .. "/Utah/Kaguya.wms" + }, + { + Identifier = "Kaguya_Sweden", + Name = "Kaguya [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Kaguya.wms" + }, + { + Identifier = "Lola_Clr_Shade_Utah", + Name = "Lola Clear Shade [Utah]", + FilePath = mapServiceConfigs .. "/Utah/LolaClrShade.wms" + }, + { + Identifier = "Lola_Clr_Shade_Sweden", + Name = "Lola Clear Shade [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Lola_Clr_Shade.wms" + }, + { + Identifier = "Lola_Shade_Utah", + Name = "Lola Shade [Utah]", + FilePath = mapServiceConfigs .. "/Utah/LolaShade.wms" + }, + { + Identifier = "Lola_Shade_Sweden", + Name = "Lola Shade [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Lola_Shade.wms" + }, }, HeightLayers = { - -- Utah based servers { - Identifier = "LolaDem", - Name = "WAC [Utah]", + Identifier = "LolaDem_Utah", + Name = "Lola DEM [Utah]", FilePath = mapServiceConfigs .. "/Utah/LolaDem.wms", Enabled = true, TilePixelSize = 64, Settings = { Multiplier = 0.5 } + }, + { + Identifier = "LolaDem_Sweden", + Name = "Lola DEM [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Lola_DEM.wms", + TilePixelSize = 64, + Settings = { Multiplier = 0.5 } } + } }, ShadowGroup = { diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Color.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Color.wms new file mode 100644 index 0000000000..4ea03c3a24 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Color.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/Color/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + GEOGCS["Mars2000",DATUM["D_Mars_2000",SPHEROID["Mars_2000_IAU_IAG",3396190,169.8944472236118]],PRIMEM["Greenwich",0],UNIT["Decimal_Degree",0.0174532925199433]] + 512 + 512 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/MDIM.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/MDIM.wms new file mode 100644 index 0000000000..6fb65da473 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/MDIM.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/MDIM/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 92160 + 46080 + 7 + top + + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_CTX.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_CTX.wms new file mode 100644 index 0000000000..e5f9f9f92a --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_CTX.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/Mola_CTX/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 46080 + 23040 + 7 + top + + PROJCS["Mars2000_ECylindrical_clon0",GEOGCS["GCS_Mars_2000_Sphere",DATUM["Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere",3396190,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",0],PARAMETER["standard_parallel_1",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]] + 256 + 256 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms index 52c6b9c84b..06b51a1f68 100644 --- a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_Elevation.wms @@ -21,28 +21,3 @@ ./gdal-cache/mola_elevation 5 - - - \ No newline at end of file diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_HRSC.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_HRSC.wms new file mode 100644 index 0000000000..434f9b8be7 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_HRSC.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/Mola_HRSC/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 106694 + 53347 + 7 + top + + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 512 + 512 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_PseudoColor.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_PseudoColor.wms new file mode 100644 index 0000000000..115fc98bd1 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Mola_PseudoColor.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/Mola_PseudoColor/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 46080 + 23040 + 6 + top + + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 360 + 360 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Day.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Day.wms new file mode 100644 index 0000000000..b52cfeb603 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Day.wms @@ -0,0 +1,20 @@ + + + http:/wms.itn.liu.se/Mars/Themis_IR_Day/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 213390 + 106695 + 9 + top + + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Night.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Night.wms new file mode 100644 index 0000000000..849d34bc5b --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/LiU/Themis_IR_Night.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mars/Themis_IR_Night/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 213388 + 71130 + 9 + top + + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Mars_Color.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Mars_Color.wms index 9129fa1e8c..294a2bcbef 100644 --- a/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Mars_Color.wms +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Mars_Color.wms @@ -12,7 +12,7 @@ 7 top - + GEOGCS["GCS_Mars_2000_Sphere",DATUM["D_Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere_IAU_IAG",3396190.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] 512 512 3 diff --git a/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Themis_IR_Night.wms b/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Themis_IR_Night.wms index 16c4c4380f..6ae6c9848d 100644 --- a/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Themis_IR_Night.wms +++ b/data/assets/scene/solarsystem/planets/mars/map_service_configs/Utah/Themis_IR_Night.wms @@ -7,8 +7,8 @@ 90.0 180.0 -90.0 - 213390 - 106695 + 213388 + 71130 9 top diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index 703eeff975..73c0488c87 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -19,8 +19,8 @@ local mapServiceConfigs = asset.localResource("map_service_configs") local color_layers = { { - Identifier = "MOC_WA_AMNH_Color", - Name = "MOC WA AMNH Color", + Identifier = "MOC_WA_Color_Utah", + Name = "MOC WA Color [Utah]", FilePath = mapServiceConfigs .. "/Utah/Mars_Color.wms", Enabled = true, Fallback = { @@ -30,40 +30,54 @@ local color_layers = { } }, { - Identifier = "Viking_MDIM", - Name = "Viking MDIM", - FilePath = mapServiceConfigs .. "/MARS_Viking_MDIM21.wms" - }, - { - Identifier = "MOLA_Pseudo_Color", - Name = "MOLA Pseudo Color", - FilePath = mapServiceConfigs .. "/Utah/Mola_PseudoColor.wms" - }, - { - Identifier = "MOLA_HRSC", - Name = "MOLA HRSC", - FilePath = mapServiceConfigs .. "/Utah/Mola_HRSC.wms" + Identifier = "MOC_WA_Color_LiU", + Name = "MOC WA Color [LiU]", + FilePath = mapServiceConfigs .. "/LiU/Color.wms", + Fallback = { + Name = "Mars Texture", + FilePath = textures .. "/mars.jpg", + Enabled = true + } }, { Identifier = "Viking_MDIM_Utah", Name = "Viking MDIM [Utah]", FilePath = mapServiceConfigs .. "/Utah/Mdim.wms" }, + { + Identifier = "Viking_MDIM_Sweden", + Name = "Viking MDIM [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/MDIM.wms" + }, { Identifier = "Viking_MDIM_AWS", Name = "Viking MDIM [AWS]", FilePath = mapServiceConfigs .. "/AWS/Mdim.wms" }, + { + Identifier = "MOLA_Pseudo_Color_Utah", + Name = "MOLA Pseudo Color [Utah]", + FilePath = mapServiceConfigs .. "/Utah/Mola_PseudoColor.wms" + }, + { + Identifier = "MOLA_Pseudo_Color_Sweden", + Name = "MOLA Pseudo Color [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Mola_PseudoColor.wms" + }, { Identifier = "MOLA_Pseudo_Color_AWS", Name = "MOLA Pseudo Color [AWS]", FilePath = mapServiceConfigs .. "/AWS/Mola_PseudoColor.wms" }, { - Identifier = "CTX_Mosaic_LiU", - Name = "CTX Mosaic [LiU]", - FilePath = mapServiceConfigs .. "/LiU/CTX.wms", - BlendMode = "Color" + Identifier = "MOLA_HRSC_Utah", + Name = "MOLA HRSC [Utah]", + FilePath = mapServiceConfigs .. "/Utah/Mola_HRSC.wms" + }, + { + Identifier = "MOLA_HRSC_Sweden", + Name = "MOLA HRSC [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Mola_HRSC.wms" }, { Identifier = "CTX_Mosaic_Utah", @@ -71,6 +85,12 @@ local color_layers = { FilePath = mapServiceConfigs .. "/Utah/CTX.wms", BlendMode = "Color" }, + { + Identifier = "CTX_Mosaic_Sweden", + Name = "CTX Mosaic [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/CTX.wms", + BlendMode = "Color" + }, { Identifier = "CTX_Mosaic_AWS", Name = "CTX Mosaic [AWS]", @@ -83,6 +103,18 @@ local color_layers = { FilePath = mapServiceConfigs .. "/Utah/Themis_IR_Day.wms", BlendMode = "Color" }, + { + Identifier = "Themis_IR_Day_Sweden", + Name = "Themis IR Day [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Themis_IR_Day.wms", + BlendMode = "Color" + }, + { + Identifier = "Themis_IR_Day_AWS", + Name = "Themis IR Day [AWS]", + FilePath = mapServiceConfigs .. "/AWS/Themis_IR_Day.wms", + BlendMode = "Color" + }, { Identifier = "Themis_IR_Night_Utah", Name = "Themis IR Night [Utah]", @@ -90,9 +122,9 @@ local color_layers = { BlendMode = "Color" }, { - Identifier = "Themis_IR_Day_AWS_", - Name = "Themis IR Day [AWS]", - FilePath = mapServiceConfigs .. "/AWS/Themis_IR_Day.wms", + Identifier = "Themis_IR_Night_Sweden", + Name = "Themis IR Night [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Themis_IR_Night.wms", BlendMode = "Color" }, { @@ -127,13 +159,13 @@ local height_layers = { Identifier = "Mola_Europe", Name = "Mola Elevation [Europe]", FilePath = mapServiceConfigs .. "/LiU/Mola_Elevation.wms", - Enabled = true, TilePixelSize = 90 }, { Identifier = "Mola_Utah", Name = "Mola Elevation [Utah]", FilePath = mapServiceConfigs .. "/Utah/Mola_Elevation.wms", + Enabled = true, TilePixelSize = 90 }, { diff --git a/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_MDIS.wms b/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_MDIS.wms new file mode 100644 index 0000000000..04a83aa840 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_MDIS.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mercury/Messenger_MDIS/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 61324 + 30662 + 7 + top + + GEOGCS["GCS_Mercury_2015",DATUM["D_Mercury_2015",SPHEROID["Mercury_2015",2439400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_Mosaic.wms b/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_Mosaic.wms new file mode 100644 index 0000000000..938574d8f0 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/mercury/map_service_configs/LiU/Messenger_Mosaic.wms @@ -0,0 +1,20 @@ + + + http://wms.itn.liu.se/Mercury/Messenger_Mosaic/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 23054 + 11527 + 6 + top + + GEOGCS["GCS_Mercury_2015",DATUM["D_Mercury_2015",SPHEROID["Mercury_2015",2439400.0,0.0]],PRIMEM["Reference_Meridian",0.0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 3 + 10 + diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index e4a50c6964..3650676d42 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -8,7 +8,6 @@ asset.request('./trail') local mapServiceConfigs = asset.localResource("map_service_configs") local color_layers = { - -- Utah based servers { Identifier = "Messenger_MDIS_Utah", Name = "Messenger MDIS [Utah]", @@ -16,16 +15,25 @@ local color_layers = { Enabled = true }, { - Identifier = "Messenger_Mosaic_Utah", - Name = "Messenger Mosaic [Utah]", - FilePath = mapServiceConfigs .. "/Utah/MessengerMosaic.wms" + Identifier = "Messenger_MDIS_Sweden", + Name = "Messenger MDIS [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Messenger_MDIS.wms", }, - -- AWS based servers { Identifier = "Messenger_MDIS_AWS", Name = "Messenger MDIS [AWS]", FilePath = mapServiceConfigs .. "/AWS/MessengerMdis.wms" }, + { + Identifier = "Messenger_Mosaic_Utah", + Name = "Messenger Mosaic [Utah]", + FilePath = mapServiceConfigs .. "/Utah/MessengerMosaic.wms" + }, + { + Identifier = "Messenger_Mosaic_Sweden", + Name = "Messenger Mosaic [Sweden]", + FilePath = mapServiceConfigs .. "/LiU/Messenger_Mosaic.wms" + }, { Identifier = "Messenger_Mosaic_AWS", Name = "Messenger Mosaic [AWS]", diff --git a/data/assets/scene/solarsystem/planets/mercury/trail.asset b/data/assets/scene/solarsystem/planets/mercury/trail.asset index 1a7f9c1195..c3ed6f8935 100644 --- a/data/assets/scene/solarsystem/planets/mercury/trail.asset +++ b/data/assets/scene/solarsystem/planets/mercury/trail.asset @@ -16,7 +16,7 @@ local MercuryTrail = { }, Color = { 0.6, 0.5, 0.5 }, Period = 87.968, - Resolution = 100 + Resolution = 1000 }, Tag = { "planetTrail_solarSystem", "planetTrail_terrestrial" }, GUI = { diff --git a/modules/globebrowsing/scripts/layer_support.lua b/modules/globebrowsing/scripts/layer_support.lua index 71f3350027..a5a97a342e 100644 --- a/modules/globebrowsing/scripts/layer_support.lua +++ b/modules/globebrowsing/scripts/layer_support.lua @@ -182,6 +182,7 @@ openspace.globebrowsing.parseInfoFile = function (file) if ColorFile then color = { Identifier = Identifier, + Name = Name or Identifier, Description = Description or "", FilePath = dir .. '/' .. ColorFile, BlendMode = "Color" @@ -192,6 +193,7 @@ openspace.globebrowsing.parseInfoFile = function (file) if HeightFile then height = { Identifier = Identifier, + Name = Name or Identifier, Description = Description or "", FilePath = dir .. '/' .. HeightFile, TilePixelSize = 90 From e13160efb51c610ec155f0dcdbda705e2df50a95 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Wed, 2 May 2018 21:15:25 -0400 Subject: [PATCH 72/79] Add distance information to voyager 1 and 2 Update Saturn Ring texture --- .../solarsystem/planets/saturn/saturn.asset | 4 ++-- data/assets/voyager.scene | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index 0a60fdeb1b..77b45972f2 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -9,7 +9,7 @@ local textures = asset.syncedResource({ Type = "HttpSynchronization", Name = "Saturn textures", Identifier = "saturn_textures", - Version = 2 + Version = 3 }) local Saturn = { @@ -48,7 +48,7 @@ local SaturnRings = { Renderable = { Type = "RenderableRings", Texture = textures .. "/saturn_rings.png", - Size = 140220000, + Size = 140445000, Offset = { 74500 / 140445.100671159, 1.0 } -- min / max extend }, GUI = { diff --git a/data/assets/voyager.scene b/data/assets/voyager.scene index 2de0961651..10dbf3e924 100644 --- a/data/assets/voyager.scene +++ b/data/assets/voyager.scene @@ -22,6 +22,27 @@ asset.require('util/default_dashboard') local VoyagerAsset = asset.require('scene/solarsystem/missions/voyager/voyager1') +assetHelper.registerDashboardItems(asset, { + { + Type = "DashboardItemDistance", + Identifier = "Voyager1Distance", + GuiName = "Voyager 1 - Earth Distance", + SourceType = "Node", + SourceNodeName = "Voyager_1", + DestinationType = "Node", + DestinationNodeName = "Earth" + }, + { + Type = "DashboardItemDistance", + Identifier = "Voyager2Distance", + GuiName = "Voyager 2 - Earth Distance", + SourceType = "Node", + SourceNodeName = "Voyager_2", + DestinationType = "Node", + DestinationNodeName = "Earth" + } +}) + asset.onInitialize(function () openspace.time.setTime("1977 SEP 10 12:00:00") From b5be0db02cf4491732666a2c72ef4f33b200f5fa Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 3 May 2018 15:24:12 -0400 Subject: [PATCH 73/79] Make removeSceneGraphNode remove recursively correctly --- src/scene/scene_lua.inl | 27 ++++++++++++++++++++++----- src/scene/scenegraphnode.cpp | 2 +- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index b390877b16..3a05b23767 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -456,9 +456,10 @@ int addSceneGraphNode(lua_State* L) { int removeSceneGraphNode(lua_State* L) { using ghoul::lua::errorLocation; - ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeSceneGraphNode"); + const int n = ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeSceneGraphNode"); + + std::string nodeName = luaL_checkstring(L, 1); - std::string nodeName = luaL_checkstring(L, -1); SceneGraphNode* node = OsEng.renderEngine().scene()->sceneGraphNode(nodeName); if (!node) { LERRORC( @@ -475,15 +476,31 @@ int removeSceneGraphNode(lua_State* L) { ); return 0; } - node->deinitializeGL(); - parent->detachChild(*node); + + std::function removeNode = + [&removeNode](SceneGraphNode* parent, SceneGraphNode* node) { + std::vector children = node->children(); + + std::unique_ptr n = parent->detachChild(*node); + ghoul_assert(n.get() == node, "Wrong node returned from detaching"); + + for (SceneGraphNode* c : children) { + removeNode(n.get(), c); + } + + node->deinitializeGL(); + node->deinitialize(); + n = nullptr; + }; + + removeNode(parent, node); + lua_settop(L, 0); ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack"); return 0; } - int hasSceneGraphNode(lua_State* L) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::hasSceneGraphNode"); diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index d883056eed..9839d26e87 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -407,7 +407,7 @@ void SceneGraphNode::attachChild(std::unique_ptr child) { // Create link between parent and child child->_parent = this; SceneGraphNode* childRaw = child.get(); - _children.push_back(std::move(child)); + _children.push_back(std::move(child)); // Set scene of child (and children recursively) childRaw->setScene(_scene); From 20ff81017c8cb0e6b7a89d479b69b7527554c687 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 3 May 2018 17:43:29 -0400 Subject: [PATCH 74/79] Keep old image projections on a model --- .../shaders/renderableModelProjection_fs.glsl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl b/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl index cf9f0a0dfb..c47960db4d 100644 --- a/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl +++ b/modules/spacecraftinstruments/shaders/renderableModelProjection_fs.glsl @@ -65,8 +65,9 @@ void main() { stencil = vec4(1.0); } else { - color = vec4(vec3(0.0), 0.0); - stencil = vec4(0.0); + discard; + // color = vec4(vec3(0.0), 0.0); + // stencil = vec4(0.0); } } else { @@ -79,8 +80,9 @@ void main() { stencil = vec4(1.0); } else { - color = vec4(0.0); - stencil = vec4(0.0); + discard; + // color = vec4(0.0); + // stencil = vec4(0.0); } } } From 97b2311cb358bef1802448a93fcc5d8dafdbbc4f Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Fri, 4 May 2018 18:04:47 +0200 Subject: [PATCH 75/79] ToyVolume: Fix bugs, clean up and add example asset --- data/assets/examples/toyvolume.asset | 22 ++++++++++++++ .../rendering/renderabletoyvolume.cpp | 28 +++++++++--------- .../toyvolume/rendering/renderabletoyvolume.h | 2 +- .../rendering/toyvolumeraycaster.cpp | 29 ++++++++++++++++--- .../toyvolume/rendering/toyvolumeraycaster.h | 3 ++ modules/toyvolume/shaders/boundsfs.glsl | 13 ++++----- modules/toyvolume/shaders/boundsvs.glsl | 16 ++++------ 7 files changed, 76 insertions(+), 37 deletions(-) create mode 100644 data/assets/examples/toyvolume.asset diff --git a/data/assets/examples/toyvolume.asset b/data/assets/examples/toyvolume.asset new file mode 100644 index 0000000000..93730536f1 --- /dev/null +++ b/data/assets/examples/toyvolume.asset @@ -0,0 +1,22 @@ +-- This asset requires OpenSpace to be built with the OPENSPACE_MODULE_TOYVOLUME enabled + +local assetHelper = asset.require("util/asset_helper") +local transforms = asset.require("scene/solarsystem/sun/transforms") + +local ToyVolume = { + Identifier = "RenderableToyVolume", + Parent = transforms.SolarSystemBarycenter.Identifier, + Renderable = { + Type = "RenderableToyVolume", + Size = {5, 5, 5}, + ScalingExponent = 11, + StepSize = 0.01, + Color = {1, 0, 0, 1} + }, + GUI = { + Path = "/Examples" + } +} + +local objects = { ToyVolume } +assetHelper.registerSceneGraphNodesAndExport(asset, objects) diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index 8b1e83e99d..b64aee902f 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -34,9 +34,9 @@ #include namespace { - static const openspace::properties::Property::PropertyInfo ScalingInfo = { - "Scaling", - "Scaling", + static const openspace::properties::Property::PropertyInfo SizeInfo = { + "Size", + "Size", "" // @TODO Missing documentation }; @@ -75,7 +75,7 @@ namespace openspace { RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) : Renderable(dictionary) - , _scaling(ScalingInfo, glm::vec3(1.f, 1.f, 1.f), glm::vec3(0.f), glm::vec3(10.f)) + , _size(SizeInfo, glm::vec3(1.f, 1.f, 1.f), glm::vec3(0.f), glm::vec3(10.f)) , _scalingExponent(ScalingExponentInfo, 1, -10, 20) , _stepSize(StepSizeInfo, 0.02f, 0.01f, 1.f ) , _translation(TranslationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(10.f)) @@ -83,24 +83,24 @@ RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) , _color(ColorInfo, glm::vec4(1.f, 0.f, 0.f, 0.1f), glm::vec4(0.f), glm::vec4(1.f)) { float stepSize, scalingExponent; - glm::vec3 scaling, translation, rotation; + glm::vec3 size, translation, rotation; glm::vec4 color; - if (dictionary.getValue("ScalingExponent", scalingExponent)) { + if (dictionary.getValue(ScalingExponentInfo.identifier, scalingExponent)) { _scalingExponent = static_cast(scalingExponent); } - if (dictionary.getValue("Scaling", scaling)) { - _scaling = scaling; + if (dictionary.getValue(SizeInfo.identifier, size)) { + _size = size; } - if (dictionary.getValue("Translation", translation)) { + if (dictionary.getValue(TranslationInfo.identifier, translation)) { _translation = translation; } - if (dictionary.getValue("Rotation", rotation)) { + if (dictionary.getValue(RotationInfo.identifier, rotation)) { _rotation = rotation; } - if (dictionary.getValue("Color", color)) { + if (dictionary.getValue(ColorInfo.identifier, color)) { _color = color; } - if (dictionary.getValue("StepSize", stepSize)) { + if (dictionary.getValue(StepSizeInfo.identifier, stepSize)) { _stepSize = stepSize; } } @@ -124,7 +124,7 @@ void RenderableToyVolume::initializeGL() { onEnabledChange(onChange); - addProperty(_scaling); + addProperty(_size); addProperty(_scalingExponent); addProperty(_stepSize); addProperty(_translation); @@ -158,7 +158,7 @@ void RenderableToyVolume::update(const UpdateData& data) { transform = glm::scale( transform, - static_cast(_scaling) * + static_cast(_size) * std::pow(10.0f, static_cast(_scalingExponent)) ); diff --git a/modules/toyvolume/rendering/renderabletoyvolume.h b/modules/toyvolume/rendering/renderabletoyvolume.h index 0f19ef6f8a..ac2c1e568e 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.h +++ b/modules/toyvolume/rendering/renderabletoyvolume.h @@ -51,7 +51,7 @@ public: void update(const UpdateData& data) override; private: - properties::Vec3Property _scaling; + properties::Vec3Property _size; properties::IntProperty _scalingExponent; properties::FloatProperty _stepSize; properties::Vec3Property _translation; diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.cpp b/modules/toyvolume/rendering/toyvolumeraycaster.cpp index 2ef0828b83..691b295ab4 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.cpp +++ b/modules/toyvolume/rendering/toyvolumeraycaster.cpp @@ -57,9 +57,8 @@ void ToyVolumeRaycaster::deinitialize() { void ToyVolumeRaycaster::renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) { - program.setUniform("modelTransform", _modelTransform); + program.setUniform("modelViewTransform", glm::mat4(modelViewTransform(data))); program.setUniform("viewProjection", data.camera.viewProjectionMatrix()); - Renderable::setPscUniforms(program, data.camera, data.position); // Cull back face glEnable(GL_CULL_FACE); @@ -73,9 +72,8 @@ void ToyVolumeRaycaster::renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) { // Uniforms - program.setUniform("modelTransform", _modelTransform); + program.setUniform("modelViewTransform", glm::mat4(modelViewTransform(data))); program.setUniform("viewProjection", data.camera.viewProjectionMatrix()); - Renderable::setPscUniforms(program, data.camera, data.position); // Cull front face glEnable(GL_CULL_FACE); @@ -88,6 +86,16 @@ void ToyVolumeRaycaster::renderExitPoints(const RenderData& data, glCullFace(GL_BACK); } +glm::dmat4 ToyVolumeRaycaster::modelViewTransform(const RenderData& data) { + glm::dmat4 modelTransform = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * + glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * + glm::dmat4(_modelTransform); + + return data.camera.combinedViewMatrix() * modelTransform; +} + void ToyVolumeRaycaster::preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) { @@ -103,6 +111,19 @@ void ToyVolumeRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramO // For example: release texture units } +bool ToyVolumeRaycaster::cameraIsInside(const RenderData& data, + glm::vec3& localPosition) +{ + glm::vec4 modelPos = + glm::inverse(modelViewTransform(data)) * glm::vec4(0.0, 0.0, 0.0, 1.0); + + localPosition = (glm::vec3(modelPos) + glm::vec3(0.5)); + + return (localPosition.x > 0 && localPosition.x < 1 && + localPosition.y > 0 && localPosition.y < 1 && + localPosition.z > 0 && localPosition.z < 1); +} + std::string ToyVolumeRaycaster::getBoundsVsPath() const { return GlslBoundsVsPath; } diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.h b/modules/toyvolume/rendering/toyvolumeraycaster.h index dd036a94cd..af35b0fb8d 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.h +++ b/modules/toyvolume/rendering/toyvolumeraycaster.h @@ -58,6 +58,7 @@ public: ghoul::opengl::ProgramObject& program) override; void postRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; + bool cameraIsInside(const RenderData& data, glm::vec3& localPosition) override; std::string getBoundsVsPath() const override; std::string getBoundsFsPath() const override; @@ -69,6 +70,8 @@ public: void setTime(double time); void setStepSize(float time); private: + glm::dmat4 modelViewTransform(const RenderData& data); + BoxGeometry _boundingBox; glm::vec4 _color; glm::mat4 _modelTransform; diff --git a/modules/toyvolume/shaders/boundsfs.glsl b/modules/toyvolume/shaders/boundsfs.glsl index d6aa37a100..29a8a3d446 100644 --- a/modules/toyvolume/shaders/boundsfs.glsl +++ b/modules/toyvolume/shaders/boundsfs.glsl @@ -22,18 +22,15 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include "PowerScaling/powerScaling_fs.hglsl" +#include "floatoperations.glsl" #include "fragment.glsl" -in vec3 vPosition; -in vec4 worldPosition; - +in vec3 modelPosition; +in vec4 viewPosition; Fragment getFragment() { - vec4 position = worldPosition; - Fragment frag; - frag.color = vec4(vPosition + 0.5, 1.0); - frag.depth = pscDepth(position); + frag.color = vec4(modelPosition + 0.5, 1.0); + frag.depth = safeLength(viewPosition); return frag; } diff --git a/modules/toyvolume/shaders/boundsvs.glsl b/modules/toyvolume/shaders/boundsvs.glsl index 405a3087d8..68b9d5e9ab 100644 --- a/modules/toyvolume/shaders/boundsvs.glsl +++ b/modules/toyvolume/shaders/boundsvs.glsl @@ -24,24 +24,20 @@ #version __CONTEXT__ -#include "PowerScaling/powerScaling_vs.hglsl" - layout(location = 0) in vec4 vertPosition; -out vec3 vPosition; -out vec4 worldPosition; +out vec3 modelPosition; +out vec4 viewPosition; uniform mat4 viewProjection; -uniform mat4 modelTransform; +uniform mat4 modelViewTransform; void main() { - vPosition = vertPosition.xyz; - worldPosition = modelTransform*vertPosition; - - vec4 position = pscTransform(worldPosition, mat4(1.0)); + modelPosition = vertPosition.xyz; + viewPosition = modelViewTransform*vertPosition; // project the position to view space - gl_Position = viewProjection * position; + gl_Position = viewProjection * viewPosition; gl_Position.z = 1.0; } From 25fbaf42945b1dbc765237d1270e31bc79c39710 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 14 May 2018 13:38:45 -0400 Subject: [PATCH 76/79] Removed extra comma from configuration file. --- openspace.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspace.cfg b/openspace.cfg index 351927681a..c05e089cae 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -24,7 +24,7 @@ SGCTConfig = sgct.config.single{} -- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"} -- Stereo --- SGCTConfig = "${CONFIG}/stereo.xml", +-- SGCTConfig = "${CONFIG}/stereo.xml" -- Spout exit -- SGCTConfig = "${CONFIG}/spout_output.xml" From 959dfa8ede59e41e89e869ed6a5df0ed3d7ff727 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 14 May 2018 14:16:15 -0400 Subject: [PATCH 77/79] Temporarilly moved star's rendering back to original one in order to avoid unkown night sky for non-stereo users. --- data/assets/scene/digitaluniverse/stars.asset | 7 +- modules/space/rendering/renderablestars.cpp | 1096 +++++++++-------- modules/space/rendering/renderablestars.h | 152 +-- modules/space/shaders/star_fs.glsl | 32 +- modules/space/shaders/star_ge.glsl | 98 +- modules/space/shaders/star_vs.glsl | 23 +- 6 files changed, 698 insertions(+), 710 deletions(-) diff --git a/data/assets/scene/digitaluniverse/stars.asset b/data/assets/scene/digitaluniverse/stars.asset index 4203a6b8c7..7f87ad6ea8 100644 --- a/data/assets/scene/digitaluniverse/stars.asset +++ b/data/assets/scene/digitaluniverse/stars.asset @@ -29,10 +29,7 @@ local object = { Type = "RenderableStars", File = speck .. "/stars.speck", Texture = textures .. "/halo.png", - ColorMap = colorLUT .. "/colorbv.cmap", - MagnitudeExponent = 19, - BillboardSize = 30, - Sharpness = 1.3 + ColorMap = colorLUT .. "/colorbv.cmap" }, GUI = { Path = "/Milky Way/Stars" @@ -41,4 +38,4 @@ local object = { -assetHelper.registerSceneGraphNodesAndExport(asset, { object }) +assetHelper.registerSceneGraphNodesAndExport(asset, { object }) \ No newline at end of file diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index dfb5e1394a..7a2e9e2a5e 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -1,33 +1,32 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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 @@ -42,9 +41,6 @@ #include #include #include -#include - -//#define USING_STELLAR_TEST_GRID namespace { constexpr const char* _loggerCat = "RenderableStars"; @@ -104,34 +100,35 @@ namespace { "stars." }; - static const openspace::properties::Property::PropertyInfo MagnitudeExponentInfo = { - "MagnitudeExponent", - "MagnitudeExponent", - "Adjust star magnitude by 10^MagnitudeExponent. " - "Stars closer than this distance are given full opacity. " - "Farther away, stars dim proportionally to the logarithm of their distance." + static const openspace::properties::Property::PropertyInfo TransparencyInfo = { + "Transparency", + "Transparency", + "This value is a multiplicative factor that is applied to the transparency of " + "all stars." }; - static const openspace::properties::Property::PropertyInfo SharpnessInfo = { - "Sharpness", - "Sharpness", - "Adjust star sharpness" + static const openspace::properties::Property::PropertyInfo ScaleFactorInfo = { + "ScaleFactor", + "Scale Factor", + "This value is used as a multiplicative factor that is applied to the apparent " + "size of each star." }; - static const openspace::properties::Property::PropertyInfo BillboardSizeInfo = { - "BillboardSize", - "Billboard Size", - "Set the billboard size of all stars" + static const openspace::properties::Property::PropertyInfo MinBillboardSizeInfo = { + "MinBillboardSize", + "Min Billboard Size", + "This value is used as a lower limit on the size of stars that are rendered. Any " + "stars that have a smaller apparent size will be discarded entirely." }; } // namespace namespace openspace { -documentation::Documentation RenderableStars::Documentation() { - using namespace documentation; - return { - "RenderableStars", - "space_renderablestars", + documentation::Documentation RenderableStars::Documentation() { + using namespace documentation; + return { + "RenderableStars", + "space_renderablestars", { { "Type", @@ -160,286 +157,276 @@ documentation::Documentation RenderableStars::Documentation() { { ColorOptionInfo.identifier, new StringInListVerifier({ - "Color", "Velocity", "Speed" - }), - Optional::Yes, - ColorOptionInfo.description + "Color", "Velocity", "Speed" + }), + Optional::Yes, + ColorOptionInfo.description }, { - MagnitudeExponentInfo.identifier, + TransparencyInfo.identifier, new DoubleVerifier, Optional::Yes, - MagnitudeExponentInfo.description + TransparencyInfo.description }, { - SharpnessInfo.identifier, + ScaleFactorInfo.identifier, new DoubleVerifier, Optional::Yes, - SharpnessInfo.description + ScaleFactorInfo.description }, { - BillboardSizeInfo.identifier, + MinBillboardSizeInfo.identifier, new DoubleVerifier, Optional::Yes, - BillboardSizeInfo.description + MinBillboardSizeInfo.description } } - }; -} + }; + } -RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) - : Renderable(dictionary) - , _pointSpreadFunctionTexturePath(PsfTextureInfo) - , _pointSpreadFunctionTexture(nullptr) - , _pointSpreadFunctionTextureIsDirty(true) - , _colorTexturePath(ColorTextureInfo) - , _colorTexture(nullptr) - , _colorTextureIsDirty(true) - , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) - , _dataIsDirty(true) - , _magnitudeExponent(MagnitudeExponentInfo, 19.f, 0.f, 30.f) - , _sharpness(SharpnessInfo, 1.f, 0.f, 5.f) - , _billboardSize(BillboardSizeInfo, 30.f, 1.f, 100.f) - , _program(nullptr) - , _speckFile("") - , _nValuesPerStar(0) - , _vao(0) - , _vbo(0) -{ - using File = ghoul::filesystem::File; + RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) + , _pointSpreadFunctionTexturePath(PsfTextureInfo) + , _pointSpreadFunctionTexture(nullptr) + , _pointSpreadFunctionTextureIsDirty(true) + , _colorTexturePath(ColorTextureInfo) + , _colorTexture(nullptr) + , _colorTextureIsDirty(true) + , _colorOption(ColorOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _dataIsDirty(true) + , _alphaValue(TransparencyInfo, 1.f, 0.f, 1.f) + , _scaleFactor(ScaleFactorInfo, 1.f, 0.f, 10.f) + , _minBillboardSize(MinBillboardSizeInfo, 1.f, 1.f, 100.f) + , _program(nullptr) + , _speckFile("") + , _nValuesPerStar(0) + , _vao(0) + , _vbo(0) + { + using File = ghoul::filesystem::File; - documentation::testSpecificationAndThrow( - Documentation(), - dictionary, - "RenderableStars" - ); - - _pointSpreadFunctionTexturePath = absPath(dictionary.value( - PsfTextureInfo.identifier - )); - _pointSpreadFunctionFile = std::make_unique(_pointSpreadFunctionTexturePath); - - _colorTexturePath = absPath(dictionary.value( - ColorTextureInfo.identifier - )); - _colorTextureFile = std::make_unique(_colorTexturePath); - - _speckFile = absPath(dictionary.value(KeyFile)); - - _colorOption.addOptions({ - { ColorOption::Color, "Color" }, - { ColorOption::Velocity, "Velocity" }, - { ColorOption::Speed, "Speed" } - }); - if (dictionary.hasKey(ColorOptionInfo.identifier)) { - const std::string colorOption = dictionary.value( - ColorOptionInfo.identifier + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableStars" ); - if (colorOption == "Color") { - _colorOption = ColorOption::Color; - } - else if (colorOption == "Velocity") { - _colorOption = ColorOption::Velocity; - } - else { - _colorOption = ColorOption::Speed; - } - } - _colorOption.onChange([&] { _dataIsDirty = true; }); - addProperty(_colorOption); - _pointSpreadFunctionTexturePath.onChange( - [&]{ _pointSpreadFunctionTextureIsDirty = true; } - ); - _pointSpreadFunctionFile->setCallback( - [&](const File&) { _pointSpreadFunctionTextureIsDirty = true; } - ); - addProperty(_pointSpreadFunctionTexturePath); + _pointSpreadFunctionTexturePath = absPath(dictionary.value( + PsfTextureInfo.identifier + )); + _pointSpreadFunctionFile = std::make_unique(_pointSpreadFunctionTexturePath); - _colorTexturePath.onChange([&]{ _colorTextureIsDirty = true; }); - _colorTextureFile->setCallback( - [&](const File&) { _colorTextureIsDirty = true; } - ); - addProperty(_colorTexturePath); + _colorTexturePath = absPath(dictionary.value( + ColorTextureInfo.identifier + )); + _colorTextureFile = std::make_unique(_colorTexturePath); - if (dictionary.hasKey(MagnitudeExponentInfo.identifier)) { - _magnitudeExponent = static_cast( - dictionary.value(MagnitudeExponentInfo.identifier) + _speckFile = absPath(dictionary.value(KeyFile)); + + _colorOption.addOptions({ + { ColorOption::Color, "Color" }, + { ColorOption::Velocity, "Velocity" }, + { ColorOption::Speed, "Speed" } + }); + if (dictionary.hasKey(ColorOptionInfo.identifier)) { + const std::string colorOption = dictionary.value( + ColorOptionInfo.identifier + ); + if (colorOption == "Color") { + _colorOption = ColorOption::Color; + } + else if (colorOption == "Velocity") { + _colorOption = ColorOption::Velocity; + } + else { + _colorOption = ColorOption::Speed; + } + } + _colorOption.onChange([&] { _dataIsDirty = true; }); + addProperty(_colorOption); + + _pointSpreadFunctionTexturePath.onChange( + [&] { _pointSpreadFunctionTextureIsDirty = true; } ); - } - addProperty(_magnitudeExponent); - - if (dictionary.hasKey(SharpnessInfo.identifier)) { - _sharpness = static_cast( - dictionary.value(SharpnessInfo.identifier) - ); - } - addProperty(_sharpness); - - if (dictionary.hasKey(BillboardSizeInfo.identifier)) { - _billboardSize = static_cast( - dictionary.value(BillboardSizeInfo.identifier) + _pointSpreadFunctionFile->setCallback( + [&](const File&) { _pointSpreadFunctionTextureIsDirty = true; } ); - } - addProperty(_billboardSize); -} + addProperty(_pointSpreadFunctionTexturePath); -RenderableStars::~RenderableStars() {} + _colorTexturePath.onChange([&] { _colorTextureIsDirty = true; }); + _colorTextureFile->setCallback( + [&](const File&) { _colorTextureIsDirty = true; } + ); + addProperty(_colorTexturePath); -bool RenderableStars::isReady() const { - return (_program != nullptr) && (!_fullData.empty()); -} - -void RenderableStars::initializeGL() { - RenderEngine& renderEngine = OsEng.renderEngine(); - _program = renderEngine.buildRenderProgram("Star", - absPath("${MODULE_SPACE}/shaders/star_vs.glsl"), - absPath("${MODULE_SPACE}/shaders/star_fs.glsl"), - absPath("${MODULE_SPACE}/shaders/star_ge.glsl") - ); - - _uniformCache.model = _program->uniformLocation("model"); - _uniformCache.view = _program->uniformLocation("view"); - _uniformCache.viewScaling = _program->uniformLocation("viewScaling"); - _uniformCache.projection = _program->uniformLocation("projection"); - _uniformCache.colorOption = _program->uniformLocation("colorOption"); - _uniformCache.magnitudeExponent = _program->uniformLocation("magnitudeExponent"); - _uniformCache.sharpness = _program->uniformLocation("sharpness"); - _uniformCache.billboardSize = _program->uniformLocation("billboardSize"); - _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); - _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); - - bool success = loadData(); - if (!success) { - throw ghoul::RuntimeError("Error loading data"); - } -} - -void RenderableStars::deinitializeGL() { - glDeleteBuffers(1, &_vbo); - _vbo = 0; - glDeleteVertexArrays(1, &_vao); - _vao = 0; - - _pointSpreadFunctionTexture = nullptr; - _colorTexture = nullptr; - - RenderEngine& renderEngine = OsEng.renderEngine(); - if (_program) { - renderEngine.removeRenderProgram(_program.get()); - _program = nullptr; - } -} - -void RenderableStars::render(const RenderData& data, RendererTasks&) { - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDepthMask(false); - - _program->activate(); - - glm::mat4 model = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - glm::dmat4(data.modelTransform.rotation) * - glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - - glm::mat4 view = data.camera.combinedViewMatrix(); - glm::mat4 projection = data.camera.projectionMatrix(); - float viewScaling = data.camera.scaling(); - - _program->setUniform(_uniformCache.model, model); - _program->setUniform(_uniformCache.view, view); - _program->setUniform(_uniformCache.projection, projection); - _program->setUniform(_uniformCache.viewScaling, viewScaling); - - _program->setUniform(_uniformCache.colorOption, _colorOption); - _program->setUniform(_uniformCache.magnitudeExponent, _magnitudeExponent); - _program->setUniform(_uniformCache.sharpness, _sharpness); - _program->setUniform(_uniformCache.billboardSize, _billboardSize); - _program->setUniform( - _uniformCache.screenSize, - glm::vec2(OsEng.renderEngine().renderingResolution()) - ); - - _program->setUniform("eyePosition", glm::vec3(data.camera.eyePositionVec3())); - - ghoul::opengl::TextureUnit psfUnit; - psfUnit.activate(); - _pointSpreadFunctionTexture->bind(); - _program->setUniform(_uniformCache.psfTexture, psfUnit); - - ghoul::opengl::TextureUnit colorUnit; - colorUnit.activate(); - _colorTexture->bind(); - _program->setUniform(_uniformCache.colorTexture, colorUnit); - - glBindVertexArray(_vao); - const GLsizei nStars = static_cast(_fullData.size() / _nValuesPerStar); - glDrawArrays(GL_POINTS, 0, nStars); - - glBindVertexArray(0); - _program->deactivate(); - - glDepthMask(true); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -} - -void RenderableStars::update(const UpdateData&) { - if (_dataIsDirty) { - const int value = _colorOption; - LDEBUG("Regenerating data"); - - createDataSlice(ColorOption(value)); - - int size = static_cast(_slicedData.size()); - - if (_vao == 0) { - glGenVertexArrays(1, &_vao); + if (dictionary.hasKey(TransparencyInfo.identifier)) { + _alphaValue = static_cast( + dictionary.value(TransparencyInfo.identifier) + ); } - if (_vbo == 0) { - glGenBuffers(1, &_vbo); + addProperty(_alphaValue); + + if (dictionary.hasKey(ScaleFactorInfo.identifier)) { + _scaleFactor = static_cast( + dictionary.value(ScaleFactorInfo.identifier) + ); } + addProperty(_scaleFactor); + + if (dictionary.hasKey(MinBillboardSizeInfo.identifier)) { + _minBillboardSize = static_cast( + dictionary.value(MinBillboardSizeInfo.identifier) + ); + } + addProperty(_minBillboardSize); + } + + RenderableStars::~RenderableStars() {} + + bool RenderableStars::isReady() const { + return (_program != nullptr) && (!_fullData.empty()); + } + + void RenderableStars::initializeGL() { + RenderEngine& renderEngine = OsEng.renderEngine(); + _program = renderEngine.buildRenderProgram("Star", + absPath("${MODULE_SPACE}/shaders/star_vs.glsl"), + absPath("${MODULE_SPACE}/shaders/star_fs.glsl"), + absPath("${MODULE_SPACE}/shaders/star_ge.glsl") + ); + + _uniformCache.view = _program->uniformLocation("view"); + _uniformCache.projection = _program->uniformLocation("projection"); + _uniformCache.colorOption = _program->uniformLocation("colorOption"); + _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); + _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); + _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.screenSize = _program->uniformLocation("screenSize"); + _uniformCache.scaling = _program->uniformLocation("scaling"); + _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); + _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); + + bool success = loadData(); + if (!success) { + throw ghoul::RuntimeError("Error loading data"); + } + } + + void RenderableStars::deinitializeGL() { + glDeleteBuffers(1, &_vbo); + _vbo = 0; + glDeleteVertexArrays(1, &_vao); + _vao = 0; + + _pointSpreadFunctionTexture = nullptr; + _colorTexture = nullptr; + + RenderEngine& renderEngine = OsEng.renderEngine(); + if (_program) { + renderEngine.removeRenderProgram(_program.get()); + _program = nullptr; + } + } + + void RenderableStars::render(const RenderData& data, RendererTasks&) { + glDepthMask(false); + _program->activate(); + + // @Check overwriting the scaling from the camera; error as parsec->meter conversion + // is done twice? ---abock + glm::vec2 scaling = glm::vec2(1, -19); + + _program->setUniform(_uniformCache.view, data.camera.viewMatrix()); + _program->setUniform(_uniformCache.projection, data.camera.projectionMatrix()); + + _program->setUniform(_uniformCache.colorOption, _colorOption); + _program->setUniform(_uniformCache.alphaValue, _alphaValue); + _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); + _program->setUniform(_uniformCache.minBillboardSize, _minBillboardSize); + _program->setUniform( + _uniformCache.screenSize, + glm::vec2(OsEng.renderEngine().renderingResolution()) + ); + + setPscUniforms(*_program.get(), data.camera, data.position); + _program->setUniform(_uniformCache.scaling, scaling); + + ghoul::opengl::TextureUnit psfUnit; + psfUnit.activate(); + _pointSpreadFunctionTexture->bind(); + _program->setUniform(_uniformCache.psfTexture, psfUnit); + + ghoul::opengl::TextureUnit colorUnit; + colorUnit.activate(); + _colorTexture->bind(); + _program->setUniform(_uniformCache.colorTexture, colorUnit); + glBindVertexArray(_vao); - glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferData( - GL_ARRAY_BUFFER, - size * sizeof(GLfloat), - &_slicedData[0], - GL_STATIC_DRAW - ); + const GLsizei nStars = static_cast(_fullData.size() / _nValuesPerStar); + glDrawArrays(GL_POINTS, 0, nStars); - GLint positionAttrib = _program->attributeLocation("in_position"); - GLint brightnessDataAttrib = _program->attributeLocation("in_brightness"); + glBindVertexArray(0); + _program->deactivate(); - const size_t nStars = _fullData.size() / _nValuesPerStar; - const size_t nValues = _slicedData.size() / nStars; + glDepthMask(true); + } - GLsizei stride = static_cast(sizeof(GLfloat) * nValues); + void RenderableStars::update(const UpdateData&) { + if (_dataIsDirty) { + const int value = _colorOption; + LDEBUG("Regenerating data"); - glEnableVertexAttribArray(positionAttrib); - glEnableVertexAttribArray(brightnessDataAttrib); - const int colorOption = _colorOption; - switch (colorOption) { - case ColorOption::Color: - glVertexAttribPointer( - positionAttrib, - 4, - GL_FLOAT, - GL_FALSE, - stride, - nullptr // = offsetof(ColorVBOLayout, position) - ); - glVertexAttribPointer( - brightnessDataAttrib, - 3, - GL_FLOAT, - GL_FALSE, - stride, - reinterpret_cast(offsetof(ColorVBOLayout, bvColor)) + createDataSlice(ColorOption(value)); + + int size = static_cast(_slicedData.size()); + + if (_vao == 0) { + glGenVertexArrays(1, &_vao); + } + if (_vbo == 0) { + glGenBuffers(1, &_vbo); + } + glBindVertexArray(_vao); + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + glBufferData( + GL_ARRAY_BUFFER, + size * sizeof(GLfloat), + &_slicedData[0], + GL_STATIC_DRAW ); - break; - case ColorOption::Velocity: + GLint positionAttrib = _program->attributeLocation("in_position"); + GLint brightnessDataAttrib = _program->attributeLocation("in_brightness"); + + const size_t nStars = _fullData.size() / _nValuesPerStar; + const size_t nValues = _slicedData.size() / nStars; + + GLsizei stride = static_cast(sizeof(GLfloat) * nValues); + + glEnableVertexAttribArray(positionAttrib); + glEnableVertexAttribArray(brightnessDataAttrib); + const int colorOption = _colorOption; + switch (colorOption) { + case ColorOption::Color: + glVertexAttribPointer( + positionAttrib, + 4, + GL_FLOAT, + GL_FALSE, + stride, + nullptr // = offsetof(ColorVBOLayout, position) + ); + glVertexAttribPointer( + brightnessDataAttrib, + 3, + GL_FLOAT, + GL_FALSE, + stride, + reinterpret_cast(offsetof(ColorVBOLayout, bvColor)) + ); + + break; + case ColorOption::Velocity: { glVertexAttribPointer( positionAttrib, @@ -471,7 +458,7 @@ void RenderableStars::update(const UpdateData&) { break; } - case ColorOption::Speed: + case ColorOption::Speed: { glVertexAttribPointer( positionAttrib, @@ -501,293 +488,310 @@ void RenderableStars::update(const UpdateData&) { reinterpret_cast(offsetof(SpeedVBOLayout, speed)) ); } + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); + + _dataIsDirty = false; } - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - _dataIsDirty = false; - } - - if (_pointSpreadFunctionTextureIsDirty) { - LDEBUG("Reloading Point Spread Function texture"); - _pointSpreadFunctionTexture = nullptr; - if (_pointSpreadFunctionTexturePath.value() != "") { - _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( - absPath(_pointSpreadFunctionTexturePath) - ); - - if (_pointSpreadFunctionTexture) { - LDEBUG(fmt::format( - "Loaded texture from '{}'", + if (_pointSpreadFunctionTextureIsDirty) { + LDEBUG("Reloading Point Spread Function texture"); + _pointSpreadFunctionTexture = nullptr; + if (_pointSpreadFunctionTexturePath.value() != "") { + _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_pointSpreadFunctionTexturePath) - )); - _pointSpreadFunctionTexture->uploadTexture(); - } - _pointSpreadFunctionTexture->setFilter( - ghoul::opengl::Texture::FilterMode::AnisotropicMipMap - ); + ); - _pointSpreadFunctionFile = std::make_unique( - _pointSpreadFunctionTexturePath - ); - _pointSpreadFunctionFile->setCallback( - [&](const ghoul::filesystem::File&) { + if (_pointSpreadFunctionTexture) { + LDEBUG(fmt::format( + "Loaded texture from '{}'", + absPath(_pointSpreadFunctionTexturePath) + )); + _pointSpreadFunctionTexture->uploadTexture(); + } + _pointSpreadFunctionTexture->setFilter( + ghoul::opengl::Texture::FilterMode::AnisotropicMipMap + ); + + _pointSpreadFunctionFile = std::make_unique( + _pointSpreadFunctionTexturePath + ); + _pointSpreadFunctionFile->setCallback( + [&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; } - ); - } - _pointSpreadFunctionTextureIsDirty = false; - } - - if (_colorTextureIsDirty) { - LDEBUG("Reloading Color Texture"); - _colorTexture = nullptr; - if (_colorTexturePath.value() != "") { - _colorTexture = ghoul::io::TextureReader::ref().loadTexture( - absPath(_colorTexturePath) - ); - if (_colorTexture) { - LDEBUG(fmt::format( - "Loaded texture from '{}'", - absPath(_colorTexturePath) - )); - _colorTexture->uploadTexture(); + ); } - - _colorTextureFile = std::make_unique( - _colorTexturePath - ); - _colorTextureFile->setCallback( - [&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; } - ); + _pointSpreadFunctionTextureIsDirty = false; + } + + if (_colorTextureIsDirty) { + LDEBUG("Reloading Color Texture"); + _colorTexture = nullptr; + if (_colorTexturePath.value() != "") { + _colorTexture = ghoul::io::TextureReader::ref().loadTexture( + absPath(_colorTexturePath) + ); + if (_colorTexture) { + LDEBUG(fmt::format( + "Loaded texture from '{}'", + absPath(_colorTexturePath) + )); + _colorTexture->uploadTexture(); + } + + _colorTextureFile = std::make_unique( + _colorTexturePath + ); + _colorTextureFile->setCallback( + [&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; } + ); + } + _colorTextureIsDirty = false; + } + + if (_program->isDirty()) { + _program->rebuildFromFile(); + + _uniformCache.view = _program->uniformLocation("view"); + _uniformCache.projection = _program->uniformLocation("projection"); + _uniformCache.colorOption = _program->uniformLocation("colorOption"); + _uniformCache.alphaValue = _program->uniformLocation("alphaValue"); + _uniformCache.scaleFactor = _program->uniformLocation("scaleFactor"); + _uniformCache.minBillboardSize = _program->uniformLocation("minBillboardSize"); + _uniformCache.screenSize = _program->uniformLocation("screenSize"); + _uniformCache.scaling = _program->uniformLocation("scaling"); + _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); + _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); } - _colorTextureIsDirty = false; } - if (_program->isDirty()) { - _program->rebuildFromFile(); + bool RenderableStars::loadData() { + std::string _file = _speckFile; + std::string cachedFile = FileSys.cacheManager()->cachedFilename( + _file, + ghoul::filesystem::CacheManager::Persistent::Yes + ); - _uniformCache.model = _program->uniformLocation("model"); - _uniformCache.view = _program->uniformLocation("view"); - _uniformCache.viewScaling = _program->uniformLocation("viewScaling"); - _uniformCache.projection = _program->uniformLocation("projection"); - _uniformCache.colorOption = _program->uniformLocation("colorOption"); - _uniformCache.magnitudeExponent = _program->uniformLocation("magnitudeExponent"); - _uniformCache.sharpness = _program->uniformLocation("sharpness"); - _uniformCache.billboardSize = _program->uniformLocation("billboardSize"); - _uniformCache.screenSize = _program->uniformLocation("screenSize"); - _uniformCache.psfTexture = _program->uniformLocation("psfTexture"); - _uniformCache.colorTexture = _program->uniformLocation("colorTexture"); - } -} + bool hasCachedFile = FileSys.fileExists(cachedFile); + if (hasCachedFile) { + LINFO(fmt::format( + "Cached file '{}' used for Speck file '{}'", + cachedFile, + _file + )); -bool RenderableStars::loadData() { - std::string _file = _speckFile; - std::string cachedFile = FileSys.cacheManager()->cachedFilename( - _file, - ghoul::filesystem::CacheManager::Persistent::Yes - ); - - bool hasCachedFile = FileSys.fileExists(cachedFile); - if (hasCachedFile) { - LINFO(fmt::format( - "Cached file '{}' used for Speck file '{}'", - cachedFile, - _file - )); - - bool success = loadCachedFile(cachedFile); - if (success) { - return true; + bool success = loadCachedFile(cachedFile); + if (success) { + return true; + } + else { + FileSys.cacheManager()->removeCacheFile(_file); + // Intentional fall-through to the 'else' computation to generate the cache + // file for the next run + } } else { - FileSys.cacheManager()->removeCacheFile(_file); - // Intentional fall-through to the 'else' computation to generate the cache - // file for the next run + LINFO(fmt::format("Cache for Speck file '{}' not found", _file)); } - } - else { - LINFO(fmt::format("Cache for Speck file '{}' not found", _file)); - } - LINFO(fmt::format("Loading Speck file '{}'", _file)); + LINFO(fmt::format("Loading Speck file '{}'", _file)); - bool success = readSpeckFile(); - if (!success) { - return false; - } - - LINFO("Saving cache"); - success = saveCachedFile(cachedFile); - - return success; -} - -bool RenderableStars::readSpeckFile() { - std::string _file = _speckFile; - std::ifstream file(_file); - if (!file.good()) { - LERROR(fmt::format("Failed to open Speck file '{}'", _file)); - return false; - } - - _nValuesPerStar = 0; - - // The beginning of the speck file has a header that either contains comments - // (signaled by a preceding '#') or information about the structure of the file - // (signaled by the keywords 'datavar', 'texturevar', and 'texture') - std::string line = ""; - while (true) { - std::streampos position = file.tellg(); - std::getline(file, line); - - if (line[0] == '#' || line.empty()) { - continue; + bool success = readSpeckFile(); + if (!success) { + return false; } - if (line.substr(0, 7) != "datavar" && - line.substr(0, 10) != "texturevar" && - line.substr(0, 7) != "texture") - { - // we read a line that doesn't belong to the header, so we have to jump back - // before the beginning of the current line - file.seekg(position); - break; - } - - if (line.substr(0, 7) == "datavar") { - // datavar lines are structured as follows: - // datavar # description - // where # is the index of the data variable; so if we repeatedly overwrite - // the 'nValues' variable with the latest index, we will end up with the total - // number of values (+3 since X Y Z are not counted in the Speck file index) - std::stringstream str(line); + LINFO("Saving cache"); + success = saveCachedFile(cachedFile); - std::string dummy; - str >> dummy; - str >> _nValuesPerStar; - _nValuesPerStar += 1; // We want the number, but the index is 0 based - } + return success; } - _nValuesPerStar += 3; // X Y Z are not counted in the Speck file indices - - float minLumValue = std::numeric_limits::max(); - float maxLumValue = std::numeric_limits::min(); - - do { - std::vector values(_nValuesPerStar); - - std::getline(file, line); - std::stringstream str(line); - - for (int i = 0; i < _nValuesPerStar; ++i) { - str >> values[i]; + bool RenderableStars::readSpeckFile() { + std::string _file = _speckFile; + std::ifstream file(_file); + if (!file.good()) { + LERROR(fmt::format("Failed to open Speck file '{}'", _file)); + return false; } - bool nullArray = true; - for (size_t i = 0; i < values.size(); ++i) { - if (values[i] != 0.0) { - nullArray = false; + + _nValuesPerStar = 0; + + // The beginning of the speck file has a header that either contains comments + // (signaled by a preceding '#') or information about the structure of the file + // (signaled by the keywords 'datavar', 'texturevar', and 'texture') + std::string line = ""; + while (true) { + std::streampos position = file.tellg(); + std::getline(file, line); + + if (line[0] == '#' || line.empty()) { + continue; + } + + if (line.substr(0, 7) != "datavar" && + line.substr(0, 10) != "texturevar" && + line.substr(0, 7) != "texture") + { + // we read a line that doesn't belong to the header, so we have to jump back + // before the beginning of the current line + file.seekg(position); break; } - } - minLumValue = std::min(values[4], minLumValue); - maxLumValue = std::max(values[4], minLumValue); - if (!nullArray) { - _fullData.insert(_fullData.end(), values.begin(), values.end()); - } - } while (!file.eof()); - // Normalize Luminosity: - int luminosityVarColumnPos = 4; - for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { - _fullData[i + luminosityVarColumnPos] = - (_fullData[i + luminosityVarColumnPos] - minLumValue) / - (maxLumValue - minLumValue); + if (line.substr(0, 7) == "datavar") { + // datavar lines are structured as follows: + // datavar # description + // where # is the index of the data variable; so if we repeatedly overwrite + // the 'nValues' variable with the latest index, we will end up with the total + // number of values (+3 since X Y Z are not counted in the Speck file index) + std::stringstream str(line); + + std::string dummy; + str >> dummy; + str >> _nValuesPerStar; + _nValuesPerStar += 1; // We want the number, but the index is 0 based + } + } + + _nValuesPerStar += 3; // X Y Z are not counted in the Speck file indices + + do { + std::vector values(_nValuesPerStar); + + std::getline(file, line); + std::stringstream str(line); + + for (int i = 0; i < _nValuesPerStar; ++i) { + str >> values[i]; + } + bool nullArray = true; + for (size_t i = 0; i < values.size(); ++i) { + if (values[i] != 0.0) { + nullArray = false; + break; + } + } + if (!nullArray) { + _fullData.insert(_fullData.end(), values.begin(), values.end()); + } + } while (!file.eof()); + + return true; } - return true; -} + bool RenderableStars::loadCachedFile(const std::string& file) { + std::ifstream fileStream(file, std::ifstream::binary); + if (fileStream.good()) { + int8_t version = 0; + fileStream.read(reinterpret_cast(&version), sizeof(int8_t)); + if (version != CurrentCacheVersion) { + LINFO("The format of the cached file has changed: deleting old cache"); + fileStream.close(); + FileSys.deleteFile(file); + return false; + } -bool RenderableStars::loadCachedFile(const std::string& file) { - std::ifstream fileStream(file, std::ifstream::binary); - if (fileStream.good()) { - int8_t version = 0; - fileStream.read(reinterpret_cast(&version), sizeof(int8_t)); - if (version != CurrentCacheVersion) { - LINFO("The format of the cached file has changed: deleting old cache"); - fileStream.close(); - FileSys.deleteFile(file); + int32_t nValues = 0; + fileStream.read(reinterpret_cast(&nValues), sizeof(int32_t)); + fileStream.read(reinterpret_cast(&_nValuesPerStar), sizeof(int32_t)); + + _fullData.resize(nValues); + fileStream.read(reinterpret_cast(&_fullData[0]), + nValues * sizeof(_fullData[0])); + + bool success = fileStream.good(); + return success; + } + else { + LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); return false; } - - int32_t nValues = 0; - fileStream.read(reinterpret_cast(&nValues), sizeof(int32_t)); - fileStream.read(reinterpret_cast(&_nValuesPerStar), sizeof(int32_t)); - - _fullData.resize(nValues); - fileStream.read(reinterpret_cast(&_fullData[0]), - nValues * sizeof(_fullData[0])); - - bool success = fileStream.good(); - return success; } - else { - LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); - return false; - } -} -bool RenderableStars::saveCachedFile(const std::string& file) const { - std::ofstream fileStream(file, std::ofstream::binary); - if (fileStream.good()) { - fileStream.write(reinterpret_cast(&CurrentCacheVersion), - sizeof(int8_t)); + bool RenderableStars::saveCachedFile(const std::string& file) const { + std::ofstream fileStream(file, std::ofstream::binary); + if (fileStream.good()) { + fileStream.write(reinterpret_cast(&CurrentCacheVersion), + sizeof(int8_t)); - int32_t nValues = static_cast(_fullData.size()); - if (nValues == 0) { - LERROR("Error writing cache: No values were loaded"); + int32_t nValues = static_cast(_fullData.size()); + if (nValues == 0) { + LERROR("Error writing cache: No values were loaded"); + return false; + } + fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); + + int32_t nValuesPerStar = static_cast(_nValuesPerStar); + fileStream.write(reinterpret_cast(&nValuesPerStar), sizeof(int32_t)); + + size_t nBytes = nValues * sizeof(_fullData[0]); + fileStream.write(reinterpret_cast(&_fullData[0]), nBytes); + + bool success = fileStream.good(); + return success; + } + else { + LERROR(fmt::format("Error opening file '{}' for save cache file", file)); return false; } - fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); - - int32_t nValuesPerStar = static_cast(_nValuesPerStar); - fileStream.write(reinterpret_cast(&nValuesPerStar), sizeof(int32_t)); - - size_t nBytes = nValues * sizeof(_fullData[0]); - fileStream.write(reinterpret_cast(&_fullData[0]), nBytes); - - bool success = fileStream.good(); - return success; } - else { - LERROR(fmt::format("Error opening file '{}' for save cache file", file)); - return false; - } -} -void RenderableStars::createDataSlice(ColorOption option) { - _slicedData.clear(); + void RenderableStars::createDataSlice(ColorOption option) { + _slicedData.clear(); - for (size_t i = 0; i < _fullData.size(); i+=_nValuesPerStar) { - glm::vec3 p = glm::vec3(_fullData[i + 0], _fullData[i + 1], _fullData[i + 2]); - p *= openspace::distanceconstants::Parsec; + // This is only temporary until the scalegraph is in place ---abock + float minDistance = std::numeric_limits::max(); + float maxDistance = -std::numeric_limits::max(); - switch (option) { - case ColorOption::Color: + for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { + float distLy = _fullData[i + 6]; + //if (distLy < 20.f) { + minDistance = std::min(minDistance, distLy); + maxDistance = std::max(maxDistance, distLy); + //} + } + + for (size_t i = 0; i < _fullData.size(); i += _nValuesPerStar) { + glm::vec3 p = glm::vec3(_fullData[i + 0], _fullData[i + 1], _fullData[i + 2]); + + // This is only temporary until the scalegraph is in place. It places all stars + // on a sphere with a small variation in the distance to account for blending + // issues ---abock + //if (p != glm::vec3(0.f)) + // p = glm::normalize(p); + + //float distLy = _fullData[i + 6]; + //float normalizedDist = (distLy - minDistance) / (maxDistance - minDistance); + //float distance = 18.f - normalizedDist / 1.f ; + + + //psc position = psc(glm::vec4(p, distance)); + + // Convert parsecs -> meter + psc position = psc(glm::vec4(p * 0.308567756f, 17)); + + //position[1] *= parsecsToMetersFactor[0]; + //position[2] *= parsecsToMetersFactor[0]; + //position[3] += parsecsToMetersFactor[1]; + + switch (option) { + case ColorOption::Color: { union { ColorVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - p[0], p[1], p[2], 1.0 - } }; + position[0], position[1], position[2], position[3] + } }; #ifdef USING_STELLAR_TEST_GRID - layout.value.bvColor = 0.650;// _fullData[i + 3]; - layout.value.luminance = _fullData[i + 4]; + layout.value.bvColor = _fullData[i + 3]; + layout.value.luminance = _fullData[i + 3]; layout.value.absoluteMagnitude = _fullData[i + 3]; #else layout.value.bvColor = _fullData[i + 3]; @@ -796,20 +800,20 @@ void RenderableStars::createDataSlice(ColorOption option) { #endif _slicedData.insert(_slicedData.end(), - layout.data.begin(), - layout.data.end()); + layout.data.begin(), + layout.data.end()); break; } - case ColorOption::Velocity: + case ColorOption::Velocity: { union { VelocityVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - p[0], p[1], p[2], 1.0 + position[0], position[1], position[2], position[3] } }; layout.value.bvColor = _fullData[i + 3]; @@ -821,19 +825,19 @@ void RenderableStars::createDataSlice(ColorOption option) { layout.value.vz = _fullData[i + 14]; _slicedData.insert(_slicedData.end(), - layout.data.begin(), - layout.data.end()); + layout.data.begin(), + layout.data.end()); break; } - case ColorOption::Speed: + case ColorOption::Speed: { union { SpeedVBOLayout value; - std::array data; + std::array data; } layout; layout.value.position = { { - p[0], p[1], p[2], 1.0 + position[0], position[1], position[2], position[3] } }; layout.value.bvColor = _fullData[i + 3]; @@ -843,12 +847,12 @@ void RenderableStars::createDataSlice(ColorOption option) { layout.value.speed = _fullData[i + 15]; _slicedData.insert(_slicedData.end(), - layout.data.begin(), - layout.data.end()); + layout.data.begin(), + layout.data.end()); break; } + } } } -} } // namespace openspace diff --git a/modules/space/rendering/renderablestars.h b/modules/space/rendering/renderablestars.h index 3e8ced2282..e6fd355f5e 100644 --- a/modules/space/rendering/renderablestars.h +++ b/modules/space/rendering/renderablestars.h @@ -1,26 +1,26 @@ /***************************************************************************************** - * * - * 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. * - ****************************************************************************************/ +* * +* 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_MODULE_SPACE___RENDERABLESTARS___H__ #define __OPENSPACE_MODULE_SPACE___RENDERABLESTARS___H__ @@ -42,68 +42,68 @@ namespace ghoul::opengl { namespace openspace { -namespace documentation { struct Documentation; } + namespace documentation { struct Documentation; } -class RenderableStars : public Renderable { -public: - explicit RenderableStars(const ghoul::Dictionary& dictionary); - ~RenderableStars(); + class RenderableStars : public Renderable { + public: + explicit RenderableStars(const ghoul::Dictionary& dictionary); + ~RenderableStars(); - void initializeGL() override; - void deinitializeGL() override; + void initializeGL() override; + void deinitializeGL() override; - bool isReady() const override; + bool isReady() const override; - void render(const RenderData& data, RendererTasks& rendererTask) override; - void update(const UpdateData& data) override; + void render(const RenderData& data, RendererTasks& rendererTask) override; + void update(const UpdateData& data) override; - static documentation::Documentation Documentation(); + static documentation::Documentation Documentation(); -private: - enum ColorOption { - Color = 0, - Velocity = 1, - Speed = 2 + private: + enum ColorOption { + Color = 0, + Velocity = 1, + Speed = 2 + }; + + void createDataSlice(ColorOption option); + + bool loadData(); + bool readSpeckFile(); + bool loadCachedFile(const std::string& file); + bool saveCachedFile(const std::string& file) const; + + properties::StringProperty _pointSpreadFunctionTexturePath; + std::unique_ptr _pointSpreadFunctionTexture; + std::unique_ptr _pointSpreadFunctionFile; + bool _pointSpreadFunctionTextureIsDirty; + + properties::StringProperty _colorTexturePath; + std::unique_ptr _colorTexture; + std::unique_ptr _colorTextureFile; + bool _colorTextureIsDirty; + + properties::OptionProperty _colorOption; + bool _dataIsDirty; + + properties::FloatProperty _alphaValue; + properties::FloatProperty _scaleFactor; + properties::FloatProperty _minBillboardSize; + + std::unique_ptr _program; + UniformCache(view, projection, colorOption, alphaValue, scaleFactor, + minBillboardSize, screenSize, scaling, psfTexture, colorTexture) _uniformCache; + + std::string _speckFile; + + std::vector _slicedData; + std::vector _fullData; + int _nValuesPerStar; + + GLuint _vao; + GLuint _vbo; }; - void createDataSlice(ColorOption option); - - bool loadData(); - bool readSpeckFile(); - bool loadCachedFile(const std::string& file); - bool saveCachedFile(const std::string& file) const; - - properties::StringProperty _pointSpreadFunctionTexturePath; - std::unique_ptr _pointSpreadFunctionTexture; - std::unique_ptr _pointSpreadFunctionFile; - bool _pointSpreadFunctionTextureIsDirty; - - properties::StringProperty _colorTexturePath; - std::unique_ptr _colorTexture; - std::unique_ptr _colorTextureFile; - bool _colorTextureIsDirty; - - properties::OptionProperty _colorOption; - bool _dataIsDirty; - - properties::FloatProperty _magnitudeExponent; - properties::FloatProperty _sharpness; - properties::FloatProperty _billboardSize; - - std::unique_ptr _program; - UniformCache(model, view, viewScaling, projection, colorOption, magnitudeExponent, sharpness, - billboardSize, screenSize, scaling, psfTexture, colorTexture) _uniformCache; - - std::string _speckFile; - - std::vector _slicedData; - std::vector _fullData; - int _nValuesPerStar; - - GLuint _vao; - GLuint _vbo; -}; - } // namespace openspace #endif // __OPENSPACE_MODULE_SPACE___RENDERABLESTARS___H__ diff --git a/modules/space/shaders/star_fs.glsl b/modules/space/shaders/star_fs.glsl index a128debca7..57cc7fd866 100644 --- a/modules/space/shaders/star_fs.glsl +++ b/modules/space/shaders/star_fs.glsl @@ -23,7 +23,7 @@ ****************************************************************************************/ #include "fragment.glsl" -#include "floatoperations.glsl" +#include "PowerScaling/powerScaling_fs.hglsl" // keep in sync with renderablestars.h:ColorOption enum const int COLOROPTION_COLOR = 0; @@ -32,11 +32,10 @@ const int COLOROPTION_SPEED = 2; uniform sampler2D psfTexture; uniform sampler1D colorTexture; +uniform float minBillboardSize; -uniform float magnitudeExponent; -uniform float sharpness; +uniform float alphaValue; uniform int colorOption; -uniform vec3 eyePosition; in vec4 vs_position; in vec4 ge_gPosition; @@ -44,8 +43,13 @@ in vec3 ge_brightness; in vec3 ge_velocity; in float ge_speed; in vec2 texCoord; -in float ge_observationDistance; -in vec4 ge_worldPosition; +in float billboardSize; + +#include "fragment.glsl" +//#include "PowerScaling/powerScaling_fs.hglsl" + +uniform vec2 magnitudeClamp; + vec4 bv2rgb(float bv) { // BV is [-0.4,2.0] @@ -56,7 +60,7 @@ vec4 bv2rgb(float bv) { Fragment getFragment() { // Something in the color calculations need to be changed because before it was dependent // on the gl blend functions since the abuffer was not involved - + vec4 color = vec4(0.0); switch (colorOption) { case COLOROPTION_COLOR: @@ -73,15 +77,19 @@ Fragment getFragment() { vec4 textureColor = texture(psfTexture, texCoord); vec4 fullColor = vec4(color.rgb, textureColor.a); - fullColor.a = pow(fullColor.a, sharpness); + fullColor.a *= alphaValue; - float d = magnitudeExponent - log(ge_observationDistance) / log(10.0); - fullColor.a *= clamp(d, 0.0, 1.0); + vec4 position = vs_position; + // This has to be fixed when the scale graph is in place ---emiax + position.w = 15; Fragment frag; frag.color = fullColor; - frag.depth = safeLength(vs_position); + frag.depth = pscDepth(position); + + // G-Buffer frag.gPosition = ge_gPosition; + // There is no normal here frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); if (fullColor.a == 0) { @@ -89,4 +97,4 @@ Fragment getFragment() { } return frag; -} +} \ No newline at end of file diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index 64389c6e5d..4dd4ad6378 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -24,15 +24,15 @@ #version __CONTEXT__ -#include "floatoperations.glsl" +#include "PowerScaling/powerScalingMath.hglsl" layout(points) in; - +in vec4 psc_position[]; in vec3 vs_brightness[]; in vec3 vs_velocity[]; in vec4 vs_gPosition[]; in float vs_speed[]; -in vec4 vs_worldPosition[]; +in vec4 cam_position[]; layout(triangle_strip, max_vertices = 4) out; @@ -42,14 +42,13 @@ out vec3 ge_brightness; out vec3 ge_velocity; out float ge_speed; out vec2 texCoord; -out float ge_observationDistance; -out vec4 ge_worldPosition; +out float billboardSize; + +uniform mat4 projection; -uniform float viewScaling; uniform float scaleFactor; -uniform float billboardSize; +uniform float minBillboardSize; uniform vec2 screenSize; -uniform vec3 eyePosition; const vec2 corners[4] = vec2[4]( vec2(0.0, 1.0), @@ -58,77 +57,52 @@ const vec2 corners[4] = vec2[4]( vec2(1.0, 0.0) ); -void main() { - if ((vs_worldPosition[0].x == 0.0) && - (vs_worldPosition[0].y == 0.0) && - (vs_worldPosition[0].z == 0.0)) - { - return; - } +void main() { + // JCC: We want to display the Sun. + // if ((psc_position[0].x == 0.0) && + // (psc_position[0].y == 0.0) && + // (psc_position[0].z == 0.0)) + // { + // return; + // } ge_brightness = vs_brightness[0]; ge_velocity = vs_velocity[0]; ge_speed = vs_speed[0]; - ge_worldPosition = vs_worldPosition[0]; - vec4 projectedPoint = gl_in[0].gl_Position; - - float distanceToStarInParsecs = length(ge_worldPosition.xyz / 3.0856776E16 - eyePosition / 3.0856776E16); + float absoluteMagnitude = vs_brightness[0].z; + float modifiedSpriteSize = + exp((-30.623 - absoluteMagnitude) * 0.462) * scaleFactor * 2000; - float luminosity = ge_brightness.y; - - // Working like Partiview - float pSize = 3.0E5; - float slum = 1.0; - float samplingFactor = 1.0; - float apparentBrightness = (pSize * slum * samplingFactor * luminosity) / (distanceToStarInParsecs * distanceToStarInParsecs); - - vec2 multiplier = vec2(apparentBrightness * projectedPoint.w); - - // Max Star Sizes: - // Fragment Coords: - vec2 bottomLeft = screenSize * ((projectedPoint.xy + vec2(multiplier) * corners[1])/projectedPoint.w + vec2(1.0)) - vec2(0.5); - vec2 topRight = screenSize * ((projectedPoint.xy + vec2(multiplier) * corners[2])/projectedPoint.w + vec2(1.0)) - vec2(0.5); + vec4 projPos[4]; + for (int i = 0; i < 4; ++i) { + vec4 p1 = gl_in[0].gl_Position; + p1.xy += vec2(modifiedSpriteSize * (corners[i] - vec2(0.5))); + projPos[i] = projection * p1; + } - float height = abs(topRight.y - bottomLeft.y); - float width = abs(topRight.x - bottomLeft.x); - float var = (height + width); + // Calculate the positions of the lower left and upper right corners of the + // billboard in screen-space + vec2 ll = (((projPos[1].xy / projPos[1].w) + 1.0) / 2.0) * screenSize; + vec2 ur = (((projPos[2].xy / projPos[2].w) + 1.0) / 2.0) * screenSize; - float maxBillboardSize = billboardSize; - float minBillboardSize = 1.0; + // The billboard is smaller than one pixel, we can discard it + float sizeInPixels = length(ll - ur); + if (sizeInPixels < minBillboardSize) { + return; + } - if ((height > maxBillboardSize) || - (width > maxBillboardSize)) { - //if (height > maxBillboardSize) { - float correctionScale = height > maxBillboardSize ? maxBillboardSize / (topRight.y - bottomLeft.y) : - maxBillboardSize / (topRight.x - bottomLeft.x); - multiplier *= correctionScale; - } else { - if (width < 2.0f * minBillboardSize) { - float maxVar = 2.0f * minBillboardSize; - float minVar = minBillboardSize; - float ta = ( (var - minVar)/(maxVar - minVar) ); - if (ta == 0.0f) - return; - } - } - - vec2 starSize = multiplier; - for (int i = 0; i < 4; i++) { vs_position = gl_in[0].gl_Position; - gl_Position = projectedPoint + vec4(starSize * (corners[i] - 0.5), 0.0, 0.0); - gl_Position.z = 0.0; - + gl_Position = projPos[i]; texCoord = corners[i]; // G-Buffer ge_gPosition = vs_gPosition[0]; - ge_observationDistance = safeLength(vs_gPosition[0] / viewScaling); - + billboardSize = sizeInPixels; EmitVertex(); } EndPrimitive(); -} +} \ No newline at end of file diff --git a/modules/space/shaders/star_vs.glsl b/modules/space/shaders/star_vs.glsl index f204842af3..be301601a5 100644 --- a/modules/space/shaders/star_vs.glsl +++ b/modules/space/shaders/star_vs.glsl @@ -31,25 +31,30 @@ in vec3 in_brightness; in vec3 in_velocity; in float in_speed; +out vec4 psc_position; out vec3 vs_brightness; out vec3 vs_velocity; out float vs_speed; out vec4 vs_gPosition; -out vec4 vs_worldPosition; -uniform mat4 model; uniform mat4 view; uniform mat4 projection; + void main() { + vec4 p = in_position; + psc_position = p; vs_brightness = in_brightness; vs_velocity = in_velocity; vs_speed = in_speed; - vec3 modelPosition = in_position.xyz; - vs_worldPosition = model * vec4(modelPosition, 1.0); - vec4 viewPosition = view * vs_worldPosition; - - vs_gPosition = viewPosition; - gl_Position = projection * vs_gPosition; -} + vec4 tmp = p; + vec4 position = pscTransform(tmp, mat4(1.0)); + + // G-Buffer + vs_gPosition = view * (vec4(1E19, 1E19, 1E19, 1.0) * position); + + position = view * position; + + gl_Position = position; +} \ No newline at end of file From 26c65915d422b82a583f556b9f5a908c47b6b86b Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 14 May 2018 15:03:09 -0400 Subject: [PATCH 78/79] Fixed double initialization of font renderer and fixed bug in the msaa sampling pattern creation. --- src/engine/openspaceengine.cpp | 17 ----------------- src/rendering/framebufferrenderer.cpp | 6 ++++++ 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index d07ab52eb4..0812d9586d 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -858,23 +858,6 @@ void OpenSpaceEngine::loadFonts() { )); } } - - try { - bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); - if (!initSuccess) { - LERROR("Error initializing default font renderer"); - } - - using FR = ghoul::fontrendering::FontRenderer; - FR::defaultRenderer().setFramebufferSize(_renderEngine->fontResolution()); - - FR::defaultProjectionRenderer().setFramebufferSize( - _renderEngine->renderingResolution() - ); - } - catch (const ghoul::RuntimeError& err) { - LERRORC(err.component, err.message); - } } void OpenSpaceEngine::configureLogging(bool consoleLog) { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 856e0e8317..7750b74489 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -264,6 +264,10 @@ void FramebufferRenderer::deferredcastersChanged(Deferredcaster& /*deferredcaste } void FramebufferRenderer::update() { + if (_dirtyMsaaSamplingPattern) { + updateMSAASamplingPattern(); + } + if (_dirtyResolution) { updateResolution(); updateMSAASamplingPattern(); @@ -889,6 +893,8 @@ void FramebufferRenderer::updateMSAASamplingPattern() { glDeleteTextures(1, &nOneStripTexture); glDeleteBuffers(1, &nOneStripVBO); glDeleteVertexArrays(1, &nOneStripVAO); + + _dirtyMsaaSamplingPattern = false; } void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor, From a6501cb288ec61ff1e123754ab6baa07928c17b0 Mon Sep 17 00:00:00 2001 From: Emil Axelsson Date: Tue, 15 May 2018 10:03:18 +0200 Subject: [PATCH 79/79] Add missing include --- src/rendering/transferfunction.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/rendering/transferfunction.cpp b/src/rendering/transferfunction.cpp index 4d3800be54..7525713ce7 100644 --- a/src/rendering/transferfunction.cpp +++ b/src/rendering/transferfunction.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include #include