diff --git a/include/openspace/camera/camera.h b/include/openspace/camera/camera.h index fbad73b5ed..99fcba95fd 100644 --- a/include/openspace/camera/camera.h +++ b/include/openspace/camera/camera.h @@ -38,18 +38,17 @@ class SceneGraphNode; * This class still needs some more love. Suggested improvements: * - Accessors should return constant references to double precision class members. * - Remove the scaling variable (What is it used for?) - * - Remove the maxFov and sinMaxfov variables. Redundant since the fov is embedded - * within the perspective projection matrix. - * - Remove focusposition, part of the integration with the scale graph. The - * "focus position" should not be needed since we assume the camera is always - * positioned relative to its origin. When orbiting another object (not in origin), - * the focus position should probably be handled outside the camera class - * (interaction handler) since it does not affect the state of the camera - * (only how it interacts). - * - The class might need some more reasonable accessors depending on use cases. - * (up vector world space?) - * - Make clear which function returns a combined view matrix (things that are - * dependent on the separate sgct nodes). + * - Remove the maxFov and sinMaxfov variables. Redundant since the fov is embedded within + * the perspective projection matrix + * - Remove focusposition, part of the integration with the scale graph. The "focus + * position" should not be needed since we assume the camera is always positioned + * relative to its origin. When orbiting another object (not in origin), the focus + * position should probably be handled outside the camera class (interaction handler) + * since it does not affect the state of the camera (only how it interacts) + * - The class might need some more reasonable accessors depending on use cases. (up + * vector world space?) + * - Make clear which function returns a combined view matrix (things that are dependent + * on the separate sgct nodes). */ class Camera { public: diff --git a/include/openspace/engine/globalscallbacks.h b/include/openspace/engine/globalscallbacks.h index f454fb134e..1a10e1f94d 100644 --- a/include/openspace/engine/globalscallbacks.h +++ b/include/openspace/engine/globalscallbacks.h @@ -76,6 +76,6 @@ extern void (*webBrowserPerformanceHotfix)(); void create(); void destroy(); -} // namespace openspace::global +} // namespace openspace::global::callback #endif // __OPENSPACE_CORE___GLOBALSCALLBACKS___H__ diff --git a/include/openspace/scene/lightsource.h b/include/openspace/scene/lightsource.h index ece1fd50ba..964d6f0f26 100644 --- a/include/openspace/scene/lightsource.h +++ b/include/openspace/scene/lightsource.h @@ -26,8 +26,8 @@ #define __OPENSPACE_CORE___LIGHTSOURCE___H__ #include -#include +#include #include #include @@ -45,7 +45,6 @@ public: static std::unique_ptr createFromDictionary( const ghoul::Dictionary& dictionary); - LightSource(); explicit LightSource(const ghoul::Dictionary& dictionary); ~LightSource() override = default; diff --git a/include/openspace/scene/scenegraphnode.h b/include/openspace/scene/scenegraphnode.h index 58ea6a2c9a..8e5a19c81a 100644 --- a/include/openspace/scene/scenegraphnode.h +++ b/include/openspace/scene/scenegraphnode.h @@ -157,7 +157,8 @@ private: glm::dmat3 calculateWorldRotation() const; glm::dvec3 calculateWorldScale() const; void computeScreenSpaceData(RenderData& newData); - void renderDebugSphere(const Camera& camera, double size, const glm::vec4& color); + void renderDebugSphere(const Camera& camera, double size, + const glm::vec4& color) const; std::atomic _state = State::Loaded; std::vector> _children; diff --git a/include/openspace/util/planegeometry.h b/include/openspace/util/planegeometry.h index 6d34a12dc6..c3f32f8c2c 100644 --- a/include/openspace/util/planegeometry.h +++ b/include/openspace/util/planegeometry.h @@ -35,7 +35,7 @@ public: explicit PlaneGeometry(glm::vec2 size); explicit PlaneGeometry(float size); - ~PlaneGeometry(); + ~PlaneGeometry() = default; void initialize(); void deinitialize(); diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index e67dbe6146..e030993dc2 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -127,20 +127,10 @@ namespace { namespace openspace { documentation::Documentation DashboardItemAngle::Documentation() { - documentation::Documentation doc = - codegen::doc("base_dashboarditem_angle"); - - // @TODO cleanup - // Insert the parent's documentation entries until we have a verifier that can deal - // with class hierarchy - documentation::Documentation parentDoc = DashboardTextItem::Documentation(); - doc.entries.insert( - doc.entries.end(), - parentDoc.entries.begin(), - parentDoc.entries.end() + return codegen::doc( + "base_dashboarditem_angle", + DashboardTextItem::Documentation() ); - - return doc; } DashboardItemAngle::DashboardItemAngle(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemdate.cpp b/modules/base/dashboard/dashboarditemdate.cpp index cbef64632f..e73c82293c 100644 --- a/modules/base/dashboard/dashboarditemdate.cpp +++ b/modules/base/dashboard/dashboarditemdate.cpp @@ -67,7 +67,10 @@ namespace { namespace openspace { documentation::Documentation DashboardItemDate::Documentation() { - return codegen::doc("base_dashboarditem_date"); + return codegen::doc( + "base_dashboarditem_date", + DashboardTextItem::Documentation() + ); } DashboardItemDate::DashboardItemDate(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemdistance.cpp b/modules/base/dashboard/dashboarditemdistance.cpp index 5d79dd39a7..e687ec7353 100644 --- a/modules/base/dashboard/dashboarditemdistance.cpp +++ b/modules/base/dashboard/dashboarditemdistance.cpp @@ -268,7 +268,7 @@ std::pair DashboardItemDistance::positionAndLabel( Component& otherComp) const { if ((mainComp.type == Type::Node) || (mainComp.type == Type::NodeSurface)) { - if (!mainComp.node) { + if (!mainComp.node) [[unlikely]] { mainComp.node = global::renderEngine->scene()->sceneGraphNode( mainComp.nodeName ); diff --git a/modules/base/dashboard/dashboarditemelapsedtime.cpp b/modules/base/dashboard/dashboarditemelapsedtime.cpp index 4426fb6363..4a6a6f93a6 100644 --- a/modules/base/dashboard/dashboarditemelapsedtime.cpp +++ b/modules/base/dashboard/dashboarditemelapsedtime.cpp @@ -101,7 +101,10 @@ namespace { namespace openspace { documentation::Documentation DashboardItemElapsedTime::Documentation() { - return codegen::doc("base_dashboarditem_elapsedtime"); + return codegen::doc( + "base_dashboarditem_elapsedtime", + DashboardTextItem::Documentation() + ); } DashboardItemElapsedTime::DashboardItemElapsedTime(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemframerate.cpp b/modules/base/dashboard/dashboarditemframerate.cpp index 4971cb1e8e..f272e1b110 100644 --- a/modules/base/dashboard/dashboarditemframerate.cpp +++ b/modules/base/dashboard/dashboarditemframerate.cpp @@ -41,8 +41,7 @@ namespace { DtStandardDeviation, DtCoefficientOfVariation, FPS, - FPSAvg, - None + FPSAvg }; constexpr openspace::properties::Property::PropertyInfo FrametimeInfo = { @@ -184,8 +183,7 @@ DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictiona "Deltatime coefficient of variation" }, { static_cast(FrametimeType::FPS), "Frames per second" }, - { static_cast(FrametimeType::FPSAvg), "Average frames per second" }, - { static_cast(FrametimeType::None), "None" } + { static_cast(FrametimeType::FPSAvg), "Average frames per second" } }); if (p.frametimeType.has_value()) { @@ -206,7 +204,7 @@ DashboardItemFramerate::DashboardItemFramerate(const ghoul::Dictionary& dictiona void DashboardItemFramerate::update() { ZoneScoped; - if (_shouldClearCache) { + if (_shouldClearCache) [[unlikely]] { _minDeltaTimeCache = 1.0; _maxDeltaTimeCache = -1.0; _shouldClearCache = false; diff --git a/modules/base/dashboard/dashboarditempropertyvalue.cpp b/modules/base/dashboard/dashboarditempropertyvalue.cpp index 0b09c2bc23..c3b5b17ee4 100644 --- a/modules/base/dashboard/dashboarditempropertyvalue.cpp +++ b/modules/base/dashboard/dashboarditempropertyvalue.cpp @@ -110,7 +110,7 @@ DashboardItemPropertyValue::DashboardItemPropertyValue( void DashboardItemPropertyValue::update() { ZoneScoped; - if (_propertyIsDirty) { + if (_propertyIsDirty) [[unlikely]] { _property = openspace::property(_propertyUri); _propertyIsDirty = false; } diff --git a/modules/base/dashboard/dashboarditemspacing.cpp b/modules/base/dashboard/dashboarditemspacing.cpp index 2a485848e3..96778dcc06 100644 --- a/modules/base/dashboard/dashboarditemspacing.cpp +++ b/modules/base/dashboard/dashboarditemspacing.cpp @@ -47,7 +47,10 @@ namespace { namespace openspace { documentation::Documentation DashboardItemSpacing::Documentation() { - return codegen::doc("base_dashboarditem_spacing"); + return codegen::doc( + "base_dashboarditem_spacing", + DashboardItem::Documentation() + ); } DashboardItemSpacing::DashboardItemSpacing(const ghoul::Dictionary& dictionary) diff --git a/modules/base/dashboard/dashboarditemvelocity.cpp b/modules/base/dashboard/dashboarditemvelocity.cpp index 1f9b777028..162a710757 100644 --- a/modules/base/dashboard/dashboarditemvelocity.cpp +++ b/modules/base/dashboard/dashboarditemvelocity.cpp @@ -64,7 +64,6 @@ namespace { [[codegen::inlist(openspace::distanceUnitList())]]; }; #include "dashboarditemvelocity_codegen.cpp" - } // namespace namespace openspace { diff --git a/modules/base/lightsource/cameralightsource.cpp b/modules/base/lightsource/cameralightsource.cpp index ed7694d9bd..1041f60277 100644 --- a/modules/base/lightsource/cameralightsource.cpp +++ b/modules/base/lightsource/cameralightsource.cpp @@ -50,12 +50,6 @@ documentation::Documentation CameraLightSource::Documentation() { return codegen::doc("base_camera_light_source"); } -CameraLightSource::CameraLightSource() - : _intensity(IntensityInfo, 1.f, 0.f, 1.f) -{ - addProperty(_intensity); -} - CameraLightSource::CameraLightSource(const ghoul::Dictionary& dictionary) : LightSource(dictionary) , _intensity(IntensityInfo, 1.f, 0.f, 1.f) diff --git a/modules/base/lightsource/cameralightsource.h b/modules/base/lightsource/cameralightsource.h index f3c4b5e5af..c3ccad79a7 100644 --- a/modules/base/lightsource/cameralightsource.h +++ b/modules/base/lightsource/cameralightsource.h @@ -28,7 +28,6 @@ #include #include -#include namespace openspace { @@ -36,7 +35,6 @@ namespace documentation { struct Documentation; } class CameraLightSource : public LightSource { public: - CameraLightSource(); explicit CameraLightSource(const ghoul::Dictionary& dictionary); glm::vec3 directionViewSpace(const RenderData& renderData) const override; diff --git a/modules/base/lightsource/scenegraphlightsource.cpp b/modules/base/lightsource/scenegraphlightsource.cpp index efa98937f5..7e63aad5b7 100644 --- a/modules/base/lightsource/scenegraphlightsource.cpp +++ b/modules/base/lightsource/scenegraphlightsource.cpp @@ -64,23 +64,21 @@ documentation::Documentation SceneGraphLightSource::Documentation() { return codegen::doc("base_scene_graph_light_source"); } -SceneGraphLightSource::SceneGraphLightSource() - : _intensity(IntensityInfo, 1.f, 0.f, 1.f) +SceneGraphLightSource::SceneGraphLightSource(const ghoul::Dictionary& dictionary) + : LightSource(dictionary) + , _intensity(IntensityInfo, 1.f, 0.f, 1.f) , _sceneGraphNodeReference(NodeCameraStateInfo, "") { + const Parameters p = codegen::bake(dictionary); + + _intensity = p.intensity.value_or(_intensity); addProperty(_intensity); + _sceneGraphNodeReference.onChange([this]() { _sceneGraphNode = global::renderEngine->scene()->sceneGraphNode(_sceneGraphNodeReference); }); addProperty(_sceneGraphNodeReference); -} - -SceneGraphLightSource::SceneGraphLightSource(const ghoul::Dictionary& dictionary) - : SceneGraphLightSource() -{ - const Parameters p = codegen::bake(dictionary); - _intensity = p.intensity.value_or(_intensity); _sceneGraphNodeReference = p.node; } diff --git a/modules/base/lightsource/scenegraphlightsource.h b/modules/base/lightsource/scenegraphlightsource.h index caea185d75..28fe09d091 100644 --- a/modules/base/lightsource/scenegraphlightsource.h +++ b/modules/base/lightsource/scenegraphlightsource.h @@ -36,7 +36,6 @@ namespace documentation { struct Documentation; } class SceneGraphLightSource : public LightSource { public: - SceneGraphLightSource(); explicit SceneGraphLightSource(const ghoul::Dictionary& dictionary); static documentation::Documentation Documentation(); diff --git a/modules/base/rendering/grids/renderableboxgrid.cpp b/modules/base/rendering/grids/renderableboxgrid.cpp index b6b167e04b..4eaa8190aa 100644 --- a/modules/base/rendering/grids/renderableboxgrid.cpp +++ b/modules/base/rendering/grids/renderableboxgrid.cpp @@ -157,9 +157,9 @@ void RenderableBoxGrid::render(const RenderData& data, RendererTasks&) { // Change GL state: #ifndef __APPLE__ glLineWidth(_lineWidth); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(1.f); -#endif +#endif // __APPLE__ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnablei(GL_BLEND, 0); glEnable(GL_LINE_SMOOTH); @@ -178,7 +178,7 @@ void RenderableBoxGrid::render(const RenderData& data, RendererTasks&) { } void RenderableBoxGrid::update(const UpdateData&) { - if (_gridIsDirty) { + if (_gridIsDirty) [[unlikely]] { const glm::vec3 llf = -_size.value() / 2.f; const glm::vec3 urb = _size.value() / 2.f; diff --git a/modules/base/rendering/grids/renderablegrid.cpp b/modules/base/rendering/grids/renderablegrid.cpp index 14302035b2..531fea7e23 100644 --- a/modules/base/rendering/grids/renderablegrid.cpp +++ b/modules/base/rendering/grids/renderablegrid.cpp @@ -123,8 +123,7 @@ namespace { std::optional size; // [[codegen::verbatim(LabelsInfo.description)]] - std::optional labels - [[codegen::reference("labelscomponent")]]; + std::optional labels [[codegen::reference("labelscomponent")]]; }; #include "renderablegrid_codegen.cpp" } // namespace @@ -188,7 +187,7 @@ RenderableGrid::RenderableGrid(const ghoul::Dictionary& dictionary) } bool RenderableGrid::isReady() const { - return _hasLabels ? _gridProgram && _labels->isReady() : _gridProgram != nullptr; + return _gridProgram && (_hasLabels ? _labels->isReady() : true); } void RenderableGrid::initialize() { @@ -279,9 +278,9 @@ void RenderableGrid::render(const RenderData& data, RendererTasks&) { // Change GL state: #ifndef __APPLE__ glLineWidth(_lineWidth); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(1.f); -#endif +#endif // __APPLE__ glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); @@ -294,9 +293,9 @@ void RenderableGrid::render(const RenderData& data, RendererTasks&) { // Render major grid #ifndef __APPLE__ glLineWidth(_highlightLineWidth); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(1.f); -#endif +#endif // __APPLE__ _gridProgram->setUniform("gridColor", _highlightColor); glBindVertexArray(_highlightVaoID); @@ -319,7 +318,7 @@ void RenderableGrid::render(const RenderData& data, RendererTasks&) { } void RenderableGrid::update(const UpdateData&) { - if (!_gridIsDirty) { + if (!_gridIsDirty) [[likely]] { return; } diff --git a/modules/base/rendering/grids/renderableradialgrid.cpp b/modules/base/rendering/grids/renderableradialgrid.cpp index 316bb446c5..8026c729aa 100644 --- a/modules/base/rendering/grids/renderableradialgrid.cpp +++ b/modules/base/rendering/grids/renderableradialgrid.cpp @@ -164,7 +164,7 @@ RenderableRadialGrid::RenderableRadialGrid(const ghoul::Dictionary& dictionary) } bool RenderableRadialGrid::isReady() const { - return _hasLabels ? _gridProgram && _labels->isReady() : _gridProgram != nullptr; + return _gridProgram && (_hasLabels ? _labels->isReady() : true); } void RenderableRadialGrid::initialize() { @@ -258,7 +258,7 @@ void RenderableRadialGrid::render(const RenderData& data, RendererTasks&) { } void RenderableRadialGrid::update(const UpdateData&) { - if (!_gridIsDirty) { + if (!_gridIsDirty) [[likely]] { return; } diff --git a/modules/base/rendering/grids/renderablesphericalgrid.cpp b/modules/base/rendering/grids/renderablesphericalgrid.cpp index 45fd35f818..dae5723cdc 100644 --- a/modules/base/rendering/grids/renderablesphericalgrid.cpp +++ b/modules/base/rendering/grids/renderablesphericalgrid.cpp @@ -165,7 +165,7 @@ RenderableSphericalGrid::RenderableSphericalGrid(const ghoul::Dictionary& dictio } bool RenderableSphericalGrid::isReady() const { - return _hasLabels ? _gridProgram && _labels->isReady() : _gridProgram != nullptr; + return _gridProgram && (_hasLabels ? _labels->isReady() : true); } void RenderableSphericalGrid::initialize() { @@ -278,7 +278,7 @@ void RenderableSphericalGrid::render(const RenderData& data, RendererTasks&) { } void RenderableSphericalGrid::update(const UpdateData&) { - if (!_gridIsDirty) { + if (!_gridIsDirty) [[likely]] { return; } diff --git a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp index 8c640460b0..f4e965b070 100644 --- a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp +++ b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp @@ -40,6 +40,22 @@ namespace { constexpr std::string_view _loggerCat = "RenderableInterpolatedPoints"; + void triggerInterpolation(std::string_view identifier, float v, float d) { + using namespace openspace; + + std::string script = std::format( + "openspace.setPropertyValueSingle(\"{}\", {}, {})", + identifier, v, d + ); + // No syncing, as this was triggered from a property change (which happened + // based on an already synced script) + global::scriptEngine->queueScript({ + .code = script, + .synchronized = scripting::ScriptEngine::Script::ShouldBeSynchronized::No, + .sendToRemote = scripting::ScriptEngine::Script::ShouldSendToRemote::No + }); + }; + constexpr openspace::properties::Property::PropertyInfo InterpolationValueInfo = { "Value", "Value", @@ -141,10 +157,10 @@ namespace { struct Interpolation { // [[codegen::verbatim(InterpolationValueInfo.description)]] - std::optional value; + std::optional value; // [[codegen::verbatim(InterpolationSpeedInfo.description)]] - std::optional speed; + std::optional speed; // [[codegen::verbatim(UseSplineInfo.description)]] std::optional useSplineInterpolation; @@ -180,66 +196,51 @@ RenderableInterpolatedPoints::Interpolation::Interpolation() { addProperty(value); - auto triggerInterpolation = [](std::string_view identifier, float v, float d) { - std::string script = std::format( - "openspace.setPropertyValueSingle(\"{}\", {}, {})", - identifier, v, d - ); - // No syncing, as this was triggered from a property change (which happened - // based on an already synced script) - global::scriptEngine->queueScript({ - .code = script, - .synchronized = scripting::ScriptEngine::Script::ShouldBeSynchronized::No, - .sendToRemote = scripting::ScriptEngine::Script::ShouldSendToRemote::No - }); - }; - - interpolateToEnd.onChange([triggerInterpolation, this]() { - float remaining = value.maxValue() - value; - float duration = remaining / speed; + interpolateToEnd.onChange([this]() { + const float remaining = value.maxValue() - value; + const float duration = remaining / speed; triggerInterpolation( value.uri(), value.maxValue(), duration ); }); + addProperty(interpolateToEnd); - interpolateToStart.onChange([triggerInterpolation, this]() { - float duration = value / speed; + interpolateToStart.onChange([this]() { + const float duration = value / speed; triggerInterpolation(value.uri(), 0.f, duration); }); - - interpolateToNextStep.onChange([triggerInterpolation, this]() { - float prevValue = glm::floor(value); - float newValue = glm::min(prevValue + 1.f, value.maxValue()); - float duration = 1.f / speed; - triggerInterpolation(value.uri(), newValue, duration); - }); - - interpolateToPrevStep.onChange([triggerInterpolation, this]() { - float prevValue = glm::ceil(value); - float newValue = glm::max(prevValue - 1.f, value.minValue()); - float duration = 1.f / speed; - triggerInterpolation(value.uri(), newValue, duration); - }); - - addProperty(interpolateToEnd); addProperty(interpolateToStart); + + interpolateToNextStep.onChange([this]() { + const float prevValue = glm::floor(value); + const float newValue = glm::min(prevValue + 1.f, value.maxValue()); + const float duration = 1.f / speed; + triggerInterpolation(value.uri(), newValue, duration); + }); addProperty(interpolateToNextStep); + + interpolateToPrevStep.onChange([this]() { + const float prevValue = glm::ceil(value); + const float newValue = glm::max(prevValue - 1.f, value.minValue()); + const float duration = 1.f / speed; + triggerInterpolation(value.uri(), newValue, duration); + }); addProperty(interpolateToPrevStep); + addProperty(speed); goToNextStep.onChange([this]() { float prevValue = glm::floor(value); value = glm::min(prevValue + 1.f, value.maxValue()); }); + addProperty(goToNextStep); goToPrevStep.onChange([this]() { float prevValue = glm::ceil(value); value = glm::max(prevValue - 1.f, value.minValue()); }); - - addProperty(goToNextStep); addProperty(goToPrevStep); nSteps.setReadOnly(true); @@ -257,12 +258,8 @@ RenderableInterpolatedPoints::RenderableInterpolatedPoints( addPropertySubOwner(_interpolation); if (p.interpolation.has_value()) { - _interpolation.value = static_cast( - p.interpolation->value.value_or(_interpolation.value) - ); - _interpolation.speed = static_cast( - p.interpolation->speed.value_or(_interpolation.speed) - ); + _interpolation.value = p.interpolation->value.value_or(_interpolation.value); + _interpolation.speed = p.interpolation->speed.value_or(_interpolation.speed); _interpolation.useSpline = p.interpolation->useSplineInterpolation.value_or( _interpolation.useSpline ); @@ -353,7 +350,7 @@ void RenderableInterpolatedPoints::setExtraUniforms() { } void RenderableInterpolatedPoints::preUpdate() { - if (_shouldReinitializeBufferdata) { + if (_shouldReinitializeBufferdata) [[unlikely]] { initializeBufferData(); _shouldReinitializeBufferdata = false; } @@ -387,11 +384,10 @@ void RenderableInterpolatedPoints::addPositionDataForPoint(unsigned int index, std::vector& result, double& maxRadius) const { - using namespace dataloader; auto [firstIndex, secondIndex] = interpolationIndices(index); - const Dataset::Entry& e0 = _dataset.entries[firstIndex]; - const Dataset::Entry& e1 = _dataset.entries[secondIndex]; + const dataloader::Dataset::Entry& e0 = _dataset.entries[firstIndex]; + const dataloader::Dataset::Entry& e1 = _dataset.entries[secondIndex]; glm::dvec3 position0 = transformedPosition(e0); glm::dvec3 position1 = transformedPosition(e1); @@ -418,8 +414,8 @@ void RenderableInterpolatedPoints::addPositionDataForPoint(unsigned int index, maxAllowedindex ); - const Dataset::Entry& e00 = _dataset.entries[beforeIndex]; - const Dataset::Entry& e11 = _dataset.entries[afterIndex]; + const dataloader::Dataset::Entry& e00 = _dataset.entries[beforeIndex]; + const dataloader::Dataset::Entry& e11 = _dataset.entries[afterIndex]; glm::dvec3 positionBefore = transformedPosition(e00); glm::dvec3 positionAfter = transformedPosition(e11); @@ -436,10 +432,9 @@ void RenderableInterpolatedPoints::addPositionDataForPoint(unsigned int index, void RenderableInterpolatedPoints::addColorAndSizeDataForPoint(unsigned int index, std::vector& result) const { - using namespace dataloader; auto [firstIndex, secondIndex] = interpolationIndices(index); - const Dataset::Entry& e0 = _dataset.entries[firstIndex]; - const Dataset::Entry& e1 = _dataset.entries[secondIndex]; + const dataloader::Dataset::Entry& e0 = _dataset.entries[firstIndex]; + const dataloader::Dataset::Entry& e1 = _dataset.entries[secondIndex]; if (hasColorData()) { const int colorParamIndex = currentColorParameterIndex(); @@ -463,10 +458,9 @@ void RenderableInterpolatedPoints::addColorAndSizeDataForPoint(unsigned int inde void RenderableInterpolatedPoints::addOrientationDataForPoint(unsigned int index, std::vector& result) const { - using namespace dataloader; auto [firstIndex, secondIndex] = interpolationIndices(index); - const Dataset::Entry& e0 = _dataset.entries[firstIndex]; - const Dataset::Entry& e1 = _dataset.entries[secondIndex]; + const dataloader::Dataset::Entry& e0 = _dataset.entries[firstIndex]; + const dataloader::Dataset::Entry& e1 = _dataset.entries[secondIndex]; glm::quat q0 = orientationQuaternion(e0); glm::quat q1 = orientationQuaternion(e1); @@ -566,28 +560,27 @@ float RenderableInterpolatedPoints::computeCurrentLowerValue() const { } const float maxTValue = _interpolation.value.maxValue(); - float maxAllowedT0 = glm::max(maxTValue - 1.f, 0.f); + const float maxAllowedT0 = glm::max(maxTValue - 1.f, 0.f); t0 = glm::clamp(t0, 0.f, maxAllowedT0); return t0; } float RenderableInterpolatedPoints::computeCurrentUpperValue() const { - float t0 = computeCurrentLowerValue(); - float t1 = t0 + 1.f; - t1 = glm::clamp(t1, 0.f, _interpolation.value.maxValue()); + const float t0 = computeCurrentLowerValue(); + const float t1 = glm::clamp(t0 + 1.f, 0.f, _interpolation.value.maxValue()); return t1; } std::pair RenderableInterpolatedPoints::interpolationIndices(unsigned int index) const { - float t0 = computeCurrentLowerValue(); - float t1 = computeCurrentUpperValue(); - unsigned int t0Index = static_cast(t0); - unsigned int t1Index = static_cast(t1); + const float t0 = computeCurrentLowerValue(); + const float t1 = computeCurrentUpperValue(); + const unsigned int t0Index = static_cast(t0); + const unsigned int t1Index = static_cast(t1); - size_t lower = size_t(t0Index * _nDataPoints + index); - size_t upper = size_t(t1Index * _nDataPoints + index); + const size_t lower = size_t(t0Index * _nDataPoints + index); + const size_t upper = size_t(t1Index * _nDataPoints + index); return { lower, upper }; } diff --git a/modules/base/rendering/pointcloud/renderablepointcloud.cpp b/modules/base/rendering/pointcloud/renderablepointcloud.cpp index 4c7aa22eb4..4f4be5ff72 100644 --- a/modules/base/rendering/pointcloud/renderablepointcloud.cpp +++ b/modules/base/rendering/pointcloud/renderablepointcloud.cpp @@ -1374,11 +1374,11 @@ void RenderablePointCloud::update(const UpdateData&) { _colorSettings.colorMapping->update(_dataset, _useCaching); } - if (_spriteTextureIsDirty) { + if (_spriteTextureIsDirty) [[unlikely]] { updateSpriteTexture(); } - if (_dataIsDirty) { + if (_dataIsDirty) [[unlikely]] { updateBufferData(); } } @@ -1511,9 +1511,8 @@ void RenderablePointCloud::updateBufferData() { } void RenderablePointCloud::updateSpriteTexture() { - bool shouldUpdate = _hasSpriteTexture && _spriteTextureIsDirty; - - if (!shouldUpdate) { + const bool shouldUpdate = _hasSpriteTexture && _spriteTextureIsDirty; + if (!shouldUpdate) [[likely]] { return; } diff --git a/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp b/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp index 63ccddcd56..f69a9ba302 100644 --- a/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp +++ b/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp @@ -201,7 +201,7 @@ void RenderablePolygonCloud::renderToTexture(GLuint textureToRenderTo, glDeleteFramebuffers(1, &textureFBO); } -void RenderablePolygonCloud::renderPolygonGeometry(GLuint vao) { +void RenderablePolygonCloud::renderPolygonGeometry(GLuint vao) const { std::unique_ptr program = ghoul::opengl::ProgramObject::Build( "RenderablePointCloud_Polygon", diff --git a/modules/base/rendering/pointcloud/renderablepolygoncloud.h b/modules/base/rendering/pointcloud/renderablepolygoncloud.h index e639be95d4..13cf5a8aa2 100644 --- a/modules/base/rendering/pointcloud/renderablepolygoncloud.h +++ b/modules/base/rendering/pointcloud/renderablepolygoncloud.h @@ -52,7 +52,7 @@ private: void initializeCustomTexture() override; void renderToTexture(GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight); - void renderPolygonGeometry(GLuint vao); + void renderPolygonGeometry(GLuint vao) const; int _nPolygonSides = 3; diff --git a/modules/base/rendering/renderablecartesianaxes.cpp b/modules/base/rendering/renderablecartesianaxes.cpp index d236268dc4..8f7b08b091 100644 --- a/modules/base/rendering/renderablecartesianaxes.cpp +++ b/modules/base/rendering/renderablecartesianaxes.cpp @@ -132,14 +132,14 @@ void RenderableCartesianAxes::initializeGL() { glGenVertexArrays(1, &_vaoId); glBindVertexArray(_vaoId); - std::vector vertices({ + constexpr std::array vertices = { Vertex{0.f, 0.f, 0.f}, Vertex{1.f, 0.f, 0.f}, Vertex{0.f, 1.f, 0.f}, Vertex{0.f, 0.f, 1.f} - }); + }; - std::vector indices = { + constexpr std::array indices = { 0, 1, 0, 2, 0, 3 @@ -204,7 +204,11 @@ void RenderableCartesianAxes::render(const RenderData& data, RendererTasks&) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnablei(GL_BLEND, 0); glEnable(GL_LINE_SMOOTH); - glLineWidth(3.0); +#ifndef __APPLE__ + glLineWidth(3.f); +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv + glLineWidth(1.f); +#endif // __APPLE__ glBindVertexArray(_vaoId); glDrawElements(GL_LINES, 6, GL_UNSIGNED_INT, nullptr); diff --git a/modules/base/rendering/renderabledisc.cpp b/modules/base/rendering/renderabledisc.cpp index 0a706f531d..97d521b8aa 100644 --- a/modules/base/rendering/renderabledisc.cpp +++ b/modules/base/rendering/renderabledisc.cpp @@ -39,10 +39,6 @@ #include namespace { - constexpr std::array UniformNames = { - "modelViewProjectionTransform", "opacity", "width", "colorTexture" - }; - constexpr openspace::properties::Property::PropertyInfo TextureInfo = { "Texture", "Texture", @@ -97,6 +93,8 @@ RenderableDisc::RenderableDisc(const ghoul::Dictionary& dictionary) , _texturePath(TextureInfo) , _size(SizeInfo, 1.f, 0.001f, 1e13f) , _width(WidthInfo, 1.f, 0.001f, 1.f) + , _plane(_size) + , _planeIsDirty(true) { const Parameters p = codegen::bake(dictionary); @@ -119,7 +117,7 @@ RenderableDisc::RenderableDisc(const ghoul::Dictionary& dictionary) } bool RenderableDisc::isReady() const { - return _shader && _texture && _plane; + return _shader && _texture; } void RenderableDisc::initialize() { @@ -127,8 +125,6 @@ void RenderableDisc::initialize() { _texture->setFilterMode(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); _texture->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToEdge); _texture->setShouldWatchFileForChanges(true); - - _plane = std::make_unique(planeSize()); } void RenderableDisc::initializeGL() { @@ -137,12 +133,11 @@ void RenderableDisc::initializeGL() { _texture->loadFromFile(_texturePath.value()); _texture->uploadToGpu(); - _plane->initialize(); + _plane.initialize(); } void RenderableDisc::deinitializeGL() { - _plane->deinitialize(); - _plane = nullptr; + _plane.deinitialize(); _texture = nullptr; global::renderEngine->removeRenderProgram(_shader.get()); @@ -172,7 +167,7 @@ void RenderableDisc::render(const RenderData& data, RendererTasks&) { glDepthMask(false); glDisable(GL_CULL_FACE); - _plane->render(); + _plane.render(); _shader->deactivate(); @@ -183,13 +178,13 @@ void RenderableDisc::render(const RenderData& data, RendererTasks&) { } void RenderableDisc::update(const UpdateData&) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); updateUniformLocations(); } - if (_planeIsDirty) { - _plane->updateSize(planeSize()); + if (_planeIsDirty) [[unlikely]] { + _plane.updateSize(planeSize()); _planeIsDirty = false; } @@ -206,7 +201,7 @@ void RenderableDisc::initializeShader() { } void RenderableDisc::updateUniformLocations() { - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } float RenderableDisc::planeSize() const { diff --git a/modules/base/rendering/renderabledisc.h b/modules/base/rendering/renderabledisc.h index 0fabb2094b..5b20258e30 100644 --- a/modules/base/rendering/renderabledisc.h +++ b/modules/base/rendering/renderabledisc.h @@ -67,7 +67,7 @@ protected: std::unique_ptr _shader; - std::unique_ptr _plane; + PlaneGeometry _plane; std::unique_ptr _texture; private: diff --git a/modules/base/rendering/renderabledistancelabel.cpp b/modules/base/rendering/renderabledistancelabel.cpp index 7de7c4cf41..23c12267cf 100644 --- a/modules/base/rendering/renderabledistancelabel.cpp +++ b/modules/base/rendering/renderabledistancelabel.cpp @@ -139,7 +139,7 @@ RenderableDistanceLabel::RenderableDistanceLabel(const ghoul::Dictionary& dictio } void RenderableDistanceLabel::update(const UpdateData&) { - if (_errorThrown) { + if (_errorThrown) [[unlikely]] { return; } @@ -176,7 +176,7 @@ void RenderableDistanceLabel::update(const UpdateData&) { // Update placement of label with transformation matrix SceneGraphNode* startNode = RE.scene()->sceneGraphNode(nodeline->start()); SceneGraphNode* endNode = RE.scene()->sceneGraphNode(nodeline->end()); - if (startNode && endNode) { + if (startNode && endNode) [[likely]] { const glm::dvec3 start = startNode->worldPosition(); const glm::dvec3 end = endNode->worldPosition(); const glm::dvec3 goalPos = start + (end - start) / 2.0; diff --git a/modules/base/rendering/renderablelabel.cpp b/modules/base/rendering/renderablelabel.cpp index 70b699742d..85e57cf029 100644 --- a/modules/base/rendering/renderablelabel.cpp +++ b/modules/base/rendering/renderablelabel.cpp @@ -378,14 +378,12 @@ void RenderableLabel::initialize() { } void RenderableLabel::initializeGL() { - if (_font == nullptr) { - _font = global::fontManager->font( - "Mono", - _fontSize, - ghoul::fontrendering::FontManager::Outline::Yes, - ghoul::fontrendering::FontManager::LoadGlyphs::No - ); - } + _font = global::fontManager->font( + "Mono", + _fontSize, + ghoul::fontrendering::FontManager::Outline::Yes, + ghoul::fontrendering::FontManager::LoadGlyphs::No + ); } void RenderableLabel::deinitializeGL() {} diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index a22ddf579c..cfaf9d3646 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -297,17 +297,14 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) addProperty(Fadeable::_opacity); - if (p.forceRenderInvisible.has_value()) { - _forceRenderInvisible = *p.forceRenderInvisible; - - if (!_forceRenderInvisible) { - // Asset file have specifically said to not render invisible parts, - // do not notify in the log if invisible parts are detected and dropped - _notifyInvisibleDropped = false; - } + _forceRenderInvisible = p.forceRenderInvisible.value_or(_forceRenderInvisible); + if (p.forceRenderInvisible.has_value() && !_forceRenderInvisible) { + // Asset file have specifically said to not render invisible parts, do not notify + // in the log if invisible parts are detected and dropped + _notifyInvisibleDropped = false; } - _file = absPath(p.geometryFile); + _file = p.geometryFile; if (!std::filesystem::exists(_file)) { throw ghoul::RuntimeError(std::format("Cannot find model file '{}'", _file)); } @@ -366,14 +363,13 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) } if (wasFound) { - _animationTimeScale = static_cast( - convertTime(1.0, timeUnit, TimeUnit::Second) - ); + _animationTimeScale = convertTime(1.0, timeUnit, TimeUnit::Second); } else { - std::string message = std::format("The given unit name '{}' does not " - "match any currently supported unit names", stringUnit); - LERROR(message); + LERROR(std::format( + "The given unit name '{}' does not match any currently supported " + "unit names", stringUnit + )); _animationTimeScale = 1.0; } } @@ -409,12 +405,8 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) _enableDepthTest = p.enableDepthTest.value_or(_enableDepthTest); _enableFaceCulling = p.enableFaceCulling.value_or(_enableFaceCulling); - if (p.vertexShader.has_value()) { - _vertexShaderPath = p.vertexShader->string(); - } - if (p.fragmentShader.has_value()) { - _fragmentShaderPath = p.fragmentShader->string(); - } + _vertexShaderPath = p.vertexShader.value_or(_vertexShaderPath); + _fragmentShaderPath = p.fragmentShader.value_or(_fragmentShaderPath); if (p.lightSources.has_value()) { const std::vector lightsources = *p.lightSources; @@ -570,10 +562,10 @@ void RenderableModel::initializeGL() { // Initialize shaders std::string program = std::string(ProgramName); if (!_vertexShaderPath.empty()) { - program += "|vs=" + _vertexShaderPath; + program += "|vs=" + _vertexShaderPath.string(); } if (!_fragmentShaderPath.empty()) { - program += "|fs=" + _fragmentShaderPath; + program += "|fs=" + _fragmentShaderPath.string(); } _program = BaseModule::ProgramObjectManager.request( program, @@ -581,11 +573,11 @@ void RenderableModel::initializeGL() { const std::filesystem::path vs = _vertexShaderPath.empty() ? absPath("${MODULE_BASE}/shaders/model_vs.glsl") : - std::filesystem::path(_vertexShaderPath); + _vertexShaderPath; const std::filesystem::path fs = _fragmentShaderPath.empty() ? absPath("${MODULE_BASE}/shaders/model_fs.glsl") : - std::filesystem::path(_fragmentShaderPath); + _fragmentShaderPath; return global::renderEngine->buildRenderProgram(program, vs, fs); } @@ -606,7 +598,8 @@ void RenderableModel::initializeGL() { const std::filesystem::path fs = absPath("${MODULE_BASE}/shaders/modelOpacity_fs.glsl"); - return global::renderEngine->buildRenderProgram("ModelOpacityProgram", + return global::renderEngine->buildRenderProgram( + "ModelOpacityProgram", vs, fs ); @@ -705,10 +698,10 @@ void RenderableModel::deinitializeGL() { std::string program = std::string(ProgramName); if (!_vertexShaderPath.empty()) { - program += "|vs=" + _vertexShaderPath; + program += "|vs=" + _vertexShaderPath.string(); } if (!_fragmentShaderPath.empty()) { - program += "|fs=" + _fragmentShaderPath; + program += "|fs=" + _fragmentShaderPath.string(); } BaseModule::ProgramObjectManager.release( program, @@ -988,12 +981,12 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { } void RenderableModel::update(const UpdateData& data) { - if (_program->isDirty()) { + if (_program->isDirty()) [[unlikely]] { _program->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_program, _uniformCache); } - if (_quadProgram->isDirty()) { + if (_quadProgram->isDirty()) [[unlikely]] { _quadProgram->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_quadProgram, _uniformOpacityCache); } diff --git a/modules/base/rendering/renderablemodel.h b/modules/base/rendering/renderablemodel.h index 6c2f9cf471..4e951eaadc 100644 --- a/modules/base/rendering/renderablemodel.h +++ b/modules/base/rendering/renderablemodel.h @@ -103,8 +103,8 @@ private: properties::BoolProperty _enableDepthTest; properties::OptionProperty _blendingFuncOption; - std::string _vertexShaderPath; - std::string _fragmentShaderPath; + std::filesystem::path _vertexShaderPath; + std::filesystem::path _fragmentShaderPath; ghoul::opengl::ProgramObject* _program = nullptr; UniformCache(modelViewTransform, projectionTransform, normalTransform, meshTransform, meshNormalTransform, ambientIntensity, diffuseIntensity, diff --git a/modules/base/rendering/renderablenodearrow.cpp b/modules/base/rendering/renderablenodearrow.cpp index ffb78d9ad7..d98907377b 100644 --- a/modules/base/rendering/renderablenodearrow.cpp +++ b/modules/base/rendering/renderablenodearrow.cpp @@ -170,6 +170,40 @@ namespace { "Determines whether shading should be applied to the arrow model.", openspace::properties::Property::Visibility::User }; + + void updateDistanceBasedOnRelativeValues(const std::string& nodeName, + bool useRelative, + openspace::properties::FloatProperty& prop) + { + using namespace::openspace; + + SceneGraphNode* startNode = sceneGraphNode(nodeName); + if (!startNode) { + LERROR(std::format("Could not find start node '{}'", nodeName)); + return; + } + const double boundingSphere = startNode->boundingSphere(); + + if (!useRelative) { + // Recompute distance (previous value was relative) + prop = static_cast(prop * boundingSphere); + prop.setExponent(11.f); + prop.setMaxValue(1e20f); + } + else { + // Recompute distance (previous value was in meters) + if (boundingSphere < std::numeric_limits::epsilon()) { + LERROR(std::format( + "Start node '{}' has invalid bounding sphere", nodeName + )); + return; + } + prop = static_cast(prop / boundingSphere); + prop.setExponent(3.f); + prop.setMaxValue(1000.f); + } + // @TODO (emmbr, 2022-08-22): make GUI update when min/max value is updated + } // A RenderableNodeArrow can be used to create a 3D arrow pointing in the direction // of one scene graph node to another. @@ -229,40 +263,6 @@ namespace { std::optional specularIntensity [[codegen::greaterequal(0.f)]]; }; #include "renderablenodearrow_codegen.cpp" - - void updateDistanceBasedOnRelativeValues(const std::string& nodeName, - bool useRelative, - openspace::properties::FloatProperty& prop) - { - using namespace::openspace; - - SceneGraphNode* startNode = sceneGraphNode(nodeName); - if (!startNode) { - LERROR(std::format("Could not find start node '{}'", nodeName)); - return; - } - const double boundingSphere = startNode->boundingSphere(); - - if (!useRelative) { - // Recompute distance (previous value was relative) - prop = static_cast(prop * boundingSphere); - prop.setExponent(11.f); - prop.setMaxValue(1e20f); - } - else { - // Recompute distance (previous value was in meters) - if (boundingSphere < std::numeric_limits::epsilon()) { - LERROR(std::format( - "Start node '{}' has invalid bounding sphere", nodeName - )); - return; - } - prop = static_cast(prop / boundingSphere); - prop.setExponent(3.f); - prop.setMaxValue(1000.f); - } - // @TODO (emmbr, 2022-08-22): make GUI update when min/max value is updated - } } // namespace namespace openspace { diff --git a/modules/base/rendering/renderablenodearrow.h b/modules/base/rendering/renderablenodearrow.h index d438835b49..d08d6fcd32 100644 --- a/modules/base/rendering/renderablenodearrow.h +++ b/modules/base/rendering/renderablenodearrow.h @@ -71,7 +71,7 @@ private: Shading _shading; - ghoul::opengl::ProgramObject* _shaderProgram; + ghoul::opengl::ProgramObject* _shaderProgram = nullptr; properties::StringProperty _start; properties::StringProperty _end; diff --git a/modules/base/rendering/renderablenodeline.h b/modules/base/rendering/renderablenodeline.h index 9823c36381..71588fb168 100644 --- a/modules/base/rendering/renderablenodeline.h +++ b/modules/base/rendering/renderablenodeline.h @@ -65,7 +65,7 @@ private: void update(const UpdateData& data) override; void render(const RenderData& data, RendererTasks& rendererTask) override; - ghoul::opengl::ProgramObject* _program; + ghoul::opengl::ProgramObject* _program = nullptr; /// The vertex attribute location for position /// must correlate to layout location in vertex shader const GLuint _locVertex = 0; diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index b23f8d4a2a..8c0cceed64 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -155,7 +155,7 @@ RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) _blendMode.addOptions({ { static_cast(BlendMode::Normal), "Normal" }, - { static_cast(BlendMode::Additive), "Additive"} + { static_cast(BlendMode::Additive), "Additive" } }); _blendMode.onChange([this]() { const BlendMode m = static_cast(_blendMode.value()); @@ -306,12 +306,12 @@ void RenderablePlane::unbindTexture() {} void RenderablePlane::update(const UpdateData&) { ZoneScoped; - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } - if (_planeIsDirty) { + if (_planeIsDirty) [[unlikely]] { createPlane(); } } diff --git a/modules/base/rendering/renderableplaneimagelocal.cpp b/modules/base/rendering/renderableplaneimagelocal.cpp index 06af083132..749bf023eb 100644 --- a/modules/base/rendering/renderableplaneimagelocal.cpp +++ b/modules/base/rendering/renderableplaneimagelocal.cpp @@ -118,10 +118,6 @@ RenderablePlaneImageLocal::RenderablePlaneImageLocal(const ghoul::Dictionary& di }); } -bool RenderablePlaneImageLocal::isReady() const { - return RenderablePlane::isReady(); -} - void RenderablePlaneImageLocal::initializeGL() { RenderablePlane::initializeGL(); @@ -146,7 +142,7 @@ void RenderablePlaneImageLocal::update(const UpdateData& data) { RenderablePlane::update(data); - if (_textureIsDirty) { + if (_textureIsDirty) [[unlikely]] { loadTexture(); _textureIsDirty = false; } diff --git a/modules/base/rendering/renderableplaneimagelocal.h b/modules/base/rendering/renderableplaneimagelocal.h index 73f1fa7c60..e41d2f61b6 100644 --- a/modules/base/rendering/renderableplaneimagelocal.h +++ b/modules/base/rendering/renderableplaneimagelocal.h @@ -44,8 +44,6 @@ public: void initializeGL() override; void deinitializeGL() override; - bool isReady() const override; - void update(const UpdateData& data) override; static documentation::Documentation Documentation(); diff --git a/modules/base/rendering/renderableplaneimageonline.cpp b/modules/base/rendering/renderableplaneimageonline.cpp index 27753a7371..94adffe3c7 100644 --- a/modules/base/rendering/renderableplaneimageonline.cpp +++ b/modules/base/rendering/renderableplaneimageonline.cpp @@ -115,7 +115,7 @@ void RenderablePlaneImageOnline::bindTexture() { void RenderablePlaneImageOnline::update(const UpdateData& data) { RenderablePlane::update(data); - if (!_textureIsDirty) { + if (!_textureIsDirty) [[unlikely]] { return; } diff --git a/modules/base/rendering/renderableprism.cpp b/modules/base/rendering/renderableprism.cpp index 606435deff..fdba580904 100644 --- a/modules/base/rendering/renderableprism.cpp +++ b/modules/base/rendering/renderableprism.cpp @@ -215,8 +215,8 @@ void RenderablePrism::updateVertexData() { using namespace rendering::helper; // Get unit circle vertices on the XY-plane - std::vector unitVertices = createRingXYZ(_nShapeSegments.value(), 1.f); - std::vector unitVerticesLines = createRingXYZ(_nLines.value(), 1.f); + std::vector unitVertices = createRingXYZ(_nShapeSegments, 1.f); + std::vector unitVerticesLines = createRingXYZ(_nLines, 1.f); // Put base vertices into array for (int j = 0; j < _nShapeSegments; j++) { @@ -348,11 +348,12 @@ void RenderablePrism::render(const RenderData& data, RendererTasks&) { } void RenderablePrism::update(const UpdateData& data) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } - if (_prismIsDirty) { + + if (_prismIsDirty) [[unlikely]] { updateVertexData(); updateBufferData(); setBoundingSphere(_length * glm::compMax(data.modelTransform.scale)); diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 61029ddf06..8ef676b16a 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -276,7 +276,6 @@ void RenderableSphere::deinitializeGL() { global::renderEngine->removeRenderProgram(p); } ); - _shader = nullptr; } @@ -426,12 +425,12 @@ void RenderableSphere::render(const RenderData& data, RendererTasks&) { } void RenderableSphere::update(const UpdateData&) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } - if (_sphereIsDirty) { + if (_sphereIsDirty) [[unlikely]] { _sphere = std::make_unique(_size, _segments); _sphere->initialize(); _sphereIsDirty = false; diff --git a/modules/base/rendering/renderablesphereimageonline.cpp b/modules/base/rendering/renderablesphereimageonline.cpp index 2fac99afcc..d8fd116ac8 100644 --- a/modules/base/rendering/renderablesphereimageonline.cpp +++ b/modules/base/rendering/renderablesphereimageonline.cpp @@ -105,7 +105,7 @@ void RenderableSphereImageOnline::deinitializeGL() { void RenderableSphereImageOnline::update(const UpdateData& data) { RenderableSphere::update(data); - if (!_textureIsDirty) { + if (!_textureIsDirty) [[likely]] { return; } diff --git a/modules/base/rendering/renderabletimevaryingsphere.cpp b/modules/base/rendering/renderabletimevaryingsphere.cpp index 751dba6946..6434769cf3 100644 --- a/modules/base/rendering/renderabletimevaryingsphere.cpp +++ b/modules/base/rendering/renderabletimevaryingsphere.cpp @@ -167,7 +167,8 @@ void RenderableTimeVaryingSphere::update(const UpdateData& data) { // not in interval => set everything to false _activeTriggerTimeIndex = 0; } - if (_textureIsDirty) { + + if (_textureIsDirty) [[unlikely]] { loadTexture(); _textureIsDirty = false; } @@ -184,16 +185,14 @@ void RenderableTimeVaryingSphere::bindTexture() { void RenderableTimeVaryingSphere::updateActiveTriggerTimeIndex(double currentTime) { auto iter = std::upper_bound( - _files.begin(), - _files.end(), + _files.cbegin(), + _files.cend(), currentTime, - [](double value, const FileData& f) { - return value < f.time; - } + [](double value, const FileData& f) { return value < f.time; } ); - if (iter != _files.end()) { - if (iter != _files.begin()) { - const ptrdiff_t idx = std::distance(_files.begin(), iter); + if (iter != _files.cend()) { + if (iter != _files.cbegin()) { + const ptrdiff_t idx = std::distance(_files.cbegin(), iter); _activeTriggerTimeIndex = static_cast(idx - 1); } else { diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index ca90ed1ff8..8a17fc88bc 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -46,14 +46,14 @@ namespace { "stride", "pointSize", "renderPhase", "useSplitRenderMode", "floatingOffset", "numberOfUniqueVertices" }; -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv constexpr std::array UniformNames = { "opacity", "modelViewTransform", "projectionTransform", "color", "useLineFade", "lineLength", "lineFadeAmount", "vertexSortingMethod", "idOffset", "nVertices", "stride", "pointSize", "renderPhase", "viewport", "lineWidth", "floatingOffset", "useSplitRenderMode", "numberOfUniqueVertices" }; -#endif +#endif // __APPLE__ // The possible values for the _renderingModes property enum RenderingMode { @@ -264,7 +264,7 @@ void RenderableTrail::initializeGL() { ); } ); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv _programObject = BaseModule::ProgramObjectManager.request( "EphemerisProgram", []() -> std::unique_ptr { @@ -275,7 +275,7 @@ void RenderableTrail::initializeGL() { ); } ); -#endif +#endif // __APPLE__ ghoul::opengl::updateUniformLocations(*_programObject, _uniformCache, UniformNames); } @@ -335,7 +335,7 @@ void RenderableTrail::internalRender(bool renderLines, bool renderPoints, _programObject->setUniform(_uniformCache.numberOfUniqueVertices, numberOfUniqueVertices); -#if !defined(__APPLE__) +#ifndef __APPLE__ std::array viewport; global::renderEngine->openglStateCache().viewport(viewport.data()); _programObject->setUniform( @@ -349,7 +349,7 @@ void RenderableTrail::internalRender(bool renderLines, bool renderPoints, _uniformCache.lineWidth, std::ceil((2.f * 1.f + _appearance.lineWidth) * std::sqrt(2.f)) ); -#endif // !defined(__APPLE__) +#endif // __APPLE__ if (renderPoints) { // The stride parameter determines the distance between larger points and @@ -444,9 +444,9 @@ void RenderableTrail::render(const RenderData& data, RendererTasks&) { if (renderLines) { #ifdef __APPLE__ glLineWidth(1); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(std::ceil((2.f * 1.f + _appearance.lineWidth) * std::sqrt(2.f))); -#endif +#endif // __APPLE__ } if (renderPoints) { glEnable(GL_PROGRAM_POINT_SIZE); diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index d77bc82460..e43a7bb1e2 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -114,14 +114,6 @@ bool ScreenSpaceDashboard::initializeGL() { return true; } -bool ScreenSpaceDashboard::deinitializeGL() { - return ScreenSpaceFramebuffer::deinitializeGL(); -} - -bool ScreenSpaceDashboard::isReady() const { - return ScreenSpaceFramebuffer::isReady(); -} - void ScreenSpaceDashboard::update() { if (global::windowDelegate->windowHasResized()) { const glm::ivec2 size = global::windowDelegate->currentDrawBufferResolution(); diff --git a/modules/base/rendering/screenspacedashboard.h b/modules/base/rendering/screenspacedashboard.h index ba16be8526..23a5e4c81e 100644 --- a/modules/base/rendering/screenspacedashboard.h +++ b/modules/base/rendering/screenspacedashboard.h @@ -46,9 +46,7 @@ public: virtual ~ScreenSpaceDashboard() override = default; bool initializeGL() override; - bool deinitializeGL() override; - bool isReady() const override; void update() override; Dashboard& dashboard(); diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index 5e20441518..36aa7f2f2f 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -150,14 +150,7 @@ void ScreenSpaceFramebuffer::render(const RenderData& renderData) { } bool ScreenSpaceFramebuffer::isReady() const { - bool ready = true; - if (!_shader) { - ready &= false; - } - if (!_texture) { - ready &= false; - } - return ready; + return _shader && _texture; } void ScreenSpaceFramebuffer::setSize(glm::vec4 size) { diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index a336a537ea..d295b19a9d 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -55,7 +55,7 @@ namespace { std::optional identifier; // [[codegen::verbatim(TexturePathInfo.description)]] - std::optional texturePath; + std::optional texturePath; }; #include "screenspaceimagelocal_codegen.cpp" } // namespace @@ -91,17 +91,7 @@ ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary addProperty(_texturePath); if (p.texturePath.has_value()) { - if (std::filesystem::is_regular_file(absPath(*p.texturePath))) { - _texturePath = absPath(*p.texturePath).string(); - } - else { - LERRORC( - "ScreenSpaceImageLocal", - std::format( - "Image '{}' did not exist for '{}'", *p.texturePath, _identifier - ) - ); - } + _texturePath = p.texturePath->string(); } } @@ -112,7 +102,7 @@ bool ScreenSpaceImageLocal::deinitializeGL() { } void ScreenSpaceImageLocal::update() { - if (_textureIsDirty && !_texturePath.value().empty()) { + if (_textureIsDirty && !_texturePath.value().empty()) [[unlikely]] { std::unique_ptr texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath), 2); @@ -137,7 +127,7 @@ void ScreenSpaceImageLocal::update() { } void ScreenSpaceImageLocal::bindTexture() { - if (_texture) { + if (_texture) [[likely]] { _texture->bind(); } } diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index 8a8023618d..de650e697d 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -90,59 +90,61 @@ bool ScreenSpaceImageOnline::deinitializeGL() { } void ScreenSpaceImageOnline::update() { - if (_textureIsDirty) { - if (!_imageFuture.valid()) { - std::future future = downloadImageToMemory( - _texturePath - ); - if (future.valid()) { - _imageFuture = std::move(future); - } - } + if (!_textureIsDirty) [[likely]] { + return; + } - if (_imageFuture.valid() && DownloadManager::futureReady(_imageFuture)) { - const DownloadManager::MemoryFile imageFile = _imageFuture.get(); - - if (imageFile.corrupted) { - LERROR(std::format( - "Error loading image from URL '{}'", _texturePath.value() - )); - return; - } - - try { - std::unique_ptr texture = - ghoul::io::TextureReader::ref().loadTexture( - reinterpret_cast(imageFile.buffer), - imageFile.size, - 2, - imageFile.format - ); - - if (texture) { - // Images don't need to start on 4-byte boundaries, for example if the - // image is only RGB - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - if (texture->format() == ghoul::opengl::Texture::Format::Red) { - texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE }); - } - - texture->uploadTexture(); - texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); - texture->purgeFromRAM(); - - _texture = std::move(texture); - _objectSize = _texture->dimensions(); - _textureIsDirty = false; - } - } - catch (const ghoul::io::TextureReader::InvalidLoadException& e) { - _textureIsDirty = false; - LERRORC(e.component, e.message); - } + if (!_imageFuture.valid()) { + std::future future = downloadImageToMemory( + _texturePath + ); + if (future.valid()) { + _imageFuture = std::move(future); } } + + if (_imageFuture.valid() && DownloadManager::futureReady(_imageFuture)) { + const DownloadManager::MemoryFile imageFile = _imageFuture.get(); + + if (imageFile.corrupted) { + LERROR(std::format( + "Error loading image from URL '{}'", _texturePath.value() + )); + return; + } + + try { + std::unique_ptr texture = + ghoul::io::TextureReader::ref().loadTexture( + reinterpret_cast(imageFile.buffer), + imageFile.size, + 2, + imageFile.format + ); + + if (texture) { + // Images don't need to start on 4-byte boundaries, for example if the + // image is only RGB + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + if (texture->format() == ghoul::opengl::Texture::Format::Red) { + texture->setSwizzleMask({ GL_RED, GL_RED, GL_RED, GL_ONE }); + } + + texture->uploadTexture(); + texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); + texture->purgeFromRAM(); + + _texture = std::move(texture); + _objectSize = _texture->dimensions(); + _textureIsDirty = false; + } + } + catch (const ghoul::io::TextureReader::InvalidLoadException& e) { + _textureIsDirty = false; + LERRORC(e.component, e.message); + } + } } std::future ScreenSpaceImageOnline::downloadImageToMemory( @@ -162,7 +164,7 @@ std::future ScreenSpaceImageOnline::downloadImageTo } void ScreenSpaceImageOnline::bindTexture() { - if (_texture) { + if (_texture) [[likely]] { _texture->bind(); } } diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp index 0077ae110c..8c977d3f6c 100644 --- a/modules/base/rotation/fixedrotation.cpp +++ b/modules/base/rotation/fixedrotation.cpp @@ -541,7 +541,7 @@ glm::dmat3 FixedRotation::matrix(const UpdateData&) const { if (glm::dot(x, y) > 1.f - Epsilon || glm::dot(y, z) > 1.f - Epsilon || - glm::dot(x, z) > 1.f - Epsilon) + glm::dot(x, z) > 1.f - Epsilon) [[unlikely]] { LWARNINGC( "FixedRotation", @@ -553,13 +553,12 @@ glm::dmat3 FixedRotation::matrix(const UpdateData&) const { ); return glm::dmat3(); } - else { - return { - x.x, x.y, x.z, - y.x, y.y, y.z, - z.x, z.y, z.z - }; - } + + return { + x.x, x.y, x.z, + y.x, y.y, y.z, + z.x, z.y, z.z + }; } glm::vec3 FixedRotation::xAxis() const { diff --git a/modules/base/rotation/staticrotation.cpp b/modules/base/rotation/staticrotation.cpp index d1fa0c8fed..f4817b4ed3 100644 --- a/modules/base/rotation/staticrotation.cpp +++ b/modules/base/rotation/staticrotation.cpp @@ -120,7 +120,7 @@ StaticRotation::StaticRotation(const ghoul::Dictionary& dictionary) : StaticRota } glm::dmat3 StaticRotation::matrix(const UpdateData&) const { - if (_matrixIsDirty) { + if (_matrixIsDirty) [[unlikely]] { _cachedMatrix = glm::mat3_cast(glm::quat(_eulerRotation.value())); _matrixIsDirty = false; } diff --git a/modules/base/rotation/timelinerotation.cpp b/modules/base/rotation/timelinerotation.cpp index 99d049602a..52aa821ad8 100644 --- a/modules/base/rotation/timelinerotation.cpp +++ b/modules/base/rotation/timelinerotation.cpp @@ -68,9 +68,7 @@ TimelineRotation::TimelineRotation(const ghoul::Dictionary& dictionary) ghoul::mm_unique_ptr rotation = Rotation::createFromDictionary( kf.second ); - if (rotation) { - _timeline.addKeyframe(t, std::move(rotation)); - } + _timeline.addKeyframe(t, std::move(rotation)); } _shouldInterpolate = p.shouldInterpolate.value_or(_shouldInterpolate); diff --git a/modules/base/scale/timedependentscale.cpp b/modules/base/scale/timedependentscale.cpp index 92197f3997..5177a63511 100644 --- a/modules/base/scale/timedependentscale.cpp +++ b/modules/base/scale/timedependentscale.cpp @@ -105,7 +105,7 @@ TimeDependentScale::TimeDependentScale(const ghoul::Dictionary& dictionary) } glm::dvec3 TimeDependentScale::scaleValue(const UpdateData& data) const { - if (_cachedReferenceDirty) { + if (_cachedReferenceDirty) [[unlikely]] { _cachedReference = Time::convertTime(_referenceDate); _cachedReferenceDirty = false; } diff --git a/modules/base/translation/timelinetranslation.cpp b/modules/base/translation/timelinetranslation.cpp index 2f7a03f17c..bd3f0b3578 100644 --- a/modules/base/translation/timelinetranslation.cpp +++ b/modules/base/translation/timelinetranslation.cpp @@ -67,9 +67,7 @@ TimelineTranslation::TimelineTranslation(const ghoul::Dictionary& dictionary) ghoul::mm_unique_ptr translation = Translation::createFromDictionary(kf.second); - if (translation) { - _timeline.addKeyframe(t, std::move(translation)); - } + _timeline.addKeyframe(t, std::move(translation)); } _shouldInterpolate = p.shouldInterpolate.value_or(_shouldInterpolate); diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index 38a58d85bf..530662b642 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -284,16 +284,14 @@ void RenderableDUMeshes::initializeGL() { createMeshes(); - if (_hasLabel) { - if (!_font) { - constexpr int FontSize = 50; - _font = global::fontManager->font( - "Mono", - static_cast(FontSize), - ghoul::fontrendering::FontManager::Outline::Yes, - ghoul::fontrendering::FontManager::LoadGlyphs::No - ); - } + if (_hasLabel && !_font) { + constexpr int FontSize = 50; + _font = global::fontManager->font( + "Mono", + static_cast(FontSize), + ghoul::fontrendering::FontManager::Outline::Yes, + ghoul::fontrendering::FontManager::LoadGlyphs::No + ); } } @@ -435,7 +433,7 @@ void RenderableDUMeshes::render(const RenderData& data, RendererTasks&) { } void RenderableDUMeshes::update(const UpdateData&) { - if (_program->isDirty()) { + if (_program->isDirty()) [[unlikely]] { _program->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_program, _uniformCache); } diff --git a/modules/exoplanets/rendering/renderableorbitdisc.cpp b/modules/exoplanets/rendering/renderableorbitdisc.cpp index ad0b83aac0..a67653b154 100644 --- a/modules/exoplanets/rendering/renderableorbitdisc.cpp +++ b/modules/exoplanets/rendering/renderableorbitdisc.cpp @@ -210,12 +210,12 @@ void RenderableOrbitDisc::render(const RenderData& data, RendererTasks&) { } void RenderableOrbitDisc::update(const UpdateData&) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } - if (_planeIsDirty) { + if (_planeIsDirty) [[unlikely]] { _plane->updateSize(planeSize()); _planeIsDirty = false; } diff --git a/modules/galaxy/rendering/galaxyraycaster.cpp b/modules/galaxy/rendering/galaxyraycaster.cpp index 8b4606b8e6..e1700a40d6 100644 --- a/modules/galaxy/rendering/galaxyraycaster.cpp +++ b/modules/galaxy/rendering/galaxyraycaster.cpp @@ -103,29 +103,16 @@ glm::dmat4 GalaxyRaycaster::modelViewTransform(const RenderData& data) { void GalaxyRaycaster::preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) { - const std::string stepSizeUniformName = "maxStepSize" + std::to_string(data.id); - const std::string galaxyTextureUniformName = "galaxyTexture" + - std::to_string(data.id); - const std::string volumeAspectUniformName = "aspect" + std::to_string(data.id); - const std::string opacityCoefficientUniformName = "opacityCoefficient" + - std::to_string(data.id); - - const std::string absorptionMultiplyUniformName = "absorptionMultiply" + - std::to_string(data.id); - - const std::string emissionMultiplyUniformName = "emissionMultiply" + - std::to_string(data.id); - - program.setUniform(volumeAspectUniformName, _aspect); - program.setUniform(stepSizeUniformName, _stepSize); - program.setUniform(opacityCoefficientUniformName, _opacityCoefficient); - program.setUniform(absorptionMultiplyUniformName, _absorptionMultiply); - program.setUniform(emissionMultiplyUniformName, _emissionMultiply); + program.setUniform(std::format("aspect{}", data.id), _aspect); + program.setUniform(std::format("maxStepSize{}", data.id), _stepSize); + program.setUniform(std::format("opacityCoefficient{}", data.id), _opacityCoefficient); + program.setUniform(std::format("absorptionMultiply{}", data.id), _absorptionMultiply); + program.setUniform(std::format("emissionMultiply{}", data.id), _emissionMultiply); _textureUnit = std::make_unique(); _textureUnit->activate(); _texture.bind(); - program.setUniform(galaxyTextureUniformName, *_textureUnit); + program.setUniform(std::format("galaxyTexture{}", data.id), *_textureUnit); } void GalaxyRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramObject&) { diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 0af22096ca..09de6217c0 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -146,6 +146,45 @@ namespace { "The number of integration steps used during the raycasting procedure.", openspace::properties::Property::Visibility::AdvancedUser }; + + void saveCachedFile(const std::filesystem::path& file, + const std::vector& positions, + const std::vector& colors, int64_t nPoints, + float pointsRatio) + { + std::ofstream fileStream(file, std::ofstream::binary); + + if (!fileStream.good()) { + LERROR(std::format("Error opening file '{}' for save cache file", file)); + return; + } + + fileStream.write( + reinterpret_cast(&CurrentCacheVersion), + sizeof(int8_t) + ); + fileStream.write(reinterpret_cast(&nPoints), sizeof(int64_t)); + fileStream.write(reinterpret_cast(&pointsRatio), sizeof(float)); + uint64_t nPositions = positions.size(); + fileStream.write(reinterpret_cast(&nPositions), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(positions.data()), + positions.size() * sizeof(glm::vec3) + ); + uint64_t nColors = colors.size(); + fileStream.write(reinterpret_cast(&nColors), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(colors.data()), + colors.size() * sizeof(glm::vec3) + ); + } + + float safeLength(const glm::vec3& vector) { + const float maxComponent = std::max( + std::max(std::abs(vector.x), std::abs(vector.y)), std::abs(vector.z) + ); + return glm::length(vector / maxComponent) * maxComponent; + } struct [[codegen::Dictionary(RenderableGalaxy)]] Parameters { // [[codegen::verbatim(VolumeRenderingEnabledInfo.description)]] @@ -200,46 +239,6 @@ namespace { Points points; }; #include "renderablegalaxy_codegen.cpp" - - - void saveCachedFile(const std::filesystem::path& file, - const std::vector& positions, - const std::vector& colors, int64_t nPoints, - float pointsRatio) - { - std::ofstream fileStream(file, std::ofstream::binary); - - if (!fileStream.good()) { - LERROR(std::format("Error opening file '{}' for save cache file", file)); - return; - } - - fileStream.write( - reinterpret_cast(&CurrentCacheVersion), - sizeof(int8_t) - ); - fileStream.write(reinterpret_cast(&nPoints), sizeof(int64_t)); - fileStream.write(reinterpret_cast(&pointsRatio), sizeof(float)); - uint64_t nPositions = positions.size(); - fileStream.write(reinterpret_cast(&nPositions), sizeof(uint64_t)); - fileStream.write( - reinterpret_cast(positions.data()), - positions.size() * sizeof(glm::vec3) - ); - uint64_t nColors = colors.size(); - fileStream.write(reinterpret_cast(&nColors), sizeof(uint64_t)); - fileStream.write( - reinterpret_cast(colors.data()), - colors.size() * sizeof(glm::vec3) - ); - } - - float safeLength(const glm::vec3& vector) { - const float maxComponent = std::max( - std::max(std::abs(vector.x), std::abs(vector.y)), std::abs(vector.z) - ); - return glm::length(vector / maxComponent) * maxComponent; - } } // namespace namespace openspace { diff --git a/modules/globebrowsing/src/dashboarditemglobelocation.cpp b/modules/globebrowsing/src/dashboarditemglobelocation.cpp index 0bda64d749..77dc002e6c 100644 --- a/modules/globebrowsing/src/dashboarditemglobelocation.cpp +++ b/modules/globebrowsing/src/dashboarditemglobelocation.cpp @@ -144,7 +144,6 @@ void DashboardItemGlobeLocation::update() { ZoneScoped; GlobeBrowsingModule* module = global::moduleEngine->module(); - const glm::dvec3 position = module->geoPosition(); double lat = position.x; double lon = position.y; diff --git a/modules/globebrowsing/src/ellipsoid.cpp b/modules/globebrowsing/src/ellipsoid.cpp index 2e91d720c1..286a546961 100644 --- a/modules/globebrowsing/src/ellipsoid.cpp +++ b/modules/globebrowsing/src/ellipsoid.cpp @@ -52,12 +52,12 @@ void Ellipsoid::updateInternalCache() { } glm::dvec3 Ellipsoid::geocentricSurfaceProjection(const glm::dvec3& p) const { - const double beta = 1.0 / sqrt(dot(p * p, _cached.oneOverRadiiSquared)); + const double beta = 1.0 / std::sqrt(glm::dot(p * p, _cached.oneOverRadiiSquared)); return beta * p; } glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { - const double beta = 1.0 / sqrt(dot(p * p, _cached.oneOverRadiiSquared)); + const double beta = 1.0 / std::sqrt(glm::dot(p * p, _cached.oneOverRadiiSquared)); const double n = glm::length(beta * p * _cached.oneOverRadiiSquared); double alpha = (1.0 - beta) * (glm::length(p) / n); @@ -94,12 +94,12 @@ glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint( } glm::dvec3 Ellipsoid::geodeticSurfaceNormal(const Geodetic2& geodetic2) const { - const double cosLat = glm::cos(geodetic2.lat); + const double cosLat = std::cos(geodetic2.lat); //geodetic2.lon = geodetic2.lon > M_PI ? geodetic2.lon - M_PI * 2 : geodetic2.lon; return glm::dvec3( - cosLat * cos(geodetic2.lon), - cosLat * sin(geodetic2.lon), - sin(geodetic2.lat) + cosLat * std::cos(geodetic2.lon), + cosLat * std::sin(geodetic2.lon), + std::sin(geodetic2.lat) ); } @@ -116,7 +116,7 @@ double Ellipsoid::maximumRadius() const { } double Ellipsoid::longitudalDistance(double lat, double lon1, double lon2) const { - const glm::dvec2 ellipseRadii = glm::cos(lat) * glm::dvec2(_radii); + const glm::dvec2 ellipseRadii = std::cos(lat) * glm::dvec2(_radii); // Approximating with the ellipse mean radius const double meanRadius = 0.5 * (ellipseRadii.x + ellipseRadii.y); return meanRadius * std::abs(lon2 - lon1); @@ -144,8 +144,8 @@ double Ellipsoid::greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) Geodetic2 Ellipsoid::cartesianToGeodetic2(const glm::dvec3& p) const { const glm::dvec3 normal = geodeticSurfaceNormalForGeocentricallyProjectedPoint(p); return { - asin(normal.z / length(normal)), - atan2(normal.y, normal.x) + std::asin(normal.z / glm::length(normal)), + std::atan2(normal.y, normal.x) }; } @@ -157,7 +157,7 @@ glm::dvec3 Ellipsoid::cartesianSurfacePosition(const Geodetic2& geodetic2) const glm::dvec3 Ellipsoid::cartesianPosition(const Geodetic3& geodetic3) const { const glm::dvec3 normal = geodeticSurfaceNormal(geodetic3.geodetic2); const glm::dvec3 k = _cached.radiiSquared * normal; - const double gamma = sqrt(dot(k, normal)); + const double gamma = std::sqrt(glm::dot(k, normal)); const glm::dvec3 rSurface = k / gamma; return rSurface + geodetic3.height * normal; } diff --git a/modules/globebrowsing/src/geodeticpatch.cpp b/modules/globebrowsing/src/geodeticpatch.cpp index f4bcb17cae..1f0dd6fbf9 100644 --- a/modules/globebrowsing/src/geodeticpatch.cpp +++ b/modules/globebrowsing/src/geodeticpatch.cpp @@ -64,7 +64,7 @@ GeodeticPatch::GeodeticPatch(const TileIndex& tileIndex) { const double deltaLon = (2 * glm::pi()) / (static_cast(1 << tileIndex.level)); const Geodetic2 nwCorner{ - glm::pi() / 2.0 - deltaLat * tileIndex.y, + glm::half_pi() - deltaLat * tileIndex.y, -glm::pi() + deltaLon * tileIndex.x }; _halfSize = Geodetic2{ deltaLat / 2.0, deltaLon / 2.0 }; @@ -81,12 +81,12 @@ void GeodeticPatch::setHalfSize(Geodetic2 halfSize) { double GeodeticPatch::maximumTileLevel() const { // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes - return log2(glm::pi() / glm::min(_halfSize.lat, _halfSize.lon)); + return std::log2(glm::pi() / std::min(_halfSize.lat, _halfSize.lon)); } double GeodeticPatch::minimumTileLevel() const { // Numerator is just pi, not 2*pi, since we are dealing with HALF sizes - return log2(glm::pi() / glm::max(_halfSize.lat, _halfSize.lon)); + return std::log2(glm::pi() / std::max(_halfSize.lat, _halfSize.lon)); } const Geodetic2& GeodeticPatch::center() const { @@ -135,7 +135,7 @@ bool GeodeticPatch::contains(const Geodetic2& p) const { .lat = _center.lat - p.lat, .lon = _center.lon - p.lon }; - return glm::abs(diff.lat) <= _halfSize.lat && glm::abs(diff.lon) <= _halfSize.lon; + return std::abs(diff.lat) <= _halfSize.lat && std::abs(diff.lon) <= _halfSize.lon; } double GeodeticPatch::edgeLatitudeNearestEquator() const { @@ -158,8 +158,8 @@ Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { const double pointLon = normalizedAngleAround(p.lon, _center.lon); return { - glm::clamp(pointLat, minLat(), maxLat()), - glm::clamp(pointLon, minLon(), maxLon()) + std::clamp(pointLat, minLat(), maxLat()), + std::clamp(pointLon, minLon(), maxLon()) }; } @@ -228,21 +228,21 @@ Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { const double centerToPointLon = normalizedAngleAround(_center.lon - pointLon, 0.0); // Calculate the longitudinal distance to the closest patch edge - const double lonDistanceToClosestPatch = glm::abs(centerToPointLon) - _halfSize.lon; + const double lonDistanceToClosestPatch = std::abs(centerToPointLon) - _halfSize.lon; // If the longitude distance to the closest patch edge is larger than 90 deg // the latitude will have to be clamped to its closest corner, as explained in // the example above. const double clampedLat = lonDistanceToClosestPatch > glm::half_pi() ? - glm::clamp( + std::clamp( normalizedAngleAround(glm::pi() - pointLat, _center.lat), minLat(), maxLat()) : - glm::clamp(pointLat, minLat(), maxLat()); + std::clamp(pointLat, minLat(), maxLat()); // Longitude is just clamped normally - const double clampedLon = glm::clamp(pointLon, minLon(), maxLon()); + const double clampedLon = std::clamp(pointLon, minLon(), maxLon()); return Geodetic2{ clampedLat, clampedLon }; } diff --git a/modules/globebrowsing/src/geojson/geojsoncomponent.cpp b/modules/globebrowsing/src/geojson/geojsoncomponent.cpp index d7914ce978..0be69f4d40 100644 --- a/modules/globebrowsing/src/geojson/geojsoncomponent.cpp +++ b/modules/globebrowsing/src/geojson/geojsoncomponent.cpp @@ -497,8 +497,8 @@ void GeoJsonComponent::deinitializeGL() { bool GeoJsonComponent::isReady() const { const bool isReady = std::all_of( - std::begin(_geometryFeatures), - std::end(_geometryFeatures), + _geometryFeatures.cbegin(), + _geometryFeatures.cend(), std::mem_fn(&GlobeGeometryFeature::isReady) ); return isReady && _linesAndPolygonsProgram && _pointsProgram; @@ -574,11 +574,11 @@ void GeoJsonComponent::update() { } GlobeGeometryFeature& g = _geometryFeatures[i]; - if (_dataIsDirty || _heightOffsetIsDirty) { + if (_dataIsDirty || _heightOffsetIsDirty) [[unlikely]] { g.setOffsets(offsets); } - if (_textureIsDirty) { + if (_textureIsDirty) [[unlikely]] { g.updateTexture(); } diff --git a/modules/globebrowsing/src/geojson/geojsonmanager.cpp b/modules/globebrowsing/src/geojson/geojsonmanager.cpp index ff60f4b14c..ff845ae277 100644 --- a/modules/globebrowsing/src/geojson/geojsonmanager.cpp +++ b/modules/globebrowsing/src/geojson/geojsonmanager.cpp @@ -50,14 +50,11 @@ void GeoJsonManager::deinitializeGL() { } bool GeoJsonManager::isReady() const { - const bool isReady = std::all_of( - std::begin(_geoJsonObjects), - std::end(_geoJsonObjects), - [](const std::unique_ptr& g) { - return g->isReady(); - } + return std::all_of( + _geoJsonObjects.cbegin(), + _geoJsonObjects.cend(), + std::mem_fn(&GeoJsonComponent::isReady) ); - return isReady; } void GeoJsonManager::addGeoJsonLayer(const ghoul::Dictionary& layerDict) { diff --git a/modules/globebrowsing/src/geojson/geojsonproperties.cpp b/modules/globebrowsing/src/geojson/geojsonproperties.cpp index 43de1e733d..9d1609cdf8 100644 --- a/modules/globebrowsing/src/geojson/geojsonproperties.cpp +++ b/modules/globebrowsing/src/geojson/geojsonproperties.cpp @@ -110,7 +110,7 @@ namespace { } } - glm::vec3 getColorValue(const geos::io::GeoJSONValue& value) { + glm::vec3 colorValue(const geos::io::GeoJSONValue& value) { // Default garish color used for when the color loading fails glm::vec3 color = glm::vec3(1.f, 0.f, 1.f); if (value.isArray()) { @@ -504,13 +504,13 @@ GeoJsonOverrideProperties propsFromGeoJson(const geos::io::GeoJSONFeature& featu result.opacity = static_cast(value.getNumber()); } else if (keyMatches(key, propertykeys::Color, ColorInfo)) { - result.color = getColorValue(value); + result.color = colorValue(value); } else if (keyMatches(key, propertykeys::FillOpacity, FillOpacityInfo)) { result.fillOpacity = static_cast(value.getNumber()); } else if (keyMatches(key, propertykeys::FillColor, FillColorInfo)) { - result.fillColor = getColorValue(value); + result.fillColor = colorValue(value); } else if (keyMatches(key, propertykeys::LineWidth, LineWidthInfo)) { result.lineWidth = static_cast(value.getNumber()); diff --git a/modules/globebrowsing/src/geojson/globegeometryfeature.cpp b/modules/globebrowsing/src/geojson/globegeometryfeature.cpp index 1962466201..80e4c3b8ab 100644 --- a/modules/globebrowsing/src/geojson/globegeometryfeature.cpp +++ b/modules/globebrowsing/src/geojson/globegeometryfeature.cpp @@ -303,9 +303,9 @@ void GlobeGeometryFeature::render(const RenderData& renderData, int pass, #ifndef __APPLE__ glLineWidth(_properties.lineWidth() * extraRenderData.lineWidthScale); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(1.f); -#endif +#endif // __APPLE__ for (const RenderFeature& r : _renderFeatures) { if (r.isExtrusionFeature && !_properties.extrude()) { @@ -478,34 +478,32 @@ void GlobeGeometryFeature::renderPolygons(const RenderFeature& feature, } bool GlobeGeometryFeature::shouldUpdateDueToHeightMapChange() const { - if (_properties.altitudeMode() == GeoJsonProperties::AltitudeMode::RelativeToGround) { - // Cap the update to a given time interval - const auto now = std::chrono::system_clock::now(); - if (now - _lastHeightUpdateTime < HeightUpdateInterval) { - return false; - } - - // TODO: Change computation so that we return true immediately if even one height - // value is different - - // Check if last height values for the control positions have changed - std::vector newHeights = getCurrentReferencePointsHeights(); - - const bool isSame = std::equal( - _lastControlHeights.begin(), - _lastControlHeights.end(), - newHeights.begin(), - newHeights.end(), - [](double a, double b) { - return std::abs(a - b) < std::numeric_limits::epsilon(); - } - ); - - if (!isSame) { - return true; - } + if (_properties.altitudeMode() != GeoJsonProperties::AltitudeMode::RelativeToGround) { + return false; } - return false; + + // Cap the update to a given time interval + const auto now = std::chrono::system_clock::now(); + if (now - _lastHeightUpdateTime < HeightUpdateInterval) { + return false; + } + + // TODO: Change computation so that we return true immediately if even one height + // value is different + + // Check if last height values for the control positions have changed + std::vector newHeights = getCurrentReferencePointsHeights(); + + const bool isSame = std::equal( + _lastControlHeights.cbegin(), + _lastControlHeights.cend(), + newHeights.cbegin(), + newHeights.cend(), + [](double a, double b) { + return std::abs(a - b) < std::numeric_limits::epsilon(); + } + ); + return !isSame; } void GlobeGeometryFeature::update(bool dataIsDirty, bool preventHeightUpdates) { @@ -541,10 +539,7 @@ void GlobeGeometryFeature::updateGeometry() { void GlobeGeometryFeature::updateHeightsFromHeightMap() { // @TODO: do the updating piece by piece, not all in one frame for (RenderFeature& f : _renderFeatures) { - f.heights = geometryhelper::heightMapHeightsFromGeodetic2List( - _globe, - f.vertices - ); + f.heights = geometryhelper::heightMapHeightsFromGeodetic2List(_globe, f.vertices); bufferDynamicHeightData(f); } @@ -825,12 +820,7 @@ void GlobeGeometryFeature::bufferVertexData(const RenderFeature& feature, glBindVertexArray(feature.vaoId); glBindBuffer(GL_ARRAY_BUFFER, feature.vboId); - glBufferData( - GL_ARRAY_BUFFER, - fullBufferSize, - nullptr, - GL_STATIC_DRAW - ); + glBufferData(GL_ARRAY_BUFFER, fullBufferSize, nullptr, GL_STATIC_DRAW); glBufferSubData( GL_ARRAY_BUFFER, diff --git a/modules/globebrowsing/src/globelabelscomponent.cpp b/modules/globebrowsing/src/globelabelscomponent.cpp index c759181ac9..2381da8c6d 100644 --- a/modules/globebrowsing/src/globelabelscomponent.cpp +++ b/modules/globebrowsing/src/globelabelscomponent.cpp @@ -322,7 +322,7 @@ void GlobeLabelsComponent::initialize(const ghoul::Dictionary& dictionary, return; } - const bool loadSuccess = loadLabelsData(absPath(*p.fileName)); + const bool loadSuccess = loadLabelsData(*p.fileName); if (!loadSuccess) { return; } diff --git a/modules/globebrowsing/src/globerotation.cpp b/modules/globebrowsing/src/globerotation.cpp index 00c378ff7b..03008df8e0 100644 --- a/modules/globebrowsing/src/globerotation.cpp +++ b/modules/globebrowsing/src/globerotation.cpp @@ -176,8 +176,7 @@ void GlobeRotation::setUpdateVariables() { requireUpdate(); } -glm::vec3 GlobeRotation::computeSurfacePosition(double latitude, double longitude) const -{ +glm::vec3 GlobeRotation::computeSurfacePosition(double latitude, double longitude) const { ghoul_assert(_globeNode, "Globe cannot be nullptr"); GlobeBrowsingModule* mod = global::moduleEngine->module(); @@ -218,7 +217,7 @@ glm::dmat3 GlobeRotation::matrix(const UpdateData&) const { _matrixIsDirty = true; } - if (!_matrixIsDirty) { + if (!_matrixIsDirty) [[likely]] { return _matrix; } diff --git a/modules/globebrowsing/src/globetranslation.cpp b/modules/globebrowsing/src/globetranslation.cpp index 3827f2b3c5..89cecc14cd 100644 --- a/modules/globebrowsing/src/globetranslation.cpp +++ b/modules/globebrowsing/src/globetranslation.cpp @@ -211,7 +211,7 @@ glm::dvec3 GlobeTranslation::position(const UpdateData&) const { _positionIsDirty = true; } - if (!_positionIsDirty) { + if (!_positionIsDirty) [[likely]] { return _position; } diff --git a/modules/globebrowsing/src/layergroup.cpp b/modules/globebrowsing/src/layergroup.cpp index 8fef6b9b46..e6c32fd28b 100644 --- a/modules/globebrowsing/src/layergroup.cpp +++ b/modules/globebrowsing/src/layergroup.cpp @@ -240,8 +240,8 @@ void LayerGroup::moveLayer(int oldPosition, int newPosition) { _layers.insert(newLayerPos, std::move(layer)); ghoul_assert( std::is_sorted( - _layers.begin(), - _layers.end(), + _layers.cbegin(), + _layers.cend(), [](const std::unique_ptr& a, const std::unique_ptr& b) { return a->zIndex() < b->zIndex(); } diff --git a/modules/globebrowsing/src/layermanager.cpp b/modules/globebrowsing/src/layermanager.cpp index d2b758c0a7..f555e4002c 100644 --- a/modules/globebrowsing/src/layermanager.cpp +++ b/modules/globebrowsing/src/layermanager.cpp @@ -107,8 +107,8 @@ bool LayerManager::hasAnyBlendingLayersEnabled() const { ZoneScoped; return std::any_of( - _layerGroups.begin(), - _layerGroups.end(), + _layerGroups.cbegin(), + _layerGroups.cend(), [](const std::unique_ptr& lg) { return lg->layerBlendingEnabled() && !lg->activeLayers().empty(); } diff --git a/modules/globebrowsing/src/layerrendersettings.cpp b/modules/globebrowsing/src/layerrendersettings.cpp index 75d6c11db5..37e97d11fe 100644 --- a/modules/globebrowsing/src/layerrendersettings.cpp +++ b/modules/globebrowsing/src/layerrendersettings.cpp @@ -87,7 +87,7 @@ void LayerRenderSettings::onChange(const std::function& callback) { float LayerRenderSettings::performLayerSettings(float value) const { return - ((glm::sign(value) * glm::pow(glm::abs(value), gamma) * multiplier) + offset); + ((glm::sign(value) * std::pow(std::abs(value), gamma) * multiplier) + offset); } glm::vec4 LayerRenderSettings::performLayerSettings(const glm::vec4& currentValue) const { diff --git a/modules/globebrowsing/src/memoryawaretilecache.cpp b/modules/globebrowsing/src/memoryawaretilecache.cpp index 08a3db9f54..2c4f56936d 100644 --- a/modules/globebrowsing/src/memoryawaretilecache.cpp +++ b/modules/globebrowsing/src/memoryawaretilecache.cpp @@ -298,19 +298,19 @@ MemoryAwareTileCache::MemoryAwareTileCache(int tileCacheSize) addProperty(_applyTileCacheSize); _cpuAllocatedTileData.setMaxValue( - static_cast(CpuCap.installedMainMemory() * 0.95) + static_cast(CpuCap.installedMainMemory() * 0.95f) ); _cpuAllocatedTileData.setReadOnly(true); addProperty(_cpuAllocatedTileData); _gpuAllocatedTileData.setMaxValue( - static_cast(CpuCap.installedMainMemory() * 0.95) + static_cast(CpuCap.installedMainMemory() * 0.95f) ); _gpuAllocatedTileData.setReadOnly(true); addProperty(_gpuAllocatedTileData); _tileCacheSize.setMaxValue( - static_cast(CpuCap.installedMainMemory() * 0.95) + static_cast(CpuCap.installedMainMemory() * 0.95f) ); addProperty(_tileCacheSize); diff --git a/modules/globebrowsing/src/rawtiledatareader.cpp b/modules/globebrowsing/src/rawtiledatareader.cpp index d20598d538..7af9d19c15 100644 --- a/modules/globebrowsing/src/rawtiledatareader.cpp +++ b/modules/globebrowsing/src/rawtiledatareader.cpp @@ -87,7 +87,6 @@ float interpretFloat(GLenum glType, const std::byte* src) { case GL_DOUBLE: return static_cast(*reinterpret_cast(src)); default: - ghoul_assert(false, "Unknown data type"); throw ghoul::MissingCaseException(); } } @@ -235,14 +234,14 @@ RawTile::ReadError postProcessErrorCheck(const RawTile& rawTile, if (hasMissingData && onHighLevel) { return RawTile::ReadError::Fatal; } - return RawTile::ReadError::None; + else { + return RawTile::ReadError::None; + } } } // namespace - -RawTileDataReader::RawTileDataReader(std::string filePath, - TileTextureInitData initData, +RawTileDataReader::RawTileDataReader(std::string filePath, TileTextureInitData initData, TileCacheProperties cacheProperties, PerformPreprocessing preprocess) : _datasetFilePath(std::move(filePath)) diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index ba90d1f3be..bfa0efc870 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -842,7 +842,7 @@ bool RenderableGlobe::isReady() const { } void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask) { - const double distanceToCamera = distance( + const double distanceToCamera = glm::distance( data.camera.positionVec3(), data.modelTransform.translation ); @@ -952,7 +952,7 @@ void RenderableGlobe::renderSecondary(const RenderData& data, RendererTasks&) { void RenderableGlobe::update(const UpdateData& data) { ZoneScoped; - if (_localRenderer.program && _localRenderer.program->isDirty()) { + if (_localRenderer.program && _localRenderer.program->isDirty()) [[unlikely]] { _localRenderer.program->rebuildFromFile(); _localRenderer.program->setUniform("xSegments", _grid.xSegments); @@ -963,7 +963,7 @@ void RenderableGlobe::update(const UpdateData& data) { ); } - if (_globalRenderer.program && _globalRenderer.program->isDirty()) { + if (_globalRenderer.program && _globalRenderer.program->isDirty()) [[unlikely]] { _globalRenderer.program->rebuildFromFile(); _globalRenderer.program->setUniform("xSegments", _grid.xSegments); @@ -1071,12 +1071,12 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, { ZoneScoped; - if (_layerManagerDirty) { + if (_layerManagerDirty) [[unlikely]] { _layerManager.update(); _layerManagerDirty = false; } - if (_nLayersIsDirty) { + if (_nLayersIsDirty) [[unlikely]] { std::array lgs = _layerManager.layerGroups(); _nActiveLayers = std::accumulate( @@ -1090,7 +1090,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, _nLayersIsDirty = false; } - if (_shadersNeedRecompilation) { + if (_shadersNeedRecompilation) [[unlikely]] { recompileShaders(); } @@ -1098,7 +1098,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, // Setting frame-const uniforms that are not view dependent // if (_layerManager.hasAnyBlendingLayersEnabled()) { - if (_lodScaleFactorDirty) { + if (_lodScaleFactorDirty) [[unlikely]] { const float dsf = static_cast( _currentLodScaleFactor * _ellipsoid.minimumRadius() ); @@ -1553,8 +1553,8 @@ void RenderableGlobe::renderChunkLocally(const Chunk& chunk, const RenderData& d // TODO: Patch normal can be calculated for all corners and then linearly // interpolated on the GPU to avoid cracks for high altitudes. // JCC: Camera space includes the SGCT View transformation. - const glm::vec3 patchNormalCameraSpace = normalize( - cross( + const glm::vec3 patchNormalCameraSpace = glm::normalize( + glm::cross( cornersCameraSpace[Quad::SOUTH_EAST] - cornersCameraSpace[Quad::SOUTH_WEST], cornersCameraSpace[Quad::NORTH_EAST] - cornersCameraSpace[Quad::SOUTH_WEST] ) @@ -1865,8 +1865,7 @@ void RenderableGlobe::recompileShaders() { } shaderDictionary.setValue("layerGroups", layerGroupNames); - for (const std::pair& p : preprocessingData.keyValuePairs) - { + for (const std::pair& p : preprocessingData.keyValuePairs) { shaderDictionary.setValue(p.first, p.second); } @@ -2200,15 +2199,9 @@ void RenderableGlobe::calculateEclipseShadows(ghoul::opengl::ProgramObject& prog return; } - const double sourceRadiusScale = std::max( - glm::compMax(sourceNode->scale()), - 1.0 - ); + const double sourceRadiusScale = std::max(glm::compMax(sourceNode->scale()), 1.0); - const double casterRadiusScale = std::max( - glm::compMax(casterNode->scale()), - 1.0 - ); + const double casterRadiusScale = std::max(glm::compMax(casterNode->scale()), 1.0); // First we determine if the caster is shadowing the current planet (all // calculations in World Coordinates): @@ -2247,13 +2240,12 @@ void RenderableGlobe::calculateEclipseShadows(ghoul::opengl::ProgramObject& prog (casterDistSun < planetDistSun)) { // The current caster is shadowing the current planet - shadowData.isShadowing = true; - shadowData.rs = shadowConf.source.second * sourceRadiusScale; - shadowData.rc = shadowConf.caster.second * casterRadiusScale; - shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); - shadowData.xp = xp_test; - shadowData.xu = shadowData.rc * sc_length / - (shadowData.rs - shadowData.rc); + shadowData.isShadowing = true; + shadowData.rs = shadowConf.source.second * sourceRadiusScale; + shadowData.rc = shadowConf.caster.second * casterRadiusScale; + shadowData.sourceCasterVec = glm::normalize(sourceCasterVec); + shadowData.xp = xp_test; + shadowData.xu = shadowData.rc * sc_length / (shadowData.rs - shadowData.rc); shadowData.casterPositionVec = casterPos; } shadowDataArray.push_back(shadowData); @@ -2514,28 +2506,28 @@ bool RenderableGlobe::isCullableByHorizon(const Chunk& chunk, } - const double objectP = pow(length(objectPos - globePos), 2); - const double horizonP = pow(minimumGlobeRadius - maxHeight, 2); + const double objectP = std::pow(glm::length(objectPos - globePos), 2); + const double horizonP = std::pow(minimumGlobeRadius - maxHeight, 2); if (objectP < horizonP) { return false; } - const double cameraP = pow(length(cameraPos - globePos), 2); - const double minR = pow(minimumGlobeRadius, 2); + const double cameraP = std::pow(glm::length(cameraPos - globePos), 2); + const double minR = std::pow(minimumGlobeRadius, 2); if (cameraP < minR) { return false; } - const double minimumAllowedDistanceToObjectFromHorizon = sqrt(objectP - horizonP); - const double distanceToHorizon = sqrt(cameraP - minR); + const double minimumAllowedDistanceToObjFromHorizon = std::sqrt(objectP - horizonP); + const double distanceToHorizon = std::sqrt(cameraP - minR); // Minimum allowed for the object to be occluded const double minimumAllowedDistanceToObjectSquared = - pow(distanceToHorizon + minimumAllowedDistanceToObjectFromHorizon, 2) + - pow(maxHeight, 2); + std::pow(distanceToHorizon + minimumAllowedDistanceToObjFromHorizon, 2) + + std::pow(maxHeight, 2); - const double distanceToObjectSquared = pow( - length(objectPos - cameraPos), + const double distanceToObjectSquared = std::pow( + glm::length(objectPos - cameraPos), 2 ); return distanceToObjectSquared > minimumAllowedDistanceToObjectSquared; diff --git a/modules/globebrowsing/src/ringscomponent.cpp b/modules/globebrowsing/src/ringscomponent.cpp index c898579f15..6380819d94 100644 --- a/modules/globebrowsing/src/ringscomponent.cpp +++ b/modules/globebrowsing/src/ringscomponent.cpp @@ -232,6 +232,7 @@ RingsComponent::RingsComponent(const ghoul::Dictionary& dictionary) // @TODO (abock, 2021-03-25) Righto! The RenderableGlobe passes this dictionary // in as-is so it would be easy to just pass it directly to the initialize method // instead + // @TODO (abock, 2025-02-16) Why haven't you done it yet?! , _ringsDictionary(dictionary) {} @@ -580,21 +581,21 @@ void RingsComponent::draw(const RenderData& data, RenderPass renderPass, void RingsComponent::update(const UpdateData& data) { ZoneScoped; - if (_shader && _shader->isDirty()) { + if (_shader && _shader->isDirty()) [[unlikely]] { compileShadowShader(); } - if (_geometryOnlyShader->isDirty()) { + if (_geometryOnlyShader->isDirty()) [[unlikely]] { _geometryOnlyShader->rebuildFromFile(); ghoul::opengl::updateUniformLocations(*_geometryOnlyShader, _geomUniformCache); } - if (_planeIsDirty) { + if (_planeIsDirty) [[unlikely]] { createPlane(); _planeIsDirty = false; } - if (_textureIsDirty) { + if (_textureIsDirty) [[unlikely]] { loadTexture(); _textureIsDirty = false; } diff --git a/modules/globebrowsing/src/shadowcomponent.cpp b/modules/globebrowsing/src/shadowcomponent.cpp index eff7f620f2..5db7bd4a7e 100644 --- a/modules/globebrowsing/src/shadowcomponent.cpp +++ b/modules/globebrowsing/src/shadowcomponent.cpp @@ -342,7 +342,7 @@ RenderData ShadowComponent::begin(const RenderData& data) { //glPolygonOffset(2.5f, 10.f); //checkGLError("begin() -- set values for polygon offset"); - RenderData lightRenderData{ + RenderData lightRenderData { *_lightCamera, data.time, data.renderBinMask, @@ -383,12 +383,7 @@ void ShadowComponent::update(const UpdateData&) { ZoneScoped; SceneGraphNode* sun = global::renderEngine->scene()->sceneGraphNode("Sun"); - if (sun) { - _sunPosition = sun->worldPosition(); - } - else { - _sunPosition = glm::dvec3(0.0); - } + _sunPosition = sun ? sun->worldPosition() : glm::dvec3(0.0); } void ShadowComponent::createDepthTexture() { @@ -516,7 +511,6 @@ void ShadowComponent::saveDepthBuffer() const { ppmFile.open("depthBufferShadowMapping.ppm", std::fstream::out); if (ppmFile.is_open()) { - ppmFile << "P3\n"; ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight << '\n'; ppmFile << "255\n"; @@ -554,7 +548,6 @@ void ShadowComponent::saveDepthBuffer() const { ppmFile.open("positionBufferShadowMapping.ppm", std::fstream::out); if (ppmFile.is_open()) { - ppmFile << "P3\n"; ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight << '\n'; ppmFile << "255\n"; diff --git a/modules/globebrowsing/src/skirtedgrid.cpp b/modules/globebrowsing/src/skirtedgrid.cpp index 82c1f98f8b..a5d32707c6 100644 --- a/modules/globebrowsing/src/skirtedgrid.cpp +++ b/modules/globebrowsing/src/skirtedgrid.cpp @@ -87,12 +87,12 @@ namespace { for (int y = -1; y < ySegments + 2; y++) { for (int x = -1; x < xSegments + 2; x++) { textureCoordinates.emplace_back( - glm::clamp( + std::clamp( static_cast(x) / static_cast(xSegments), 0.f - 1.f / (2.f * xSegments), 1.f + 1.f / (2.f * xSegments) ), - glm::clamp( + std::clamp( static_cast(y) / static_cast(ySegments), 0.f - 1.f / (2.f * ySegments), 1.f + 1.f / (2.f * ySegments) diff --git a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp index 1e64a67bcb..721c50dd0a 100644 --- a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp @@ -63,7 +63,6 @@ SingleImageProvider::SingleImageProvider(const ghoul::Dictionary& dictionary) } Tile SingleImageProvider::tile(const TileIndex&) { - ZoneScoped; return _tile; } diff --git a/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp b/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp index ef0c329008..2ebe0e231b 100644 --- a/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp @@ -68,7 +68,7 @@ SizeReferenceTileProvider::SizeReferenceTileProvider(const ghoul::Dictionary& di Tile SizeReferenceTileProvider::tile(const TileIndex& tileIndex) { ZoneScoped; - const GeodeticPatch patch(tileIndex); + const GeodeticPatch patch = GeodeticPatch(tileIndex); const bool aboveEquator = patch.isNorthern(); const double lat = aboveEquator ? patch.minLat() : patch.maxLat(); const double lon1 = patch.minLon(); diff --git a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp index 810f36c13c..c38015bd1d 100644 --- a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp @@ -473,15 +473,15 @@ TemporalTileProvider::tileProvider( // variable into the retrieveTileProvider function as it would generate a new // non-existing TileProvider for every new frame auto it = std::lower_bound( - _folder.files.begin(), - _folder.files.end(), + _folder.files.cbegin(), + _folder.files.cend(), time.j2000Seconds(), [](const std::pair& p, double t) { return p.first < t; } ); - if (it != _folder.files.begin()) { + if (it != _folder.files.cbegin()) { it -= 1; } @@ -495,24 +495,24 @@ TemporalTileProvider::tileProvider( const Time& time) { auto next = std::lower_bound( - _folder.files.begin(), - _folder.files.end(), + _folder.files.cbegin(), + _folder.files.cend(), time.j2000Seconds(), [](const std::pair& p, double t) { return p.first < t; } ); - auto curr = next != _folder.files.begin() ? next - 1 : next; - auto nextNext = next != _folder.files.end() ? next + 1 : curr; + auto curr = next != _folder.files.cbegin() ? next - 1 : next; + auto nextNext = next != _folder.files.cend() ? next + 1 : curr; - if (next == _folder.files.end()) { - curr = _folder.files.end() - 1; + if (next == _folder.files.cend()) { + curr = _folder.files.cend() - 1; next = curr; nextNext = curr; } - auto prev = curr != _folder.files.begin() ? curr - 1 : curr; + auto prev = curr != _folder.files.cbegin() ? curr - 1 : curr; _interpolateTileProvider->t1 = retrieveTileProvider(Time(curr->first)); _interpolateTileProvider->t2 = retrieveTileProvider(Time(next->first)); diff --git a/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp b/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp index 8562562e21..d9976bad1e 100644 --- a/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp @@ -64,7 +64,7 @@ Tile TileIndexTileProvider::tile(const TileIndex& tileIndex) { ); const glm::vec2 position = glm::vec2( initData.dimensions.x / 4 - - (initData.dimensions.x / 32) * log10(1 << tileIndex.level), + (initData.dimensions.x / 32) * std::log10(1 << tileIndex.level), initData.dimensions.y / 2 + fontSize ); diff --git a/modules/globebrowsing/src/tileprovider/tileprovider.cpp b/modules/globebrowsing/src/tileprovider/tileprovider.cpp index eb8caeeacd..057ce06a29 100644 --- a/modules/globebrowsing/src/tileprovider/tileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/tileprovider.cpp @@ -58,15 +58,17 @@ #include #include "cpl_minixml.h" -namespace openspace::globebrowsing { - namespace { - -std::unique_ptr DefaultTileTexture; -Tile DefaultTile = Tile { nullptr, std::nullopt, Tile::Status::Unavailable }; - + std::unique_ptr DefaultTileTexture; + openspace::globebrowsing::Tile DefaultTile = openspace::globebrowsing::Tile { + nullptr, + std::nullopt, + openspace::globebrowsing::Tile::Status::Unavailable + }; } // namespace +namespace openspace::globebrowsing { + unsigned int TileProvider::NumTileProviders = 0; std::unique_ptr TileProvider::createFromDictionary( diff --git a/modules/globebrowsing/src/tileprovider/tileproviderbydate.cpp b/modules/globebrowsing/src/tileprovider/tileproviderbydate.cpp index 3e048bc284..269624e609 100644 --- a/modules/globebrowsing/src/tileprovider/tileproviderbydate.cpp +++ b/modules/globebrowsing/src/tileprovider/tileproviderbydate.cpp @@ -115,7 +115,6 @@ Tile::Status TileProviderByDate::tileStatus(const TileIndex& index) { Tile::Status::Unavailable; } - TileDepthTransform TileProviderByDate::depthTransform() { return _currentTileProvider ? _currentTileProvider->depthTransform() : diff --git a/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp b/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp index 3d8d8ccde7..e12fc2f793 100644 --- a/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp +++ b/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp @@ -127,12 +127,7 @@ Tile TileProviderByLevel::tile(const TileIndex& tileIndex) { ZoneScoped; TileProvider* provider = levelProvider(tileIndex.level); - if (provider) { - return provider->tile(tileIndex); - } - else { - return Tile(); - } + return provider ? provider->tile(tileIndex) : Tile(); } Tile::Status TileProviderByLevel::tileStatus(const TileIndex& index) { @@ -144,7 +139,7 @@ TileProvider* TileProviderByLevel::levelProvider(int level) const { ZoneScoped; if (!_levelTileProviders.empty()) { - const int clampedLevel = glm::clamp( + const int clampedLevel = std::clamp( level, 0, static_cast(_providerIndices.size() - 1) diff --git a/modules/space/horizonsfile.cpp b/modules/space/horizonsfile.cpp index 2cd37ce618..75f190391d 100644 --- a/modules/space/horizonsfile.cpp +++ b/modules/space/horizonsfile.cpp @@ -248,7 +248,7 @@ HorizonsResultCode isValidHorizonsAnswer(const json& answer) { // Check whether the given Horizons file is valid or not // Return an error code with what is the problem if there was one HorizonsResultCode isValidHorizonsFile(const std::filesystem::path& file) { - std::ifstream fileStream(file); + std::ifstream fileStream = std::ifstream(file); if (!fileStream.good()) { return HorizonsResultCode::Empty; } @@ -492,7 +492,7 @@ HorizonsResult readHorizonsFile(std::filesystem::path file) { return result; } - std::ifstream fileStream(file); + std::ifstream fileStream = std::ifstream(file); if (!fileStream.good()) { LERROR(std::format("Failed to open Horizons file '{}'", file)); @@ -525,7 +525,7 @@ HorizonsResult readHorizonsVectorFile(std::filesystem::path file) { result.errorCode = HorizonsResultCode::Valid; std::vector data; - std::ifstream fileStream(file); + std::ifstream fileStream = std::ifstream(file); if (!fileStream.good()) { LERROR(std::format("Failed to open Horizons text file {}", file)); return HorizonsResult(); @@ -594,7 +594,7 @@ HorizonsResult readHorizonsObserverFile(std::filesystem::path file) { result.errorCode = HorizonsResultCode::Valid; std::vector data; - std::ifstream fileStream(file); + std::ifstream fileStream = std::ifstream(file); if (!fileStream.good()) { LERROR(std::format("Failed to open Horizons text file '{}'", file)); return HorizonsResult(); @@ -658,7 +658,7 @@ std::vector HorizonsFile::parseMatches(const std::string& startPhra const std::string& endPhrase, const std::string& altStartPhrase) const { - std::ifstream fileStream(_file); + std::ifstream fileStream = std::ifstream(_file); std::vector matches; if (!fileStream.good()) { @@ -743,7 +743,7 @@ std::pair HorizonsFile::parseValidTimeRange( const std::string& altStartPhrase, bool hasTime) const { - std::ifstream fileStream(_file); + std::ifstream fileStream = std::ifstream(_file); if (!fileStream.good()) { return { "", "" }; @@ -821,7 +821,7 @@ std::pair HorizonsFile::parseValidTimeRange( } // Read and save each word. - std::stringstream str(line); + std::stringstream str = std::stringstream(line); std::vector words; std::string word; while (str >> word) { diff --git a/modules/space/kepler.cpp b/modules/space/kepler.cpp index 1d30036791..8cf8cbadfc 100644 --- a/modules/space/kepler.cpp +++ b/modules/space/kepler.cpp @@ -401,8 +401,7 @@ std::vector readTleFile(const std::filesystem::path& file) { std::vector result; - std::ifstream f; - f.open(file); + std::ifstream f = std::ifstream(file); int lineNum = 1; @@ -518,8 +517,7 @@ std::vector readOmmFile(const std::filesystem::path& file) { std::vector result; - std::ifstream f; - f.open(file); + std::ifstream f = std::ifstream(file); int lineNum = 1; std::optional current = std::nullopt; @@ -611,8 +609,7 @@ std::vector readSbdbFile(const std::filesystem::path& file) { ghoul_assert(std::filesystem::is_regular_file(file), "File must exist"); - std::ifstream f; - f.open(file); + std::ifstream f = std::ifstream(file); std::string line; ghoul::getline(f, line); @@ -670,7 +667,7 @@ std::vector readSbdbFile(const std::filesystem::path& file) { } void saveCache(const std::vector& params, const std::filesystem::path& file) { - std::ofstream stream(file, std::ofstream::binary); + std::ofstream stream = std::ofstream(file, std::ofstream::binary); stream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); @@ -700,7 +697,7 @@ void saveCache(const std::vector& params, const std::filesystem::pat } std::optional> loadCache(const std::filesystem::path& file) { - std::ifstream stream(file, std::ifstream::binary); + std::ifstream stream = std::ifstream(file, std::ifstream::binary); int8_t version = 0; stream.read(reinterpret_cast(&version), sizeof(int8_t)); diff --git a/modules/space/rendering/renderableconstellationbounds.cpp b/modules/space/rendering/renderableconstellationbounds.cpp index a0ae97a33a..60f4937b8b 100644 --- a/modules/space/rendering/renderableconstellationbounds.cpp +++ b/modules/space/rendering/renderableconstellationbounds.cpp @@ -113,7 +113,7 @@ RenderableConstellationBounds::RenderableConstellationBounds( const Parameters p = codegen::bake(dictionary); // Avoid reading files here, instead do it in multithreaded initialize() - _vertexFilename = absPath(p.file).string(); + _vertexFilename = p.file.string(); _vertexFilename.onChange([this](){ loadData(); }); addProperty(_vertexFilename); @@ -132,16 +132,16 @@ void RenderableConstellationBounds::initialize() { std::set selectedConstellations; for (const std::string& s : _assetSelection) { - auto it = std::find(options.begin(), options.end(), s); - if (it == options.end()) { + auto it = std::find(options.cbegin(), options.cend(), s); + if (it == options.cend()) { // Test if the provided name was an identifier instead of the full name it = std::find( - options.begin(), - options.end(), + options.cbegin(), + options.cend(), constellationFullName(s) ); - if (it == options.end()) { + if (it == options.cend()) { // The user has specified a constellation name that doesn't exist LWARNING(std::format( "Option '{}' not found in list of constellations", s @@ -166,6 +166,8 @@ void RenderableConstellationBounds::initializeGL() { absPath("${MODULE_SPACE}/shaders/constellationbounds_fs.glsl") ); + ghoul::opengl::updateUniformLocations(*_program, _uniformCache); + glGenVertexArrays(1, &_vao); glBindVertexArray(_vao); @@ -210,17 +212,17 @@ bool RenderableConstellationBounds::isReady() const { void RenderableConstellationBounds::render(const RenderData& data, RendererTasks& tasks) { _program->activate(); - _program->setUniform("campos", glm::vec4(data.camera.positionVec3(), 1.f)); - _program->setUniform("objpos", glm::vec4(data.modelTransform.translation, 0.f)); - _program->setUniform("camrot", glm::mat4(data.camera.viewRotationMatrix())); - _program->setUniform("scaling", glm::vec2(1.f, 0.f)); + _program->setUniform(_uniformCache.campos, glm::vec4(data.camera.positionVec3(), 1.f)); + _program->setUniform(_uniformCache.objpos, glm::vec4(data.modelTransform.translation, 0.f)); + _program->setUniform(_uniformCache.camrot, glm::mat4(data.camera.viewRotationMatrix())); + _program->setUniform(_uniformCache.scaling, glm::vec2(1.f, 0.f)); const glm::dmat4 modelTransform = calcModelTransform(data); - _program->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); - _program->setUniform("ModelTransform", glm::mat4(modelTransform)); - _program->setUniform("color", _color); - _program->setUniform("opacity", opacity()); + _program->setUniform(_uniformCache.ViewProjection, data.camera.viewProjectionMatrix()); + _program->setUniform(_uniformCache.ModelTransform, glm::mat4(modelTransform)); + _program->setUniform(_uniformCache.color, _color); + _program->setUniform(_uniformCache.opacity, opacity()); glLineWidth(_lineWidth); @@ -250,14 +252,12 @@ bool RenderableConstellationBounds::loadVertexFile() { } std::filesystem::path fileName = absPath(_vertexFilename); - std::ifstream file; - file.open(fileName); + std::ifstream file = std::ifstream(fileName); if (!file.good()) { return false; } ConstellationBound currentBound; - currentBound.constellationAbbreviation = ""; std::string currentLine; int currentLineNumber = 1; diff --git a/modules/space/rendering/renderableconstellationbounds.h b/modules/space/rendering/renderableconstellationbounds.h index 17f3181c3e..7e6dea4a7e 100644 --- a/modules/space/rendering/renderableconstellationbounds.h +++ b/modules/space/rendering/renderableconstellationbounds.h @@ -27,6 +27,8 @@ #include +#include + namespace ghoul::opengl { class ProgramObject; } namespace openspace { @@ -107,6 +109,8 @@ private: GLuint _vao = 0; GLuint _vbo = 0; + UniformCache(campos, objpos, camrot, scaling, ViewProjection, ModelTransform, color, + opacity) _uniformCache; }; } // namespace openspace diff --git a/modules/space/rendering/renderableconstellationlines.cpp b/modules/space/rendering/renderableconstellationlines.cpp index 0714fa8b73..0225426068 100644 --- a/modules/space/rendering/renderableconstellationlines.cpp +++ b/modules/space/rendering/renderableconstellationlines.cpp @@ -43,10 +43,6 @@ namespace { constexpr std::string_view _loggerCat = "RenderableConstellationLines"; - constexpr std::array UniformNames = { - "modelViewTransform", "projectionTransform", "opacity", "color" - }; - constexpr openspace::properties::Property::PropertyInfo FileInfo = { "File", "Constellation Data File Path", @@ -143,7 +139,7 @@ RenderableConstellationLines::RenderableConstellationLines( const Parameters p = codegen::bake(dictionary); // Avoid reading files here, instead do it in multithreaded initialize() - _speckFile = absPath(p.file).string(); + _speckFile = p.file.string(); _speckFile.onChange([this]() { loadData(); }); addProperty(_speckFile); @@ -218,16 +214,16 @@ void RenderableConstellationLines::initialize() { std::set selectedConstellations; for (const std::string& s : _assetSelection) { - auto it = std::find(options.begin(), options.end(), s); - if (it == options.end()) { + auto it = std::find(options.cbegin(), options.cend(), s); + if (it == options.cend()) { // Test if the provided name was an identifier instead of the full name it = std::find( - options.begin(), - options.end(), + options.cbegin(), + options.cend(), constellationFullName(s) ); - if (it == options.end()) { + if (it == options.cend()) { // The user has specified a constellation name that doesn't exist LWARNING(std::format( "Option '{}' not found in list of constellations", s @@ -252,7 +248,7 @@ void RenderableConstellationLines::initializeGL() { absPath("${MODULE_SPACE}/shaders/constellationlines_fs.glsl") ); - ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_program, _uniformCache); createConstellations(); } @@ -327,29 +323,22 @@ void RenderableConstellationLines::render(const RenderData& data, RendererTasks& void RenderableConstellationLines::update(const UpdateData&) { if (_program->isDirty()) { _program->rebuildFromFile(); - ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_program, _uniformCache); } } -bool RenderableConstellationLines::loadData() { - const bool success = readSpeckFile(); - if (!success) { - throw ghoul::RuntimeError("Error loading data"); - } - return success; -} - -bool RenderableConstellationLines::readSpeckFile() { +void RenderableConstellationLines::loadData() { if (_speckFile.value().empty()) { - return false; + throw ghoul::RuntimeError("Error loading data"); } std::filesystem::path fileName = absPath(_speckFile); LINFO(std::format("Loading Speck file '{}'", fileName)); std::ifstream file(fileName); if (!file.good()) { - LERROR(std::format("Failed to open Speck file '{}'", fileName)); - return false; + throw ghoul::RuntimeError(std::format( + "Failed to open Speck file '{}'", fileName + )); } const float scale = static_cast(toMeter(_constellationUnit)); @@ -460,12 +449,10 @@ bool RenderableConstellationLines::readSpeckFile() { _renderingConstellationsMap.insert({ lineIndex++, constellationLine }); } else { - return false; + throw ghoul::RuntimeError("Error parsing file"); } } setBoundingSphere(maxRadius); - - return true; } void RenderableConstellationLines::createConstellations() { diff --git a/modules/space/rendering/renderableconstellationlines.h b/modules/space/rendering/renderableconstellationlines.h index 75b7d3f390..4910cb75c3 100644 --- a/modules/space/rendering/renderableconstellationlines.h +++ b/modules/space/rendering/renderableconstellationlines.h @@ -73,8 +73,7 @@ private: void renderConstellations(const RenderData& data, const glm::dmat4& modelViewMatrix, const glm::dmat4& projectionMatrix); - bool loadData(); - bool readSpeckFile(); + void loadData(); /** * Callback method that gets triggered when `_constellationSelection` changes. diff --git a/modules/space/rendering/renderableconstellationsbase.cpp b/modules/space/rendering/renderableconstellationsbase.cpp index 359fc21eb3..849ec81cbe 100644 --- a/modules/space/rendering/renderableconstellationsbase.cpp +++ b/modules/space/rendering/renderableconstellationsbase.cpp @@ -105,7 +105,7 @@ RenderableConstellationsBase::RenderableConstellationsBase( // Avoid reading files here, instead do it in multithreaded initialize() if (p.namesFile.has_value()) { - _namesFilename = absPath(*p.namesFile).string(); + _namesFilename = p.namesFile->string(); } _namesFilename.onChange([this]() { loadConstellationFile(); }); addProperty(_namesFilename); @@ -156,7 +156,7 @@ void RenderableConstellationsBase::loadConstellationFile() { // Load the constellation names file std::ifstream file; file.exceptions(std::ifstream::goodbit); - file.open(absPath(_namesFilename)); + file.open(_namesFilename); std::string line; while (file.good()) { diff --git a/modules/space/rendering/renderableeclipsecone.cpp b/modules/space/rendering/renderableeclipsecone.cpp index c8bc7d5703..6630e2b547 100644 --- a/modules/space/rendering/renderableeclipsecone.cpp +++ b/modules/space/rendering/renderableeclipsecone.cpp @@ -34,10 +34,6 @@ #include namespace { - constexpr std::array UniformNames = { - "modelViewProjectionTransform", "shadowColor", "opacity" - }; - struct VBOLayout { float x = 0.f; float y = 0.f; @@ -127,6 +123,40 @@ namespace { openspace::properties::Property::Visibility::AdvancedUser }; + std::vector calculateShadowPoints( + const std::vector& srcTerminator, + const std::vector& dstTerminator, + const glm::dvec3& shadowerToLightSource, + const glm::dmat3& lightSourceToShadower, + double lengthScale) + { + ghoul_assert( + srcTerminator.size() == dstTerminator.size(), + "Unmatched termiator pts" + ); + + std::vector vertices; + vertices.reserve(dstTerminator.size() * 2); + for (size_t i = 0; i < dstTerminator.size(); i++) { + // Convert the terminator points from the reference frame of the Sun to the + // reference frame of the Moon + const glm::dvec3 src = + lightSourceToShadower * srcTerminator[i] + shadowerToLightSource; + const glm::dvec3& dst = dstTerminator[i]; + const glm::dvec3 dir = glm::normalize(dst - src); + + // The start point is the terminator point on the Moon + const glm::vec3 p1 = dst; + vertices.push_back({ p1.x, p1.y, p1.z }); + + // The end point is calculated by forward propagating the incoming direction + const glm::vec3 p2 = dst + dir * lengthScale; + vertices.push_back({ p2.x, p2.y, p2.z }); + } + return vertices; + } + + struct [[codegen::Dictionary(RenderableEclipseCone)]] Parameters { // [[codegen::verbatim(NumberPointsInfo.description)]] std::optional numberOfPoints; @@ -241,7 +271,7 @@ void RenderableEclipseCone::initializeGL() { } ); - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } void RenderableEclipseCone::deinitializeGL() { @@ -300,42 +330,13 @@ void RenderableEclipseCone::render(const RenderData& data, RendererTasks&) { } void RenderableEclipseCone::update(const UpdateData& data) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } createCone(data.time.j2000Seconds()); } -std::vector calculateShadowPoints(const std::vector& srcTerminator, - const std::vector& dstTerminator, - const glm::dvec3& shadowerToLightSource, - const glm::dmat3& lightSourceToShadower, - double lengthScale) -{ - ghoul_assert(srcTerminator.size() == dstTerminator.size(), "Unmatched termiator pts"); - - std::vector vertices; - vertices.reserve(dstTerminator.size() * 2); - for (size_t i = 0; i < dstTerminator.size(); i++) { - // Convert the terminator points from the reference frame of the Sun to the - // reference frame of the Moon - const glm::dvec3 src = - lightSourceToShadower * srcTerminator[i] + shadowerToLightSource; - const glm::dvec3& dst = dstTerminator[i]; - const glm::dvec3 dir = glm::normalize(dst - src); - - // The start point is the terminator point on the Moon - const glm::vec3 p1 = dst; - vertices.push_back({ p1.x, p1.y, p1.z }); - - // The end point is calculated by forward propagating the incoming direction - const glm::vec3 p2 = dst + dir * lengthScale; - vertices.push_back({ p2.x, p2.y, p2.z }); - } - return vertices; -} - void RenderableEclipseCone::createCone(double et) { ZoneScoped; diff --git a/modules/space/rendering/renderablehabitablezone.cpp b/modules/space/rendering/renderablehabitablezone.cpp index 2231271d7d..a708a41fba 100644 --- a/modules/space/rendering/renderablehabitablezone.cpp +++ b/modules/space/rendering/renderablehabitablezone.cpp @@ -40,11 +40,6 @@ #include namespace { - constexpr std::array UniformNames = { - "modelViewProjectionTransform", "opacity", "width", "transferFunctionTexture", - "conservativeBounds", "showOptimistic" - }; - constexpr openspace::properties::Property::PropertyInfo EffectiveTemperatureInfo = { "EffectiveTemperature", "Effective Temperature", @@ -154,14 +149,14 @@ void RenderableHabitableZone::render(const RenderData& data, RendererTasks&) { ghoul::opengl::TextureUnit unit; unit.activate(); _texture->bind(); - _shader->setUniform(_uniformCache.texture, unit); + _shader->setUniform(_uniformCache.transferFunctionTexture, unit); glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(false); glDisable(GL_CULL_FACE); - _plane->render(); + _plane.render(); _shader->deactivate(); @@ -177,11 +172,11 @@ void RenderableHabitableZone::initializeShader() { absPath("${MODULE_SPACE}/shaders/habitablezone_vs.glsl"), absPath("${MODULE_SPACE}/shaders/habitablezone_fs.glsl") ); - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + updateUniformLocations(); } void RenderableHabitableZone::updateUniformLocations() { - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } void RenderableHabitableZone::computeZone() { diff --git a/modules/space/rendering/renderablehabitablezone.h b/modules/space/rendering/renderablehabitablezone.h index ef08893d9d..01c5091bb1 100644 --- a/modules/space/rendering/renderablehabitablezone.h +++ b/modules/space/rendering/renderablehabitablezone.h @@ -68,7 +68,7 @@ private: glm::vec2 _conservativeBounds; - UniformCache(modelViewProjection, opacity, width, texture, + UniformCache(modelViewProjection, opacity, width, transferFunctionTexture, conservativeBounds, showOptimistic) _uniformCache; }; diff --git a/modules/space/rendering/renderableorbitalkepler.cpp b/modules/space/rendering/renderableorbitalkepler.cpp index df517ee0db..0c9d954e6d 100644 --- a/modules/space/rendering/renderableorbitalkepler.cpp +++ b/modules/space/rendering/renderableorbitalkepler.cpp @@ -45,7 +45,6 @@ #include namespace { - // The possible values for the _renderingModes property enum RenderingMode { RenderingModeTrail = 0, @@ -398,37 +397,8 @@ void RenderableOrbitalKepler::initializeGL() { } ); - // Init cache for line rendering - _uniformTrailCache.modelView = - _trailProgram->uniformLocation("modelViewTransform"); - _uniformTrailCache.projection = - _trailProgram->uniformLocation("projectionTransform"); - _uniformTrailCache.colorFadeCutoffValue = - _trailProgram->uniformLocation("colorFadeCutoffValue"); - _uniformTrailCache.trailFadeExponent = - _trailProgram->uniformLocation("trailFadeExponent"); - _uniformTrailCache.inGameTime = _trailProgram->uniformLocation("inGameTime"); - _uniformTrailCache.color = _trailProgram->uniformLocation("color"); - _uniformTrailCache.opacity = _trailProgram->uniformLocation("opacity"); - - // Init cache for point rendering - _uniformPointCache.modelTransform = _pointProgram->uniformLocation("modelTransform"); - _uniformPointCache.viewTransform = _pointProgram->uniformLocation("viewTransform"); - _uniformPointCache.cameraUpWorld = _pointProgram->uniformLocation("cameraUpWorld"); - _uniformPointCache.inGameTime = _pointProgram->uniformLocation("inGameTime"); - _uniformPointCache.color = _pointProgram->uniformLocation("color"); - _uniformPointCache.enableMaxSize = _pointProgram->uniformLocation("enableMaxSize"); - _uniformPointCache.maxSize = _pointProgram->uniformLocation("maxSize"); - _uniformPointCache.enableOutline = _pointProgram->uniformLocation("enableOutline"); - _uniformPointCache.outlineColor = _pointProgram->uniformLocation("outlineColor"); - _uniformPointCache.outlineWeight = _pointProgram->uniformLocation("outlineWeight"); - _uniformPointCache.opacity = _pointProgram->uniformLocation("opacity"); - _uniformPointCache.projectionTransform = - _pointProgram->uniformLocation("projectionTransform"); - _uniformPointCache.cameraPositionWorld = - _pointProgram->uniformLocation("cameraPositionWorld"); - _uniformPointCache.pointSizeExponent = - _pointProgram->uniformLocation("pointSizeExponent"); + ghoul::opengl::updateUniformLocations(*_trailProgram, _uniformTrailCache); + ghoul::opengl::updateUniformLocations(*_pointProgram, _uniformPointCache); updateBuffers(); } @@ -555,11 +525,11 @@ void RenderableOrbitalKepler::render(const RenderData& data, RendererTasks&) { data.time.j2000Seconds() ); _trailProgram->setUniform( - _uniformTrailCache.modelView, + _uniformTrailCache.modelViewTransform, calcModelViewTransform(data) ); _trailProgram->setUniform( - _uniformTrailCache.projection, + _uniformTrailCache.projectionTransform, data.camera.projectionMatrix() ); @@ -592,10 +562,7 @@ void RenderableOrbitalKepler::render(const RenderData& data, RendererTasks&) { } void RenderableOrbitalKepler::updateBuffers() { - std::vector parameters = kepler::readFile( - _path.value(), - _format - ); + std::vector parameters = kepler::readFile(_path.value(), _format); _numObjects = parameters.size(); @@ -654,7 +621,7 @@ void RenderableOrbitalKepler::updateBuffers() { const double scale = static_cast(_segmentQuality) * 10.0; const kepler::Parameters& p = parameters[i]; _segmentSize.push_back( - static_cast(scale + (scale / pow(1.0 - p.eccentricity, 1.2))) + static_cast(scale + (scale / std::pow(1.0 - p.eccentricity, 1.2))) ); _startIndex.push_back(_startIndex[i] + static_cast(_segmentSize[i])); } diff --git a/modules/space/rendering/renderableorbitalkepler.h b/modules/space/rendering/renderableorbitalkepler.h index 4608cd1716..1cdfbab048 100644 --- a/modules/space/rendering/renderableorbitalkepler.h +++ b/modules/space/rendering/renderableorbitalkepler.h @@ -81,7 +81,7 @@ private: void updateBuffers(); bool _updateDataBuffersAtNextRender = false; - std::streamoff _numObjects; + long long _numObjects = 0; std::vector _segmentSize; std::vector _startIndex; properties::UIntProperty _segmentQuality; @@ -101,19 +101,19 @@ private: /// The backend storage for the vertex buffer object containing all points std::vector _vertexBufferData; - GLuint _vertexArray; - GLuint _vertexBuffer; + GLuint _vertexArray = 0; + GLuint _vertexBuffer = 0; - ghoul::opengl::ProgramObject* _trailProgram; - ghoul::opengl::ProgramObject* _pointProgram; + ghoul::opengl::ProgramObject* _trailProgram = nullptr; + ghoul::opengl::ProgramObject* _pointProgram = nullptr; properties::StringProperty _path; properties::BoolProperty _contiguousMode; kepler::Format _format; RenderableOrbitalKepler::Appearance _appearance; // Line cache - UniformCache(modelView, projection, trailFadeExponent, colorFadeCutoffValue, - inGameTime, color, opacity) + UniformCache(modelViewTransform, projectionTransform, trailFadeExponent, + colorFadeCutoffValue, inGameTime, color, opacity) _uniformTrailCache; // Point cache diff --git a/modules/space/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp index 76675df9a2..148cfa940d 100644 --- a/modules/space/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -39,11 +39,6 @@ #include namespace { - constexpr std::array UniformNames = { - "modelViewProjectionTransform", "textureOffset", "colorFilterValue", - "_nightFactor", "sunPosition", "texture1" - }; - constexpr openspace::properties::Property::PropertyInfo TextureInfo = { "Texture", "Texture", @@ -157,7 +152,7 @@ void RenderableRings::initializeGL() { absPath("${MODULE_SPACE}/shaders/rings_fs.glsl") ); - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); glGenVertexArrays(1, &_quad); glGenBuffers(1, &_vertexPositionBuffer); @@ -208,17 +203,17 @@ void RenderableRings::render(const RenderData& data, RendererTasks&) { } void RenderableRings::update(const UpdateData& data) { - if (_shader->isDirty()) { + if (_shader->isDirty()) [[unlikely]] { _shader->rebuildFromFile(); - ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shader, _uniformCache); } - if (_planeIsDirty) { + if (_planeIsDirty) [[unlikely]] { createPlane(); _planeIsDirty = false; } - if (_textureIsDirty) { + if (_textureIsDirty) [[unlikely]] { loadTexture(); _textureIsDirty = false; } @@ -234,29 +229,25 @@ void RenderableRings::update(const UpdateData& data) { } void RenderableRings::loadTexture() { - if (!_texturePath.value().empty()) { - using namespace ghoul::io; - using namespace ghoul::opengl; - std::unique_ptr texture = TextureReader::ref().loadTexture( - absPath(_texturePath), - 1 + using namespace ghoul::io; + using namespace ghoul::opengl; + std::unique_ptr texture = TextureReader::ref().loadTexture( + _texturePath.value(), + 1 + ); + + if (texture) { + LDEBUGC( + "RenderableRings", + std::format("Loaded texture from '{}'", _texturePath.value()) ); + _texture = std::move(texture); - if (texture) { - LDEBUGC( - "RenderableRings", - std::format("Loaded texture from '{}'", absPath(_texturePath)) - ); - _texture = std::move(texture); + _texture->uploadTexture(); + _texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - _texture->uploadTexture(); - _texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - - _textureFile = std::make_unique( - _texturePath.value() - ); - _textureFile->setCallback([this]() { _textureIsDirty = true; }); - } + _textureFile = std::make_unique(_texturePath.value()); + _textureFile->setCallback([this]() { _textureIsDirty = true; }); } } diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 150e5c2452..86f35bcb67 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -50,14 +50,6 @@ namespace { constexpr std::string_view _loggerCat = "RenderableStars"; - constexpr std::array UniformNames = { - "modelMatrix", "cameraViewProjectionMatrix", "cameraUp", "eyePosition", - "colorOption", "magnitudeExponent", "sizeComposition", "lumCent", "radiusCent", - "colorTexture", "opacity", "otherDataTexture", "otherDataRange", - "filterOutOfRange", "fixedColor", "glareTexture", "glareMultiplier", "glareGamma", - "glareScale", "hasCore", "coreTexture", "coreMultiplier", "coreGamma", "coreScale" - }; - enum SizeComposition { DistanceModulus = 0, AppBrightness, @@ -674,7 +666,7 @@ void RenderableStars::initializeGL() { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindVertexArray(0); - ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_program, _uniformCache); loadData(); @@ -852,7 +844,7 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { } void RenderableStars::update(const UpdateData&) { - if (_speckFileIsDirty) { + if (_speckFileIsDirty) [[unlikely]] { loadData(); _speckFileIsDirty = false; _dataIsDirty = true; @@ -862,7 +854,7 @@ void RenderableStars::update(const UpdateData&) { return; } - if (_dataIsDirty) { + if (_dataIsDirty) [[unlikely]] { const int value = _colorOption; LDEBUG("Regenerating data"); @@ -975,12 +967,12 @@ void RenderableStars::update(const UpdateData&) { _dataIsDirty = false; } - if (_pointSpreadFunctionTextureIsDirty) { + if (_pointSpreadFunctionTextureIsDirty) [[unlikely]] { LDEBUG("Reloading Point Spread Function texture"); loadPSFTexture(); } - if (_colorTextureIsDirty) { + if (_colorTextureIsDirty) [[unlikely]] { LDEBUG("Reloading Color Texture"); _colorTexture = nullptr; if (!_colorTexturePath.value().empty()) { @@ -1001,7 +993,7 @@ void RenderableStars::update(const UpdateData&) { _colorTextureIsDirty = false; } - if (_otherDataColorMapIsDirty) { + if (_otherDataColorMapIsDirty) [[unlikely]] { LDEBUG("Reloading Color Texture"); _otherDataColorMapTexture = nullptr; if (!_otherDataColorMapPath.value().empty()) { @@ -1020,9 +1012,9 @@ void RenderableStars::update(const UpdateData&) { } - if (_program->isDirty()) { + if (_program->isDirty()) [[unlikely]] { _program->rebuildFromFile(); - ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_program, _uniformCache); } } diff --git a/modules/space/rendering/renderabletravelspeed.cpp b/modules/space/rendering/renderabletravelspeed.cpp index 059ad2af8b..de66b9ef02 100644 --- a/modules/space/rendering/renderabletravelspeed.cpp +++ b/modules/space/rendering/renderabletravelspeed.cpp @@ -37,8 +37,6 @@ #include namespace { - constexpr std::array UniformNames = { "lineColor", "opacity" }; - constexpr openspace::properties::Property::PropertyInfo SpeedInfo = { "TravelSpeed", "Speed of Travel", @@ -198,7 +196,7 @@ void RenderableTravelSpeed::initializeGL() { glGenVertexArrays(1, &_vaoId); glGenBuffers(1, &_vBufferId); - ghoul::opengl::updateUniformLocations(*_shaderProgram, _uniformCache, UniformNames); + ghoul::opengl::updateUniformLocations(*_shaderProgram, _uniformCache); } void RenderableTravelSpeed::deinitializeGL() { @@ -306,9 +304,9 @@ void RenderableTravelSpeed::render(const RenderData& data, RendererTasks&) { #ifndef __APPLE__ glLineWidth(_lineWidth); -#else +#else // ^^^^ __APPLE__ // !__APPLE__ vvvv glLineWidth(1.f); -#endif +#endif // __APPLE__ glBindVertexArray(_vaoId); glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); glDrawArrays(GL_LINE_STRIP, 0, 3); diff --git a/modules/space/shaders/habitablezone_vs.glsl b/modules/space/shaders/habitablezone_vs.glsl index 958d5739a8..4d3c4906c0 100644 --- a/modules/space/shaders/habitablezone_vs.glsl +++ b/modules/space/shaders/habitablezone_vs.glsl @@ -32,12 +32,12 @@ layout(location = 1) in vec2 in_st; out vec2 vs_st; out float vs_screenSpaceDepth; -uniform mat4 modelViewProjectionTransform; +uniform mat4 modelViewProjection; void main() { vec4 position = vec4(in_position.xy, 0.0, 1.0); - vec4 positionScreenSpace = z_normalization(modelViewProjectionTransform * position); + vec4 positionScreenSpace = z_normalization(modelViewProjection * position); // Moving the origin to the center vs_st = (in_st - vec2(0.5)) * 2.0; diff --git a/modules/space/translation/gptranslation.cpp b/modules/space/translation/gptranslation.cpp index 5e0357bade..8faf0643fc 100644 --- a/modules/space/translation/gptranslation.cpp +++ b/modules/space/translation/gptranslation.cpp @@ -55,7 +55,7 @@ namespace { namespace openspace { documentation::Documentation GPTranslation::Documentation() { - return codegen::doc("space_transform_gp"); + return codegen::doc("space_translation_gp"); } GPTranslation::GPTranslation(const ghoul::Dictionary& dictionary) { diff --git a/modules/space/translation/horizonstranslation.cpp b/modules/space/translation/horizonstranslation.cpp index f26aceea27..a2c045af69 100644 --- a/modules/space/translation/horizonstranslation.cpp +++ b/modules/space/translation/horizonstranslation.cpp @@ -69,13 +69,12 @@ documentation::Documentation HorizonsTranslation::Documentation() { HorizonsTranslation::HorizonsTranslation() : _horizonsFiles(HorizonsTextFileInfo) { - addProperty(_horizonsFiles); - _horizonsFiles.onChange([this](){ requireUpdate(); notifyObservers(); loadData(); }); + addProperty(_horizonsFiles); } HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) @@ -94,7 +93,7 @@ HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) std::vector f; std::transform( files.cbegin(), - files.end(), + files.cend(), std::back_inserter(f), [](const std::filesystem::path& p) { return p.string(); } ); @@ -197,7 +196,7 @@ bool HorizonsTranslation::readHorizonsTextFile(HorizonsFile& horizonsFile) { } bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { - std::ifstream fileStream(file, std::ifstream::binary); + std::ifstream fileStream = std::ifstream(file, std::ifstream::binary); if (!fileStream.good()) { LERROR(std::format("Error opening file '{}' for loading cache file", file)); @@ -247,7 +246,7 @@ bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { } void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) const { - std::ofstream fileStream(file, std::ofstream::binary); + std::ofstream fileStream = std::ofstream(file, std::ofstream::binary); if (!fileStream.good()) { LERROR(std::format("Error opening file '{}' for save cache file", file)); return; diff --git a/modules/space/translation/keplertranslation.cpp b/modules/space/translation/keplertranslation.cpp index 4e9d440765..75876c15a5 100644 --- a/modules/space/translation/keplertranslation.cpp +++ b/modules/space/translation/keplertranslation.cpp @@ -221,14 +221,14 @@ double KeplerTranslation::eccentricAnomaly(double meanAnomaly) const { else if (_eccentricity < 0.2) { auto solver = [this, &meanAnomaly](double x) -> double { // For low eccentricity, using a first order solver sufficient - return meanAnomaly + _eccentricity * sin(x); + return meanAnomaly + _eccentricity * std::sin(x); }; return solveIteration(solver, meanAnomaly, 0.0, 5); } else if (_eccentricity < 0.9) { auto solver = [this, &meanAnomaly](double x) -> double { const double e = _eccentricity; - return x + (meanAnomaly + e * sin(x) - x) / (1.0 - e * cos(x)); + return x + (meanAnomaly + e * std::sin(x) - x) / (1.0 - e * std::cos(x)); }; return solveIteration(solver, meanAnomaly, 0.0, 6); } @@ -236,16 +236,16 @@ double KeplerTranslation::eccentricAnomaly(double meanAnomaly) const { auto sign = [](double val) -> double { return val > 0.0 ? 1.0 : ((val < 0.0) ? -1.0 : 0.0); }; - const double e = meanAnomaly + 0.85 * _eccentricity * sign(sin(meanAnomaly)); + const double e = meanAnomaly + 0.85 * _eccentricity * sign(std::sin(meanAnomaly)); auto solver = [this, &meanAnomaly, &sign](double x) -> double { - const double s = _eccentricity * sin(x); - const double c = _eccentricity * cos(x); + const double s = _eccentricity * std::sin(x); + const double c = _eccentricity * std::cos(x); const double f = x - s - meanAnomaly; const double f1 = 1 - c; const double f2 = s; return x + (-5 * f / (f1 + sign(f1) * - sqrt(std::abs(16 * f1 * f1 - 20 * f * f2)))); + std::sqrt(std::abs(16 * f1 * f1 - 20 * f * f2)))); }; return solveIteration(solver, e, 0.0, 8); } @@ -269,11 +269,11 @@ glm::dvec3 KeplerTranslation::position(const UpdateData& data) const { // Use the eccentric anomaly to compute the actual location const glm::dvec3 p = glm::dvec3( - _semiMajorAxis * 1000.0 * (cos(e) - _eccentricity), - _semiMajorAxis * 1000.0 * sin(e) * sqrt(1.0 - _eccentricity * _eccentricity), + _semiMajorAxis * (std::cos(e) - _eccentricity), + _semiMajorAxis * std::sin(e) * std::sqrt(1.0 - _eccentricity * _eccentricity), 0.0 ); - return _orbitPlaneRotation * p; + return _orbitPlaneRotation * p * 1000.0; } void KeplerTranslation::computeOrbitPlane() const { @@ -288,17 +288,17 @@ void KeplerTranslation::computeOrbitPlane() const { // inclination // 3. Around the new z axis to place the closest approach to the correct location - const glm::vec3 ascendingNodeAxisRot = glm::vec3(0.f, 0.f, 1.f); - const glm::vec3 inclinationAxisRot = glm::vec3(1.f, 0.f, 0.f); - const glm::vec3 argPeriapsisAxisRot = glm::vec3(0.f, 0.f, 1.f); + const glm::dvec3 ascendingNodeAxisRot = glm::dvec3(0.f, 0.f, 1.f); + const glm::dvec3 inclinationAxisRot = glm::dvec3(1.f, 0.f, 0.f); + const glm::dvec3 argPeriapsisAxisRot = glm::dvec3(0.f, 0.f, 1.f); const double asc = glm::radians(_ascendingNode.value()); const double inc = glm::radians(_inclination.value()); const double per = glm::radians(_argumentOfPeriapsis.value()); - _orbitPlaneRotation = glm::rotate(asc, glm::dvec3(ascendingNodeAxisRot)) * - glm::rotate(inc, glm::dvec3(inclinationAxisRot)) * - glm::rotate(per, glm::dvec3(argPeriapsisAxisRot)); + _orbitPlaneRotation = glm::rotate(asc, ascendingNodeAxisRot) * + glm::rotate(inc, inclinationAxisRot) * + glm::rotate(per, argPeriapsisAxisRot); notifyObservers(); _orbitPlaneDirty = false; diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index 40e980d6bb..0a90015014 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -454,7 +454,7 @@ void RenderableFov::deinitializeGL() { } bool RenderableFov::isReady() const { - return _program != nullptr && !_instrument.bounds.empty(); + return _program && !_instrument.bounds.empty(); } // Orthogonal projection next to planets surface diff --git a/modules/spacecraftinstruments/util/decoder.h b/modules/spacecraftinstruments/util/decoder.h index 1a94e0bd7c..b966f0b051 100644 --- a/modules/spacecraftinstruments/util/decoder.h +++ b/modules/spacecraftinstruments/util/decoder.h @@ -41,7 +41,7 @@ public: virtual ~Decoder() = default; - virtual const std::string& decoderType() const = 0; + virtual std::string_view decoderType() const = 0; virtual const std::vector& translations() const = 0; protected: diff --git a/modules/spacecraftinstruments/util/hongkangparser.cpp b/modules/spacecraftinstruments/util/hongkangparser.cpp index 05f1f0ba2d..2d2579bf4c 100644 --- a/modules/spacecraftinstruments/util/hongkangparser.cpp +++ b/modules/spacecraftinstruments/util/hongkangparser.cpp @@ -146,7 +146,7 @@ bool HongKangParser::create() { std::ifstream file; file.exceptions(std::ofstream::failbit | std::ofstream::badbit); - file.open(absPath(_fileName)); + file.open(_fileName); constexpr double Exposure = 0.01; diff --git a/modules/spacecraftinstruments/util/imagesequencer.cpp b/modules/spacecraftinstruments/util/imagesequencer.cpp index 647d381a0a..7e2e6b26bc 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.cpp +++ b/modules/spacecraftinstruments/util/imagesequencer.cpp @@ -246,7 +246,7 @@ std::vector ImageSequencer::imagePaths(const std::string& projectee, std::copy_if( prev, curr, - back_inserter(captures), + std::back_inserter(captures), [instrument](const Image& i) { return i.activeInstruments[0] == instrument; } ); diff --git a/modules/spacecraftinstruments/util/instrumentdecoder.cpp b/modules/spacecraftinstruments/util/instrumentdecoder.cpp index eda8341fac..ac55244644 100644 --- a/modules/spacecraftinstruments/util/instrumentdecoder.cpp +++ b/modules/spacecraftinstruments/util/instrumentdecoder.cpp @@ -63,7 +63,7 @@ const std::string& InstrumentDecoder::stopCommand() { return _stopCommand; } -const std::string& InstrumentDecoder::decoderType() const { +std::string_view InstrumentDecoder::decoderType() const { return _type; } diff --git a/modules/spacecraftinstruments/util/instrumentdecoder.h b/modules/spacecraftinstruments/util/instrumentdecoder.h index 916a460c27..8106fcc5fd 100644 --- a/modules/spacecraftinstruments/util/instrumentdecoder.h +++ b/modules/spacecraftinstruments/util/instrumentdecoder.h @@ -33,7 +33,7 @@ class InstrumentDecoder : public Decoder { public: explicit InstrumentDecoder(const ghoul::Dictionary& dictionary); - virtual const std::string& decoderType() const override; + virtual std::string_view decoderType() const override; virtual const std::vector& translations() const override; const std::string& stopCommand(); diff --git a/modules/spacecraftinstruments/util/labelparser.cpp b/modules/spacecraftinstruments/util/labelparser.cpp index 9301a5fb15..cc049d4177 100644 --- a/modules/spacecraftinstruments/util/labelparser.cpp +++ b/modules/spacecraftinstruments/util/labelparser.cpp @@ -37,8 +37,8 @@ namespace { constexpr std::string_view _loggerCat = "LabelParser"; - constexpr std::string_view keySpecs = "Read"; - constexpr std::string_view keyConvert = "Convert"; + constexpr std::string_view KeySpecs = "Read"; + constexpr std::string_view KeyConvert = "Convert"; } // namespace namespace openspace { @@ -77,13 +77,13 @@ LabelParser::LabelParser(std::filesystem::path fileName, } } if (decoderStr == "Target") { - if (!typeDict.hasValue(keySpecs) || - !typeDict.hasValue(keySpecs)) + if (!typeDict.hasValue(KeySpecs) || + !typeDict.hasValue(KeySpecs)) { continue; } - const Dictionary specsOfInterestDict = typeDict.value(keySpecs); + const Dictionary specsOfInterestDict = typeDict.value(KeySpecs); _specsOfInterest.resize(specsOfInterestDict.size()); for (size_t n = 0; n < _specsOfInterest.size(); ++n) { @@ -93,7 +93,7 @@ LabelParser::LabelParser(std::filesystem::path fileName, _specsOfInterest[n] = std::move(readMe); } } - const Dictionary convertDict = typeDict.value(keyConvert); + const Dictionary convertDict = typeDict.value(KeyConvert); for (const std::string_view key : convertDict.keys()) { if (!convertDict.hasValue(key)) { diff --git a/modules/spacecraftinstruments/util/projectioncomponent.cpp b/modules/spacecraftinstruments/util/projectioncomponent.cpp index b9840d14f8..a429957f1c 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.cpp +++ b/modules/spacecraftinstruments/util/projectioncomponent.cpp @@ -42,7 +42,7 @@ #include namespace { - constexpr std::string_view placeholderFile = "${DATA}/placeholder.png"; + constexpr std::string_view PlaceholderFile = "${DATA}/placeholder.png"; constexpr std::string_view _loggerCat = "ProjectionComponent"; @@ -355,7 +355,7 @@ bool ProjectionComponent::initializeGL() { using ghoul::opengl::Texture; std::unique_ptr texture = ghoul::io::TextureReader::ref().loadTexture( - absPath(placeholderFile), + absPath(PlaceholderFile), 2 ); if (texture) { @@ -418,7 +418,7 @@ void ProjectionComponent::imageProjectBegin() { // keep handle to the current bound FBO glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); - if (_textureSizeDirty) { + if (_textureSizeDirty) [[unlikely]] { glm::ivec2 size = _textureSize; LDEBUG(std::format("Changing texture size to ({}, {})", size.x, size.y)); @@ -802,12 +802,7 @@ float ProjectionComponent::projectionFading() const { } ghoul::opengl::Texture& ProjectionComponent::projectionTexture() const { - if (_dilation.isEnabled) { - return *_dilation.texture; - } - else { - return *_projectionTexture; - } + return _dilation.isEnabled ? *_dilation.texture : *_projectionTexture; } std::string ProjectionComponent::projectorId() const { @@ -873,7 +868,7 @@ void ProjectionComponent::generateMipMap() { std::shared_ptr ProjectionComponent::loadProjectionTexture( const std::filesystem::path& texturePath, - bool isPlaceholder) + bool isPlaceholder) { using ghoul::opengl::Texture; diff --git a/modules/spacecraftinstruments/util/scannerdecoder.cpp b/modules/spacecraftinstruments/util/scannerdecoder.cpp index d08cf21ba9..83ed3e9e41 100644 --- a/modules/spacecraftinstruments/util/scannerdecoder.cpp +++ b/modules/spacecraftinstruments/util/scannerdecoder.cpp @@ -26,10 +26,6 @@ #include -namespace { - std::string Type = "SCANNER"; -} // namespace - namespace openspace { ScannerDecoder::ScannerDecoder(const ghoul::Dictionary& dictionary) { @@ -37,8 +33,9 @@ ScannerDecoder::ScannerDecoder(const ghoul::Dictionary& dictionary) { _spiceIDs.push_back(dictionary.value(std::to_string(k + 1))); } } -const std::string& ScannerDecoder::decoderType() const { - return Type; + +std::string_view ScannerDecoder::decoderType() const { + return "SCANNER"; } const std::vector& ScannerDecoder::spiceIDs() const { diff --git a/modules/spacecraftinstruments/util/scannerdecoder.h b/modules/spacecraftinstruments/util/scannerdecoder.h index 8fece01635..65564c1321 100644 --- a/modules/spacecraftinstruments/util/scannerdecoder.h +++ b/modules/spacecraftinstruments/util/scannerdecoder.h @@ -35,7 +35,7 @@ class ScannerDecoder : public Decoder { public: explicit ScannerDecoder(const ghoul::Dictionary& dictionary); - virtual const std::string& decoderType() const override; + virtual std::string_view decoderType() const override; const std::vector& spiceIDs() const; void setStopCommand(std::string stopCommand); diff --git a/modules/spacecraftinstruments/util/targetdecoder.cpp b/modules/spacecraftinstruments/util/targetdecoder.cpp index eb819af446..c11c34e8e6 100644 --- a/modules/spacecraftinstruments/util/targetdecoder.cpp +++ b/modules/spacecraftinstruments/util/targetdecoder.cpp @@ -26,10 +26,6 @@ #include -namespace { - std::string Type = "TARGET"; -} // namespace - namespace openspace { TargetDecoder::TargetDecoder(const ghoul::Dictionary& dictionary) { @@ -42,8 +38,8 @@ TargetDecoder::TargetDecoder(const ghoul::Dictionary& dictionary) { } } -const std::string& TargetDecoder::decoderType() const { - return Type; +std::string_view TargetDecoder::decoderType() const { + return "TARGET"; } const std::vector& TargetDecoder::translations() const { diff --git a/modules/spacecraftinstruments/util/targetdecoder.h b/modules/spacecraftinstruments/util/targetdecoder.h index 4d770f3e2e..c27e3d1aa6 100644 --- a/modules/spacecraftinstruments/util/targetdecoder.h +++ b/modules/spacecraftinstruments/util/targetdecoder.h @@ -33,7 +33,7 @@ class TargetDecoder : public Decoder { public: explicit TargetDecoder(const ghoul::Dictionary& dictionary); - virtual const std::string& decoderType() const override; + virtual std::string_view decoderType() const override; virtual const std::vector& translations() const override; private: diff --git a/modules/spout/renderablespherespout.cpp b/modules/spout/renderablespherespout.cpp index 4ff41950c7..d60e6be45d 100644 --- a/modules/spout/renderablespherespout.cpp +++ b/modules/spout/renderablespherespout.cpp @@ -34,7 +34,6 @@ // The RenderableSphereSpout can be used to render a sphere with a texture that is // provided by another application on the same computer using the SPOUT library. Note that // this library is only available on Windows. - namespace { struct [[codegen::Dictionary(RenderableSphereSpout)]] Parameters { // Specifies the GUI name of the RenderableSphereSpout diff --git a/modules/spout/spoutwrapper.cpp b/modules/spout/spoutwrapper.cpp index 273e673edf..0d4501f1ef 100644 --- a/modules/spout/spoutwrapper.cpp +++ b/modules/spout/spoutwrapper.cpp @@ -74,7 +74,6 @@ namespace { // [[codegen::verbatim(NameSenderInfo.description)]] std::string spoutName; }; - #include "spoutwrapper_codegen.cpp" } // namespace diff --git a/modules/statemachine/src/transition.cpp b/modules/statemachine/src/transition.cpp index def576efcb..9ab9eaad52 100644 --- a/modules/statemachine/src/transition.cpp +++ b/modules/statemachine/src/transition.cpp @@ -54,7 +54,7 @@ Transition::Transition(const ghoul::Dictionary& dictionary) { const Parameters p = codegen::bake(dictionary); _from = p.from; _to = p.to; - _action = p.action.value_or(""); + _action = p.action.value_or(_action); } const std::string& Transition::from() const { @@ -66,9 +66,6 @@ const std::string& Transition::to() const { } void Transition::performAction() const { - if (_action.empty()) { - return; - } global::scriptEngine->queueScript(_action); } diff --git a/modules/sync/syncs/httpsynchronization.cpp b/modules/sync/syncs/httpsynchronization.cpp index bf0a6ffbfc..9b866fa25f 100644 --- a/modules/sync/syncs/httpsynchronization.cpp +++ b/modules/sync/syncs/httpsynchronization.cpp @@ -165,7 +165,7 @@ void HttpSynchronization::createSyncFile(bool isFullySynchronized) const { std::filesystem::create_directories(dir); dir.replace_extension("ossync"); - std::ofstream syncFile(dir, std::ofstream::out); + std::ofstream syncFile = std::ofstream(dir, std::ofstream::out); syncFile << std::format( "{}\n{}\n", @@ -193,7 +193,7 @@ bool HttpSynchronization::isEachFileDownloaded() { } // Read contents of file - std::ifstream file(path); + std::ifstream file = std::ifstream(path); std::string line; file >> line; diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index 9583f39dc3..096c0aa2b7 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -119,10 +119,9 @@ UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dictionary, // Disregard override variable if user specified a specific time to live. _secondsUntilResync = p.secondsUntilResync.value_or(_secondsUntilResync); - const bool useHash = p.useHash.value_or(true); - _identifier = p.identifier; + const bool useHash = p.useHash.value_or(true); if (useHash) { // We just merge all of the URLs together to generate a hash that works for this std::vector urls = _urls; @@ -271,7 +270,7 @@ void UrlSynchronization::createSyncFile(bool) const { std::filesystem::create_directories(dir); dir.replace_extension("ossync"); - std::ofstream syncFile(dir, std::ofstream::out); + std::ofstream syncFile = std::ofstream(dir, std::ofstream::out); const std::string currentTimeAsISO8601 = Time::currentWallTime(); const double currentTimeAsJ2000 = Time::convertTime(currentTimeAsISO8601); diff --git a/modules/touch/src/directinputsolver.cpp b/modules/touch/src/directinputsolver.cpp index fd4d0fc2f2..d7e9d1755e 100644 --- a/modules/touch/src/directinputsolver.cpp +++ b/modules/touch/src/directinputsolver.cpp @@ -37,6 +37,172 @@ namespace { openspace::SceneGraphNode* node; LMstat stats; }; + + // project back a 3D point in model view to clip space [-1,1] coordinates on the view + // plane + glm::dvec2 castToNDC(const glm::dvec3& vec, openspace::Camera& camera, + openspace::SceneGraphNode* node) + { + glm::dvec3 posInCamSpace = glm::inverse(camera.rotationQuaternion()) * + (node->worldRotationMatrix() * vec + + (node->worldPosition() - camera.positionVec3())); + + glm::dvec4 clipspace = camera.projectionMatrix() * glm::dvec4(posInCamSpace, 1.0); + return (glm::dvec2(clipspace) / clipspace.w); + } + + // Returns screen point s(xi,par) dependent the transform M(par) and object point xi + double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { + FunctionData* ptr = reinterpret_cast(fdata); + + // Apply transform to camera and find the screen point of the updated camera state + + // { vec2 globalRot, zoom, roll, vec2 localRot } + double q[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; + for (int i = 0; i < ptr->nDOF; i++) { + q[i] = par[i]; + } + + using namespace glm; + // Create variables from current state + dvec3 camPos = ptr->camera->positionVec3(); + dvec3 centerPos = ptr->node->worldPosition(); + + dvec3 directionToCenter = normalize(centerPos - camPos); + dvec3 lookUp = ptr->camera->lookUpVectorWorldSpace(); + dvec3 camDirection = ptr->camera->viewDirectionWorldSpace(); + + // Make a representation of the rotation quaternion with local and global + // rotations + dmat4 lookAtMat = lookAt( + dvec3(0, 0, 0), + directionToCenter, + // To avoid problem with lookup in up direction + normalize(camDirection + lookUp) + ); + dquat globalCamRot = normalize(quat_cast(inverse(lookAtMat))); + dquat localCamRot = inverse(globalCamRot) * ptr->camera->rotationQuaternion(); + + { + // Roll + dquat rollRot = angleAxis(q[3], dvec3(0.0, 0.0, 1.0)); + localCamRot = localCamRot * rollRot; + } + { + // Panning (local rotation) + dvec3 eulerAngles(q[5], q[4], 0); + dquat panRot = dquat(eulerAngles); + localCamRot = localCamRot * panRot; + } + { + // Orbit (global rotation) + dvec3 eulerAngles(q[1], q[0], 0); + dquat rotationDiffCamSpace = dquat(eulerAngles); + + dvec3 centerToCamera = camPos - centerPos; + + dquat rotationDiffWorldSpace = + globalCamRot * rotationDiffCamSpace * inverse(globalCamRot); + dvec3 rotationDiffVec3 = + centerToCamera * rotationDiffWorldSpace - centerToCamera; + camPos += rotationDiffVec3; + + centerToCamera = camPos - centerPos; + directionToCenter = normalize(-centerToCamera); + dvec3 lookUpWhenFacingCenter = + globalCamRot * dvec3(ptr->camera->lookUpVectorCameraSpace()); + lookAtMat = lookAt( + dvec3(0, 0, 0), + directionToCenter, + lookUpWhenFacingCenter + ); + globalCamRot = normalize(quat_cast(inverse(lookAtMat))); + } + { // Zooming + camPos += directionToCenter * q[2]; + } + // Update the camera state + openspace::Camera cam = *(ptr->camera); + cam.setPositionVec3(camPos); + cam.setRotation(globalCamRot * localCamRot); + + // we now have a new position and orientation of camera, project surfacePoint to + // the new screen to get distance to minimize + glm::dvec2 newScreenPoint = castToNDC( + ptr->selectedPoints.at(x), + cam, + ptr->node + ); + lmstat->pos.push_back(newScreenPoint); + return glm::length(ptr->screenPoints.at(x) - newScreenPoint); + } + + // Gradient of distToMinimize w.r.t par (using forward difference) + void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { + FunctionData* ptr = reinterpret_cast(fdata); + double f0 = distToMinimize(par, x, fdata, lmstat); + // scale value to find minimum step size h, dependant on planet size + double scale = log10(ptr->node->interactionSphere()); + std::vector dPar(ptr->nDOF, 0.0); + dPar.assign(par, par + ptr->nDOF); + + for (int i = 0; i < ptr->nDOF; i++) { + // Initial values + double h = 1e-8; + double lastG = 1; + dPar.at(i) += h; + double f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar.at(i) = par[i]; + // Iterative process to find the minimum step h that gives a good gradient + for (int j = 0; j < 100; j++) { + if ((f1 - f0) != 0 && lastG == 0) { // found minimum step size h + // scale up to get a good initial guess value + h *= scale * scale * scale; + + // clamp min step size to a fraction of the incoming parameter + if (i == 2) { + double epsilon = 1e-3; + // make sure incoming parameter is larger than 0 + h = std::max(std::max(std::abs(dPar.at(i)), epsilon) * 0.001, h); + } + else if (ptr->nDOF == 2) { + h = std::max(std::abs(dPar.at(i)) * 0.001, h); + } + + // calculate f1 with good h for finite difference + dPar[i] += h; + f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar[i] = par[i]; + break; + } + else if ((f1 - f0) != 0 && lastG != 0) { + // h too big + h /= scale; + } + else if ((f1 - f0) == 0) { + // h too small + h *= scale; + } + lastG = f1 - f0; + dPar.at(i) += h; + f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar.at(i) = par[i]; + } + g[i] = (f1 - f0) / h; + } + if (ptr->nDOF == 2) { + // normalize on 1 finger case to allow for horizontal/vertical movement + for (int i = 0; i < 2; i++) { + g[i] = g[i] / std::abs(g[i]); + } + } + else if (ptr->nDOF == 6) { + for (int i = 0; i < ptr->nDOF; i++) { + // lock to only pan and zoom on 3 finger case, no roll/orbit + g[i] = (i == 2) ? g[i] : g[i] / std::abs(g[i]); + } + } + } } // namespace namespace openspace { @@ -45,169 +211,6 @@ DirectInputSolver::DirectInputSolver() { levmarq_init(&_lmstat); } -// project back a 3D point in model view to clip space [-1,1] coordinates on the view -// plane -glm::dvec2 castToNDC(const glm::dvec3& vec, Camera& camera, SceneGraphNode* node) { - glm::dvec3 posInCamSpace = glm::inverse(camera.rotationQuaternion()) * - (node->worldRotationMatrix() * vec + - (node->worldPosition() - camera.positionVec3())); - - glm::dvec4 clipspace = camera.projectionMatrix() * glm::dvec4(posInCamSpace, 1.0); - return (glm::dvec2(clipspace) / clipspace.w); -} - -// Returns the screen point s(xi,par) dependent the transform M(par) and object point xi -double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { - FunctionData* ptr = reinterpret_cast(fdata); - - // Apply transform to camera and find the new screen point of the updated camera state - - // { vec2 globalRot, zoom, roll, vec2 localRot } - double q[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; - for (int i = 0; i < ptr->nDOF; i++) { - q[i] = par[i]; - } - - using namespace glm; - // Create variables from current state - dvec3 camPos = ptr->camera->positionVec3(); - dvec3 centerPos = ptr->node->worldPosition(); - - dvec3 directionToCenter = normalize(centerPos - camPos); - dvec3 lookUp = ptr->camera->lookUpVectorWorldSpace(); - dvec3 camDirection = ptr->camera->viewDirectionWorldSpace(); - - // Make a representation of the rotation quaternion with local and global - // rotations - dmat4 lookAtMat = lookAt( - dvec3(0, 0, 0), - directionToCenter, - // To avoid problem with lookup in up direction - normalize(camDirection + lookUp) - ); - dquat globalCamRot = normalize(quat_cast(inverse(lookAtMat))); - dquat localCamRot = inverse(globalCamRot) * ptr->camera->rotationQuaternion(); - - { - // Roll - dquat rollRot = angleAxis(q[3], dvec3(0.0, 0.0, 1.0)); - localCamRot = localCamRot * rollRot; - } - { - // Panning (local rotation) - dvec3 eulerAngles(q[5], q[4], 0); - dquat panRot = dquat(eulerAngles); - localCamRot = localCamRot * panRot; - } - { - // Orbit (global rotation) - dvec3 eulerAngles(q[1], q[0], 0); - dquat rotationDiffCamSpace = dquat(eulerAngles); - - dvec3 centerToCamera = camPos - centerPos; - - dquat rotationDiffWorldSpace = - globalCamRot * rotationDiffCamSpace * inverse(globalCamRot); - dvec3 rotationDiffVec3 = centerToCamera * rotationDiffWorldSpace - centerToCamera; - camPos += rotationDiffVec3; - - centerToCamera = camPos - centerPos; - directionToCenter = normalize(-centerToCamera); - dvec3 lookUpWhenFacingCenter = - globalCamRot * dvec3(ptr->camera->lookUpVectorCameraSpace()); - lookAtMat = lookAt( - dvec3(0, 0, 0), - directionToCenter, - lookUpWhenFacingCenter - ); - globalCamRot = normalize(quat_cast(inverse(lookAtMat))); - } - { // Zooming - camPos += directionToCenter * q[2]; - } - // Update the camera state - Camera cam = *(ptr->camera); - cam.setPositionVec3(camPos); - cam.setRotation(globalCamRot * localCamRot); - - // we now have a new position and orientation of camera, project surfacePoint to - // the new screen to get distance to minimize - glm::dvec2 newScreenPoint = castToNDC( - ptr->selectedPoints.at(x), - cam, - ptr->node - ); - lmstat->pos.push_back(newScreenPoint); - return glm::length(ptr->screenPoints.at(x) - newScreenPoint); -} - -// Gradient of distToMinimize w.r.t par (using forward difference) -void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { - FunctionData* ptr = reinterpret_cast(fdata); - double f0 = distToMinimize(par, x, fdata, lmstat); - // scale value to find minimum step size h, dependant on planet size - double scale = log10(ptr->node->interactionSphere()); - std::vector dPar(ptr->nDOF, 0.0); - dPar.assign(par, par + ptr->nDOF); - - for (int i = 0; i < ptr->nDOF; i++) { - // Initial values - double h = 1e-8; - double lastG = 1; - dPar.at(i) += h; - double f1 = distToMinimize(dPar.data(), x, fdata, lmstat); - dPar.at(i) = par[i]; - // Iterative process to find the minimum step h that gives a good gradient - for (int j = 0; j < 100; j++) { - if ((f1 - f0) != 0 && lastG == 0) { // found minimum step size h - // scale up to get a good initial guess value - h *= scale * scale * scale; - - // clamp min step size to a fraction of the incoming parameter - if (i == 2) { - double epsilon = 1e-3; - // make sure incoming parameter is larger than 0 - h = std::max(std::max(std::abs(dPar.at(i)), epsilon) * 0.001, h); - } - else if (ptr->nDOF == 2) { - h = std::max(std::abs(dPar.at(i)) * 0.001, h); - } - - // calculate f1 with good h for finite difference - dPar[i] += h; - f1 = distToMinimize(dPar.data(), x, fdata, lmstat); - dPar[i] = par[i]; - break; - } - else if ((f1 - f0) != 0 && lastG != 0) { - // h too big - h /= scale; - } - else if ((f1 - f0) == 0) { - // h too small - h *= scale; - } - lastG = f1 - f0; - dPar.at(i) += h; - f1 = distToMinimize(dPar.data(), x, fdata, lmstat); - dPar.at(i) = par[i]; - } - g[i] = (f1 - f0) / h; - } - if (ptr->nDOF == 2) { - // normalize on 1 finger case to allow for horizontal/vertical movement - for (int i = 0; i < 2; i++) { - g[i] = g[i] / std::abs(g[i]); - } - } - else if (ptr->nDOF == 6) { - for (int i = 0; i < ptr->nDOF; i++) { - // lock to only pan and zoom on 3 finger case, no roll/orbit - g[i] = (i == 2) ? g[i] : g[i] / std::abs(g[i]); - } - } -} - bool DirectInputSolver::solve(const std::vector& list, const std::vector& selectedBodies, std::vector* parameters, const Camera& camera) diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 33cb76b74c..802b9e53d2 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -360,7 +360,7 @@ TouchInteraction::TouchInteraction() #ifdef TOUCH_DEBUG_PROPERTIES addPropertySubOwner(_debugProperties); -#endif +#endif // TOUCH_DEBUG_PROPERTIES _zoomInBoundarySphereMultiplier.setExponent(20.f); _zoomOutBoundarySphereMultiplier.setExponent(20.f); @@ -380,7 +380,7 @@ void TouchInteraction::updateStateFromInput(const std::vector& #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.nFingers = numFingers; -#endif +#endif // TOUCH_DEBUG_PROPERTIES if (numFingers == 0) { // No fingers, no input (note that this function should not even be called then) @@ -392,9 +392,8 @@ void TouchInteraction::updateStateFromInput(const std::vector& // Why? // Check for doubletap - using namespace std::chrono; - milliseconds timestamp = duration_cast( - high_resolution_clock::now().time_since_epoch() + std::chrono::milliseconds timestamp = duration_cast( + std::chrono::high_resolution_clock::now().time_since_epoch() ); if ((timestamp - _time).count() < _maxTapTime) { _doubleTap = true; @@ -440,13 +439,13 @@ void TouchInteraction::updateStateFromInput(const std::vector& if (_directTouchMode) { #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.interactionMode = "Direct"; -#endif +#endif // TOUCH_DEBUG_PROPERTIES directControl(list); } else { #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.interactionMode = "Velocities"; -#endif +#endif // TOUCH_DEBUG_PROPERTIES computeVelocities(list, lastProcessed); } @@ -463,7 +462,7 @@ void TouchInteraction::directControl(const std::vector& list) #ifdef TOUCH_DEBUG_PROPERTIES LINFO("DirectControl"); -#endif +#endif // TOUCH_DEBUG_PROPERTIES // Find best transform values for the new camera state and store them in par std::vector par(6, 0.0); @@ -479,17 +478,17 @@ void TouchInteraction::directControl(const std::vector& list) if (lmSuccess && !_unitTest) { // If good values were found set new camera state - _vel.orbit = glm::dvec2(par.at(0), par.at(1)); + _vel.orbit = glm::dvec2(par[0], par[1]); if (nDof > 2) { if (!_disableZoom) { - _vel.zoom = par.at(2); + _vel.zoom = par[2]; } if (!_disableRoll) { - _vel.roll = par.at(3); + _vel.roll = par[3]; } if (_panEnabled && nDof > 4) { _vel.roll = 0.0; - _vel.pan = glm::dvec2(par.at(4), par.at(5)); + _vel.pan = glm::dvec2(par[4], par[5]); } } step(1.0, true); @@ -529,14 +528,13 @@ void TouchInteraction::updateNodeSurfacePoints(const std::vectorprojectionMatrix()) * glm::dvec4(xCo, yCo, -1.0, 1.0)); - glm::dvec3 raytrace = glm::normalize(cursorInWorldSpace); - - size_t id = inputHolder.fingerId(); + const glm::dvec3 raytrace = glm::normalize(cursorInWorldSpace); + const size_t id = inputHolder.fingerId(); // Compute positions on anchor node, by checking if touch input // intersect interaction sphere @@ -565,7 +563,7 @@ void TouchInteraction::updateNodeSurfacePoints(const std::vector& list, - const std::vector& lastProcessed) + const std::vector& lastProcessed) { ghoul_assert(!list.empty(), "Cannot interpret interaction of no input"); @@ -641,11 +639,11 @@ TouchInteraction::interpretInteraction(const std::vector& list float currentAngle = inputHolder.latestInput().angleToPos(_centroid.x, _centroid.y); - if (lastAngle > currentAngle + 1.5 * glm::pi()) { - res = currentAngle + (2.0 * glm::pi() - lastAngle); + if (lastAngle > currentAngle + 1.5f * glm::pi()) { + res = currentAngle + (2.f * glm::pi() - lastAngle); } - else if (currentAngle > lastAngle + 1.5 * glm::pi()) { - res = (2.0 * glm::pi() - currentAngle) + lastAngle; + else if (currentAngle > lastAngle + 1.5f * glm::pi()) { + res = (2.f * glm::pi() - currentAngle) + lastAngle; } else { res = currentAngle - lastAngle; @@ -669,7 +667,7 @@ TouchInteraction::interpretInteraction(const std::vector& list _debugProperties.normalizedCentroidDistance = normalizedCentroidDistance; _debugProperties.rollOn = rollOn; _debugProperties.minDiff = minDiff; -#endif +#endif // TOUCH_DEBUG_PROPERTIES if (_zoomOutTap) { return InteractionType::ZOOM_OUT; @@ -739,7 +737,7 @@ void TouchInteraction::computeVelocities(const std::vector& li pinchConsecCt = 0; pinchConsecZoomFactor = 0.0; } -#endif +#endif // TOUCH_DEBUG_PROPERTIES const TouchInputHolder& inputHolder = list.at(0); const glm::ivec2 windowSize = global::windowDelegate->currentWindowSize(); @@ -781,7 +779,7 @@ void TouchInteraction::computeVelocities(const std::vector& li #ifdef TOUCH_DEBUG_PROPERTIES pinchConsecCt++; pinchConsecZoomFactor += zoomFactor; -#endif +#endif // TOUCH_DEBUG_PROPERTIES _constTimeDecayCoeff.zoom = 1.0; _vel.zoom = zoomFactor * _pinchZoomFactor * _zoomSensitivityProportionalDist * @@ -882,10 +880,7 @@ double TouchInteraction::computeTapZoomDistance(double zoomGain) { } bool TouchInteraction::hasNonZeroVelocities() const { - glm::dvec2 sum = _vel.orbit; - sum += glm::dvec2(_vel.zoom, 0.0); - sum += glm::dvec2(_vel.roll, 0.0); - sum += _vel.pan; + glm::dvec2 sum = _vel.orbit + glm::dvec2(_vel.zoom + _vel.roll, 0.0) + _vel.pan; // Epsilon size based on that even if no interaction is happening, // there might still be some residual velocity in the return glm::length(sum) > 0.001; @@ -999,7 +994,7 @@ void TouchInteraction::step(double dt, bool directTouch) { "Zoom In limit should be larger than anchor " "center to surface, setting it to {}", zoomInBounds )); -#endif +#endif // TOUCH_DEBUG_PROPERTIES zoomInBounds = _zoomInLimit.value(); } } @@ -1063,7 +1058,7 @@ void TouchInteraction::step(double dt, bool directTouch) { "You are outside zoom out {} limit, only zoom in allowed", zoomOutBounds )); -#endif +#endif // TOUCH_DEBUG_PROPERTIES // Only allow zooming in if you are outside the zoom out limit if (newPosDistance < currentPosDistance) { camPos += zoomDistanceInc; @@ -1072,7 +1067,7 @@ void TouchInteraction::step(double dt, bool directTouch) { else { #ifdef TOUCH_DEBUG_PROPERTIES LINFO("Zero the zoom velocity close to surface"); -#endif +#endif // TOUCH_DEBUG_PROPERTIES _vel.zoom = 0.0; } } @@ -1107,7 +1102,7 @@ void TouchInteraction::step(double dt, bool directTouch) { length(centerToCamera), _vel.zoom )); } -#endif +#endif // TOUCH_DEBUG_PROPERTIES _tap = false; _doubleTap = false; @@ -1135,9 +1130,9 @@ void TouchInteraction::decelerate(double dt) { times = std::min(times, 1); _vel.orbit *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.orbit, times); - _vel.roll *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.roll, times); - _vel.pan *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.pan, times); - _vel.zoom *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.zoom, times); + _vel.roll *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.roll, times); + _vel.pan *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.pan, times); + _vel.zoom *= computeDecayCoeffFromFrametime(_constTimeDecayCoeff.zoom, times); } // Called if all fingers are off the screen @@ -1145,7 +1140,7 @@ void TouchInteraction::resetAfterInput() { #ifdef TOUCH_DEBUG_PROPERTIES _debugProperties.nFingers = 0; _debugProperties.interactionMode = "None"; -#endif +#endif // TOUCH_DEBUG_PROPERTIES // @TODO (emmbr 2023-02-03) Bring back feature that allows node to spin when // the direct manipulaiton finger is let go. Should implement this using the // orbitalnavigator's friction values. This also implies passing velocities to @@ -1254,6 +1249,6 @@ TouchInteraction::DebugProperties::DebugProperties() addProperty(minDiff); addProperty(rollOn); } -#endif +#endif // TOUCH_DEBUG_PROPERTIES } // openspace namespace diff --git a/modules/touch/src/touchmarker.cpp b/modules/touch/src/touchmarker.cpp index 9afc508aa3..f9117fa801 100644 --- a/modules/touch/src/touchmarker.cpp +++ b/modules/touch/src/touchmarker.cpp @@ -139,8 +139,8 @@ void TouchMarker::createVertexList(const std::vector(tcur->getTuioSourceID()), static_cast(tcur->getCursorID()), tcur->getX(), tcur->getY(), static_cast(tcur->getTuioTime().getTotalMilliseconds()) / 1000.0 ); - _inputList.emplace_back(input); - _mx.unlock(); } void TuioEar::updateTuioCursor(TuioCursor* tcur) { - _mx.lock(); - TouchInput input( + std::unique_lock lock(_mx); + _inputList.emplace_back( static_cast(tcur->getTuioSourceID()), static_cast(tcur->getCursorID()), tcur->getX(), tcur->getY(), static_cast(tcur->getTuioTime().getTotalMilliseconds()) / 1000.0 ); - _inputList.emplace_back(input); - _mx.unlock(); } // save id to be removed and remove it in clearInput void TuioEar::removeTuioCursor(TuioCursor* tcur) { - _mx.lock(); - TouchInput input( + std::unique_lock lock(_mx); + _removalList.emplace_back( static_cast(tcur->getTuioSourceID()), static_cast(tcur->getCursorID()), tcur->getX(), tcur->getY(), static_cast(tcur->getTuioTime().getTotalMilliseconds()) / 1000.0 ); - _removalList.emplace_back(input); - _mx.unlock(); } -void TuioEar::addTuioBlob(TuioBlob*) { } +void TuioEar::addTuioBlob(TuioBlob*) {} -void TuioEar::updateTuioBlob(TuioBlob*) { } +void TuioEar::updateTuioBlob(TuioBlob*) {} -void TuioEar::removeTuioBlob(TuioBlob*) { } +void TuioEar::removeTuioBlob(TuioBlob*) {} -void TuioEar::refresh(TuioTime) { } // about every 15ms +void TuioEar::refresh(TuioTime) {} // about every 15ms std::vector TuioEar::takeInput() { std::vector outputList; diff --git a/modules/touch/src/win32_touch.cpp b/modules/touch/src/win32_touch.cpp index cd97a14861..74da61931f 100644 --- a/modules/touch/src/win32_touch.cpp +++ b/modules/touch/src/win32_touch.cpp @@ -55,14 +55,13 @@ namespace { #ifdef ENABLE_TUIOMESSAGES TUIO::TuioServer* gTuioServer = nullptr; std::unordered_map gCursorMap; -#endif +#endif // ENABLE_TUIOMESSAGES const long long gFrequency = []() -> long long { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); return frequency.QuadPart; }(); - } // namespace namespace openspace { @@ -122,13 +121,13 @@ LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) { auto points = std::make_unique(touchInput); gTouchInputsMap.emplace(info.pointerId, std::move(points)); global::openSpaceEngine->touchDetectionCallback(touchInput); -#endif +#endif // ENABLE_DIRECTMSG #ifdef ENABLE_TUIOMESSAGES // Handle new touchpoint gTuioServer->initFrame(TUIO::TuioTime::getSessionTime()); gCursorMap[info.pointerId] = gTuioServer->addTuioCursor(xPos, yPos); gTuioServer->commitFrame(); -#endif +#endif // ENABLE_TUIOMESSAGES } else if (info.pointerFlags & POINTER_FLAG_UPDATE) { // Handle update of touchpoint @@ -138,7 +137,7 @@ LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) { if (points->tryAddInput(touchInput)) { global::openSpaceEngine->touchUpdateCallback(points->latestInput()); } -#endif +#endif // ENABLE_DIRECTMSG #ifdef ENABLE_TUIOMESSAGES TUIO::TuioTime frameTime = TUIO::TuioTime::getSessionTime(); if (gCursorMap[info.pointerId]->getTuioTime() == frameTime) { @@ -147,20 +146,20 @@ LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) { gTuioServer->initFrame(frameTime); gTuioServer->updateTuioCursor(gCursorMap[info.pointerId], xPos, yPos); gTuioServer->commitFrame(); -#endif +#endif // ENABLE_TUIOMESSAGES } else if (info.pointerFlags & POINTER_FLAG_UP) { #ifdef ENABLE_DIRECTMSG gTouchInputsMap.erase(info.pointerId); global::openSpaceEngine->touchExitCallback(touchInput); -#endif +#endif // ENABLE_DIRECTMSG #ifdef ENABLE_TUIOMESSAGES // Handle removed touchpoint gTuioServer->initFrame(TUIO::TuioTime::getSessionTime()); gTuioServer->removeTuioCursor(gCursorMap[info.pointerId]); gTuioServer->commitFrame(); gCursorMap.erase(info.pointerId); -#endif +#endif // ENABLE_TUIOMESSAGES } break; } @@ -219,7 +218,7 @@ Win32TouchHook::Win32TouchHook(void* nativeWindow) { #ifdef ENABLE_TUIOMESSAGES gTuioServer = new TUIO::TuioServer("localhost", 3333); TUIO::TuioTime::initSession(); -#endif +#endif // ENABLE_TUIOMESSAGES gTouchHook = SetWindowsHookExW( WH_GETMESSAGE, HookCallback, @@ -257,7 +256,7 @@ Win32TouchHook::Win32TouchHook(void* nativeWindow) { LINFO(std::format("Failed to setup WindowsHook for touch input redirection")); #ifdef ENABLE_TUIOMESSAGES delete gTuioServer; -#endif +#endif // ENABLE_TUIOMESSAGES gStarted = false; } } @@ -270,7 +269,7 @@ Win32TouchHook::~Win32TouchHook() { UnhookWindowsHookEx(gMouseHook); #ifdef ENABLE_TUIOMESSAGES delete gTuioServer; -#endif +#endif // ENABLE_TUIOMESSAGES } } diff --git a/modules/touch/touchmodule.cpp b/modules/touch/touchmodule.cpp index 0be504f2b0..84cf1eda70 100644 --- a/modules/touch/touchmodule.cpp +++ b/modules/touch/touchmodule.cpp @@ -67,7 +67,7 @@ namespace { "relatively spherical objects.", openspace::properties::Property::Visibility::AdvancedUser }; -} // namespace openspace +} // namespace namespace openspace { @@ -130,7 +130,7 @@ void TouchModule::internalInitialize(const ghoul::Dictionary&) { if (nativeWindowHandle) { _win32TouchHook = std::make_unique(nativeWindowHandle); } -#endif +#endif // WIN32 }); global::callback::deinitializeGL->push_back([this]() { @@ -142,14 +142,14 @@ void TouchModule::internalInitialize(const ghoul::Dictionary&) { // thread so we don't need a mutex here global::callback::touchDetected->push_back( [this](TouchInput i) { - addTouchInput(i); + addTouchInput(std::move(i)); return true; } ); global::callback::touchUpdated->push_back( [this](TouchInput i) { - updateOrAddTouchInput(i); + updateOrAddTouchInput(std::move(i)); return true; } ); @@ -245,9 +245,7 @@ bool TouchModule::processNewInput() { } // Return true if we got new input - if (_touchPoints.size() == _lastTouchInputs.size() && - !_touchPoints.empty()) - { + if (_touchPoints.size() == _lastTouchInputs.size() && !_touchPoints.empty()) { // @TODO (emmbr26, 2023-02-03) Looks to me like this code will always return // true? That's a bit weird and should probably be investigated bool newInput = true; diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index 55a5c3f899..0aa88ac8c9 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -187,32 +187,34 @@ bool RenderableToyVolume::isReady() const { } void RenderableToyVolume::update(const UpdateData& data) { - if (_raycaster) { - glm::mat4 transform = glm::translate( - glm::mat4(1.f), - static_cast(_translation) * - std::pow(10.f, static_cast(_scalingExponent)) - ); - const glm::vec3 eulerRotation = _rotation; - transform = glm::rotate(transform, eulerRotation.x, glm::vec3(1.f, 0.f, 0.f)); - transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0.f, 1.f, 0.f)); - transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0.f, 0.f, 1.f)); - - transform = glm::scale( - transform, - static_cast(_size) * - std::pow(10.f, static_cast(_scalingExponent)) - ); - - const glm::vec4 color = glm::vec4(glm::vec3(_color), opacity()); - - _raycaster->setColor(color); - _raycaster->setStepSize(_stepSize); - _raycaster->setModelTransform(transform); - _raycaster->setTime(data.time.j2000Seconds()); - _raycaster->setDownscaleRender(_downScaleVolumeRendering); - _raycaster->setMaxSteps(_rayCastSteps); + if (!_raycaster) { + return; } + + glm::mat4 transform = glm::translate( + glm::mat4(1.f), + static_cast(_translation) * + std::pow(10.f, static_cast(_scalingExponent)) + ); + const glm::vec3 eulerRotation = _rotation; + transform = glm::rotate(transform, eulerRotation.x, glm::vec3(1.f, 0.f, 0.f)); + transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0.f, 1.f, 0.f)); + transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0.f, 0.f, 1.f)); + + transform = glm::scale( + transform, + static_cast(_size) * + std::pow(10.f, static_cast(_scalingExponent)) + ); + + const glm::vec4 color = glm::vec4(glm::vec3(_color), opacity()); + + _raycaster->setColor(color); + _raycaster->setStepSize(_stepSize); + _raycaster->setModelTransform(transform); + _raycaster->setTime(data.time.j2000Seconds()); + _raycaster->setDownscaleRender(_downScaleVolumeRendering); + _raycaster->setMaxSteps(_rayCastSteps); } void RenderableToyVolume::render(const RenderData& data, RendererTasks& tasks) { diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.cpp b/modules/toyvolume/rendering/toyvolumeraycaster.cpp index 7acd30a4d4..58ec72c94e 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.cpp +++ b/modules/toyvolume/rendering/toyvolumeraycaster.cpp @@ -24,17 +24,15 @@ #include -#include #include -#include #include - -#include +#include +#include #include #include -#include - +#include #include +#include namespace { constexpr std::string_view GlslRaycastPath = @@ -103,12 +101,12 @@ glm::dmat4 ToyVolumeRaycaster::modelViewTransform(const RenderData& data) { void ToyVolumeRaycaster::preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) { - const std::string& colorUniformName = "color" + std::to_string(data.id); - const std::string& timeUniformName = "time" + std::to_string(data.id); - const std::string& stepSizeUniformName = "maxStepSize" + std::to_string(data.id); - program.setUniform(colorUniformName, _color); - program.setUniform(stepSizeUniformName, _stepSize); - program.setUniform(timeUniformName, static_cast(std::fmod(_time, 3600.0))); + program.setUniform(std::format("color{}", data.id), _color); + program.setUniform(std::format("maxStepSize{}", data.id), _stepSize); + program.setUniform( + std::format("time{}", data.id), + static_cast(std::fmod(_time, 3600.0)) + ); } void ToyVolumeRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramObject&) {} diff --git a/modules/video/src/videoplayer.cpp b/modules/video/src/videoplayer.cpp index 35e5aefbcf..62312b04fe 100644 --- a/modules/video/src/videoplayer.cpp +++ b/modules/video/src/videoplayer.cpp @@ -37,7 +37,6 @@ #include #include - namespace { constexpr std::string_view _loggerCat = "VideoPlayer"; @@ -99,6 +98,20 @@ namespace { "end of the video." }; + bool checkMpvError(int status) { + if (status < 0) { + LERROR(std::format("Libmpv API error: {}", mpv_error_string(status))); + return false; + } + return true; + } + + void* getOpenGLProcAddress(void*, const char* name) { + return reinterpret_cast( + openspace::global::windowDelegate->openGLProcedureAddress(name) + ); + } + struct [[codegen::Dictionary(VideoPlayer)]] Parameters { // [[codegen::verbatim(VideoInfo.description)]] std::filesystem::path video; @@ -129,23 +142,6 @@ namespace { namespace openspace { -namespace { - -bool checkMpvError(int status) { - if (status < 0) { - LERROR(std::format("Libmpv API error: {}", mpv_error_string(status))); - return false; - } - return true; -} - -void* getOpenGLProcAddress(void*, const char* name) { - return reinterpret_cast( - global::windowDelegate->openGLProcedureAddress(name) - ); -} -} // namespace - void VideoPlayer::onMpvRenderUpdate(void* ctx) { // The wakeup flag is set here to enable the mpv_render_context_render // path in the main loop. @@ -155,12 +151,7 @@ void VideoPlayer::onMpvRenderUpdate(void* ctx) { } void VideoPlayer::observePropertyMpv(MpvKey key) { - mpv_observe_property( - _mpvHandle, - static_cast(key), - keys[key], - formats[key] - ); + mpv_observe_property(_mpvHandle, static_cast(key), keys[key], formats[key]); } void VideoPlayer::setPropertyStringMpv(const char* name, const char* value) { @@ -414,13 +405,13 @@ void VideoPlayer::initializeMpv() { LINFO("mpv init failed"); } - mpv_opengl_init_params gl_init_params{ getOpenGLProcAddress, nullptr }; + mpv_opengl_init_params gl_init_params { getOpenGLProcAddress, nullptr }; int adv = 1; // Use libmpv advanced mode since we will use the update callback // Decouple mpv from waiting to get the correct fps. Use with flag video-timing-offset // set to 0 int blockTime = 0; - mpv_render_param params[]{ + mpv_render_param params[] = { { MPV_RENDER_PARAM_API_TYPE, const_cast(MPV_RENDER_API_TYPE_OPENGL) }, { MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params }, { MPV_RENDER_PARAM_ADVANCED_CONTROL, &adv }, @@ -439,11 +430,7 @@ void VideoPlayer::initializeMpv() { // request a new frame to be rendered. // (Separate from the normal event handling mechanism for the sake of // users which run OpenGL on a different thread.) - mpv_render_context_set_update_callback( - _mpvRenderContext, - onMpvRenderUpdate, - this - ); + mpv_render_context_set_update_callback(_mpvRenderContext, onMpvRenderUpdate, this); // Load file const std::string file = _videoFile.string(); @@ -455,10 +442,10 @@ void VideoPlayer::initializeMpv() { } glGenFramebuffers(1, &_fbo); - //Create FBO to render video into + // Create FBO to render video into createTexture(_videoResolution); - //Observe video parameters + // Observe video parameters observePropertyMpv(MpvKey::Duration); observePropertyMpv(MpvKey::Meta); observePropertyMpv(MpvKey::Height); @@ -546,7 +533,7 @@ void VideoPlayer::renderFrame() { // details. This function fills the fbo and texture with data, after it // we can get the data on the GPU, not the CPU const int fboInt = static_cast(_fbo); - mpv_opengl_fbo mpfbo{ + mpv_opengl_fbo mpfbo = { fboInt, _videoResolution.x, _videoResolution.y, @@ -688,7 +675,6 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { // Each time a size property is updated, it means libmpv is updating the video // so we have to re-render the first frame to show it renderFrame(); - break; } case MpvKey::Width: { @@ -708,7 +694,6 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { // Each time a size property is updated, it means libmpv is updating the video // so we have to re-render the first frame to show it renderFrame(); - break; } case MpvKey::Time: { @@ -903,9 +888,7 @@ void VideoPlayer::resizeTexture(glm::ivec2 size) { _videoResolution = size; LINFO(std::format("Resizing texture: width: {} height: {}", size.x, size.y)); - // Delete texture _frameTexture = nullptr; - createTexture(size); } } diff --git a/modules/video/src/videotileprovider.cpp b/modules/video/src/videotileprovider.cpp index bafe84aedc..a21f25a488 100644 --- a/modules/video/src/videotileprovider.cpp +++ b/modules/video/src/videotileprovider.cpp @@ -118,7 +118,7 @@ ChunkTile VideoTileProvider::chunkTile(TileIndex tileIndex, int parents, int max std::pow(2, tileIndex.level), std::pow(2, tileIndex.level - 1) }; - const glm::vec2 ratios = { 1.f / nTiles.x, 1.f / nTiles.y }; + const glm::vec2 ratios = glm::vec2(1.f / nTiles.x, 1.f / nTiles.y); const float offsetX = ratios.x * static_cast(tileIndex.x); // The tiles on the y-axis should be traversed backwards const float offsetY = ratios.y * (nTiles.y - static_cast(tileIndex.y) - 1.f); diff --git a/modules/volume/envelope.cpp b/modules/volume/envelope.cpp index 7bb89ad003..8126f51490 100644 --- a/modules/volume/envelope.cpp +++ b/modules/volume/envelope.cpp @@ -95,31 +95,31 @@ bool Envelope::isEnvelopeValid() const { } glm::vec3 Envelope::normalizeColor(const glm::vec3& vec) const { - return { vec.r / 255.f, vec.g / 255.f , vec.b / 255.f }; + return glm::vec3(vec.r / 255.f, vec.g / 255.f , vec.b / 255.f); } glm::vec4 Envelope::valueAtPosition(float pos) const { auto afterIter = _points.begin(); while (afterIter->position.first < pos) { if (afterIter == _points.end()) { - return { 0.f, 0.f, 0.f ,0.f }; + return glm::vec4(0.f, 0.f, 0.f ,0.f); } ++afterIter; } if (afterIter->position.first == pos) { - return { afterIter->color, afterIter->position.second }; + return glm::vec4(afterIter->color, afterIter->position.second); } auto beforeIter = afterIter - 1; const float dist = afterIter->position.first - beforeIter->position.first; if (dist < 0.0001) { - return { + return glm::vec4( normalizeColor((beforeIter->color + afterIter->color) / 2.f), std::max(beforeIter->position.second, afterIter->position.second) - }; + ); } else { - return { + return glm::vec4( normalizeColor( beforeIter->color * (std::fabs(pos - afterIter->position.first) / dist) + afterIter->color * (std::fabs(pos - beforeIter->position.first) / dist) @@ -128,7 +128,7 @@ glm::vec4 Envelope::valueAtPosition(float pos) const { (std::fabs(pos - afterIter->position.first) / dist) + afterIter->position.second * (std::fabs(pos - beforeIter->position.first) / dist) - }; + ); } } @@ -176,7 +176,6 @@ glm::vec3 EnvelopePoint::hexadecimalToRGBConversion(const std::string& hex) cons const float r = static_cast(hexadecimalToDecimal(hex.substr(1, 2))); const float g = static_cast(hexadecimalToDecimal(hex.substr(3, 2))); const float b = static_cast(hexadecimalToDecimal(hex.substr(5, 2))); - return glm::vec3(r, g, b); } @@ -184,7 +183,6 @@ std::string EnvelopePoint::hexadecimalFromVec3(const glm::vec3& vec) const { const std::string r = decimalToHexadecimal(static_cast(vec.r)); const std::string g = decimalToHexadecimal(static_cast(vec.g)); const std::string b = decimalToHexadecimal(static_cast(vec.b)); - return ("#" + r + g + b); } diff --git a/modules/volume/rawvolumewriter.inl b/modules/volume/rawvolumewriter.inl index 0aaebabbf3..8a09a6a9df 100644 --- a/modules/volume/rawvolumewriter.inl +++ b/modules/volume/rawvolumewriter.inl @@ -97,14 +97,13 @@ void RawVolumeWriter::write(const RawVolume& volume) { const char* const buffer = reinterpret_cast(volume.data()); size_t length = volume.nCells() * sizeof(VoxelType); - std::ofstream file(_path, std::ios::binary); + std::ofstream file = std::ofstream(_path, std::ios::binary); if (!file.good()) { throw ghoul::RuntimeError(std::format("Could not create file '{}'", _path)); } file.write(buffer, length); - file.close(); } } // namespace openspace::volume diff --git a/modules/volume/rendering/basicvolumeraycaster.cpp b/modules/volume/rendering/basicvolumeraycaster.cpp index 5548e48d3d..e0c66211eb 100644 --- a/modules/volume/rendering/basicvolumeraycaster.cpp +++ b/modules/volume/rendering/basicvolumeraycaster.cpp @@ -154,7 +154,7 @@ bool BasicVolumeRaycaster::isCameraInside(const RenderData& data, const glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * glm::vec4(0.f, 0.f, 0.f, 1.f); - localPosition = (glm::vec3(modelPos) + glm::vec3(0.5f)); + localPosition = glm::vec3(modelPos) + glm::vec3(0.5f); return (localPosition.x > 0 && localPosition.x < 1 && localPosition.y > 0 && localPosition.y < 1 && diff --git a/modules/volume/rendering/basicvolumeraycaster.h b/modules/volume/rendering/basicvolumeraycaster.h index f68b79e17a..80e12645f4 100644 --- a/modules/volume/rendering/basicvolumeraycaster.h +++ b/modules/volume/rendering/basicvolumeraycaster.h @@ -97,7 +97,7 @@ private: std::shared_ptr _volumeTexture; std::shared_ptr _transferFunction; BoxGeometry _boundingBox; - VolumeGridType _gridType; + VolumeGridType _gridType = VolumeGridType::Cartesian; glm::mat4 _modelTransform = glm::mat4(1.f); float _brightness = 1.f; float _rNormalization = 0.f; diff --git a/modules/volume/rendering/volumeclipplanes.cpp b/modules/volume/rendering/volumeclipplanes.cpp index 21a8721c69..14ad128458 100644 --- a/modules/volume/rendering/volumeclipplanes.cpp +++ b/modules/volume/rendering/volumeclipplanes.cpp @@ -50,8 +50,6 @@ void VolumeClipPlanes::initialize() { } } -void VolumeClipPlanes::deinitialize() {} - std::vector VolumeClipPlanes::normals() { std::vector normals; normals.reserve(_clipPlanes.size()); diff --git a/modules/volume/rendering/volumeclipplanes.h b/modules/volume/rendering/volumeclipplanes.h index cd6d3e4626..1343c61251 100644 --- a/modules/volume/rendering/volumeclipplanes.h +++ b/modules/volume/rendering/volumeclipplanes.h @@ -43,7 +43,6 @@ public: ~VolumeClipPlanes() override = default; void initialize(); - void deinitialize(); std::vector normals(); std::vector offsets(); diff --git a/modules/volume/tasks/generaterawvolumefromfiletask.cpp b/modules/volume/tasks/generaterawvolumefromfiletask.cpp index fc30cd26d3..71b82e687c 100644 --- a/modules/volume/tasks/generaterawvolumefromfiletask.cpp +++ b/modules/volume/tasks/generaterawvolumefromfiletask.cpp @@ -108,8 +108,7 @@ void GenerateRawVolumeFromFileTask::perform(const ProgressCallback& progressCall } // Get min/max x, y, z position - ie. domain bounds of the volume - for (const dataloader::Dataset::Entry& p : data.entries) - { + for (const dataloader::Dataset::Entry& p : data.entries) { _lowerDomainBound = glm::vec3( std::min(_lowerDomainBound.x, p.position.x), std::min(_lowerDomainBound.y, p.position.y), @@ -129,14 +128,14 @@ void GenerateRawVolumeFromFileTask::perform(const ProgressCallback& progressCall float maxVal = std::numeric_limits::lowest(); auto dataIndex = std::find_if( - data.variables.begin(), - data.variables.end(), + data.variables.cbegin(), + data.variables.cend(), [this](const dataloader::Dataset::Variable& var) { return var.name == _dataValue; } ); - if (dataIndex == data.variables.end()) { + if (dataIndex == data.variables.cend()) { LERROR(std::format( "Could not find specified variable '{}' in dataset", _dataValue )); @@ -146,19 +145,17 @@ void GenerateRawVolumeFromFileTask::perform(const ProgressCallback& progressCall // Write data into volume data structure int k = 0; - for (auto& entry : data.entries) { + for (const dataloader::Dataset::Entry& entry : data.entries) { // Get the closest i, j , k voxel that should contain this data - glm::vec3 normalizedPos{ (entry.position - _lowerDomainBound) / - (_upperDomainBound - _lowerDomainBound) }; + glm::vec3 normalizedPos = (entry.position - _lowerDomainBound) / + (_upperDomainBound - _lowerDomainBound); - glm::uvec3 cell{ - glm::min( - static_cast(glm::floor( - normalizedPos * static_cast(_dimensions) - )), - _dimensions - 1u - ) - }; + glm::uvec3 cell = glm::min( + static_cast(glm::floor( + normalizedPos * static_cast(_dimensions) + )), + _dimensions - 1u + ); const float value = entry.data[dataIndex->index]; minVal = std::min(minVal, value); diff --git a/modules/volume/tasks/generaterawvolumetask.cpp b/modules/volume/tasks/generaterawvolumetask.cpp index eb2ee0a520..3d35b70aae 100644 --- a/modules/volume/tasks/generaterawvolumetask.cpp +++ b/modules/volume/tasks/generaterawvolumetask.cpp @@ -117,16 +117,8 @@ void GenerateRawVolumeTask::perform(const Task::ProgressCallback& progressCallba ghoul::lua::LuaState state; ghoul::lua::runScript(state, _valueFunctionLua); -#if (defined(NDEBUG) || defined(DEBUG)) - ghoul::lua::verifyStackSize(state, 1); -#endif - int functionReference = luaL_ref(state, LUA_REGISTRYINDEX); -#if (defined(NDEBUG) || defined(DEBUG)) - ghoul::lua::verifyStackSize(state, 0); -#endif - glm::vec3 domainSize = _upperDomainBound - _lowerDomainBound; @@ -137,19 +129,12 @@ void GenerateRawVolumeTask::perform(const Task::ProgressCallback& progressCallba const glm::vec3 coord = _lowerDomainBound + glm::vec3(cell) / glm::vec3(_dimensions) * domainSize; -#if (defined(NDEBUG) || defined(DEBUG)) - ghoul::lua::verifyStackSize(state, 0); -#endif lua_rawgeti(state, LUA_REGISTRYINDEX, functionReference); lua_pushnumber(state, coord.x); lua_pushnumber(state, coord.y); lua_pushnumber(state, coord.z); -#if (defined(NDEBUG) || defined(DEBUG)) - ghoul::lua::verifyStackSize(state, 4); -#endif - if (lua_pcall(state, 3, 1, 0) != LUA_OK) { return; } diff --git a/modules/volume/transferfunction.cpp b/modules/volume/transferfunction.cpp index 8a464c0ae4..edacc27ef3 100644 --- a/modules/volume/transferfunction.cpp +++ b/modules/volume/transferfunction.cpp @@ -194,37 +194,36 @@ bool TransferFunction::createTexture(ghoul::opengl::Texture& ptr) { if (_envelopes.empty()) { return false; } - else { - float* transferFunction = new float[_width * 4]; - std::memset(transferFunction, 0, _width * 4 * sizeof(float)); - for (int i = 0; i < _width ; i++) { - const float position = static_cast(i) / static_cast(_width); - int count = 0; - glm::vec4 rgbFromEnvelopes(0.f); - float alpha = 0.f; - for (const Envelope& env : _envelopes) { - if (env.isValueInEnvelope(position) && env.isEnvelopeValid()) { - count++; - const glm::vec4 tmp = env.valueAtPosition(position); - rgbFromEnvelopes.r += tmp.r * tmp.a; - rgbFromEnvelopes.g += tmp.g * tmp.a; - rgbFromEnvelopes.b += tmp.b * tmp.a; - alpha = std::min(alpha, tmp.a); - } - } - rgbFromEnvelopes /= (count == 0) ? 1.f : static_cast(count); - rgbFromEnvelopes.w = alpha; + float* transferFunction = new float[_width * 4]; + std::memset(transferFunction, 0, _width * 4 * sizeof(float)); - for (int channel = 0; channel < 4; ++channel) { - const int p = 4 * i + channel; - const float value = rgbFromEnvelopes[channel]; - transferFunction[p] = value; + for (int i = 0; i < _width ; i++) { + const float position = static_cast(i) / static_cast(_width); + int count = 0; + glm::vec4 rgbFromEnvelopes(0.f); + float alpha = 0.f; + for (const Envelope& env : _envelopes) { + if (env.isValueInEnvelope(position) && env.isEnvelopeValid()) { + count++; + const glm::vec4 tmp = env.valueAtPosition(position); + rgbFromEnvelopes.r += tmp.r * tmp.a; + rgbFromEnvelopes.g += tmp.g * tmp.a; + rgbFromEnvelopes.b += tmp.b * tmp.a; + alpha = std::min(alpha, tmp.a); } } - ptr.setPixelData(transferFunction); - return true; + rgbFromEnvelopes /= (count == 0) ? 1.f : static_cast(count); + rgbFromEnvelopes.w = alpha; + + for (int channel = 0; channel < 4; ++channel) { + const int p = 4 * i + channel; + const float value = rgbFromEnvelopes[channel]; + transferFunction[p] = value; + } } + ptr.setPixelData(transferFunction); + return true; } } // namespace openspace::volume diff --git a/modules/volume/transferfunctionhandler.cpp b/modules/volume/transferfunctionhandler.cpp index 4352cc7984..9560323368 100644 --- a/modules/volume/transferfunctionhandler.cpp +++ b/modules/volume/transferfunctionhandler.cpp @@ -75,11 +75,10 @@ TransferFunctionHandler::TransferFunctionHandler(properties::StringProperty prop , _maxValue(MaxValueInfo) , _saveTransferFunction(SaveTransferFunctionInfo) , _transferFunctionProperty(TransferFunctionInfo) -{ - _transferFunction = std::make_shared( + , _transferFunction(std::make_shared( _transferFunctionPath.value() - ); -} + )) +{} void TransferFunctionHandler::initialize() { addProperty(_transferFunctionPath); @@ -105,7 +104,6 @@ void TransferFunctionHandler::initialize() { } _transferFunctionProperty.onChange([this]() { setTexture(); }); - _saveTransferFunction.onChange([this]() { saveEnvelopes(); }); } @@ -149,7 +147,7 @@ void TransferFunctionHandler::uploadTexture() { _texture->uploadTexture(); } -bool TransferFunctionHandler::hasTexture() { +bool TransferFunctionHandler::hasTexture() const { return _texture != nullptr; } diff --git a/modules/volume/transferfunctionhandler.h b/modules/volume/transferfunctionhandler.h index d07dceb6c2..38a275ac8a 100644 --- a/modules/volume/transferfunctionhandler.h +++ b/modules/volume/transferfunctionhandler.h @@ -57,7 +57,7 @@ public: ghoul::opengl::Texture& texture(); void uploadTexture(); - bool hasTexture(); + bool hasTexture() const; std::shared_ptr transferFunction(); diff --git a/modules/volume/volumegridtype.cpp b/modules/volume/volumegridtype.cpp index 00b796af1f..3421cda0fe 100644 --- a/modules/volume/volumegridtype.cpp +++ b/modules/volume/volumegridtype.cpp @@ -27,7 +27,7 @@ namespace openspace::volume { InvalidGridTypeError::InvalidGridTypeError(std::string gridType_) - : RuntimeError("Invalid grid type: '" + gridType_ + "'") + : RuntimeError(std::format("Invalid grid type: '{}'", gridType_)) , gridType(std::move(gridType_)) {} diff --git a/modules/webbrowser/src/browserinstance.cpp b/modules/webbrowser/src/browserinstance.cpp index 170887f4ef..1f65d83d75 100644 --- a/modules/webbrowser/src/browserinstance.cpp +++ b/modules/webbrowser/src/browserinstance.cpp @@ -126,7 +126,6 @@ void BrowserInstance::draw() { ZoneScoped; TracyGpuZone("CEF Draw"); - if (_zoomLevel != _browser->GetHost()->GetZoomLevel()) { _browser->GetHost()->SetZoomLevel(_zoomLevel); } diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index 132c953a31..69ee6f866b 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -46,7 +46,7 @@ bool DefaultBrowserLauncher::OnBeforePopup(CefRefPtr, CefRefPtremplace( global::callback::keyboard->begin(), [this](Key key, KeyModifier mod, KeyAction action, - IsGuiWindow isGuiWindow) -> bool + IsGuiWindow isGuiWindow) -> bool { if (_browserInstance && isGuiWindow) { return keyboardCallback(key, mod, action); @@ -219,7 +219,7 @@ void EventHandler::initialize() { cef_touch_event_type_t::CEF_TET_PRESSED ); _browserInstance->sendTouchEvent(event); -#else +#else // ^^^^ WIN32 // !WIN32 vvvv _mousePosition.x = windowPos.x; _mousePosition.y = windowPos.y; _leftButton.down = true; @@ -229,7 +229,7 @@ void EventHandler::initialize() { false, BrowserInstance::SingleClick ); -#endif +#endif // WIN32 } _validTouchStates.emplace_back(input); @@ -282,10 +282,7 @@ void EventHandler::initialize() { global::callback::touchExit->emplace( global::callback::touchExit->begin(), [this](TouchInput input) { - if (!_browserInstance) { - return; - } - if (_validTouchStates.empty()) { + if (!_browserInstance || _validTouchStates.empty()) { return; } @@ -397,7 +394,7 @@ bool EventHandler::mouseWheelCallback(glm::ivec2 delta) { // scroll wheel returns very low numbers on Windows machines delta.x *= 50; delta.y *= 50; -#endif +#endif // WIN32 return _browserInstance->sendMouseWheelEvent(mouseEvent(), delta); } @@ -408,7 +405,6 @@ bool EventHandler::charCallback(unsigned int charCode, KeyModifier modifier) { keyEvent.native_key_code = mapFromGlfwToNative(Key(charCode)); keyEvent.modifiers = static_cast(modifier); keyEvent.type = KEYEVENT_CHAR; - return _browserInstance->sendKeyEvent(keyEvent); } diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index 0c42d921e5..ed30cc91fd 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -145,13 +145,8 @@ bool ScreenSpaceBrowser::deinitializeGL() { _browserInstance->close(true); WebBrowserModule* webBrowser = global::moduleEngine->module(); - if (webBrowser) { - webBrowser->removeBrowser(_browserInstance.get()); - _browserInstance.reset(); - } - else { - LWARNING("Could not find WebBrowserModule"); - } + webBrowser->removeBrowser(_browserInstance.get()); + _browserInstance.reset(); return ScreenSpaceRenderable::deinitializeGL(); } diff --git a/modules/webbrowser/src/webbrowserapp.cpp b/modules/webbrowser/src/webbrowserapp.cpp index d983dfdef6..96414d1b50 100644 --- a/modules/webbrowser/src/webbrowserapp.cpp +++ b/modules/webbrowser/src/webbrowserapp.cpp @@ -51,7 +51,7 @@ void WebBrowserApp::OnBeforeCommandLineProcessing(const CefString&, #ifdef __APPLE__ commandline->AppendSwitch("--disable-gpu-sandbox"); commandline->AppendSwitch("--no-sandbox"); -#endif +#endif // __APPLE__ } } // namespace openspace diff --git a/modules/webbrowser/src/webrenderhandler.cpp b/modules/webbrowser/src/webrenderhandler.cpp index 1da83f8c3d..8b6c2f010c 100644 --- a/modules/webbrowser/src/webrenderhandler.cpp +++ b/modules/webbrowser/src/webrenderhandler.cpp @@ -184,7 +184,7 @@ void WebRenderHandler::updateTexture() { return; } - if (_textureSizeIsDirty) { + if (_textureSizeIsDirty) [[unlikely]] { glBindTexture(GL_TEXTURE_2D, _texture); glTexImage2D( GL_TEXTURE_2D, diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index b656e17282..a5d8243143 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -59,16 +59,15 @@ namespace { "UpdateBrowserBetweenRenderables", "Update Browser Between Renderables", "Run the message loop of the browser between calls to render individual " - "renderables. When disabled, the browser message loop only runs " - "once per frame.", + "renderables. When disabled, the browser message loop only runs once per frame.", openspace::properties::Property::Visibility::Developer }; constexpr openspace::properties::Property::PropertyInfo BrowserUpdateIntervalInfo = { "BrowserUpdateInterval", "Browser Update Interval", - "The time in microseconds between running the message loop of the browser. " - "Only used if UpdateBrowserBetweenRenderables is true.", + "The time in microseconds between running the message loop of the browser. Only " + "used if UpdateBrowserBetweenRenderables is true.", openspace::properties::Property::Visibility::Developer }; @@ -123,7 +122,7 @@ WebBrowserModule::WebBrowserModule() : OpenSpaceModule(WebBrowserModule::Name) , _updateBrowserBetweenRenderables(UpdateBrowserBetweenRenderablesInfo, true) , _browserUpdateInterval(BrowserUpdateIntervalInfo, 1.f, 1.f, 1000.f) - , _eventHandler(new EventHandler) + , _eventHandler(std::make_unique()) { global::callback::deinitialize->emplace_back([this]() { ZoneScopedN("WebBrowserModule"); @@ -197,6 +196,7 @@ void WebBrowserModule::internalDeinitialize() { void WebBrowserModule::addBrowser(BrowserInstance* browser) { ZoneScoped; + ghoul_assert(browser, "Browser must not be a nullptr"); if (_enabled) { _browsers.push_back(browser); if (_updateBrowserBetweenRenderables) { @@ -258,9 +258,9 @@ bool WebBrowserModule::canUseAcceleratedRendering() { ghoul::systemcapabilities::OpenGLCapabilitiesComponent::Vendor::Nvidia; return isVersionOk && isExtensionsOk && isVendorOk && !_disableAcceleratedRendering; -#else +#else // ^^^^ WIN32 // !WIN32 vvvv return false; -#endif +#endif // WIN32 } std::vector WebBrowserModule::documentations() const { diff --git a/modules/webbrowser/webbrowsermodule.h b/modules/webbrowser/webbrowsermodule.h index fa47c3cfb3..6129c866b7 100644 --- a/modules/webbrowser/webbrowsermodule.h +++ b/modules/webbrowser/webbrowsermodule.h @@ -26,6 +26,7 @@ #define __OPENSPACE_MODULE_WEBBROWSER___WEBBROWSERMODULE___H__ #include + #include #include #include diff --git a/modules/webgui/webguimodule.cpp b/modules/webgui/webguimodule.cpp index 84f6663a62..db29e8e351 100644 --- a/modules/webgui/webguimodule.cpp +++ b/modules/webgui/webguimodule.cpp @@ -252,9 +252,9 @@ void WebGuiModule::startProcess() { #ifdef _MSC_VER const std::filesystem::path node = absPath("${MODULE_WEBGUI}/ext/nodejs/node.exe"); -#else +#else // ^^^^ _MSC_VER // !_MSC_VER vvvv const std::filesystem::path node = absPath("${MODULE_WEBGUI}/ext/nodejs/node"); -#endif +#endif // _MSC_VER std::string formattedDirectories = "["; @@ -287,11 +287,11 @@ void WebGuiModule::startProcess() { command, absPath("${BIN}"), [](const char* data, size_t n) { - const std::string str = std::string(data, n); + const std::string_view str = std::string_view(data, n); LDEBUG(std::format("Web GUI server output: {}", str)); }, [](const char* data, size_t n) { - const std::string str = std::string(data, n); + const std::string_view str = std::string_view(data, n); LERROR(std::format("Web GUI server error: {}", str)); } ); diff --git a/src/camera/camera.cpp b/src/camera/camera.cpp index 764b4d4b25..0a9a9453d8 100644 --- a/src/camera/camera.cpp +++ b/src/camera/camera.cpp @@ -46,14 +46,14 @@ void Camera::setPose(CameraPose pose) { void Camera::setPositionVec3(glm::dvec3 pos) { if (!glm::any(glm::isnan(pos))) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _position = std::move(pos); _cachedCombinedViewMatrix.isDirty = true; } } void Camera::setRotation(glm::dquat rotation) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _rotation = std::move(rotation); _cachedViewDirection.isDirty = true; _cachedLookupVector.isDirty = true; @@ -62,14 +62,14 @@ void Camera::setRotation(glm::dquat rotation) { } void Camera::setScaling(float scaling) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _scaling = scaling; _cachedViewScaleMatrix.isDirty = true; _cachedCombinedViewMatrix.isDirty = true; } void Camera::setMaxFov(float fov) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _maxFov = fov; _cachedSinMaxFov.isDirty = true; } @@ -79,7 +79,7 @@ void Camera::setParent(SceneGraphNode* parent) { } void Camera::rotate(const glm::dquat& rotation) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _rotation = rotation * static_cast(_rotation); _cachedViewDirection.isDirty = true; @@ -236,20 +236,20 @@ Camera::SgctInternal::SgctInternal(const SgctInternal& o) {} void Camera::SgctInternal::setSceneMatrix(glm::mat4 sceneMatrix) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _sceneMatrix = std::move(sceneMatrix); } void Camera::SgctInternal::setViewMatrix(glm::mat4 viewMatrix) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _viewMatrix = std::move(viewMatrix); _cachedViewProjectionMatrix.isDirty = true; } void Camera::SgctInternal::setProjectionMatrix(glm::mat4 projectionMatrix) { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _projectionMatrix = std::move(projectionMatrix); _cachedViewProjectionMatrix.isDirty = true; @@ -268,7 +268,7 @@ const glm::mat4& Camera::SgctInternal::projectionMatrix() const { } const glm::mat4& Camera::SgctInternal::viewProjectionMatrix() const { - const std::lock_guard _lock(_mutex); + const std::lock_guard lock(_mutex); _cachedViewProjectionMatrix.datum = _projectionMatrix * _viewMatrix; _cachedViewProjectionMatrix.isDirty = false; return _cachedViewProjectionMatrix.datum; diff --git a/src/rendering/dashboarditem.cpp b/src/rendering/dashboarditem.cpp index 333a9becbe..855a654965 100644 --- a/src/rendering/dashboarditem.cpp +++ b/src/rendering/dashboarditem.cpp @@ -42,12 +42,17 @@ namespace { }; struct [[codegen::Dictionary(DashboardItem)]] Parameters { + // Determines the type of the DashbordItem that should be created. std::string type; + // The unique identifier for this DashboardItem. std::string identifier [[codegen::identifier()]]; + // The name for the DashboardItem that is used when showing it in the user + // interface. std::optional guiName; + // [[codegen::verbatim(EnabledInfo.description)]] std::optional enabled; }; #include "dashboarditem_codegen.cpp" diff --git a/src/scene/lightsource.cpp b/src/scene/lightsource.cpp index 51b1fd010d..c57096255a 100644 --- a/src/scene/lightsource.cpp +++ b/src/scene/lightsource.cpp @@ -81,17 +81,12 @@ std::unique_ptr LightSource::createFromDictionary( return std::unique_ptr(source); } -LightSource::LightSource() +LightSource::LightSource(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "LightSource", "Light Source" }) , _enabled(EnabledInfo, true) -{ - addProperty(_enabled); -} - -LightSource::LightSource(const ghoul::Dictionary& dictionary) - : LightSource() { const Parameters p = codegen::bake(dictionary); + addProperty(_enabled); _enabled = p.enabled.value_or(_enabled); } diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index 414b16dd47..9a95cded12 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -767,24 +767,18 @@ void SceneGraphNode::update(const UpdateData& data) { TracyPlot("VRAM", static_cast(global::openSpaceEngine->vramInUse())); #endif // TRACY_ENABLE - if (_state != State::GLInitialized) { - return; - } - if (!isTimeFrameActive(data.time)) { + if (_state != State::GLInitialized || !isTimeFrameActive(data.time)) { return; } - if (_transform.translation) { - _transform.translation->update(data); - } + ghoul_assert(_transform.translation, "No translation exists"); + _transform.translation->update(data); - if (_transform.rotation) { - _transform.rotation->update(data); - } + ghoul_assert(_transform.rotation, "No rotation exists"); + _transform.rotation->update(data); - if (_transform.scale) { - _transform.scale->update(data); - } + ghoul_assert(_transform.scale, "No scale exists"); + _transform.scale->update(data); UpdateData newUpdateData = data; // Assumes _worldRotationCached and _worldScaleCached have been calculated for parent @@ -821,18 +815,10 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { TracyPlot("VRAM", static_cast(global::openSpaceEngine->vramInUse())); #endif // TRACY_ENABLE - if (_state != State::GLInitialized) { - return; - } - - const bool visible = _renderable && _renderable->isVisible() && - _renderable->isReady(); - - if (!visible) { - return; - } - - if (!isTimeFrameActive(data.time)) { + if (_state != State::GLInitialized || + !(_renderable && _renderable->isVisible() && _renderable->isReady()) || + !isTimeFrameActive(data.time)) + { return; } @@ -857,15 +843,14 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { _renderable->render(newData, tasks); - if (_computeScreenSpaceValues) { + if (_computeScreenSpaceValues) [[unlikely]] { computeScreenSpaceData(newData); } } const bool isInStickerBin = data.renderBinMask & static_cast(Renderable::RenderBin::Sticker); - - if (_showDebugSphere && isInStickerBin) { + if (_showDebugSphere && isInStickerBin) [[unlikely]] { if (const double bs = boundingSphere(); bs > 0.0) { renderDebugSphere(data.camera, bs, glm::vec4(0.5f, 0.15f, 0.5f, 0.75f)); } @@ -877,7 +862,7 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { } void SceneGraphNode::renderDebugSphere(const Camera& camera, double size, - const glm::vec4& color) + const glm::vec4& color) const { const glm::dvec3 scaleVec = _worldScaleCached * size; const glm::dmat4 modelTransform = diff --git a/src/util/planegeometry.cpp b/src/util/planegeometry.cpp index 0705239d47..ce1bed4e43 100644 --- a/src/util/planegeometry.cpp +++ b/src/util/planegeometry.cpp @@ -34,11 +34,6 @@ PlaneGeometry::PlaneGeometry(glm::vec2 size) : _size(std::move(size)) {} PlaneGeometry::PlaneGeometry(float size) : PlaneGeometry(glm::vec2(size, size)) {} -PlaneGeometry::~PlaneGeometry() { - glDeleteBuffers(1, &_vBufferId); - glDeleteVertexArrays(1, &_vaoId); -} - void PlaneGeometry::initialize() { glGenVertexArrays(1, &_vaoId); glGenBuffers(1, &_vBufferId);