From 758e26789c62ac7ffa17278be2f8fe5b2c90e20b Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 11 Nov 2017 11:25:49 -0500 Subject: [PATCH] More coding style conformance --- apps/TaskRunner/main.cpp | 13 +- apps/TimelineView/controlwidget.cpp | 23 +- apps/TimelineView/main.cpp | 8 +- apps/TimelineView/mainwindow.cpp | 30 +- apps/TimelineView/timelinewidget.cpp | 75 +++- apps/TimelineView/timelinewidget.h | 6 +- .../openspace/documentation/documentation.h | 2 +- include/openspace/documentation/verifier.h | 4 +- include/openspace/documentation/verifier.inl | 4 +- .../openspace/engine/configurationmanager.h | 4 +- include/openspace/engine/downloadmanager.h | 12 +- include/openspace/interaction/touchbar.h | 2 +- include/openspace/network/messagestructures.h | 70 +++- include/openspace/network/networkengine.h | 3 +- .../performance/performancemanager.h | 6 +- .../performance/performancemeasurement.h | 3 +- .../openspace/properties/numericalproperty.h | 7 +- .../openspace/properties/selectionproperty.h | 12 +- .../openspace/properties/templateproperty.inl | 4 +- include/openspace/rendering/abufferrenderer.h | 4 +- .../openspace/rendering/framebufferrenderer.h | 12 +- include/openspace/rendering/renderable.h | 6 +- include/openspace/rendering/renderengine.h | 3 +- .../openspace/rendering/transferfunction.h | 3 +- include/openspace/rendering/volume.h | 20 +- include/openspace/rendering/volumeraycaster.h | 32 +- include/openspace/scene/rotation.h | 3 +- include/openspace/scene/scale.h | 3 +- include/openspace/scene/scene.h | 9 +- include/openspace/scene/scenegraphnode.h | 20 +- include/openspace/scene/sceneloader.h | 9 +- include/openspace/scene/translation.h | 3 +- include/openspace/scripting/scriptengine.h | 5 - include/openspace/util/spicemanager.h | 5 +- include/openspace/util/syncbuffer.h | 12 +- include/openspace/util/taskloader.h | 3 +- include/openspace/util/timeline.h | 3 +- include/openspace/util/timeline.inl | 120 +++++- include/openspace/util/timerange.h | 6 +- .../openspace/util/transformationmanager.h | 6 +- .../base/rendering/screenspaceframebuffer.h | 9 +- modules/base/rotation/fixedrotation.cpp | 2 +- .../digitaluniverse/digitaluniversemodule.cpp | 4 +- .../rendering/renderablefieldlines.cpp | 48 ++- .../rendering/renderablefieldlines.h | 1 - .../fieldlinessequencemodule.cpp | 6 +- .../renderablefieldlinessequence.cpp | 13 +- .../rendering/renderablefieldlinessequence.h | 180 +++++--- .../util/fieldlinesstate.cpp | 130 ++++-- .../fieldlinessequence/util/fieldlinesstate.h | 16 +- .../util/kameleonfieldlinehelper.cpp | 41 +- modules/galaxy/rendering/galaxyraycaster.h | 15 +- .../tasks/milkywaypointsconversiontask.cpp | 3 +- .../globebrowsing/cache/texturecontainer.cpp | 4 +- modules/globebrowsing/chunk/chunk.cpp | 13 +- .../projectedareaevaluator.cpp | 2 +- .../chunk/culling/frustumculler.cpp | 9 +- modules/globebrowsing/geometry/ellipsoid.cpp | 4 +- modules/globebrowsing/geometry/ellipsoid.h | 7 +- .../globebrowsing/geometry/geodeticpatch.cpp | 24 +- modules/globebrowsing/globebrowsingmodule.cpp | 67 ++- .../globebrowsing/globebrowsingmodule_lua.inl | 12 +- .../globebrowsing/globes/chunkedlodglobe.cpp | 16 +- modules/globebrowsing/globes/pointglobe.cpp | 7 +- modules/globebrowsing/meshes/grid.h | 8 +- modules/globebrowsing/meshes/skirtedgrid.cpp | 4 +- modules/globebrowsing/other/pixelbuffer.cpp | 4 +- .../other/pixelbuffercontainer.h | 4 +- .../globebrowsing/rendering/chunkrenderer.cpp | 5 +- .../globebrowsing/rendering/gpu/gpulayer.cpp | 22 +- .../rendering/gpu/gpulayeradjustment.cpp | 10 +- .../rendering/gpu/gpulayerrendersettings.h | 3 +- .../globebrowsing/rendering/layer/layer.cpp | 15 +- modules/globebrowsing/rendering/layer/layer.h | 11 +- .../rendering/layer/layergroup.cpp | 5 +- .../rendering/layershadermanager.cpp | 33 +- .../gdalrawtiledatareader.cpp | 6 +- .../rawtiledatareader/rawtiledatareader.cpp | 72 +++- .../rawtiledatareader/rawtiledatareader.h | 3 +- .../simplerawtiledatareader.cpp | 3 +- .../tile/tileprovider/defaulttileprovider.cpp | 45 +- .../sizereferencetileprovider.cpp | 3 +- .../tileprovider/temporaltileprovider.cpp | 13 +- .../tile/tileprovider/temporaltileprovider.h | 7 +- .../tile/tileprovider/tileproviderbyindex.h | 4 +- .../tile/tileprovider/tileproviderbylevel.cpp | 8 +- modules/globebrowsing/tile/tileselector.h | 3 +- .../tile/tiletextureinitdata.cpp | 5 +- modules/imgui/imguimodule.cpp | 16 +- modules/imgui/src/gui.cpp | 24 +- modules/imgui/src/guiiswacomponent.cpp | 2 - modules/imgui/src/guimissioncomponent.cpp | 16 +- modules/imgui/src/guiparallelcomponent.cpp | 10 +- modules/imgui/src/guiperformancecomponent.cpp | 6 +- modules/imgui/src/guipropertycomponent.cpp | 11 +- modules/imgui/src/guispacetimecomponent.cpp | 14 +- modules/iswa/rendering/datacygnet.h | 3 +- modules/iswa/rendering/dataplane.cpp | 29 +- modules/iswa/rendering/iswabasegroup.cpp | 10 +- modules/iswa/rendering/iswacygnet.h | 3 +- modules/iswa/rendering/iswadatagroup.cpp | 51 ++- modules/iswa/rendering/iswadatagroup.h | 3 +- modules/iswa/rendering/iswakameleongroup.cpp | 34 +- modules/iswa/rendering/kameleonplane.cpp | 47 ++- modules/iswa/rendering/kameleonplane.h | 6 +- modules/iswa/rendering/screenspacecygnet.cpp | 19 +- modules/iswa/rendering/texturecygnet.cpp | 2 +- modules/iswa/rendering/texturecygnet.h | 3 +- modules/iswa/rendering/textureplane.cpp | 18 +- modules/iswa/util/dataprocessor.cpp | 80 +++- modules/iswa/util/dataprocessor.h | 15 +- modules/iswa/util/dataprocessorjson.cpp | 22 +- modules/iswa/util/dataprocessorjson.h | 9 +- modules/iswa/util/dataprocessorkameleon.cpp | 73 ++-- modules/iswa/util/dataprocessorkameleon.h | 15 +- modules/iswa/util/dataprocessortext.cpp | 27 +- modules/iswa/util/dataprocessortext.h | 9 +- modules/iswa/util/iswamanager.cpp | 106 +++-- modules/iswa/util/iswamanager.h | 8 +- modules/iswa/util/iswamanager_lua.inl | 9 +- modules/kameleon/include/kameleonwrapper.h | 34 +- modules/kameleon/src/kameleonhelper.cpp | 4 - modules/kameleon/src/kameleonwrapper.cpp | 391 ++++++++++++------ .../kameleonvolume/kameleonvolumereader.cpp | 63 ++- modules/kameleonvolume/kameleonvolumereader.h | 4 +- .../rendering/renderablekameleonvolume.cpp | 6 +- modules/multiresvolume/rendering/tsp.cpp | 2 +- .../rendering/renderablefov.h | 9 +- .../util/imagesequencer.h | 8 +- modules/touch/touchmodule.h | 3 +- .../toyvolume/rendering/toyvolumeraycaster.h | 12 +- modules/volume/lrucache.h | 4 +- modules/volume/rawvolumewriter.inl | 10 +- .../volume/rendering/basicvolumeraycaster.h | 12 +- .../rendering/renderabletimevaryingvolume.cpp | 209 ++++++++-- modules/volume/textureslicevolumereader.h | 3 +- modules/volume/textureslicevolumereader.inl | 11 +- modules/volume/volumesampler.inl | 22 +- src/engine/downloadmanager.cpp | 5 +- src/engine/openspaceengine.cpp | 14 +- src/engine/settingsengine.cpp | 4 +- src/engine/wrapper/sgctwindowwrapper.cpp | 10 +- src/interaction/keybindingmanager.cpp | 18 +- src/interaction/keyframenavigator.cpp | 36 +- src/interaction/navigationhandler.cpp | 17 +- src/network/parallelconnection.cpp | 38 +- src/performance/performancemanager.cpp | 25 +- src/properties/scalar/wcharproperty.cpp | 44 +- src/query/query.cpp | 2 +- src/rendering/abufferrenderer.cpp | 14 +- src/rendering/framebufferrenderer.cpp | 6 +- src/rendering/renderable.cpp | 4 +- src/rendering/renderengine.cpp | 113 ++--- src/rendering/renderengine_lua.inl | 13 +- src/rendering/transferfunction.cpp | 43 +- src/scene/rotation.cpp | 4 +- src/scene/scene.cpp | 48 ++- src/scene/scene_lua.inl | 6 +- src/scene/scenegraphnode.cpp | 36 +- src/scene/scenelicensewriter.cpp | 3 +- src/scene/sceneloader.cpp | 80 +++- src/scripting/scriptengine.cpp | 126 +----- src/util/camera.cpp | 8 +- src/util/histogram.cpp | 39 +- src/util/progressbar.cpp | 3 +- src/util/spicemanager.cpp | 11 +- src/util/spicemanager_lua.inl | 2 +- src/util/taskloader.cpp | 4 +- src/util/timemanager.cpp | 23 +- src/util/timerange.cpp | 4 +- 170 files changed, 2585 insertions(+), 1229 deletions(-) diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 83d426cd23..75a7b3bfc5 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -58,10 +58,14 @@ namespace { void initTextureReaders() { #ifdef GHOUL_USE_DEVIL - ghoul::io::TextureReader::ref().addReader(std::make_shared()); + ghoul::io::TextureReader::ref().addReader( + std::make_shared() + ); #endif // GHOUL_USE_DEVIL #ifdef GHOUL_USE_FREEIMAGE - ghoul::io::TextureReader::ref().addReader(std::make_shared()); + ghoul::io::TextureReader::ref().addReader( + std::make_shared() + ); #endif // GHOUL_USE_FREEIMAGE } @@ -81,7 +85,10 @@ void performTasks(const std::string& path) { for (size_t i = 0; i < tasks.size(); i++) { Task& task = *tasks[i].get(); - LINFO("Performing task " << (i + 1) << " out of " << tasks.size() << ": " << task.description()); + LINFO( + "Performing task " << (i + 1) << " out of " << + tasks.size() << ": " << task.description() + ); ProgressBar progressBar(100); auto onProgress = [&progressBar](float progress) { progressBar.print(progress * 100); diff --git a/apps/TimelineView/controlwidget.cpp b/apps/TimelineView/controlwidget.cpp index a4f501d830..a872a2e6f8 100644 --- a/apps/TimelineView/controlwidget.cpp +++ b/apps/TimelineView/controlwidget.cpp @@ -253,7 +253,8 @@ void ControlWidget::onDateChange() { QString script = "openspace.time.setTime('" + date + "');\ openspace.setPropertyValue('Interaction.origin', '" + focus + "');\ - openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "')"; + openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "')"; emit scriptActivity(script); } _setTime->blockSignals(true); @@ -265,18 +266,28 @@ void ControlWidget::onFocusChange() { int index = _focusNode->currentIndex(); QString name = FocusNodes[index].name; QString coordinateSystem = FocusNodes[index].coordinateSystem; - QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "');"; emit scriptActivity(script); } void ControlWidget::onFocusToTargetButton() { std::string target = reinterpret_cast(parent())->nextTarget(); if (!target.empty()) { - auto it = std::find_if(std::begin(FocusNodes), std::end(FocusNodes), [target](const FocusNode& n) { return n.guiName.toLower() == QString::fromStdString(target).toLower(); }); + auto it = std::find_if( + std::begin(FocusNodes), + std::end(FocusNodes), + [target](const FocusNode& n) { + return n.guiName.toLower() == QString::fromStdString(target).toLower(); + }); if (it != std::end(FocusNodes)) { QString name = it->name; QString coordinateSystem = it->coordinateSystem; - QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = + "openspace.setPropertyValue('Interaction.origin', '" + name + + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "');"; emit scriptActivity(script); } } @@ -292,7 +303,9 @@ void ControlWidget::onFocusToNewHorizonsButton() { else coordinateSystem = "Pluto"; - QString script = "openspace.setPropertyValue('Interaction.origin', 'NewHorizons');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = "openspace.setPropertyValue('Interaction.origin', 'NewHorizons');\ + openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + + "');"; emit scriptActivity(script); } diff --git a/apps/TimelineView/main.cpp b/apps/TimelineView/main.cpp index 6add883ca7..64da99f345 100644 --- a/apps/TimelineView/main.cpp +++ b/apps/TimelineView/main.cpp @@ -58,7 +58,9 @@ QLineEdit { QSlider::groove:horizontal { border: 1px solid #999999; - height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */ + /* the groove expands to the size of the slider by default. by giving it a height, + it has a fixed size */ + height: 8px; background: qlineargradient( x1:0, y1:0, x2:1, y2:0, stop:0 #c4c4c4, @@ -72,7 +74,9 @@ QSlider::handle:horizontal { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f); border: 1px solid #5c5c5c; width: 18px; - margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */ + /* handle is placed by default on the contents rect of the groove. + Expand outside the groove */ + margin: -2px 0; border-radius: 3px; } diff --git a/apps/TimelineView/mainwindow.cpp b/apps/TimelineView/mainwindow.cpp index b227633515..88b00581cb 100644 --- a/apps/TimelineView/mainwindow.cpp +++ b/apps/TimelineView/mainwindow.cpp @@ -257,17 +257,23 @@ void MainWindow::handleStatusMessage(QByteArray data) { QString::fromStdString(std::string(timeString.begin(), timeString.end())), QString::number(delta.value) ); - _timelineWidget->setCurrentTime(std::string(timeString.begin(), timeString.end()), et.value); + _timelineWidget->setCurrentTime( + std::string(timeString.begin(), timeString.end()), + et.value + ); } -std::vector instrumentsFromId(uint16_t instrumentId, std::map instrumentMap) { +std::vector instrumentsFromId(uint16_t instrumentId, + std::map instrumentMap) +{ std::vector results; for (int i = 0; i < 16; ++i) { uint16_t testValue = 1 << i; if ((testValue & instrumentId) != 0) { std::string t = instrumentMap.at(testValue); - if (t.empty()) + if (t.empty()) { qDebug() << "Empty instrument"; + } results.push_back(t); } } @@ -318,15 +324,21 @@ QByteArray MainWindow::handlePlaybook(QByteArray data) { qDebug() << "Instruments were empty"; images.push_back(image); } - _timelineWidget->setData(std::move(images), std::move(targetMap), std::move(instrumentMap)); + _timelineWidget->setData( + std::move(images), + std::move(targetMap), + std::move(instrumentMap) + ); auto dataSize = data.size(); auto readSize = currentReadLocation; auto extraBytes = dataSize - readSize; - if (extraBytes > 0) + if (extraBytes > 0) { return data.mid(currentReadLocation); - else + } + else { return QByteArray(); + } } void MainWindow::sendScript(QString script) { @@ -361,7 +373,10 @@ std::string MainWindow::nextTarget() const { } void MainWindow::fullyConnected() { - _informationWidget->logInformation("Connected to " + _socket->peerName() + " on port " + QString::number(_socket->peerPort()) + "."); + _informationWidget->logInformation( + "Connected to " + _socket->peerName() + " on port " + + QString::number(_socket->peerPort()) + "." + ); _configurationWidget->socketConnected(); _timeControlWidget->socketConnected(); @@ -379,6 +394,5 @@ void MainWindow::printMapping(QByteArray data) { std::string mapping = readFromBuffer(buffer, currentReadPosition); qDebug() << identifier << ": " << QString::fromStdString(mapping); - } } diff --git a/apps/TimelineView/timelinewidget.cpp b/apps/TimelineView/timelinewidget.cpp index b4014b12bf..73da3a324b 100644 --- a/apps/TimelineView/timelinewidget.cpp +++ b/apps/TimelineView/timelinewidget.cpp @@ -89,7 +89,12 @@ void TimelineWidget::paintEvent(QPaintEvent* event) { QRectF fullRect = contentsRect(); QRectF contentRect(0, 0, fullRect.width() - 1, fullRect.height() - LegendHeight); - QRectF legendRect(0, fullRect.bottom() - LegendHeight, fullRect.right(), fullRect.bottom()); + QRectF legendRect( + 0, + fullRect.bottom() - LegendHeight, + fullRect.right(), + fullRect.bottom() + ); painter.save(); drawContent(painter, contentRect); @@ -101,10 +106,17 @@ void TimelineWidget::paintEvent(QPaintEvent* event) { painter.restore(); } -void TimelineWidget::setData(std::vector images, std::map targetMap, std::map instrumentMap) { +void TimelineWidget::setData(std::vector images, + std::map targetMap, + std::map instrumentMap) +{ _images.insert(_images.end(), images.begin(), images.end()); - std::sort(_images.begin(), _images.end(), [](const Image& a, const Image& b) { return a.beginning < b.beginning; }); + std::sort( + _images.begin(), + _images.end(), + [](const Image& a, const Image& b) { return a.beginning < b.beginning; } + ); _targetMap.insert(targetMap.begin(), targetMap.end()); _instrumentMap.insert(instrumentMap.begin(), instrumentMap.end()); @@ -148,8 +160,15 @@ void TimelineWidget::drawContent(QPainter& painter, QRectF rect) { // Draw current time painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black, 2)); - painter.drawLine(QPointF(0, timelineRect.height() / 2), QPointF(timelineRect.width(), timelineRect.height() / 2)); - painter.drawText(timelineRect.width(), timelineRect.height() / 2 + TextOffset, QString::fromStdString(_currentTime.time)); + painter.drawLine( + QPointF(0, timelineRect.height() / 2), + QPointF(timelineRect.width(), timelineRect.height() / 2) + ); + painter.drawText( + timelineRect.width(), + timelineRect.height() / 2 + TextOffset, + QString::fromStdString(_currentTime.time) + ); } void TimelineWidget::drawLegend(QPainter& painter, QRectF rect) { @@ -171,14 +190,21 @@ void TimelineWidget::drawLegend(QPainter& painter, QRectF rect) { ; painter.setBrush(QBrush(InstrumentColors[QString::fromStdString(instrument)])); painter.setPen(QPen(InstrumentColors[QString::fromStdString(instrument)])); - painter.drawRect(currentHorizontalPosition, currentVerticalPosition, BoxSize, BoxSize); + painter.drawRect( + currentHorizontalPosition, + currentVerticalPosition, + BoxSize, + BoxSize + ); currentHorizontalPosition += BoxSize + Padding; painter.setPen(QPen(QColor(200, 200, 200))); //painter.setPen(QPen(Qt::black)); - painter.drawText(currentHorizontalPosition, currentVerticalPosition + BoxSize / 2 + TextOffset, InstrumentConversion[QString::fromStdString(instrument)]); -// int textWidth = painter.boundingRect(QRect(), QString::fromStdString(instrument)).width(); - //currentHorizontalPosition += std::max(textWidth, 25) + Padding; + painter.drawText( + currentHorizontalPosition, + currentVerticalPosition + BoxSize / 2 + TextOffset, + InstrumentConversion[QString::fromStdString(instrument)] + ); currentHorizontalPosition += 125; } } @@ -198,11 +224,12 @@ void TimelineWidget::drawImages( { std::set instrumentSet; for (Image* i : images) { - for (std::string instrument : i->instruments) + for (std::string instrument : i->instruments) { instrumentSet.insert(instrument); + } } std::map instruments; - for (std::set::const_iterator it = instrumentSet.begin(); it != instrumentSet.end(); ++it) + for (auto it = instrumentSet.begin(); it != instrumentSet.end(); ++it) instruments[*it] = std::distance(instrumentSet.begin(), it); for (Image* i : images) { @@ -215,8 +242,9 @@ void TimelineWidget::drawImages( int height = (timelineRect.top() + timelineRect.height() * tEnd) - loc; height = std::max(height, 5); - if (loc + height > timelineRect.height()) + if (loc + height > timelineRect.height()) { height = timelineRect.height() - loc; + } std::string target = i->target; auto it = std::find(_targets.begin(), _targets.end(), target); @@ -224,10 +252,13 @@ void TimelineWidget::drawImages( for (std::string instrument : i->instruments) { auto it = std::find(_instruments.begin(), _instruments.end(), instrument); - if (it == _instruments.end()) + if (it == _instruments.end()) { qDebug() << "Instrument not found"; + } - painter.setBrush(QBrush(InstrumentColors[QString::fromStdString(instrument)])); + painter.setBrush( + QBrush(InstrumentColors[QString::fromStdString(instrument)]) + ); double width = timelineRect.width() / instruments.size(); double pos = instruments[instrument] * width; @@ -238,7 +269,8 @@ void TimelineWidget::drawImages( if (height >= 5) { painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black)); - QString line = QString::fromStdString(i->beginningString) + QString(" (") + QString::fromStdString(i->target) + QString(")"); + QString line = QString::fromStdString(i->beginningString) + QString(" (") + + QString::fromStdString(i->target) + QString(")"); painter.drawText(timelineRect.width(), loc + height / 2 + TextOffset, line); } @@ -257,9 +289,16 @@ void TimelineWidget::socketDisconnected() { } std::string TimelineWidget::nextTarget() const { - auto it = std::lower_bound(_images.begin(), _images.end(), _currentTime.et, [](const Image& i, double et) { return i.beginning < et; }); - if (it != _images.end()) + auto it = std::lower_bound( + _images.begin(), + _images.end(), + _currentTime.et, + [](const Image& i, double et) { return i.beginning < et; } + ); + if (it != _images.end()) { return it->target; - else + } + else { return ""; + } } diff --git a/apps/TimelineView/timelinewidget.h b/apps/TimelineView/timelinewidget.h index ca0618f065..f20ee4e956 100644 --- a/apps/TimelineView/timelinewidget.h +++ b/apps/TimelineView/timelinewidget.h @@ -40,7 +40,8 @@ Q_OBJECT public: TimelineWidget(QWidget* parent); - void setData(std::vector images, std::map targetMap, std::map instrumentMap); + void setData(std::vector images, std::map targetMap, + std::map instrumentMap); void setCurrentTime(std::string currentTime, double et); void socketConnected(); void socketDisconnected(); @@ -51,7 +52,8 @@ protected: void paintEvent(QPaintEvent* event); void drawContent(QPainter& painter, QRectF rect); void drawLegend(QPainter& painter, QRectF rect); - void drawImages(QPainter& painter, QRectF timelineRect, std::vector images, double minimumTime, double maximumTime); + void drawImages(QPainter& painter, QRectF timelineRect, std::vector images, + double minimumTime, double maximumTime); private: std::vector _images; diff --git a/include/openspace/documentation/documentation.h b/include/openspace/documentation/documentation.h index 82cfcde267..2725272987 100644 --- a/include/openspace/documentation/documentation.h +++ b/include/openspace/documentation/documentation.h @@ -60,7 +60,7 @@ struct TestResult { ExtraKey, ///< The exhaustive documentation contained an extra key WrongType, ///< The key's value was not of the expected type Verification, ///< The value did not pass a necessary non-type verifier - UnknownIdentifier ///< If the identifier for a ReferencingVerifier did not exist + UnknownIdentifier ///< The identifier for a ReferencingVerifier did not exist }; /// The offending key that caused the Offense. In the case of a nested table, /// this value will be the fully qualified name of the key diff --git a/include/openspace/documentation/verifier.h b/include/openspace/documentation/verifier.h index 123f3ec1f3..a4113b818f 100644 --- a/include/openspace/documentation/verifier.h +++ b/include/openspace/documentation/verifier.h @@ -546,7 +546,9 @@ struct GreaterVerifier : public OperatorVerifier -struct GreaterEqualVerifier : public OperatorVerifier> { +struct GreaterEqualVerifier : public OperatorVerifier> +{ static_assert( !std::is_base_of::value, "T cannot be BoolVerifier" diff --git a/include/openspace/documentation/verifier.inl b/include/openspace/documentation/verifier.inl index 012591802c..81ec2cd14e 100644 --- a/include/openspace/documentation/verifier.inl +++ b/include/openspace/documentation/verifier.inl @@ -345,7 +345,9 @@ TestResult DeprecatedVerifier::operator()(const ghoul::Dictionary& dict, const std::string& key) const { TestResult res = T::operator()(dict, key); - res.warnings.push_back(TestResult::Warning{ key, TestResult::Warning::Reason::Deprecated }); + res.warnings.push_back( + TestResult::Warning{ key, TestResult::Warning::Reason::Deprecated } + ); return res; } diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h index d13734aee8..a07db7d5e2 100644 --- a/include/openspace/engine/configurationmanager.h +++ b/include/openspace/engine/configurationmanager.h @@ -131,9 +131,9 @@ public: static const std::string PartHttpProxyPort; /// The key that stores the authentication method of the http proxy static const std::string PartHttpProxyAuthentication; - /// The key that stores the username to use for authentication to access the http proxy + /// Key that stores the username to use for authentication to access the http proxy static const std::string PartHttpProxyUser; - /// The key that stores the password to use for authentication to access the http proxy + /// Key that stores the password to use for authentication to access the http proxy static const std::string PartHttpProxyPassword; /// The key that stores the dictionary containing information about debug contexts static const std::string KeyOpenGLDebugContext; diff --git a/include/openspace/engine/downloadmanager.h b/include/openspace/engine/downloadmanager.h index db7cff07ea..addce8435c 100644 --- a/include/openspace/engine/downloadmanager.h +++ b/include/openspace/engine/downloadmanager.h @@ -102,13 +102,13 @@ public: DownloadProgressCallback progressCallback = DownloadProgressCallback() ); - std::future fetchFile( - const std::string& url, - SuccessCallback successCallback = SuccessCallback(), ErrorCallback errorCallback = ErrorCallback()); + std::future fetchFile(const std::string& url, + SuccessCallback successCallback = SuccessCallback(), + ErrorCallback errorCallback = ErrorCallback()); - std::vector> downloadRequestFiles(const std::string& identifier, - const ghoul::filesystem::Directory& destination, int version, - bool overrideFiles = true, + std::vector> downloadRequestFiles( + const std::string& identifier, const ghoul::filesystem::Directory& destination, + int version, bool overrideFiles = true, DownloadFinishedCallback finishedCallback = DownloadFinishedCallback(), DownloadProgressCallback progressCallback = DownloadProgressCallback() ); diff --git a/include/openspace/interaction/touchbar.h b/include/openspace/interaction/touchbar.h index bff9985b43..99fdf4e977 100644 --- a/include/openspace/interaction/touchbar.h +++ b/include/openspace/interaction/touchbar.h @@ -27,7 +27,7 @@ namespace openspace { -// Initializes the touch bar on MacOS (if available) and creates all the buttons and +// Initializes the touch bar on MacOS (if available) and creates all the buttons and // callbacks void showTouchbar(); diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index 6d7c3d5d6a..b065f2d9d6 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -52,27 +52,51 @@ struct CameraKeyframe { double _timestamp; - void serialize(std::vector &buffer){ + void serialize(std::vector &buffer) { // Add position - buffer.insert(buffer.end(), reinterpret_cast(&_position), reinterpret_cast(&_position) + sizeof(_position)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_position), + reinterpret_cast(&_position) + sizeof(_position) + ); // Add orientation - buffer.insert(buffer.end(), reinterpret_cast(&_rotation), reinterpret_cast(&_rotation) + sizeof(_rotation)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_rotation), + reinterpret_cast(&_rotation) + sizeof(_rotation) + ); // Follow focus node rotation? - buffer.insert(buffer.end(), reinterpret_cast(&_followNodeRotation), reinterpret_cast(&_followNodeRotation) + sizeof(_followNodeRotation)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_followNodeRotation), + reinterpret_cast(&_followNodeRotation) + sizeof(_followNodeRotation) + ); int nodeNameLength = static_cast(_focusNode.size()); // Add focus node - buffer.insert(buffer.end(), reinterpret_cast(&nodeNameLength), reinterpret_cast(&nodeNameLength) + sizeof(nodeNameLength)); - buffer.insert(buffer.end(), _focusNode.data(), _focusNode.data() + nodeNameLength); + buffer.insert( + buffer.end(), + reinterpret_cast(&nodeNameLength), + reinterpret_cast(&nodeNameLength) + sizeof(nodeNameLength) + ); + buffer.insert( + buffer.end(), + _focusNode.data(), + _focusNode.data() + nodeNameLength + ); // Add timestamp - buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_timestamp), + reinterpret_cast(&_timestamp) + sizeof(_timestamp) + ); }; - void deserialize(const std::vector &buffer){ + void deserialize(const std::vector &buffer) { int offset = 0; int size = 0; @@ -120,19 +144,39 @@ struct TimeKeyframe { void serialize(std::vector &buffer){ // Add current time - buffer.insert(buffer.end(), reinterpret_cast(&_time), reinterpret_cast(&_time) + sizeof(_time)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_time), + reinterpret_cast(&_time) + sizeof(_time) + ); // Add delta time - buffer.insert(buffer.end(), reinterpret_cast(&_dt), reinterpret_cast(&_dt) + sizeof(_dt)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_dt), + reinterpret_cast(&_dt) + sizeof(_dt) + ); // Add whether time is paused or not - buffer.insert(buffer.end(), reinterpret_cast(&_paused), reinterpret_cast(&_paused) + sizeof(_paused)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_paused), + reinterpret_cast(&_paused) + sizeof(_paused) + ); // Add whether a time jump is necessary (recompute paths etc) - buffer.insert(buffer.end(), reinterpret_cast(&_requiresTimeJump), reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_requiresTimeJump), + reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump) + ); // Add timestamp - buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_timestamp), + reinterpret_cast(&_timestamp) + sizeof(_timestamp) + ); }; void deserialize(const std::vector &buffer){ diff --git a/include/openspace/network/networkengine.h b/include/openspace/network/networkengine.h index 8d0008b406..6d36f0d130 100644 --- a/include/openspace/network/networkengine.h +++ b/include/openspace/network/networkengine.h @@ -48,7 +48,8 @@ public: void sendMessages(); // Initial Connection Messages - void setInitialConnectionMessage(MessageIdentifier identifier, std::vector message); + void setInitialConnectionMessage(MessageIdentifier identifier, + std::vector message); void sendInitialInformation(); // Background diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index 890657363c..f894d1d817 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -53,8 +53,10 @@ public: bool isMeasuringPerformance() const; - void storeIndividualPerformanceMeasurement(std::string identifier, long long nanoseconds); - void storeScenePerformanceMeasurements(const std::vector& sceneNodes); + void storeIndividualPerformanceMeasurement(std::string identifier, + long long nanoseconds); + void storeScenePerformanceMeasurements( + const std::vector& sceneNodes); void outputLogs(); diff --git a/include/openspace/performance/performancemeasurement.h b/include/openspace/performance/performancemeasurement.h index 7815492e51..b45558be76 100644 --- a/include/openspace/performance/performancemeasurement.h +++ b/include/openspace/performance/performancemeasurement.h @@ -37,7 +37,8 @@ class PerformanceManager; class PerformanceMeasurement { public: - PerformanceMeasurement(std::string identifier, performance::PerformanceManager* manager); + PerformanceMeasurement(std::string identifier, + performance::PerformanceManager* manager); ~PerformanceMeasurement(); private: diff --git a/include/openspace/properties/numericalproperty.h b/include/openspace/properties/numericalproperty.h index 25abe7a01b..9bf680556c 100644 --- a/include/openspace/properties/numericalproperty.h +++ b/include/openspace/properties/numericalproperty.h @@ -34,9 +34,10 @@ class NumericalProperty : public TemplateProperty { public: NumericalProperty(Property::PropertyInfo info); NumericalProperty(Property::PropertyInfo info, T value); - NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, T maximumValue); - NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, T maximumValue, - T steppingValue); + NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, + T maximumValue); + NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, + T maximumValue, T steppingValue); bool getLuaValue(lua_State* state) const override; bool setLuaValue(lua_State* state) override; diff --git a/include/openspace/properties/selectionproperty.h b/include/openspace/properties/selectionproperty.h index f60d7b5217..81b6bd9973 100644 --- a/include/openspace/properties/selectionproperty.h +++ b/include/openspace/properties/selectionproperty.h @@ -63,22 +63,26 @@ std::string PropertyDelegate>>::className(); template <> template <> -std::vector PropertyDelegate>>::fromLuaValue(lua_State* state, bool& success); +std::vector PropertyDelegate>>::fromLuaValue( + lua_State* state, bool& success); template <> template <> -bool PropertyDelegate>>::toLuaValue(lua_State* state, std::vector value); +bool PropertyDelegate>>::toLuaValue( + lua_State* state, std::vector value); template <> int PropertyDelegate>>::typeLua(); template <> template <> -std::vector PropertyDelegate>>::fromString(std::string value, bool& success); +std::vector PropertyDelegate>>::fromString( + std::string value, bool& success); template <> template <> -bool PropertyDelegate>>::toString(std::string& outValue, std::vector inValue); +bool PropertyDelegate>>::toString( + std::string& outValue, std::vector inValue); } // namespace openspace::properties diff --git a/include/openspace/properties/templateproperty.inl b/include/openspace/properties/templateproperty.inl index 9569ecad35..32ecffb1ab 100644 --- a/include/openspace/properties/templateproperty.inl +++ b/include/openspace/properties/templateproperty.inl @@ -29,8 +29,8 @@ namespace openspace::properties { // The following macros can be used to quickly generate the necessary PropertyDelegate // specializations required by the TemplateProperty class. Use the // REGISTER_TEMPLATEPROPERTY_HEADER macro in the header file and the - // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new specialization of - // a TemplateProperty + // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new + // specialization of a TemplateProperty // CLASS_NAME = The string that the Property::className() should return as well as the diff --git a/include/openspace/rendering/abufferrenderer.h b/include/openspace/rendering/abufferrenderer.h index ce9c356e47..ad9d616cd9 100644 --- a/include/openspace/rendering/abufferrenderer.h +++ b/include/openspace/rendering/abufferrenderer.h @@ -111,7 +111,9 @@ private: * (id, namespace, etc) */ std::map _raycastData; - std::map> _boundsPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _boundsPrograms; std::vector _helperPaths; ghoul::Dictionary _resolveDictionary; diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index d38ed1ffd7..fa8051b36c 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -78,9 +78,15 @@ public: private: std::map _raycastData; - std::map> _exitPrograms; - std::map> _raycastPrograms; - std::map> _insideRaycastPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _exitPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _raycastPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _insideRaycastPrograms; std::unique_ptr _resolveProgram; diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index bef7b25d43..7f775f4138 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -58,7 +58,8 @@ public: Overlay = 8 }; - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); // constructors & destructor Renderable(const ghoul::Dictionary& dictionary); @@ -89,7 +90,8 @@ public: void onEnabledChange(std::function callback); - static void setPscUniforms(ghoul::opengl::ProgramObject& program, const Camera& camera, const PowerScaledCoordinate& position); + static void setPscUniforms(ghoul::opengl::ProgramObject& program, + const Camera& camera, const PowerScaledCoordinate& position); static documentation::Documentation Documentation(); diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index 7b76d55a22..6190d10e6b 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -127,7 +127,8 @@ public: std::string progressToStr(int size, double t); - void removeRenderProgram(const std::unique_ptr& program); + void removeRenderProgram( + const std::unique_ptr& program); /** * Set raycasting uniforms on the program object, and setup raycasting. diff --git a/include/openspace/rendering/transferfunction.h b/include/openspace/rendering/transferfunction.h index 2c462f7845..f317c1485f 100644 --- a/include/openspace/rendering/transferfunction.h +++ b/include/openspace/rendering/transferfunction.h @@ -38,7 +38,8 @@ class TransferFunction { public: typedef std::function TfChangedCallback; - TransferFunction(const std::string& filepath, TfChangedCallback tfChangedCallback = TfChangedCallback()); + TransferFunction(const std::string& filepath, + TfChangedCallback tfChangedCallback = TfChangedCallback()); void setPath(const std::string& filepath); ghoul::opengl::Texture& getTexture(); void bind(); diff --git a/include/openspace/rendering/volume.h b/include/openspace/rendering/volume.h index a9fda2e452..4e7eaa105c 100644 --- a/include/openspace/rendering/volume.h +++ b/include/openspace/rendering/volume.h @@ -50,16 +50,19 @@ public: /** * Render the volume's entry points (front face of the bounding geometry) */ - //virtual void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject* program) = 0; + //virtual void renderEntryPoints(const RenderData& data, + // ghoul::opengl::ProgramObject* program) = 0; /** * Render the volume's exit points (back face of the bounding geometry) */ - //virtual void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject* program) = 0; + //virtual void renderExitPoints(const RenderData& data, + // ghoul::opengl::ProgramObject* program) = 0; /** * Prepare the volume for the ABuffer's resolve step. - * Make sure textures are up to date, bind them to texture units, set program uniforms etc. + * Make sure textures are up to date, bind them to texture units, set program uniforms + * etc. */ //virtual void preRayCast(ghoul::opengl::ProgramObject* program) {}; @@ -83,8 +86,8 @@ public: //virtual std::string getBoundsVsPath() = 0; /* - * Return a path to a file with the functions, uniforms and fragment shader in variables - * required to generate the fragment color and depth. + * Return a path to a file with the functions, uniforms and fragment shader in + * variables required to generate the fragment color and depth. * * Should define the function: * Fragment getFragment() @@ -99,7 +102,8 @@ public: * required to perform ray casting through this volume. * * The header should define the following two functions: - * vec4 sampler#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, inout float maxStepSize) + * vec4 sampler#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, + * inout float maxStepSize) * (return color of sample) * float stepSize#{id}(vec3 samplePos, vec3 dir) * (return the preferred step size at this sample position) @@ -117,8 +121,8 @@ public: * regardless of how many volumes say they require the file. * Ideal to avoid redefinitions of helper functions. * - * The shader preprocessor will have access to the #{namespace} variable (unique per helper file) - * which should be a prefix to all symbols defined by the helper + * The shader preprocessor will have access to the #{namespace} variable (unique per + * helper file) which should be a prefix to all symbols defined by the helper */ //virtual std::string getHelperPath() = 0; diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index b01517a22b..7e1e60bfa0 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -49,30 +49,37 @@ public: /** * Render the volume's entry points (front face of the bounding geometry) */ - virtual void renderEntryPoints(const RenderData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) = 0; + virtual void renderEntryPoints(const RenderData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) = 0; /** * Render the volume's exit points (back face of the bounding geometry) */ - virtual void renderExitPoints(const RenderData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) = 0; + virtual void renderExitPoints(const RenderData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) = 0; /** * Prepare the volume for the ABuffer's resolve step. - * Make sure textures are up to date, bind them to texture units, set program uniforms etc. + * Make sure textures are up to date, bind them to texture units, set program uniforms + * etc. */ - virtual void preRaycast(const RaycastData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) {}; + virtual void preRaycast(const RaycastData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) {}; /** * Clean up for the volume after the ABuffer's resolve step. * Make sure texture units are deinitialized, etc. */ - virtual void postRaycast(const RaycastData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) {}; + virtual void postRaycast(const RaycastData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) {}; /** * Return true if the camera is inside the volume. - * Also set localPosition to the camera position in the volume's local coordainte system. + * Also set localPosition to the camera position in the volume's local coordinate + * system. */ - virtual bool cameraIsInside(const RenderData& /*data*/, glm::vec3& /*localPosition*/) { return false; }; + virtual bool cameraIsInside(const RenderData& /*data*/, + glm::vec3& /*localPosition*/) { return false; }; /** * Return a path the file to use as vertex shader @@ -83,8 +90,8 @@ public: virtual std::string getBoundsVsPath() const = 0; /* - * Return a path to a file with the functions, uniforms and fragment shader in variables - * required to generate the fragment color and depth. + * Return a path to a file with the functions, uniforms and fragment shader in + * variables required to generate the fragment color and depth. * * Should define the function: * Fragment getFragment() @@ -99,7 +106,8 @@ public: * required to perform ray casting through this volume. * * The header should define the following two functions: - * vec4 sample#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, inout float maxStepSize) + * vec4 sample#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, + * inout float maxStepSize) * (return color of sample) * float stepSize#{id}(vec3 samplePos, vec3 dir) * (return the preferred step size at this sample position) @@ -117,8 +125,8 @@ public: * regardless of how many volumes say they require the file. * Ideal to avoid redefinitions of helper functions. * - * The shader preprocessor will have access to the #{namespace} variable (unique per helper file) - * which should be a prefix to all symbols defined by the helper + * The shader preprocessor will have access to the #{namespace} variable (unique per + * helper file) which should be a prefix to all symbols defined by the helper */ virtual std::string getHelperPath() const = 0; }; diff --git a/include/openspace/scene/rotation.h b/include/openspace/scene/rotation.h index 18d1f0a7c1..9566e50ef6 100644 --- a/include/openspace/scene/rotation.h +++ b/include/openspace/scene/rotation.h @@ -41,7 +41,8 @@ namespace documentation { struct Documentation; } class Rotation : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Rotation(const ghoul::Dictionary& dictionary); virtual ~Rotation() = default; diff --git a/include/openspace/scene/scale.h b/include/openspace/scene/scale.h index a9f8cbd856..13948adcee 100644 --- a/include/openspace/scene/scale.h +++ b/include/openspace/scene/scale.h @@ -41,7 +41,8 @@ namespace documentation { struct Documentation; } class Scale : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Scale(); virtual ~Scale() = default; diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index f4d132cc15..f64441e9ad 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -61,7 +61,8 @@ public: * \param component The optional compoment that caused this exception to be thrown * \pre message may not be empty */ - explicit InvalidSceneError(const std::string& message, const std::string& component = ""); + explicit InvalidSceneError(const std::string& message, + const std::string& component = ""); }; // constructors & destructor @@ -118,12 +119,14 @@ public: /** * Add a node and all its children to the scene. */ - void addNode(SceneGraphNode* node, UpdateDependencies updateDeps = UpdateDependencies::Yes); + void addNode(SceneGraphNode* node, + UpdateDependencies updateDeps = UpdateDependencies::Yes); /** * Remove a node and all its children from the scene. */ - void removeNode(SceneGraphNode* node, UpdateDependencies updateDeps = UpdateDependencies::Yes); + void removeNode(SceneGraphNode* node, + UpdateDependencies updateDeps = UpdateDependencies::Yes); void addSceneLicense(SceneLicense license); diff --git a/include/openspace/scene/scenegraphnode.h b/include/openspace/scene/scenegraphnode.h index 0261328d6a..95be6e487f 100644 --- a/include/openspace/scene/scenegraphnode.h +++ b/include/openspace/scene/scenegraphnode.h @@ -73,7 +73,8 @@ public: SceneGraphNode(); ~SceneGraphNode(); - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); void initialize(); void deinitialize(); @@ -84,16 +85,21 @@ public: void render(const RenderData& data, RendererTasks& tasks); void updateCamera(Camera* camera) const; - void attachChild(std::unique_ptr child, UpdateScene updateScene = UpdateScene::Yes); - std::unique_ptr detachChild(SceneGraphNode& child, UpdateScene updateScene = UpdateScene::Yes); + void attachChild(std::unique_ptr child, + UpdateScene updateScene = UpdateScene::Yes); + std::unique_ptr detachChild(SceneGraphNode& child, + UpdateScene updateScene = UpdateScene::Yes); void setParent(SceneGraphNode& parent, UpdateScene updateScene = UpdateScene::Yes); - void addDependency(SceneGraphNode& dependency, UpdateScene updateScene = UpdateScene::Yes); - void removeDependency(SceneGraphNode& dependency, UpdateScene updateScene = UpdateScene::Yes); + void addDependency(SceneGraphNode& dependency, + UpdateScene updateScene = UpdateScene::Yes); + void removeDependency(SceneGraphNode& dependency, + UpdateScene updateScene = UpdateScene::Yes); void clearDependencies(UpdateScene updateScene = UpdateScene::Yes); - void setDependencies(const std::vector& dependencies, UpdateScene updateScene = UpdateScene::Yes); + void setDependencies(const std::vector& dependencies, + UpdateScene updateScene = UpdateScene::Yes); SurfacePositionHandle calculateSurfacePositionHandle( - const glm::dvec3& targetModelSpace); + const glm::dvec3& targetModelSpace); const std::vector& dependencies() const; const std::vector& dependentNodes() const; diff --git a/include/openspace/scene/sceneloader.h b/include/openspace/scene/sceneloader.h index 140bbc0f29..a605e4d8d0 100644 --- a/include/openspace/scene/sceneloader.h +++ b/include/openspace/scene/sceneloader.h @@ -59,7 +59,8 @@ public: /** * Import a scene graph node from a dictionary into an existing scene. */ - SceneGraphNode* importNodeDictionary(Scene& scene, const ghoul::Dictionary& dictionary); + SceneGraphNode* importNodeDictionary(Scene& scene, + const ghoul::Dictionary& dictionary); private: struct LoadedNode { @@ -99,7 +100,8 @@ private: /** * Load a mod file. */ - std::vector loadModule(const std::string& path, lua_State* luaState); + std::vector loadModule(const std::string& path, + lua_State* luaState); /** * Loads an existing license file @@ -120,7 +122,8 @@ private: /** * Add loaded nodes to an existing scene */ - std::vector addLoadedNodes(Scene& scene, std::vector&& nodes); + std::vector addLoadedNodes(Scene& scene, + std::vector&& nodes); }; } // namespace openspace diff --git a/include/openspace/scene/translation.h b/include/openspace/scene/translation.h index bcd7597c68..f685c55182 100644 --- a/include/openspace/scene/translation.h +++ b/include/openspace/scene/translation.h @@ -42,7 +42,8 @@ namespace documentation { struct Documentation; } class Translation : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Translation(); virtual ~Translation() = default; diff --git a/include/openspace/scripting/scriptengine.h b/include/openspace/scripting/scriptengine.h index 793e07f21d..0c5e120beb 100644 --- a/include/openspace/scripting/scriptengine.h +++ b/include/openspace/scripting/scriptengine.h @@ -91,11 +91,6 @@ public: std::vector allLuaFunctions() const; - //parallel functions - //bool parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script); - //bool shouldScriptBeSent(const std::string &library, const std::string &function); - //void cacheScript(const std::string &library, const std::string &function, const std::string &script); - static std::string OpenSpaceLibraryName; private: diff --git a/include/openspace/util/spicemanager.h b/include/openspace/util/spicemanager.h index aa38bd9c25..ac0693bf68 100644 --- a/include/openspace/util/spicemanager.h +++ b/include/openspace/util/spicemanager.h @@ -64,7 +64,7 @@ public: LightTime, ///< One-way light time (LT) LightTimeStellar, ///< One-way light time and stellar (LT+S) ConvergedNewtonian, ///< Converged newtonian light time (CN) - ConvergedNewtonianStellar ///< Converged newtonian + stellar (CN+S) + ConvergedNewtonianStellar ///< Converged newtonian+stellar (CN+S) }; /// The direction of the aberration correct enum class Direction { @@ -896,7 +896,8 @@ private: * position will be retrieved. If the coverage has ended, the last position will be * retrieved. If \p time is in a coverage gap, the position will be interpolated. * \param target The body which is missing SPK data for this time - * \param observer The observer. The position will be retrieved in relation to this body + * \param observer The observer. The position will be retrieved in relation to this + * body * \param referenceFrame The reference frame of the output position vector * \param aberrationCorrection The aberration correction used for the position * calculation diff --git a/include/openspace/util/syncbuffer.h b/include/openspace/util/syncbuffer.h index a64ee9191e..e3954d5202 100644 --- a/include/openspace/util/syncbuffer.h +++ b/include/openspace/util/syncbuffer.h @@ -52,7 +52,11 @@ public: ghoul_assert(_encodeOffset + size < _n, ""); int32_t length = static_cast(s.length()); - memcpy(_dataStream.data() + _encodeOffset, reinterpret_cast(&length), sizeof(int32_t)); + memcpy( + _dataStream.data() + _encodeOffset, + reinterpret_cast(&length), + sizeof(int32_t) + ); _encodeOffset += sizeof(int32_t); memcpy(_dataStream.data() + _encodeOffset, s.c_str(), length); _encodeOffset += length; @@ -69,7 +73,11 @@ public: std::string decode() { int32_t length; - memcpy(reinterpret_cast(&length), _dataStream.data() + _decodeOffset, sizeof(int32_t)); + memcpy( + reinterpret_cast(&length), + _dataStream.data() + _decodeOffset, + sizeof(int32_t) + ); char* tmp = new char[length + 1]; _decodeOffset += sizeof(int32_t); memcpy(tmp, _dataStream.data() + _decodeOffset, length); diff --git a/include/openspace/util/taskloader.h b/include/openspace/util/taskloader.h index 4081523c7d..63672bff0f 100644 --- a/include/openspace/util/taskloader.h +++ b/include/openspace/util/taskloader.h @@ -33,7 +33,8 @@ namespace openspace { class TaskLoader { public: - std::vector> tasksFromDictionary(const ghoul::Dictionary& dictionary); + std::vector> tasksFromDictionary( + const ghoul::Dictionary& dictionary); std::vector> tasksFromFile(const std::string& path); }; diff --git a/include/openspace/util/timeline.h b/include/openspace/util/timeline.h index 9c96f0b582..0798580e62 100644 --- a/include/openspace/util/timeline.h +++ b/include/openspace/util/timeline.h @@ -64,7 +64,8 @@ public: void removeKeyframe(size_t id); void removeKeyframesBefore(double timestamp, bool inclusive = false); void removeKeyframesAfter(double timestamp, bool inclusive = false); - void removeKeyframesBetween(double begin, double end, bool inclusiveBegin = false, bool inclusiveEnd = false); + void removeKeyframesBetween(double begin, double end, bool inclusiveBegin = false, + bool inclusiveEnd = false); size_t nKeyframes() const; const Keyframe* firstKeyframeAfter(double timestamp, bool inclusive = false) const; const Keyframe* lastKeyframeBefore(double timestamp, bool inclusive = false) const; diff --git a/include/openspace/util/timeline.inl b/include/openspace/util/timeline.inl index f3b4a3774f..1ed2d1d45a 100644 --- a/include/openspace/util/timeline.inl +++ b/include/openspace/util/timeline.inl @@ -35,15 +35,30 @@ Timeline::~Timeline() {} template void Timeline::addKeyframe(double timestamp, T data) { Keyframe keyframe(++_nextKeyframeId, timestamp, data); - auto iter = std::upper_bound(_keyframes.begin(), _keyframes.end(), keyframe, &compareKeyframeTimes); + auto iter = std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + keyframe, + &compareKeyframeTimes + ); _keyframes.insert(iter, keyframe); } template void Timeline::removeKeyframesAfter(double timestamp, bool inclusive) { auto iter = inclusive - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ); _keyframes.erase(iter, _keyframes.end()); } @@ -51,21 +66,53 @@ void Timeline::removeKeyframesAfter(double timestamp, bool inclusive) { template void Timeline::removeKeyframesBefore(double timestamp, bool inclusive) { auto iter = inclusive - ? std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime) - : std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime); + ? std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime) + ; _keyframes.erase(_keyframes.begin(), iter); } template -void Timeline::removeKeyframesBetween(double begin, double end, bool inclusiveBegin, bool inclusiveEnd) { +void Timeline::removeKeyframesBetween(double begin, double end, bool inclusiveBegin, + bool inclusiveEnd) +{ auto beginIter = inclusiveBegin - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), begin, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), begin, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + begin, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + begin, + &compareTimeWithKeyframeTime + ); auto endIter = inclusiveEnd - ? std::upper_bound(beginIter, _keyframes.end(), end, &compareTimeWithKeyframeTime) - : std::lower_bound(beginIter, _keyframes.end(), end, &compareKeyframeTimeWithTime); + ? std::upper_bound( + beginIter, + _keyframes.end(), + end, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + beginIter, + _keyframes.end(), + end, + &compareKeyframeTimeWithTime + ); _keyframes.erase(beginIter, endIter); } @@ -77,9 +124,14 @@ void Timeline::clearKeyframes() { template void Timeline::removeKeyframe(size_t id) { - _keyframes.erase(std::remove_if(_keyframes.begin(), _keyframes.end(), [id] (Keyframe keyframe) { - return keyframe.id == id; - }), _keyframes.end()); + _keyframes.erase( + std::remove_if( + _keyframes.begin(), + _keyframes.end(), + [id] (Keyframe keyframe) { return keyframe.id == id; } + ), + _keyframes.end() + ); } template @@ -88,10 +140,23 @@ size_t Timeline::nKeyframes() const { } template -const Keyframe* Timeline::firstKeyframeAfter(double timestamp, bool inclusive) const { +const Keyframe* Timeline::firstKeyframeAfter(double timestamp, + bool inclusive) const +{ auto it = inclusive - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ); + if (it == _keyframes.end()) { return nullptr; } @@ -99,10 +164,23 @@ const Keyframe* Timeline::firstKeyframeAfter(double timestamp, bool inclus } template -const Keyframe* Timeline::lastKeyframeBefore(double timestamp, bool inclusive) const { +const Keyframe* Timeline::lastKeyframeBefore(double timestamp, + bool inclusive) const +{ auto it = inclusive - ? std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime) - : std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime); + ? std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ); + if (it == _keyframes.begin()) { return nullptr; } @@ -116,6 +194,4 @@ const std::deque>& Timeline::keyframes() const { return _keyframes; } - -} - +} // namespace openspace diff --git a/include/openspace/util/timerange.h b/include/openspace/util/timerange.h index 90a532a64c..14da40957d 100644 --- a/include/openspace/util/timerange.h +++ b/include/openspace/util/timerange.h @@ -49,9 +49,11 @@ struct TimeRange { TimeRange(const ghoul::Dictionary& dict); /** - * \returns true if timeRange could be initialized from the dictionary, false otherwise. + * \returns true if timeRange could be initialized from the dictionary, + * false otherwise. */ - static bool initializeFromDictionary(const ghoul::Dictionary& dict, TimeRange& timeRange); + static bool initializeFromDictionary(const ghoul::Dictionary& dict, + TimeRange& timeRange); void include(double val); diff --git a/include/openspace/util/transformationmanager.h b/include/openspace/util/transformationmanager.h index 054933a67d..642aa182ad 100644 --- a/include/openspace/util/transformationmanager.h +++ b/include/openspace/util/transformationmanager.h @@ -59,10 +59,12 @@ public: TransformationManager(); ~TransformationManager(); - glm::dmat3 frameTransformationMatrix(const std::string& from, const std::string& to, double ephemerisTime) const; + glm::dmat3 frameTransformationMatrix(const std::string& from, const std::string& to, + double ephemerisTime) const; private: - glm::dmat3 kameleonTransformationMatrix(const std::string& from, const std::string& to, double ephemerisTime) const; + glm::dmat3 kameleonTransformationMatrix(const std::string& from, + const std::string& to, double ephemerisTime) const; #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED std::shared_ptr _kameleon; diff --git a/modules/base/rendering/screenspaceframebuffer.h b/modules/base/rendering/screenspaceframebuffer.h index 2b76d1ea09..0bb96c53d5 100644 --- a/modules/base/rendering/screenspaceframebuffer.h +++ b/modules/base/rendering/screenspaceframebuffer.h @@ -36,9 +36,12 @@ namespace openspace { namespace documentation { struct Documentation; } /** - * @brief Creates a texture by rendering to a framebuffer, this is then used on a screen space plane. - * @details This class lets you ass renderfunctions that should render to a framebuffer with an attached texture. - * The texture is then used on a screen space plane that works both in fisheye and flat screens. + * @brief Creates a texture by rendering to a framebuffer, this is then used on a screen + * space plane. + * @details This class lets you ass renderfunctions that should render to a framebuffer + * with an attached texture. + * The texture is then used on a screen space plane that works both in fisheye and flat + * screens. */ class ScreenSpaceFramebuffer : public ScreenSpaceRenderable { public: diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp index beb8a36a32..5d7b1e1f08 100644 --- a/modules/base/rotation/fixedrotation.cpp +++ b/modules/base/rotation/fixedrotation.cpp @@ -437,7 +437,7 @@ void FixedRotation::update(const UpdateData&) { { LWARNINGC( "FixedRotation", - "Dangerously collinear vectors detected: " << + "Dangerously collinear vectors detected: " << "x: " << x << " y: " << y << " z: " << z ); _matrix = glm::dmat3(); diff --git a/modules/digitaluniverse/digitaluniversemodule.cpp b/modules/digitaluniverse/digitaluniversemodule.cpp index 72fa1b0406..3d47edb9d9 100644 --- a/modules/digitaluniverse/digitaluniversemodule.cpp +++ b/modules/digitaluniverse/digitaluniversemodule.cpp @@ -40,7 +40,9 @@ namespace openspace { -DigitalUniverseModule::DigitalUniverseModule() : OpenSpaceModule(DigitalUniverseModule::Name) {} +DigitalUniverseModule::DigitalUniverseModule() + : OpenSpaceModule(DigitalUniverseModule::Name) +{} void DigitalUniverseModule::internalInitialize() { auto fRenderable = FactoryManager::ref().factory(); diff --git a/modules/fieldlines/rendering/renderablefieldlines.cpp b/modules/fieldlines/rendering/renderablefieldlines.cpp index 863a89d530..8fb00b0131 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.cpp +++ b/modules/fieldlines/rendering/renderablefieldlines.cpp @@ -265,7 +265,10 @@ void RenderableFieldlines::render(const RenderData& data, RendererTasks&) { _program->activate(); _program->setUniform("modelViewProjection", data.camera.viewProjectionMatrix()); _program->setUniform("modelTransform", glm::mat4(1.0)); - _program->setUniform("cameraViewDir", glm::vec3(data.camera.viewDirectionWorldSpace())); + _program->setUniform( + "cameraViewDir", + glm::vec3(data.camera.viewDirectionWorldSpace()) + ); glDisable(GL_CULL_FACE); setPscUniforms(*_program, data.camera, data.position); @@ -310,7 +313,11 @@ void RenderableFieldlines::update(const UpdateData&) { _lineStart.push_back(prevEnd); _lineCount.push_back(static_cast(fieldlines[j].size())); prevEnd = prevEnd + static_cast(fieldlines[j].size()); - vertexData.insert(vertexData.end(), fieldlines[j].begin(), fieldlines[j].end()); + vertexData.insert( + vertexData.end(), + fieldlines[j].begin(), + fieldlines[j].end() + ); } LDEBUG("Number of vertices : " << vertexData.size()); @@ -324,15 +331,34 @@ void RenderableFieldlines::update(const UpdateData&) { } glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, vertexData.size()*sizeof(LinePoint), &vertexData.front(), GL_STATIC_DRAW); + glBufferData( + GL_ARRAY_BUFFER, + vertexData.size() * sizeof(LinePoint), + &vertexData.front(), + GL_STATIC_DRAW + ); GLuint vertexLocation = 0; glEnableVertexAttribArray(vertexLocation); - glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(LinePoint), reinterpret_cast(0)); + glVertexAttribPointer( + vertexLocation, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(LinePoint), + reinterpret_cast(0) + ); GLuint colorLocation = 1; glEnableVertexAttribArray(colorLocation); - glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(LinePoint), (void*)(sizeof(glm::vec3))); + glVertexAttribPointer( + colorLocation, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(LinePoint), + (void*)(sizeof(glm::vec3)) + ); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); @@ -360,7 +386,9 @@ void RenderableFieldlines::loadSeedPointsFromFile() { std::ifstream seedFile(_seedPointSourceFile); if (!seedFile.good()) - LERROR("Could not open seed points file '" << _seedPointSourceFile.value() << "'"); + LERROR( + "Could not open seed points file '" << _seedPointSourceFile.value() << "'" + ); else { std::string line; glm::vec3 point; @@ -457,7 +485,13 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() _vectorFieldInfo.getValue(v3, zVariable); KameleonWrapper kw(fileName); - return kw.getClassifiedFieldLines(xVariable, yVariable, zVariable, _seedPoints, _stepSize); + return kw.getClassifiedFieldLines( + xVariable, + yVariable, + zVariable, + _seedPoints, + _stepSize + ); } if (lorentzForce) { diff --git a/modules/fieldlines/rendering/renderablefieldlines.h b/modules/fieldlines/rendering/renderablefieldlines.h index 1fc72680e4..c2701af6f9 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.h +++ b/modules/fieldlines/rendering/renderablefieldlines.h @@ -57,7 +57,6 @@ private: typedef std::vector Line; void initializeDefaultPropertyValues(); - //std::vector > getFieldlinesData(std::string filename, ghoul::Dictionary hintsDictionary); std::vector getFieldlinesData(); void loadSeedPoints(); void loadSeedPointsFromFile(); diff --git a/modules/fieldlinessequence/fieldlinessequencemodule.cpp b/modules/fieldlinessequence/fieldlinessequencemodule.cpp index 040625f1f9..fa9109c060 100644 --- a/modules/fieldlinessequence/fieldlinessequencemodule.cpp +++ b/modules/fieldlinessequence/fieldlinessequencemodule.cpp @@ -38,10 +38,10 @@ FieldlinesSequenceModule::FieldlinesSequenceModule() : OpenSpaceModule("FieldlinesSequence") {} void FieldlinesSequenceModule::internalInitialize() { - auto fRenderable = FactoryManager::ref().factory(); - ghoul_assert(fRenderable, "No renderable factory existed"); + auto factory = FactoryManager::ref().factory(); + ghoul_assert(factory, "No renderable factory existed"); - fRenderable->registerClass("RenderableFieldlinesSequence"); + factory->registerClass("RenderableFieldlinesSequence"); } } // namespace openspace diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index c75b589abf..65914800e0 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -78,9 +78,9 @@ void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks& // Calculate Model View MatrixProjection const glm::dmat4 rotMat = glm::dmat4(data.modelTransform.rotation); const glm::dmat4 modelMat = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - rotMat * - glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale))); + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + rotMat * + glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale))); const glm::dmat4 modelViewMat = data.camera.combinedViewMatrix() * modelMat; _shaderProgram->setUniform("modelViewProjection", @@ -232,12 +232,15 @@ void RenderableFieldlinesSequence::update(const UpdateData& data) { } } -inline bool RenderableFieldlinesSequence::isWithinSequenceInterval(const double currentTime) const { +inline bool RenderableFieldlinesSequence::isWithinSequenceInterval( + const double currentTime) const +{ return (currentTime >= _startTimes[0]) && (currentTime < _sequenceEndTime); } // Assumes we already know that currentTime is within the sequence interval -void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) { +void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) +{ auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime); if (iter != _startTimes.end()) { if ( iter != _startTimes.begin()) { diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h index 54f666b660..3c13d6d588 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h @@ -58,7 +58,8 @@ public: void update(const UpdateData& data) override; private: // ------------------------------------- ENUMS -------------------------------------// - enum ColorMethod : int { // Used to determine if lines should be colored UNIFORMLY or by an extraQuantity + // Used to determine if lines should be colored UNIFORMLY or by an extraQuantity + enum ColorMethod : int { Uniform = 0, ByQuantity }; @@ -67,73 +68,139 @@ private: std::string _name; // Name of the Node! // ------------------------------------- FLAGS -------------------------------------// - std::atomic _isLoadingStateFromDisk { false}; // Used for 'runtime-states'. True when loading a new state from disk on another thread. - bool _isReady = false; // If initialization proved successful - bool _loadingStatesDynamically = false; // False => states are stored in RAM (using 'in-RAM-states'), True => states are loaded from disk during runtime (using 'runtime-states') - bool _mustLoadNewStateFromDisk = false; // Used for 'runtime-states': True if new 'runtime-state' must be loaded from disk. False => the previous frame's state should still be shown - bool _needsUpdate = false; // Used for 'in-RAM-states' : True if new 'in-RAM-state' must be loaded. False => the previous frame's state should still be shown - std::atomic _newStateIsReady { false}; // Used for 'runtime-states'. True when finished loading a new state from disk on another thread. - bool _shouldUpdateColorBuffer = false; // True when new state is loaded or user change which quantity to color the lines by - bool _shouldUpdateMaskingBuffer = false; // True when new state is loaded or user change which quantity used for masking out line segments + // Used for 'runtime-states'. True when loading a new state from disk on another + // thread. + std::atomic _isLoadingStateFromDisk { false}; + // If initialization proved successful + bool _isReady = false; + // False => states are stored in RAM (using 'in-RAM-states'), True => states are + // loaded from disk during runtime (using 'runtime-states') + bool _loadingStatesDynamically = false; + // Used for 'runtime-states': True if new 'runtime-state' must be loaded from disk. + // False => the previous frame's state should still be shown + bool _mustLoadNewStateFromDisk = false; + // Used for 'in-RAM-states' : True if new 'in-RAM-state' must be loaded. + // False => the previous frame's state should still be shown + bool _needsUpdate = false; + // Used for 'runtime-states'. True when finished loading a new state from disk on + // another thread. + std::atomic _newStateIsReady = false; + // True when new state is loaded or user change which quantity to color the lines by + bool _shouldUpdateColorBuffer = false; + // True when new state is loaded or user change which quantity used for masking out + // line segments + bool _shouldUpdateMaskingBuffer = false; // --------------------------------- NUMERICALS ----------------------------------- // - int _activeStateIndex = -1; // Active index of _states. If(==-1)=>no state available for current time. Always the same as _activeTriggerTimeIndex if(_loadingStatesDynamically==true), else always = 0 - int _activeTriggerTimeIndex = -1; // Active index of _startTimes - size_t _nStates = 0; // Number of states in the sequence - float _scalingFactor = 1.f; // In setup it is used to scale JSON coordinates. During runtime it is used to scale domain limits. - double _sequenceEndTime; // Estimated end of sequence. - GLuint _vertexArrayObject = 0; // OpenGL Vertex Array Object - GLuint _vertexColorBuffer = 0; // OpenGL Vertex Buffer Object containing the extraQuantity values used for coloring the lines - GLuint _vertexMaskingBuffer = 0; // OpenGL Vertex Buffer Object containing the extraQuantity values used for masking out segments of the lines - GLuint _vertexPositionBuffer = 0; // OpenGL Vertex Buffer Object containing the vertex positions + // Active index of _states. If(==-1)=>no state available for current time. Always the + // same as _activeTriggerTimeIndex if(_loadingStatesDynamically==true), else + // always = 0 + int _activeStateIndex = -1; + // Active index of _startTimes + int _activeTriggerTimeIndex = -1; + // Number of states in the sequence + size_t _nStates = 0; + // In setup it is used to scale JSON coordinates. During runtime it is used to scale + // domain limits. + float _scalingFactor = 1.f; + // Estimated end of sequence. + double _sequenceEndTime; + // OpenGL Vertex Array Object + GLuint _vertexArrayObject = 0; + // OpenGL Vertex Buffer Object containing the extraQuantity values used for coloring + // the lines + GLuint _vertexColorBuffer = 0; + // OpenGL Vertex Buffer Object containing the extraQuantity values used for masking + // out segments of the lines + GLuint _vertexMaskingBuffer = 0; + // OpenGL Vertex Buffer Object containing the vertex positions + GLuint _vertexPositionBuffer = 0; // ----------------------------------- POINTERS ------------------------------------// - std::unique_ptr _dictionary; // The Lua-Modfile-Dictionary used during initialization - std::unique_ptr _newState; // Used for 'runtime-states' when switching out current state to a new state + // The Lua-Modfile-Dictionary used during initialization + std::unique_ptr _dictionary; + // Used for 'runtime-states' when switching out current state to a new state + std::unique_ptr _newState; std::unique_ptr _shaderProgram; - std::shared_ptr _transferFunction; // Transfer function used to color lines when _pColorMethod is set to BY_QUANTITY + // Transfer function used to color lines when _pColorMethod is set to BY_QUANTITY + std::shared_ptr _transferFunction; // ------------------------------------ VECTORS ----------------------------------- // - std::vector _colorTablePaths; // Paths to color tables. One for each 'extraQuantity' - std::vector _colorTableRanges; // Values represents min & max values represented in the color table - std::vector _maskingRanges; // Values represents min & max limits for valid masking range - std::vector _sourceFiles; // Stores the provided source file paths if using 'runtime-states', else emptied after initialization - std::vector _startTimes; // Contains the _triggerTimes for all FieldlineStates in the sequence - std::vector _states; // Stores the FieldlineStates + // Paths to color tables. One for each 'extraQuantity' + std::vector _colorTablePaths; + // Values represents min & max values represented in the color table + std::vector _colorTableRanges; + // Values represents min & max limits for valid masking range + std::vector _maskingRanges; + // Stores the provided source file paths if using 'runtime-states', else emptied after + // initialization + std::vector _sourceFiles; + // Contains the _triggerTimes for all FieldlineStates in the sequence + std::vector _startTimes; + // Stores the FieldlineStates + std::vector _states; // ---------------------------------- Properties ---------------------------------- // - properties::PropertyOwner _pColorGroup; // Group to hold the color properties - properties::OptionProperty _pColorMethod; // Uniform/transfer function/topology? - properties::OptionProperty _pColorQuantity; // Index of the extra quantity to color lines by - properties::StringProperty _pColorQuantityMin; // Color table/transfer function min - properties::StringProperty _pColorQuantityMax; // Color table/transfer function max - properties::StringProperty _pColorTablePath; // Color table/transfer function for "By Quantity" coloring - properties::Vec4Property _pColorUniform; // Uniform Field Line Color - properties::BoolProperty _pColorABlendEnabled; // Whether or not to use additive blending + // Group to hold the color properties + properties::PropertyOwner _pColorGroup; + // Uniform/transfer function/topology? + properties::OptionProperty _pColorMethod; + // Index of the extra quantity to color lines by + properties::OptionProperty _pColorQuantity; + // Color table/transfer function min + properties::StringProperty _pColorQuantityMin; + // Color table/transfer function max + properties::StringProperty _pColorQuantityMax; + // Color table/transfer function for "By Quantity" coloring + properties::StringProperty _pColorTablePath; + // Uniform Field Line Color + properties::Vec4Property _pColorUniform; + // Whether or not to use additive blending + properties::BoolProperty _pColorABlendEnabled; - properties::BoolProperty _pDomainEnabled; // Whether or not to use Domain - properties::PropertyOwner _pDomainGroup; // Group to hold the Domain properties - properties::Vec2Property _pDomainX; // Domain Limits along x-axis - properties::Vec2Property _pDomainY; // Domain Limits along y-axis - properties::Vec2Property _pDomainZ; // Domain Limits along z-axis - properties::Vec2Property _pDomainR; // Domain Limits radially +// Whether or not to use Domain + properties::BoolProperty _pDomainEnabled; + // Group to hold the Domain properties + properties::PropertyOwner _pDomainGroup; + // Domain Limits along x-axis + properties::Vec2Property _pDomainX; + // Domain Limits along y-axis + properties::Vec2Property _pDomainY; + // Domain Limits along z-axis + properties::Vec2Property _pDomainZ; + // Domain Limits radially + properties::Vec2Property _pDomainR; - properties::Vec4Property _pFlowColor; // Simulated particles' color - properties::BoolProperty _pFlowEnabled; // Toggle flow [ON/OFF] - properties::PropertyOwner _pFlowGroup; // Group to hold the flow/particle properties - properties::IntProperty _pFlowParticleSize; // Size of simulated flow particles - properties::IntProperty _pFlowParticleSpacing; // Size of simulated flow particles - properties::BoolProperty _pFlowReversed; // Toggle flow direction [FORWARDS/BACKWARDS] - properties::IntProperty _pFlowSpeed; // Speed of simulated flow +// Simulated particles' color + properties::Vec4Property _pFlowColor; + // Toggle flow [ON/OFF] + properties::BoolProperty _pFlowEnabled; + // Group to hold the flow/particle properties + properties::PropertyOwner _pFlowGroup; + // Size of simulated flow particles + properties::IntProperty _pFlowParticleSize; + // Size of simulated flow particles + properties::IntProperty _pFlowParticleSpacing; + // Toggle flow direction [FORWARDS/BACKWARDS] + properties::BoolProperty _pFlowReversed; + // Speed of simulated flow + properties::IntProperty _pFlowSpeed; - properties::BoolProperty _pMaskingEnabled; // Whether or not to use masking - properties::PropertyOwner _pMaskingGroup; // Group to hold the masking properties - properties::StringProperty _pMaskingMin; // Lower limit for allowed values - properties::StringProperty _pMaskingMax; // Upper limit for allowed values - properties::OptionProperty _pMaskingQuantity; // Index of the extra quantity to use for masking +// Whether or not to use masking + properties::BoolProperty _pMaskingEnabled; + // Group to hold the masking properties + properties::PropertyOwner _pMaskingGroup; + // Lower limit for allowed values + properties::StringProperty _pMaskingMin; + // Upper limit for allowed values + properties::StringProperty _pMaskingMax; + // Index of the extra quantity to use for masking + properties::OptionProperty _pMaskingQuantity; - properties::TriggerProperty _pFocusOnOriginBtn; // Button which sets camera focus to parent node of the renderable - properties::TriggerProperty _pJumpToStartBtn; // Button which executes a time jump to start of sequence +// Button which sets camera focus to parent node of the renderable + properties::TriggerProperty _pFocusOnOriginBtn; + // Button which executes a time jump to start of sequence + properties::TriggerProperty _pJumpToStartBtn; // --------------------- FUNCTIONS USED DURING INITIALIZATION --------------------- // void addStateToSequence(FieldlinesState& STATE); @@ -147,7 +214,8 @@ private: bool extractMandatoryInfoFromDictionary(SourceFileType& sourceFileType); void extractOptionalInfoFromDictionary(std::string& outputFolderPath); void extractOsflsInfoFromDictionary(); - bool extractSeedPointsFromFile(const std::string& path, std::vector& outVec); + bool extractSeedPointsFromFile(const std::string& path, + std::vector& outVec); void extractTriggerTimesFromFileNames(); bool loadJsonStatesIntoRAM(const std::string& outputFolder); void loadOsflsStatesIntoRAM(const std::string& outputFolder); diff --git a/modules/fieldlinessequence/util/fieldlinesstate.cpp b/modules/fieldlinessequence/util/fieldlinesstate.cpp index 3d61f1c384..51c8b7b0d9 100644 --- a/modules/fieldlinessequence/util/fieldlinesstate.cpp +++ b/modules/fieldlinessequence/util/fieldlinesstate.cpp @@ -33,7 +33,7 @@ #include namespace { - std::string _loggerCat = "FieldlinesState"; + const char* _loggerCat = "FieldlinesState"; const int CurrentVersion = 0; using json = nlohmann::json; } @@ -99,7 +99,8 @@ bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { ifs.read( reinterpret_cast(&byteSizeAllNames), sizeof(size_t)); // RESERVE/RESIZE vectors - // TODO: Do this without initializing values? Resize is slower than just using reserve, due to initialization of all values + // TODO: Do this without initializing values? Resize is slower than just using + // reserve, due to initialization of all values _lineStart.resize(nLines); _lineCount.resize(nLines); _vertexPositions.resize(nPoints); @@ -107,9 +108,12 @@ bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { _extraQuantityNames.reserve(nExtras); // Read vertex position data - ifs.read( reinterpret_cast(_lineStart.data()), sizeof(GLint)*nLines); - ifs.read( reinterpret_cast(_lineCount.data()), sizeof(GLsizei)*nLines); - ifs.read( reinterpret_cast(_vertexPositions.data()), sizeof(glm::vec3)*nPoints); + ifs.read( reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); + ifs.read( reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); + ifs.read( + reinterpret_cast(_vertexPositions.data()), + sizeof(glm::vec3) * nPoints + ); // Read all extra quantities for (std::vector& vec : _extraQuantities) { @@ -168,8 +172,10 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, const size_t nPosComponents = 3; // x,y,z if (nVariables < nPosComponents) { - LERROR(pathToJsonFile + ": Each field '" + sColumns + - "' must contain the variables: 'x', 'y' and 'z' (order is important)."); + LERROR( + pathToJsonFile + ": Each field '" + sColumns + + "' must contain the variables: 'x', 'y' and 'z' (order is important)." + ); return false; } @@ -215,19 +221,27 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, * @param absPath must be the path to the file (incl. filename but excl. extension!) * Directory must exist! File is created (or overwritten if already existing). * File is structured like this: (for version 0) - * 0. int - version number of binary state file! (in case something needs to be altered in the future, then increase CurrentVersion) + * 0. int - version number of binary state file! (in case something + * needs to be altered in the future, then increase + * CurrentVersion) * 1. double - _triggerTime * 2. int - _model * 3. bool - _isMorphable - * 4. size_t - Number of lines in the state == _lineStart.size() == _lineCount.size() - * 5. size_t - Total number of vertex points == _vertexPositions.size() == _extraQuantities[i].size() - * 6. size_t - Number of extra quantites == _extraQuantities.size() == _extraQuantityNames.size() - * 7. site_t - Number of total bytes that ALL _extraQuantityNames consists of (Each such name is stored as a c_str which means it ends with the null char '\0' ) + * 4. size_t - Number of lines in the state == _lineStart.size() + * == _lineCount.size() + * 5. size_t - Total number of vertex points == _vertexPositions.size() + * == _extraQuantities[i].size() + * 6. size_t - Number of extra quantites == _extraQuantities.size() + * == _extraQuantityNames.size() + * 7. site_t - Number of total bytes that ALL _extraQuantityNames + * consists of (Each such name is stored as a c_str which + * means it ends with the null char '\0' ) * 7. std::vector - _lineStart * 8. std::vector - _lineCount * 9. std::vector - _vertexPositions * 10. std::vector - _extraQuantities - * 11. array of c_str - Strings naming the extra quantities (elements of _extraQuantityNames). Each string ends with null char '\0' + * 11. array of c_str - Strings naming the extra quantities (elements of + * _extraQuantityNames). Each string ends with null char '\0' */ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { // ------------------------------- Create the file ------------------------------- // @@ -246,7 +260,7 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { // --------- Add each string of _extraQuantityNames into one long string --------- // std::string allExtraQuantityNamesInOne = ""; for (std::string str : _extraQuantityNames) { - allExtraQuantityNamesInOne += str + '\0'; // Add the null char '\0' for easier reading + allExtraQuantityNamesInOne += str + '\0'; // Add null char '\0' for easier reading } const size_t nLines = _lineStart.size(); @@ -254,24 +268,27 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { const size_t nExtras = _extraQuantities.size(); const size_t nStringBytes = allExtraQuantityNamesInOne.size(); - //------------------------------ WRITE EVERYTHING TO FILE ------------------------------ - // WHICH VERSION OF BINARY FIELDLINES STATE FILE - IN CASE STRUCTURE CHANGES IN THE FUTURE + //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- + // VERSION OF BINARY FIELDLINES STATE FILE - IN CASE STRUCTURE CHANGES IN THE FUTURE ofs.write( (char*)(&CurrentVersion), sizeof( int ) ); //-------------------- WRITE META DATA FOR STATE -------------------------------- - ofs.write( reinterpret_cast(&_triggerTime), sizeof( _triggerTime ) ); - ofs.write( reinterpret_cast(&_model), sizeof( int ) ); - ofs.write( reinterpret_cast(&_isMorphable), sizeof( bool ) ); + ofs.write(reinterpret_cast(&_triggerTime), sizeof( _triggerTime )); + ofs.write(reinterpret_cast(&_model), sizeof( int )); + ofs.write(reinterpret_cast(&_isMorphable), sizeof( bool )); - ofs.write( reinterpret_cast(&nLines), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nPoints), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nExtras), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nStringBytes), sizeof( size_t ) ); + ofs.write(reinterpret_cast(&nLines), sizeof( size_t )); + ofs.write(reinterpret_cast(&nPoints), sizeof( size_t )); + ofs.write(reinterpret_cast(&nExtras), sizeof( size_t )); + ofs.write(reinterpret_cast(&nStringBytes), sizeof( size_t )); //---------------------- WRITE ALL ARRAYS OF DATA -------------------------------- - ofs.write( reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); - ofs.write( reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); - ofs.write( reinterpret_cast(_vertexPositions.data()), sizeof(glm::vec3) * nPoints); + ofs.write(reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); + ofs.write(reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); + ofs.write( + reinterpret_cast(_vertexPositions.data()), + sizeof(glm::vec3) * nPoints + ); // Write the data for each vector in _extraQuantities for (std::vector& vec : _extraQuantities) { ofs.write( reinterpret_cast(vec.data()), sizeof(float) * nPoints); @@ -279,23 +296,27 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { ofs.write( allExtraQuantityNamesInOne.c_str(), nStringBytes); } -// TODO: This should probably be rewritten, but this is the way the files were structured by CCMC +// TODO: This should probably be rewritten, but this is the way the files were structured +// by CCMC // Structure of File! NO TRAILING COMMAS ALLOWED! -// Additional info can be stored within each line as the code only extracts the keys it needs (time, trace & data) +// Additional info can be stored within each line as the code only extracts the keys it +// needs (time, trace & data) // The key/name of each line ("0" & "1" in the example below) is arbitrary // { // "0":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX", // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], -// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],...,[8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] +// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., +// [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // }, // "1":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], -// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],...,[8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] +// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., +// [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // } // } @@ -343,7 +364,7 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { }; } - //------------------------------ WRITE EVERYTHING TO FILE ------------------------------ + //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- const int indentationSpaces = 2; ofs << std::setw(indentationSpaces) << jFile << std::endl; @@ -351,7 +372,7 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { } // Returns one of the extra quantity vectors, _extraQuantities[index]. -// If index is out of scope an empty vector is returned and the referenced bool will be false. +// If index is out of scope an empty vector is returned and the referenced bool is false. const std::vector& FieldlinesState::extraQuantity(const size_t index, bool& isSuccessful) const { if (index < _extraQuantities.size()) { @@ -364,16 +385,20 @@ const std::vector& FieldlinesState::extraQuantity(const size_t index, return std::vector(); } -/** Moves the points in @param line over to _vertexPositions and updates _lineStart & _lineCount accordingly. - */ +// Moves the points in @param line over to _vertexPositions and updates +// _lineStart & _lineCount accordingly. + void FieldlinesState::addLine(std::vector& line) { const size_t nNewPoints = line.size(); const size_t nOldPoints = _vertexPositions.size(); _lineStart.push_back(static_cast(nOldPoints)); _lineCount.push_back(static_cast(nNewPoints)); _vertexPositions.reserve(nOldPoints + nNewPoints); - _vertexPositions.insert(_vertexPositions.end(), std::make_move_iterator(line.begin()), - std::make_move_iterator(line.end())); + _vertexPositions.insert( + _vertexPositions.end(), + std::make_move_iterator(line.begin()), + std::make_move_iterator(line.end()) + ); line.clear(); } @@ -382,4 +407,37 @@ void FieldlinesState::setExtraQuantityNames(std::vector& names) { names.clear(); _extraQuantities.resize(_extraQuantityNames.size()); } + +const std::vector>& FieldlinesState::extraQuantities() const { + return _extraQuantities; +} + +const std::vector& FieldlinesState::extraQuantityNames() const { + return _extraQuantityNames; +} + +const std::vector& FieldlinesState::lineCount() const { + return _lineCount; +} + +const std::vector& FieldlinesState::lineStart() const { + return _lineStart; +} + +fls::Model FieldlinesState::FieldlinesState::model() const { + return _model; +} + +size_t FieldlinesState::nExtraQuantities() const { + return _extraQuantities.size(); +} + +double FieldlinesState::triggerTime() const { + return _triggerTime; +} + +const std::vector& FieldlinesState::vertexPositions() const { + return _vertexPositions; +} + } // namespace openspace diff --git a/modules/fieldlinessequence/util/fieldlinesstate.h b/modules/fieldlinessequence/util/fieldlinesstate.h index 35b1fb9db3..66d417deff 100644 --- a/modules/fieldlinessequence/util/fieldlinesstate.h +++ b/modules/fieldlinessequence/util/fieldlinesstate.h @@ -54,14 +54,14 @@ public: void saveStateToJson(const std::string& pathToJsonFile); // ----------------------------------- GETTERS ----------------------------------- // - const std::vector>& extraQuantities() const { return _extraQuantities; } - const std::vector& extraQuantityNames() const { return _extraQuantityNames; } - const std::vector& lineCount() const { return _lineCount; } - const std::vector& lineStart() const { return _lineStart; } - fls::Model model() const { return _model; } - size_t nExtraQuantities() const { return _extraQuantities.size(); } - double triggerTime() const { return _triggerTime; } - const std::vector& vertexPositions() const { return _vertexPositions; } + const std::vector>& extraQuantities() const; + const std::vector& extraQuantityNames() const; + const std::vector& lineCount() const; + const std::vector& lineStart() const; + fls::Model model() const; + size_t nExtraQuantities() const; + double triggerTime() const; + const std::vector& vertexPositions() const; // Special getter. Returns extraQuantities[INDEX]. const std::vector& extraQuantity(const size_t INDEX, bool& isSuccesful) const; diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp index 283207ec1c..be5a64d975 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp @@ -42,7 +42,8 @@ namespace { const std::string TAsPOverRho = "T = p/rho"; const std::string JParallelB = "Current: mag(J||B)"; - const float ToKelvin = 72429735.6984f; // <-- [nPa]/[amu/cm^3] * ToKelvin => Temperature in Kelvin + // [nPa]/[amu/cm^3] * ToKelvin => Temperature in Kelvin + const float ToKelvin = 72429735.6984f; } namespace openspace { @@ -63,14 +64,20 @@ namespace fls { #endif // OPENSPACE_MODULE_KAMELEON_ENABLED // ----------------------------------------------------------------------------------- // -/** Traces field lines from the provided cdf file using kameleon and stores the data in the provided FieldlinesState. - * Returns `false` if it fails to create a valid state. Requires the kameleon module to be activated! +/** Traces field lines from the provided cdf file using kameleon and stores the data in + * the provided FieldlinesState. + * Returns `false` if it fails to create a valid state. Requires the kameleon module to be + * activated! * @param state, FieldlineState which should hold the extracted data * @param cdfPath, std::string of the absolute path to a .cdf file * @param seedPoints, vector of seed points from which to trace field lines - * @param tracingVar, which quantity to trace lines from. Typically "b" for magnetic field lines and "u" for velocity flow lines - * @param extraVars, extra scalar quantities to be stored in the FieldlinesState; e.g. "T" for temperature, "rho" for density or "P" for pressure - * @param extraMagVars, variables which should be used for extracting magnitudes, must be a multiple of 3; e.g. "ux", "uy" & "uz" to get the magnitude of the velocity vector at each line vertex + * @param tracingVar, which quantity to trace lines from. Typically "b" for magnetic field + * lines and "u" for velocity flow lines + * @param extraVars, extra scalar quantities to be stored in the FieldlinesState; e.g. "T" + * for temperature, "rho" for density or "P" for pressure + * @param extraMagVars, variables which should be used for extracting magnitudes, must be + * a multiple of 3; e.g. "ux", "uy" & "uz" to get the magnitude of the velocity + * vector at each line vertex */ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string cdfPath, const std::vector& seedPoints, @@ -118,7 +125,8 @@ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string cdfPa #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED /** * Traces and adds line vertices to state. - * Vertices are not scaled to meters nor converted from spherical into cartesian coordinates. + * Vertices are not scaled to meters nor converted from spherical into cartesian + * coordinates. * Note that extraQuantities will NOT be set! */ bool addLinesToState(ccmc::Kameleon* kameleon, const std::vector& seedPoints, @@ -184,8 +192,9 @@ bool addLinesToState(ccmc::Kameleon* kameleon, const std::vector& see * coordinate system)! * * @param kameleon raw pointer to an already opened Kameleon object - * @param extraScalarVars vector of strings. Strings should be names of a scalar quantities - * to load into _extraQuantites; such as: "T" for temperature or "rho" for density. + * @param extraScalarVars vector of strings. Strings should be names of a scalar + * quantities to load into _extraQuantites; such as: "T" for temperature or "rho" for + * density. * @param extraMagVars vector of strings. Size must be multiple of 3. Strings should be * names of the components needed to calculate magnitude. E.g. {"ux", "uy", "uz"} will * calculate: sqrt(ux*ux + uy*uy + uz*uz). Magnitude will be stored in _extraQuantities @@ -256,8 +265,10 @@ void addExtraQuantities(ccmc::Kameleon* kameleon, * _extraQuantityNames vector. * * @param kameleon, raw pointer to an already opened kameleon object - * @param extraScalarVars, names of scalar quantities to add to state; e.g "rho" for density - * @param extraMagVars, names of the variables used for calculating magnitudes. Must be multiple of 3. + * @param extraScalarVars, names of scalar quantities to add to state; e.g "rho" for + * density + * @param extraMagVars, names of the variables used for calculating magnitudes. Must be + * multiple of 3. */ #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, @@ -271,7 +282,8 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, // Remove non-existing variables from vector for (int i = 0; i < extraScalarVars.size(); i++) { std::string& str = extraScalarVars[i]; - bool isSuccesful = kameleon->doesVariableExist(str) && kameleon->loadVariable(str); + bool isSuccesful = kameleon->doesVariableExist(str) && + kameleon->loadVariable(str); if (!isSuccesful && (model == fls::Model::Batsrus && (str == TAsPOverRho || str == "T" ))) { LDEBUG("BATSRUS doesn't contain variable T for temperature. Trying to " @@ -321,7 +333,10 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, LWARNING("FAILED TO LOAD AT LEAST ONE OF THE MAGNITUDE VARIABLES: " << s1 << ", " << s2 << " & " << s3 << ". Removing ability to store corresponding magnitude!"); - extraMagVars.erase(extraMagVars.begin() + i, extraMagVars.begin() + i + 3); + extraMagVars.erase( + extraMagVars.begin() + i, + extraMagVars.begin() + i + 3 + ); i -= 3; } else { extraQuantityNames.push_back(name); diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index f3ea1a32e2..1e70c70b4b 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -52,11 +52,16 @@ public: virtual ~GalaxyRaycaster(); void initialize(); void deinitialize(); - void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - void postRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - bool cameraIsInside(const RenderData& data, glm::vec3& localPosition) override; + void renderEntryPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void renderExitPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void preRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + void postRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + bool cameraIsInside(const RenderData& data, + glm::vec3& localPosition) override; std::string getBoundsVsPath() const override; diff --git a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp index eb8b61c0be..9428186f62 100644 --- a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp +++ b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp @@ -51,7 +51,8 @@ std::string MilkywayPointsConversionTask::description() return std::string(); } -void MilkywayPointsConversionTask::perform(const Task::ProgressCallback & progressCallback) { +void MilkywayPointsConversionTask::perform(const Task::ProgressCallback& progressCallback) +{ std::ifstream in(_inFilename, std::ios::in); std::ofstream out(_outFilename, std::ios::out | std::ios::binary); diff --git a/modules/globebrowsing/cache/texturecontainer.cpp b/modules/globebrowsing/cache/texturecontainer.cpp index a1006be9a5..a6bdd9cb9e 100644 --- a/modules/globebrowsing/cache/texturecontainer.cpp +++ b/modules/globebrowsing/cache/texturecontainer.cpp @@ -75,7 +75,9 @@ ghoul::opengl::Texture* TextureContainer::getTextureIfFree() { return texture; } -const openspace::globebrowsing::TileTextureInitData& TextureContainer::tileTextureInitData() const { +const openspace::globebrowsing::TileTextureInitData& +TextureContainer::tileTextureInitData() const +{ return _initData; } diff --git a/modules/globebrowsing/chunk/chunk.cpp b/modules/globebrowsing/chunk/chunk.cpp index 19c0799545..215283b33a 100644 --- a/modules/globebrowsing/chunk/chunk.cpp +++ b/modules/globebrowsing/chunk/chunk.cpp @@ -62,7 +62,14 @@ bool Chunk::isVisible() const { Chunk::Status Chunk::update(const RenderData& data) { const auto& savedCamera = _owner.savedCamera(); const Camera& camRef = savedCamera != nullptr ? *savedCamera : data.camera; - RenderData myRenderData = { camRef, data.position, data.time, data.doPerformanceMeasurement, data.renderBinMask, data.modelTransform }; + RenderData myRenderData = { + camRef, + data.position, + data.time, + data.doPerformanceMeasurement, + data.renderBinMask, + data.modelTransform + }; _isVisible = true; if (_owner.chunkedLodGlobe()->testIfCullable(*this, myRenderData)) { @@ -100,7 +107,9 @@ Chunk::BoundingHeights Chunk::getBoundingHeights() const { // a single raster image. If it is not we will just use the first raster // (that is channel 0). const size_t HeightChannel = 0; - const LayerGroup& heightmaps = layerManager->layerGroup(layergroupid::GroupID::HeightLayers); + const LayerGroup& heightmaps = layerManager->layerGroup( + layergroupid::GroupID::HeightLayers + ); std::vector chunkTileSettingPairs = tileselector::getTilesAndSettingsUnsorted( heightmaps, _tileIndex); diff --git a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp index 5760f519c0..d8abd70f72 100644 --- a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp +++ b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp @@ -64,7 +64,7 @@ int ProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) c // oo // [ ]< // *geodetic space* - // + // // closestCorner // +-----------------+ <-- north east corner // | | diff --git a/modules/globebrowsing/chunk/culling/frustumculler.cpp b/modules/globebrowsing/chunk/culling/frustumculler.cpp index 3d23475162..8c9eeab47a 100644 --- a/modules/globebrowsing/chunk/culling/frustumculler.cpp +++ b/modules/globebrowsing/chunk/culling/frustumculler.cpp @@ -38,8 +38,9 @@ bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { // Calculate the MVP matrix glm::dmat4 modelTransform = chunk.owner().modelTransform(); glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); - glm::dmat4 modelViewProjectionTransform = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) - * viewTransform * modelTransform; + glm::dmat4 modelViewProjectionTransform = glm::dmat4( + data.camera.sgctInternal.projectionMatrix() + ) * viewTransform * modelTransform; const std::vector& corners = chunk.getBoundingPolyhedronCorners(); @@ -50,7 +51,9 @@ bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { glm::dvec4 cornerClippingSpace = modelViewProjectionTransform * corners[i]; clippingSpaceCorners[i] = cornerClippingSpace; - glm::dvec3 ndc = glm::dvec3((1.0f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace); + glm::dvec3 ndc = glm::dvec3( + (1.f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace + ); bounds.expand(ndc); } diff --git a/modules/globebrowsing/geometry/ellipsoid.cpp b/modules/globebrowsing/geometry/ellipsoid.cpp index d679960709..a3bff9491e 100644 --- a/modules/globebrowsing/geometry/ellipsoid.cpp +++ b/modules/globebrowsing/geometry/ellipsoid.cpp @@ -81,7 +81,9 @@ glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { return p / d; } -glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const { +glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint( + const glm::dvec3& p) const +{ glm::dvec3 normal = p * _cached._oneOverRadiiSquared; return glm::normalize(normal); } diff --git a/modules/globebrowsing/geometry/ellipsoid.h b/modules/globebrowsing/geometry/ellipsoid.h index ee7d53bae0..de16801b09 100644 --- a/modules/globebrowsing/geometry/ellipsoid.h +++ b/modules/globebrowsing/geometry/ellipsoid.h @@ -36,8 +36,8 @@ namespace openspace::globebrowsing { * This class is based largely on the Ellipsoid class defined in the book * "3D Engine Design for Virtual Globes". Most planets or planetary objects are better * described using ellipsoids than spheres. All inputs and outputs to this class is - * based on the WGS84 standard coordinate system where the x-axis points towards geographic - * (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the + * based on the WGS84 standard coordinate system where the x-axis points towards + * geographic (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the * z-axis points towards the north pole. For other globes than earth of course the radii * can differ. */ @@ -64,7 +64,8 @@ public: */ glm::dvec3 geodeticSurfaceProjection(const glm::dvec3& p) const; - glm::dvec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const; + glm::dvec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint( + const glm::dvec3& p) const; glm::dvec3 geodeticSurfaceNormal(Geodetic2 geodetic2) const; const glm::dvec3& radii() const; diff --git a/modules/globebrowsing/geometry/geodeticpatch.cpp b/modules/globebrowsing/geometry/geodeticpatch.cpp index 3258e96a43..28a9d891b4 100644 --- a/modules/globebrowsing/geometry/geodeticpatch.cpp +++ b/modules/globebrowsing/geometry/geodeticpatch.cpp @@ -48,9 +48,14 @@ GeodeticPatch::GeodeticPatch(const GeodeticPatch& patch) {} GeodeticPatch::GeodeticPatch(const TileIndex& tileIndex) { - double deltaLat = (2 * glm::pi()) / (static_cast(1 << tileIndex.level)); - double deltaLon = (2 * glm::pi()) / (static_cast(1 << tileIndex.level)); - Geodetic2 nwCorner(glm::pi() / 2 - deltaLat * tileIndex.y, -glm::pi() + deltaLon * tileIndex.x); + double deltaLat = (2 * glm::pi()) / + (static_cast(1 << tileIndex.level)); + double deltaLon = (2 * glm::pi()) / + (static_cast(1 << tileIndex.level)); + Geodetic2 nwCorner( + glm::pi() / 2 - deltaLat * tileIndex.y, + -glm::pi() + deltaLon * tileIndex.x + ); _halfSize = Geodetic2(deltaLat / 2, deltaLon / 2); _center = Geodetic2(nwCorner.lat - _halfSize.lat, nwCorner.lon + _halfSize.lon); } @@ -224,14 +229,19 @@ Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { Ang centerToPointLon = (centerLon - pointLon).normalizeAround(Ang::ZERO); // Calculate the longitudinal distance to the closest patch edge - Ang longitudeDistanceToClosestPatchEdge = centerToPointLon.abs() - Ang::fromRadians(_halfSize.lon); + Ang longitudeDistanceToClosestPatchEdge = + centerToPointLon.abs() - Ang::fromRadians(_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. - double clampedLat = longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? - clampedLat = glm::clamp((Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), minLat(), maxLat()) : - clampedLat = glm::clamp(pointLat.asRadians(), minLat(), maxLat()); + double clampedLat = + longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? + glm::clamp( + (Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), + minLat(), + maxLat()) : + glm::clamp(pointLat.asRadians(), minLat(), maxLat()); // Longitude is just clamped normally double clampedLon = glm::clamp(pointLon.asRadians(), minLon(), maxLon()); diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index 2b62d3b820..4d9dc9f22d 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -66,8 +66,9 @@ namespace { openspace::GlobeBrowsingModule::Capabilities parseSubDatasets(char** subDatasets, int nSubdatasets) { - // Idea: Iterate over the list of sublayers keeping a current layer and identify it - // by its number. If this number changes, we know that we have a new layer + // Idea: Iterate over the list of sublayers keeping a current layer and identify + // it by its number. If this number changes, we know that we have a new + // layer using Layer = openspace::GlobeBrowsingModule::Layer; std::vector result; @@ -104,7 +105,9 @@ namespace { currentLayer.url = value; } else { - LINFOC("GlobeBrowsingGUI", "Unknown subdataset identifier: " + identifier); + LINFOC( + "GlobeBrowsingGUI", "Unknown subdataset identifier: " + identifier + ); } } @@ -139,18 +142,18 @@ void GlobeBrowsingModule::internalInitialize() { // Convert from MB to Bytes GdalWrapper::create( 16ULL * 1024ULL * 1024ULL, // 16 MB - static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024)); // 25% of total RAM + static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024));// 25% addPropertySubOwner(GdalWrapper::ref()); #endif // GLOBEBROWSING_USE_GDAL }); // Render - OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Render, [&]{ + OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Render, [&] { _tileCache->update(); }); // Deinitialize - OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Deinitialize, [&]{ + OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Deinitialize, [&] { #ifdef GLOBEBROWSING_USE_GDAL GdalWrapper::ref().destroy(); #endif // GLOBEBROWSING_USE_GDAL @@ -169,21 +172,35 @@ void GlobeBrowsingModule::internalInitialize() { // Register TileProvider classes fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::DefaultTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::DefaultTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::SingleImageTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::SingleImageTileLayer + )]); #ifdef GLOBEBROWSING_USE_GDAL fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::TemporalTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::TemporalTileLayer + )]); #endif // GLOBEBROWSING_USE_GDAL fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::TileIndexTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::TileIndexTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::SizeReferenceTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::SizeReferenceTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::ByLevelTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::ByLevelTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::ByIndexTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::ByIndexTileLayer + )]); FactoryManager::ref().addFactory(std::move(fTileProvider)); } @@ -381,7 +398,8 @@ void GlobeBrowsingModule::goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 glm::dvec3 positionModelSpace = globe->ellipsoid().cartesianPosition(geo3); glm::dmat4 modelTransform = globe->modelTransform(); - glm::dvec3 positionWorldSpace = glm::dvec3(modelTransform * glm::dvec4(positionModelSpace, 1.0)); + glm::dvec3 positionWorldSpace = glm::dvec3(modelTransform * + glm::dvec4(positionModelSpace, 1.0)); camera.setPositionVec3(positionWorldSpace); if (resetCameraDirection) { @@ -389,7 +407,8 @@ void GlobeBrowsingModule::goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 } } -void GlobeBrowsingModule::resetCameraDirection(Camera& camera, globebrowsing::Geodetic2 geo2) +void GlobeBrowsingModule::resetCameraDirection(Camera& camera, + globebrowsing::Geodetic2 geo2) { using namespace globebrowsing; @@ -410,7 +429,8 @@ void GlobeBrowsingModule::resetCameraDirection(Camera& camera, globebrowsing::Ge glm::dvec3 lookUpWorldSpace = glm::dmat3(modelTransform) * lookUpModelSpace; // Lookat vector - glm::dvec3 lookAtWorldSpace = glm::dvec3(modelTransform * glm::dvec4(positionModelSpace, 1.0)); + glm::dvec3 lookAtWorldSpace = glm::dvec3(modelTransform * + glm::dvec4(positionModelSpace, 1.0)); // Eye position glm::dvec3 eye = camera.positionVec3(); @@ -459,10 +479,13 @@ std::string GlobeBrowsingModule::layerGroupNamesList() { std::string GlobeBrowsingModule::layerTypeNamesList() { std::string listLayerTypes; for (int i = 0; i < globebrowsing::layergroupid::NUM_LAYER_TYPES - 1; ++i) { - listLayerTypes += std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[i]) + ", "; + listLayerTypes += std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[i]) + + ", "; } - listLayerTypes += - " and " + std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[globebrowsing::layergroupid::NUM_LAYER_TYPES - 1]); + listLayerTypes += " and " + + std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[ + globebrowsing::layergroupid::NUM_LAYER_TYPES - 1 + ]); return listLayerTypes; } @@ -489,7 +512,11 @@ void GlobeBrowsingModule::loadWMSCapabilities(std::string name, std::string glob return cap; }; - _inFlightCapabilitiesMap[name] = std::async(std::launch::async, downloadFunction, url); + _inFlightCapabilitiesMap[name] = std::async( + std::launch::async, + downloadFunction, + url + ); _urlList.emplace(std::move(globe), UrlInfo{ std::move(name), std::move(url) }); } diff --git a/modules/globebrowsing/globebrowsingmodule_lua.inl b/modules/globebrowsing/globebrowsingmodule_lua.inl index 7900c3f72e..b2407b1a59 100644 --- a/modules/globebrowsing/globebrowsingmodule_lua.inl +++ b/modules/globebrowsing/globebrowsingmodule_lua.inl @@ -179,9 +179,8 @@ int getGeoPosition(lua_State* L) { if (nArguments != 0) { return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); } - - RenderableGlobe* globe = - OsEng.moduleEngine().module()->castFocusNodeRenderableToGlobe(); + GlobeBrowsingModule* module = OsEng.moduleEngine().module(); + RenderableGlobe* globe = module->castFocusNodeRenderableToGlobe(); if (!globe) { return luaL_error(L, "Focus node must be a RenderableGlobe"); } @@ -194,8 +193,11 @@ int getGeoPosition(lua_State* L) { SurfacePositionHandle posHandle = globe->calculateSurfacePositionHandle( cameraPositionModelSpace); - Geodetic2 geo2 = globe->ellipsoid().cartesianToGeodetic2(posHandle.centerToReferenceSurface); - double altitude = glm::length(cameraPositionModelSpace - posHandle.centerToReferenceSurface); + Geodetic2 geo2 = globe->ellipsoid().cartesianToGeodetic2( + posHandle.centerToReferenceSurface + ); + double altitude = glm::length(cameraPositionModelSpace - + posHandle.centerToReferenceSurface); lua_pushnumber(L, Angle::fromRadians(geo2.lat).asDegrees()); lua_pushnumber(L, Angle::fromRadians(geo2.lon).asDegrees()); diff --git a/modules/globebrowsing/globes/chunkedlodglobe.cpp b/modules/globebrowsing/globes/chunkedlodglobe.cpp index d21fd18e7d..ca2201935e 100644 --- a/modules/globebrowsing/globes/chunkedlodglobe.cpp +++ b/modules/globebrowsing/globes/chunkedlodglobe.cpp @@ -133,12 +133,13 @@ int ChunkedLodGlobe::getDesiredLevel( desiredLevel = _chunkEvaluatorByDistance->getDesiredLevel(chunk, renderData); } - int desiredLevelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel( + int levelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel( chunk, renderData ); - if (desiredLevelByAvailableData != chunklevelevaluator::Evaluator::UnknownDesiredLevel && - _owner.debugProperties().limitLevelByAvailableData) { - desiredLevel = glm::min(desiredLevel, desiredLevelByAvailableData); + if (levelByAvailableData != chunklevelevaluator::Evaluator::UnknownDesiredLevel && + _owner.debugProperties().limitLevelByAvailableData) + { + desiredLevel = glm::min(desiredLevel, levelByAvailableData); } desiredLevel = glm::clamp(desiredLevel, minSplitDepth, maxSplitDepth); @@ -291,7 +292,8 @@ void ChunkedLodGlobe::render(const RenderData& data, RendererTasks&) { // Calculate the MVP matrix glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); - glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * viewTransform; + glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * + viewTransform; glm::dmat4 mvp = vp * _owner.modelTransform(); // Render function @@ -315,8 +317,8 @@ void ChunkedLodGlobe::render(const RenderData& data, RendererTasks&) { //_rightRoot->reverseBreadthFirst(renderJob); auto duration2 = std::chrono::system_clock::now().time_since_epoch(); - auto millis2 = std::chrono::duration_cast(duration2).count(); - stats.i["chunk globe render time"] = millis2 - millis; + auto ms2 = std::chrono::duration_cast(duration2).count(); + stats.i["chunk globe render time"] = ms2 - millis; } void ChunkedLodGlobe::debugRenderChunk(const Chunk& chunk, const glm::dmat4& mvp) const { diff --git a/modules/globebrowsing/globes/pointglobe.cpp b/modules/globebrowsing/globes/pointglobe.cpp index 1101a7d103..e39b47ece8 100644 --- a/modules/globebrowsing/globes/pointglobe.cpp +++ b/modules/globebrowsing/globes/pointglobe.cpp @@ -141,15 +141,16 @@ void PointGlobe::render(const RenderData& data, RendererTasks&) { glm::inverse(rotationTransform) * scaleTransform; // Scale glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; - //glm::vec3 directionToSun = glm::normalize(glm::vec3(0) - glm::vec3(bodyPosition)); - //glm::vec3 directionToSunViewSpace = glm::mat3(data.camera.combinedViewMatrix()) * directionToSun; _programObject->setUniform("lightIntensityClamped", lightIntensityClamped); //_programObject->setUniform("lightOverflow", lightOverflow); //_programObject->setUniform("directionToSunViewSpace", directionToSunViewSpace); _programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform)); - _programObject->setUniform("projectionTransform", data.camera.sgctInternal.projectionMatrix()); + _programObject->setUniform( + "projectionTransform", + data.camera.sgctInternal.projectionMatrix() + ); glBlendFunc(GL_SRC_ALPHA, GL_ONE); diff --git a/modules/globebrowsing/meshes/grid.h b/modules/globebrowsing/meshes/grid.h index 4465eda9ad..05444c26f7 100644 --- a/modules/globebrowsing/meshes/grid.h +++ b/modules/globebrowsing/meshes/grid.h @@ -63,8 +63,8 @@ public: protected: /** * Should return the indices of vertices for a grid with size xSegments - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. + * ySegments. Where the number of vertices in each direction is the + * number of segments + 1. */ virtual std::vector createElements(int xSegments, int ySegments) = 0; @@ -85,8 +85,8 @@ protected: /** * Should return the normals of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. + * ySegments. Where the number of vertices in each direction is the + * number of segments + 1. */ virtual std::vector createNormals(int xSegments, int ySegments) = 0; diff --git a/modules/globebrowsing/meshes/skirtedgrid.cpp b/modules/globebrowsing/meshes/skirtedgrid.cpp index e3b194308d..bead0e6e66 100644 --- a/modules/globebrowsing/meshes/skirtedgrid.cpp +++ b/modules/globebrowsing/meshes/skirtedgrid.cpp @@ -45,7 +45,9 @@ SkirtedGrid::SkirtedGrid(unsigned int xSegments, unsigned int ySegments, _geometry->setVertexPositions(createPositions(_xSegments, _ySegments)); } if (useTextureCoordinates) { - _geometry->setVertexTextureCoordinates(createTextureCoordinates(_xSegments, _ySegments)); + _geometry->setVertexTextureCoordinates( + createTextureCoordinates(_xSegments, _ySegments) + ); } if (useNormals) { _geometry->setVertexNormals(createNormals(_xSegments, _ySegments)); diff --git a/modules/globebrowsing/other/pixelbuffer.cpp b/modules/globebrowsing/other/pixelbuffer.cpp index 5c313cd4a0..c34050495a 100644 --- a/modules/globebrowsing/other/pixelbuffer.cpp +++ b/modules/globebrowsing/other/pixelbuffer.cpp @@ -52,7 +52,9 @@ void* PixelBuffer::mapBuffer(Access access) { return dataPtr; } -void* PixelBuffer::mapBufferRange(GLintptr offset, GLsizeiptr length, BufferAccessMask access) { +void* PixelBuffer::mapBufferRange(GLintptr offset, GLsizeiptr length, + BufferAccessMask access) +{ void* dataPtr = glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, length, access); _isMapped = dataPtr ? true : false; return dataPtr; diff --git a/modules/globebrowsing/other/pixelbuffercontainer.h b/modules/globebrowsing/other/pixelbuffercontainer.h index 03259c6d88..f5e617aaec 100644 --- a/modules/globebrowsing/other/pixelbuffercontainer.h +++ b/modules/globebrowsing/other/pixelbuffercontainer.h @@ -92,8 +92,8 @@ public: bool unMapBuffer(KeyType key); /** - * \returns the GLuint id of a pixel buffer identified by key - * if it currently is mapped. + * \returns the GLuint id of a pixel buffer identified by + * key if it currently is mapped. */ GLuint idOfMappedBuffer(KeyType key); private: diff --git a/modules/globebrowsing/rendering/chunkrenderer.cpp b/modules/globebrowsing/rendering/chunkrenderer.cpp index a35c59ef99..41e504094f 100644 --- a/modules/globebrowsing/rendering/chunkrenderer.cpp +++ b/modules/globebrowsing/rendering/chunkrenderer.cpp @@ -307,7 +307,10 @@ void ChunkRenderer::renderChunkLocally(const Chunk& chunk, const RenderData& dat cornersCameraSpace[Quad::SOUTH_WEST])); programObject->setUniform("patchNormalCameraSpace", patchNormalCameraSpace); - programObject->setUniform("projectionTransform", data.camera.sgctInternal.projectionMatrix()); + programObject->setUniform( + "projectionTransform", + data.camera.sgctInternal.projectionMatrix() + ); if (_layerManager->layerGroup(layergroupid::HeightLayers).activeLayers().size() > 0) { // Apply an extra scaling to the height if the object is scaled diff --git a/modules/globebrowsing/rendering/gpu/gpulayer.cpp b/modules/globebrowsing/rendering/gpu/gpulayer.cpp index 6168fa3ae5..7ce7541e3c 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayer.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayer.cpp @@ -46,7 +46,10 @@ void GPULayer::setValue(ghoul::opengl::ProgramObject* programObject, const Layer ChunkTilePile chunkTilePile = layer.getChunkTilePile(tileIndex, pileSize); gpuChunkTilePile.setValue(programObject, chunkTilePile); paddingStartOffset.setValue(programObject, layer.tilePixelStartOffset()); - paddingSizeDifference.setValue(programObject, layer.tilePixelSizeDifference()); + paddingSizeDifference.setValue( + programObject, + layer.tilePixelSizeDifference() + ); break; } case layergroupid::TypeID::SolidColor: @@ -60,8 +63,16 @@ void GPULayer::setValue(ghoul::opengl::ProgramObject* programObject, const Layer void GPULayer::bind(ghoul::opengl::ProgramObject* programObject, const Layer& layer, const std::string& nameBase, int pileSize) { - gpuRenderSettings.bind(layer.renderSettings(), programObject, nameBase + "settings."); - gpuLayerAdjustment.bind(layer.layerAdjustment(), programObject, nameBase + "adjustment."); + gpuRenderSettings.bind( + layer.renderSettings(), + programObject, + nameBase + "settings." + ); + gpuLayerAdjustment.bind( + layer.layerAdjustment(), + programObject, + nameBase + "adjustment." + ); switch (layer.type()) { // Intentional fall through. Same for all tile layers @@ -74,7 +85,10 @@ void GPULayer::bind(ghoul::opengl::ProgramObject* programObject, const Layer& la case layergroupid::TypeID::ByLevelTileLayer: { gpuChunkTilePile.bind(programObject, nameBase + "pile.", pileSize); paddingStartOffset.bind(programObject, nameBase + "padding.startOffset"); - paddingSizeDifference.bind(programObject, nameBase + "padding.sizeDifference"); + paddingSizeDifference.bind( + programObject, + nameBase + "padding.sizeDifference" + ); break; } case layergroupid::TypeID::SolidColor: diff --git a/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp b/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp index 7634e693fe..a74b2f9217 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp @@ -34,8 +34,14 @@ void GPULayerAdjustment::setValue(ghoul::opengl::ProgramObject* programObject, case layergroupid::AdjustmentTypeID::None: break; case layergroupid::AdjustmentTypeID::ChromaKey: { - gpuChromaKeyColor.setValue(programObject, layerAdjustment.chromaKeyColor.value()); - gpuChromaKeyTolerance.setValue(programObject, layerAdjustment.chromaKeyTolerance.value()); + gpuChromaKeyColor.setValue( + programObject, + layerAdjustment.chromaKeyColor.value() + ); + gpuChromaKeyTolerance.setValue( + programObject, + layerAdjustment.chromaKeyTolerance.value() + ); break; } case layergroupid::AdjustmentTypeID::TransferFunction: diff --git a/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h b/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h index ddaafcaa18..b0c206142c 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h +++ b/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h @@ -53,7 +53,8 @@ public: * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ - void bind(const LayerRenderSettings& layerSettings, ghoul::opengl::ProgramObject* programObject, const std::string& nameBase); + void bind(const LayerRenderSettings& layerSettings, + ghoul::opengl::ProgramObject* programObject, const std::string& nameBase); private: GPUData gpuOpacity; diff --git a/modules/globebrowsing/rendering/layer/layer.cpp b/modules/globebrowsing/rendering/layer/layer.cpp index 23a27a63f7..e99d0d1d23 100644 --- a/modules/globebrowsing/rendering/layer/layer.cpp +++ b/modules/globebrowsing/rendering/layer/layer.cpp @@ -91,7 +91,9 @@ Layer::Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, LayerGroup& parent) : properties::PropertyOwner({ layerDict.value(keyName), - layerDict.hasKey(keyDescription) ? layerDict.value(keyDescription) : "" + layerDict.hasKey(keyDescription) ? + layerDict.value(keyDescription) : + "" }) , _parent(parent) , _typeOption(TypeInfo, properties::OptionProperty::DisplayType::Dropdown) @@ -299,7 +301,8 @@ glm::ivec2 Layer::tilePixelSizeDifference() const { return _padTilePixelSizeDifference; } -glm::vec2 Layer::compensateSourceTextureSampling(glm::vec2 startOffset, glm::vec2 sizeDiff, +glm::vec2 Layer::compensateSourceTextureSampling(glm::vec2 startOffset, + glm::vec2 sizeDiff, glm::uvec2 resolution, glm::vec2 tileUV) { glm::vec2 sourceSize = glm::vec2(resolution) + sizeDiff; @@ -333,7 +336,8 @@ layergroupid::TypeID Layer::parseTypeIdFromDictionary( } } -void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict) { +void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict) +{ switch (typeId) { // Intentional fall through. Same for all tile layers case layergroupid::TypeID::DefaultTileLayer: @@ -353,7 +357,10 @@ void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary LDEBUG("Initializing tile provider for layer: '" + name + "'"); } _tileProvider = std::shared_ptr( - tileprovider::TileProvider::createFromDictionary(typeId, tileProviderInitDict) + tileprovider::TileProvider::createFromDictionary( + typeId, + tileProviderInitDict + ) ); break; } diff --git a/modules/globebrowsing/rendering/layer/layer.h b/modules/globebrowsing/rendering/layer/layer.h index 2b86269615..9af39b7a02 100644 --- a/modules/globebrowsing/rendering/layer/layer.h +++ b/modules/globebrowsing/rendering/layer/layer.h @@ -53,7 +53,8 @@ public: properties::Vec3Property color; }; - Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, LayerGroup& parent); + Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, + LayerGroup& parent); ChunkTilePile getChunkTilePile(const TileIndex& tileIndex, int pileSize) const; Tile::Status getTileStatus(const TileIndex& index) const; @@ -74,12 +75,14 @@ public: glm::ivec2 tilePixelStartOffset() const; glm::ivec2 tilePixelSizeDifference() const; glm::vec2 compensateSourceTextureSampling(glm::vec2 startOffset, glm::vec2 sizeDiff, - glm::uvec2 resolution, glm::vec2 tileUV); + glm::uvec2 resolution, glm::vec2 tileUV); glm::vec2 TileUvToTextureSamplePosition(const TileUvTransform& uvTransform, - glm::vec2 tileUV, glm::uvec2 resolution); + glm::vec2 tileUV, glm::uvec2 resolution); private: - layergroupid::TypeID parseTypeIdFromDictionary(const ghoul::Dictionary& initDict) const; + layergroupid::TypeID parseTypeIdFromDictionary( + const ghoul::Dictionary& initDict) const; + void initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict); void addVisibleProperties(); void removeVisibleProperties(); diff --git a/modules/globebrowsing/rendering/layer/layergroup.cpp b/modules/globebrowsing/rendering/layer/layergroup.cpp index 85ddabfecf..aaa6aed481 100644 --- a/modules/globebrowsing/rendering/layer/layergroup.cpp +++ b/modules/globebrowsing/rendering/layer/layergroup.cpp @@ -113,7 +113,10 @@ void LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { } void LayerGroup::deleteLayer(const std::string& layerName) { - for (std::vector>::iterator it = _layers.begin(); it != _layers.end(); ++it) { + for (std::vector>::iterator it = _layers.begin(); + it != _layers.end(); + ++it) + { if (it->get()->name() == layerName) { removePropertySubOwner(it->get()); _layers.erase(it); diff --git a/modules/globebrowsing/rendering/layershadermanager.cpp b/modules/globebrowsing/rendering/layershadermanager.cpp index 657dc25544..1ba3456403 100644 --- a/modules/globebrowsing/rendering/layershadermanager.cpp +++ b/modules/globebrowsing/rendering/layershadermanager.cpp @@ -37,13 +37,15 @@ namespace openspace::globebrowsing { -bool LayerShaderManager::LayerShaderPreprocessingData::LayerGroupPreprocessingData::operator==( - const LayerGroupPreprocessingData& other) const { +bool +LayerShaderManager::LayerShaderPreprocessingData::LayerGroupPreprocessingData::operator==( + const LayerGroupPreprocessingData& other) const +{ return layerType == other.layerType && - blendMode == other.blendMode && - layerAdjustmentType == other.layerAdjustmentType && - lastLayerIdx == other.lastLayerIdx && - layerBlendingEnabled == other.layerBlendingEnabled; + blendMode == other.blendMode && + layerAdjustmentType == other.layerAdjustmentType && + lastLayerIdx == other.lastLayerIdx && + layerBlendingEnabled == other.layerBlendingEnabled; } bool LayerShaderManager::LayerShaderPreprocessingData::operator==( @@ -92,7 +94,9 @@ LayerShaderManager::LayerShaderPreprocessingData for (const std::shared_ptr& layer : layers) { layeredTextureInfo.layerType.push_back(layer->type()); layeredTextureInfo.blendMode.push_back(layer->blendMode()); - layeredTextureInfo.layerAdjustmentType.push_back(layer->layerAdjustment().type()); + layeredTextureInfo.layerAdjustmentType.push_back( + layer->layerAdjustment().type() + ); } preprocessingData.layeredTextureInfo[i] = layeredTextureInfo; @@ -173,7 +177,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "LayerType"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].layerType[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].layerType[j]) + ); } // This is to avoid errors from shader preprocessor @@ -182,7 +189,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "BlendMode"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].blendMode[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].blendMode[j]) + ); } // This is to avoid errors from shader preprocessor @@ -191,7 +201,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "LayerAdjustmentType"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].layerAdjustmentType[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].layerAdjustmentType[j]) + ); } } diff --git a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp index 66fd37cc96..38b1198d33 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp @@ -130,8 +130,10 @@ void GdalRawTileDataReader::initialize() { _gdalDatasetMetaDataCached.offset = _dataset->GetRasterBand(1)->GetOffset(); _gdalDatasetMetaDataCached.rasterXSize = _dataset->GetRasterXSize(); _gdalDatasetMetaDataCached.rasterYSize = _dataset->GetRasterYSize(); - _gdalDatasetMetaDataCached.noDataValue = _dataset->GetRasterBand(1)->GetNoDataValue(); - _gdalDatasetMetaDataCached.dataType = tiledatatype::getGdalDataType(_initData.glType()); + _gdalDatasetMetaDataCached.noDataValue = + _dataset->GetRasterBand(1)->GetNoDataValue(); + _gdalDatasetMetaDataCached.dataType = + tiledatatype::getGdalDataType(_initData.glType()); CPLErr err = _dataset->GetGeoTransform(&_gdalDatasetMetaDataCached.padfTransform[0]); if (err == CE_Failure) { diff --git a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp index e40233e187..ed49aa1620 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp @@ -131,11 +131,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -143,11 +145,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } // Last read is the alpha channel @@ -161,11 +165,17 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < nRastersToRead; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); - RawTile::ReadError err = repeatedRasterRead(i + 1, io, dataDestination); + RawTile::ReadError err = repeatedRasterRead( + i + 1, + io, + dataDestination + ); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -177,11 +187,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -189,29 +201,38 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } // Last read is the alpha channel char* dataDestination = imageDataDest + (3 * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(2, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } else { // Three or more rasters for (int i = 0; i < 3 && i < nRastersToRead; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); - RawTile::ReadError err = repeatedRasterRead(3 - i, io, dataDestination); + RawTile::ReadError err = repeatedRasterRead( + 3 - i, + io, + dataDestination + ); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -337,7 +358,8 @@ PixelRegion::PixelCoordinate RawTileDataReader::geodeticToPixel( //ghoul_assert(a[2] != 0.0, "a2 must not be zero!"); double P = (a[0] * b[2] - a[2] * b[0] + a[2] * Y - b[2] * X) / divisor; double L = (-a[0] * b[1] + a[1] * b[0] - a[1] * Y + b[1] * X) / divisor; - // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L,+Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L + // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L, + // +Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L double Xp = a[0] + P*a[1] + L*a[2]; double Yp = b[0] + P*b[1] + L*b[2]; @@ -358,7 +380,9 @@ Geodetic2 RawTileDataReader::pixelToGeodetic( return geodetic; } -PixelRegion RawTileDataReader::highestResPixelRegion(const GeodeticPatch& geodeticPatch) const { +PixelRegion RawTileDataReader::highestResPixelRegion( + const GeodeticPatch& geodeticPatch) const +{ Geodetic2 nwCorner = geodeticPatch.getCorner(Quad::NORTH_WEST); Geodetic2 swCorner = geodeticPatch.getCorner(Quad::SOUTH_EAST); PixelRegion::PixelCoordinate pixelStart = geodeticToPixel(nwCorner); @@ -374,7 +398,7 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( RawTile::ReadError worstError = RawTile::ReadError::None; // NOTE: - // Ascii graphics illustrates the implementation details of this method, for one + // Ascii graphics illustrates the implementation details of this method, for one // specific case. Even though the illustrated case is specific, readers can // hopefully find it useful to get the general idea. @@ -428,7 +452,9 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( if (cutoff.read.region.area() > 0) { // Wrap by repeating - PixelRegion::Side oppositeSide = static_cast((i + 2) % 4); + PixelRegion::Side oppositeSide = static_cast( + (i + 2) % 4 + ); cutoff.read.region.align( oppositeSide, io.read.fullRegion.edge(oppositeSide)); @@ -516,7 +542,9 @@ std::shared_ptr RawTileDataReader::getTileMetaData( } else { preprocessData->hasMissingData[raster] = true; - float& floatToRewrite = reinterpret_cast(rawTile->imageData[yi + i]); + float& floatToRewrite = reinterpret_cast( + rawTile->imageData[yi + i] + ); floatToRewrite = -FLT_MAX; } i += _initData.bytesPerDatum(); @@ -541,7 +569,9 @@ float RawTileDataReader::depthScale() const { TileDepthTransform RawTileDataReader::calculateTileDepthTransform() { bool isFloat = - (_initData.glType() == GL_HALF_FLOAT || _initData.glType() == GL_FLOAT || _initData.glType() == GL_DOUBLE); + (_initData.glType() == GL_HALF_FLOAT || + _initData.glType() == GL_FLOAT || + _initData.glType() == GL_DOUBLE); double maximumValue = isFloat ? 1.0 : tiledatatype::getMaximumValue(_initData.glType()); diff --git a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h index 37562e4d8f..fe4cae764c 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h +++ b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h @@ -155,7 +155,8 @@ protected: std::shared_ptr getTileMetaData( std::shared_ptr result, const PixelRegion& region) const; TileDepthTransform calculateTileDepthTransform(); - RawTile::ReadError postProcessErrorCheck(std::shared_ptr ioResult) const; + RawTile::ReadError postProcessErrorCheck( + std::shared_ptr ioResult) const; struct Cached { int _maxLevel = -1; diff --git a/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp index 98f35f2302..46d8c6052d 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp @@ -187,7 +187,8 @@ RawTile::ReadError SimpleRawTileDataReader::rasterRead( return RawTile::ReadError::None; } -IODescription SimpleRawTileDataReader::adjustIODescription(const IODescription& io) const { +IODescription SimpleRawTileDataReader::adjustIODescription(const IODescription& io) const +{ // Modify to match OpenGL texture layout IODescription modifiedIO = io; modifiedIO.read.region.start.y = diff --git a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp index 3b72e93b68..80a6d5051c 100644 --- a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp @@ -126,8 +126,8 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) addProperty(_tilePixelSize); } -DefaultTileProvider::DefaultTileProvider(std::shared_ptr tileReader) - : _asyncTextureDataProvider(tileReader) +DefaultTileProvider::DefaultTileProvider(std::shared_ptr tr) + : _asyncTextureDataProvider(tr) , _filePath(FilePathInfo, "") , _tilePixelSize(TilePixelSizeInfo, 32, 32, 2048) {} @@ -140,10 +140,11 @@ void DefaultTileProvider::update() { initTexturesFromLoadedData(); if (_asyncTextureDataProvider->shouldBeDeleted()) { _asyncTextureDataProvider = nullptr; - TileTextureInitData initData( - LayerManager::getTileTextureInitData(_layerGroupID, _padTiles, - _tilePixelSize) - ); + TileTextureInitData initData(LayerManager::getTileTextureInitData( + _layerGroupID, + _padTiles, + _tilePixelSize + )); initAsyncTileDataReader(initData); } } @@ -155,10 +156,11 @@ void DefaultTileProvider::reset() { _asyncTextureDataProvider->prepairToBeDeleted(); } else { - TileTextureInitData initData( - LayerManager::getTileTextureInitData(_layerGroupID, _padTiles, - _tilePixelSize) - ); + TileTextureInitData initData(LayerManager::getTileTextureInitData( + _layerGroupID, + _padTiles, + _tilePixelSize + )); initAsyncTileDataReader(initData); } } @@ -206,7 +208,8 @@ float DefaultTileProvider::noDataValueAsFloat() { void DefaultTileProvider::initTexturesFromLoadedData() { if (_asyncTextureDataProvider) { - std::shared_ptr rawTile = _asyncTextureDataProvider->popFinishedRawTile(); + std::shared_ptr rawTile = + _asyncTextureDataProvider->popFinishedRawTile(); if (rawTile) { cache::ProviderTileKey key = { rawTile->tileIndex, uniqueIdentifier() }; ghoul_assert(!_tileCache->exist(key), "Tile must not be existing in cache"); @@ -224,14 +227,24 @@ void DefaultTileProvider::initAsyncTileDataReader(TileTextureInitData initData) // Initialize instance variables #ifdef GLOBEBROWSING_USE_GDAL - auto tileDataset = std::make_shared(_filePath, initData, - _basePath, preprocess); + auto tileDataset = std::make_shared( + _filePath, + initData, + _basePath, + preprocess + ); #else // GLOBEBROWSING_USE_GDAL - auto tileDataset = std::make_shared(_filePath, initData, - preprocess); + auto tileDataset = std::make_shared( + _filePath, + initData, + preprocess + ); #endif // GLOBEBROWSING_USE_GDAL - _asyncTextureDataProvider = std::make_shared(_name, tileDataset); + _asyncTextureDataProvider = std::make_shared( + _name, + tileDataset + ); // Tiles are only available for levels 2 and higher. if (_preCacheLevel >= 2) { diff --git a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp index 4bb13d4a73..4cdb6bc8df 100644 --- a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp @@ -106,7 +106,8 @@ int SizeReferenceTileProvider::roundedLongitudalLength(const TileIndex& tileInde return l; } -TileIndex::TileHashKey SizeReferenceTileProvider::toHash(const TileIndex& tileIndex) const { +TileIndex::TileHashKey SizeReferenceTileProvider::toHash(const TileIndex& tileIndex) const +{ int l = roundedLongitudalLength(tileIndex); TileIndex::TileHashKey key = static_cast(l); return key; diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp index 858d625e98..85999d9b84 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp @@ -79,7 +79,9 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) addProperty(_filePath); if (readFilePath()) { - const bool hasStart = dictionary.hasKeyAndValue(KeyPreCacheStartTime); + const bool hasStart = dictionary.hasKeyAndValue( + KeyPreCacheStartTime + ); const bool hasEnd = dictionary.hasKeyAndValue(KeyPreCacheEndTime); if (hasStart && hasEnd) { const std::string start = dictionary.value(KeyPreCacheStartTime); @@ -266,7 +268,8 @@ void TemporalTileProvider::update() { void TemporalTileProvider::reset() { if (_successfulInitialization) { - for (std::pair>& it : _tileProviderMap) { + using T = std::pair>; + for (T& it : _tileProviderMap) { it.second->reset(); } } @@ -289,7 +292,7 @@ std::shared_ptr TemporalTileProvider::getTileProvider(const Time& std::shared_ptr TemporalTileProvider::getTileProvider( const TimeKey& timekey) { - std::unordered_map>::iterator it = _tileProviderMap.find(timekey); + auto it = _tileProviderMap.find(timekey); if (it != _tileProviderMap.end()) { return it->second; } @@ -456,7 +459,9 @@ double TimeQuantizer::parseTimeResolutionStr(const std::string& resoltutionStr) bool TimeQuantizer::quantize(Time& t, bool clamp) const { double unquantized = t.j2000Seconds(); if (_timerange.includes(unquantized)) { - double quantized = std::floor((unquantized - _timerange.start) / _resolution) * _resolution + _timerange.start; + double quantized = std::floor( + (unquantized - _timerange.start) / _resolution) * + _resolution + _timerange.start; t.setTime(quantized); return true; } diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h index e8c37f8d9b..72f6d511d4 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.h @@ -131,7 +131,9 @@ struct TimeIdProviderFactory { */ static void init(); - static std::unordered_map> _timeIdProviderMap; + static std::unordered_map< + std::string, std::unique_ptr + > _timeIdProviderMap; static bool initialized; }; @@ -306,7 +308,8 @@ private: * \param defaultVal value to return if key was not found * \returns the value of the Key, or defaultVal if key was undefined. */ - std::string getXMLValue(CPLXMLNode* node, const std::string& key, const std::string& defaultVal); + std::string getXMLValue(CPLXMLNode* node, const std::string& key, + const std::string& defaultVal); /** * Ensures that the TemporalTileProvider is up to date. diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h index 5d21d540a0..4a9763f626 100644 --- a/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbyindex.h @@ -45,7 +45,9 @@ public: private: TileProvider* indexProvider(const TileIndex& tileIndex) const; - std::unordered_map> _tileProviderMap; + std::unordered_map< + TileIndex::TileHashKey, std::shared_ptr + > _tileProviderMap; std::shared_ptr _defaultTileProvider; }; diff --git a/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp index 225b289f9e..8d734381bf 100644 --- a/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp +++ b/modules/globebrowsing/tile/tileprovider/tileproviderbylevel.cpp @@ -64,7 +64,8 @@ TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { maxLevel = std::round(floatMaxLevel); ghoul::Dictionary providerDict; - if (!levelProviderDict.getValue(KeyTileProvider, providerDict)) { + if (!levelProviderDict.getValue(KeyTileProvider, providerDict)) + { throw std::runtime_error( "Must define key '" + std::string(KeyTileProvider) + "'" ); @@ -86,7 +87,10 @@ TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { } _levelTileProviders.push_back( - std::shared_ptr(TileProvider::createFromDictionary(typeID, providerDict)) + std::shared_ptr(TileProvider::createFromDictionary( + typeID, + providerDict + )) ); std::string providerName; diff --git a/modules/globebrowsing/tile/tileselector.h b/modules/globebrowsing/tile/tileselector.h index 39d64acdd5..baa81dde95 100644 --- a/modules/globebrowsing/tile/tileselector.h +++ b/modules/globebrowsing/tile/tileselector.h @@ -37,7 +37,8 @@ namespace openspace::globebrowsing { namespace openspace::globebrowsing::tileselector { -ChunkTile getHighestResolutionTile(const LayerGroup& layerGroup, const TileIndex& tileIndex); +ChunkTile getHighestResolutionTile(const LayerGroup& layerGroup, + const TileIndex& tileIndex); std::vector getTilesSortedByHighestResolution(const LayerGroup& layerGroup, const TileIndex& tileIndex); diff --git a/modules/globebrowsing/tile/tiletextureinitdata.cpp b/modules/globebrowsing/tile/tiletextureinitdata.cpp index 97099dbfff..683a0c9ea9 100644 --- a/modules/globebrowsing/tile/tiletextureinitdata.cpp +++ b/modules/globebrowsing/tile/tiletextureinitdata.cpp @@ -60,7 +60,10 @@ TileTextureInitData::TileTextureInitData(const TileTextureInitData& original) original.glType(), original.ghoulTextureFormat(), original._padTiles, - original.shouldAllocateDataOnCPU() ? ShouldAllocateDataOnCPU::Yes : ShouldAllocateDataOnCPU::No) + original.shouldAllocateDataOnCPU() ? + ShouldAllocateDataOnCPU::Yes : + ShouldAllocateDataOnCPU::No + ) {} glm::ivec3 TileTextureInitData::dimensions() const { diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index 6dc0529b71..b865c92c71 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -86,7 +86,10 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { []() { const std::vector& nodes = OsEng.renderEngine().scene()->allSceneGraphNodes(); - return std::vector(nodes.begin(), nodes.end()); + return std::vector( + nodes.begin(), + nodes.end() + ); } ); @@ -111,13 +114,20 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { nodes.end(), [](SceneGraphNode* n) { const std::vector& tags = n->tags(); - auto it = std::find(tags.begin(), tags.end(), "GUI.Interesting"); + auto it = std::find( + tags.begin(), + tags.end(), + "GUI.Interesting" + ); return it == tags.end(); } ), nodes.end() ); - return std::vector(nodes.begin(), nodes.end()); + return std::vector( + nodes.begin(), + nodes.end() + ); } ); } diff --git a/modules/imgui/src/gui.cpp b/modules/imgui/src/gui.cpp index e3bd6d3db6..6db4244e94 100644 --- a/modules/imgui/src/gui.cpp +++ b/modules/imgui/src/gui.cpp @@ -128,7 +128,10 @@ static void RenderDrawLists(ImDrawData* drawData) { GL_STREAM_DRAW ); - for (const ImDrawCmd* pcmd = cmdList->CmdBuffer.begin(); pcmd != cmdList->CmdBuffer.end(); pcmd++) { + for (const ImDrawCmd* pcmd = cmdList->CmdBuffer.begin(); + pcmd != cmdList->CmdBuffer.end(); + pcmd++) + { if (pcmd->UserCallback) { pcmd->UserCallback(cmdList, pcmd); } @@ -221,16 +224,25 @@ void addScreenSpaceRenderableLocal(std::string texturePath) { } const std::string luaTable = - "{Type = 'ScreenSpaceImageLocal', TexturePath = openspace.absPath('" + texturePath + "') }"; - const std::string script = "openspace.registerScreenSpaceRenderable(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script, openspace::scripting::ScriptEngine::RemoteScripting::Yes); + "{Type = 'ScreenSpaceImageLocal', TexturePath = openspace.absPath('" + + texturePath + "') }"; + const std::string script = "openspace.registerScreenSpaceRenderable(" + + luaTable + ");"; + OsEng.scriptEngine().queueScript( + script, + openspace::scripting::ScriptEngine::RemoteScripting::Yes + ); } void addScreenSpaceRenderableOnline(std::string texturePath) { const std::string luaTable = "{Type = 'ScreenSpaceImageOnline', TexturePath = '" + texturePath + "' }"; - const std::string script = "openspace.registerScreenSpaceRenderable(" + luaTable + ");"; - OsEng.scriptEngine().queueScript(script, openspace::scripting::ScriptEngine::RemoteScripting::Yes); + const std::string script = "openspace.registerScreenSpaceRenderable(" + + luaTable + ");"; + OsEng.scriptEngine().queueScript( + script, + openspace::scripting::ScriptEngine::RemoteScripting::Yes + ); } } // namespace diff --git a/modules/imgui/src/guiiswacomponent.cpp b/modules/imgui/src/guiiswacomponent.cpp index a6731d7cf5..ef742966b6 100644 --- a/modules/imgui/src/guiiswacomponent.cpp +++ b/modules/imgui/src/guiiswacomponent.cpp @@ -152,8 +152,6 @@ void GuiIswaComponent::render() { if (cdfOptionValue != cdfOption) { if (cdfOptionValue >= 0) { groupName = cdfs[cdfOptionValue].group; - // std::cout << groupName << std::endl; - // OsEng.scriptEngine().queueScript("openspace.iswa.removeGroup('"+groupName+"');"); } std::string path = cdfs[cdfOption].path; diff --git a/modules/imgui/src/guimissioncomponent.cpp b/modules/imgui/src/guimissioncomponent.cpp index 34e086f342..b531f071ed 100644 --- a/modules/imgui/src/guimissioncomponent.cpp +++ b/modules/imgui/src/guimissioncomponent.cpp @@ -47,7 +47,13 @@ namespace { openspace::MissionPhase::Trace t = mission.phaseTrace(currentTime, 0); int treeOption = t.empty() ? 0 : ImGuiTreeNodeFlags_DefaultOpen; - if (ImGui::TreeNodeEx(("%s" + missionHashname).c_str(), treeOption, "%s", mission.name().c_str())) { + if (ImGui::TreeNodeEx( + ("%s" + missionHashname).c_str(), + treeOption, + "%s", + mission.name().c_str()) + ) + { if (!mission.description().empty()) { ImGui::Text("%s", mission.description().c_str()); } @@ -64,7 +70,13 @@ namespace { float s = static_cast(startTime.j2000Seconds()); float e = static_cast(endTime.j2000Seconds()); - ImGui::SliderFloat(missionHashname.c_str(), &v, s, e, OsEng.timeManager().time().UTC().c_str()); + ImGui::SliderFloat( + missionHashname.c_str(), + &v, + s, + e, + OsEng.timeManager().time().UTC().c_str() + ); ImGui::SameLine(); ImGui::Text("%s", endTime.UTC().c_str()); diff --git a/modules/imgui/src/guiparallelcomponent.cpp b/modules/imgui/src/guiparallelcomponent.cpp index a879fe9bb6..5f155f3471 100644 --- a/modules/imgui/src/guiparallelcomponent.cpp +++ b/modules/imgui/src/guiparallelcomponent.cpp @@ -78,12 +78,14 @@ void GuiParallelComponent::renderClientWithHost() { ImGui::Text("%s", connectionInfo.c_str()); renderClientCommon(); - const size_t nTimeKeyframes = OsEng.timeManager().nKeyframes(); - const size_t nCameraKeyframes = OsEng.navigationHandler().keyframeNavigator().nKeyframes(); + size_t nTimeKeyframes = OsEng.timeManager().nKeyframes(); + size_t nCameraKeyframes = OsEng.navigationHandler().keyframeNavigator().nKeyframes(); std::string timeKeyframeInfo = "TimeKeyframes : " + std::to_string(nTimeKeyframes); - std::string cameraKeyframeInfo = "CameraKeyframes : " + std::to_string(nCameraKeyframes); - std::string latencyStandardDeviation = "Latency standard deviation: " + std::to_string(parallel.latencyStandardDeviation()) + " s"; + std::string cameraKeyframeInfo = "CameraKeyframes : " + + std::to_string(nCameraKeyframes); + std::string latencyStandardDeviation = "Latency standard deviation: " + + std::to_string(parallel.latencyStandardDeviation()) + " s"; const bool resetTimeOffset = ImGui::Button("Reset time offset"); diff --git a/modules/imgui/src/guiperformancecomponent.cpp b/modules/imgui/src/guiperformancecomponent.cpp index a6232e38ce..26cee553c2 100644 --- a/modules/imgui/src/guiperformancecomponent.cpp +++ b/modules/imgui/src/guiperformancecomponent.cpp @@ -100,7 +100,8 @@ void GuiPerformanceComponent::render() { bool v = _isEnabled; ImGui::Begin("Performance", &v); _isEnabled = v; - PerformanceLayout* layout = OsEng.renderEngine().performanceManager()->performanceData(); + RenderEngine& re = OsEng.renderEngine(); + PerformanceLayout* layout = re.performanceManager()->performanceData(); v = _sceneGraphIsEnabled; ImGui::Checkbox("SceneGraph", &v); @@ -321,7 +322,8 @@ void GuiPerformanceComponent::render() { indices.begin(), indices.end(), [layout](size_t a, size_t b) { - return std::string(layout->sceneGraphEntries[a].name) < std::string(layout->sceneGraphEntries[b].name); + return std::string(layout->sceneGraphEntries[a].name) < + std::string(layout->sceneGraphEntries[b].name); } ); } diff --git a/modules/imgui/src/guipropertycomponent.cpp b/modules/imgui/src/guipropertycomponent.cpp index 14f9fbe798..95f7327ba4 100644 --- a/modules/imgui/src/guipropertycomponent.cpp +++ b/modules/imgui/src/guipropertycomponent.cpp @@ -124,7 +124,9 @@ namespace { } } - void renderTree(const TreeNode& node, const std::function& renderFunc) { + void renderTree(const TreeNode& node, + const std::function& renderFunc) + { if (node.path.empty() || ImGui::TreeNode(node.path.c_str())) { for (const std::unique_ptr& c : node.children) { renderTree(*c, renderFunc); @@ -144,7 +146,8 @@ namespace { namespace openspace::gui { -GuiPropertyComponent::GuiPropertyComponent(std::string name, UseTreeLayout useTree, IsTopLevelWindow topLevel) +GuiPropertyComponent::GuiPropertyComponent(std::string name, UseTreeLayout useTree, + IsTopLevelWindow topLevel) : GuiComponent(std::move(name)) , _useTreeLayout(useTree) , _currentUseTreeLayout(useTree) @@ -368,7 +371,9 @@ void GuiPropertyComponent::render() { void GuiPropertyComponent::renderProperty(properties::Property* prop, properties::PropertyOwner* owner) { - using Func = std::function; + using Func = std::function< + void(properties::Property*, const std::string&, IsRegularProperty) + >; static const std::map FunctionMapping = { { "BoolProperty", &renderBoolProperty }, { "DoubleProperty", &renderDoubleProperty}, diff --git a/modules/imgui/src/guispacetimecomponent.cpp b/modules/imgui/src/guispacetimecomponent.cpp index 7ccb55bba3..746e9118c4 100644 --- a/modules/imgui/src/guispacetimecomponent.cpp +++ b/modules/imgui/src/guispacetimecomponent.cpp @@ -255,7 +255,14 @@ void GuiSpaceTimeComponent::render() { float deltaTime = static_cast(OsEng.timeManager().time().deltaTime()); - bool changed = ImGui::SliderFloat("Delta Time", &deltaTime, -100000.f, 100000.f, "%.3f", 5.f); + bool changed = ImGui::SliderFloat( + "Delta Time", + &deltaTime, + -100000.f, + 100000.f, + "%.3f", + 5.f + ); if (changed) { OsEng.scriptEngine().queueScript( "openspace.time.setDeltaTime(" + std::to_string(deltaTime) + ")", @@ -273,7 +280,10 @@ void GuiSpaceTimeComponent::render() { bool isPaused = OsEng.timeManager().time().paused(); - bool pauseChanged = ImGui::Button(isPaused ? "Resume" : "Pause", { ImGui::GetWindowWidth() - 7.5f, 0.f } ); + bool pauseChanged = ImGui::Button( + isPaused ? "Resume" : "Pause", + { ImGui::GetWindowWidth() - 7.5f, 0.f } + ); if (pauseChanged) { OsEng.scriptEngine().queueScript( "openspace.time.togglePause()", diff --git a/modules/iswa/rendering/datacygnet.h b/modules/iswa/rendering/datacygnet.h index f75726c802..7e570cef17 100644 --- a/modules/iswa/rendering/datacygnet.h +++ b/modules/iswa/rendering/datacygnet.h @@ -109,7 +109,8 @@ protected: private: bool readyToRender() const override; - bool downloadTextureResource(double timestamp = OsEng.timeManager().time().j2000Seconds()) override; + bool downloadTextureResource( + double timestamp = OsEng.timeManager().time().j2000Seconds()) override; }; } //namespace openspace diff --git a/modules/iswa/rendering/dataplane.cpp b/modules/iswa/rendering/dataplane.cpp index bc03293756..5b6659dc2f 100644 --- a/modules/iswa/rendering/dataplane.cpp +++ b/modules/iswa/rendering/dataplane.cpp @@ -103,9 +103,23 @@ bool DataPlane::createGeometry() { glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(0)); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 6, + reinterpret_cast(0) + ); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(sizeof(GLfloat) * 4)); + glVertexAttribPointer( + 1, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 6, + reinterpret_cast(sizeof(GLfloat) * 4) + ); return true; } @@ -155,14 +169,19 @@ std::vector DataPlane::textureData(){ std::chrono::time_point start, end; start = std::chrono::system_clock::now(); // =========== - std::vector d = _dataProcessor->processData(_dataBuffer, _dataOptions, _textureDimensions); + std::vector d = _dataProcessor->processData( + _dataBuffer, + _dataOptions, + _textureDimensions + ); // FOR TESTING // =========== end = std::chrono::system_clock::now(); _numOfBenchmarks++; std::chrono::duration elapsed_seconds = end-start; - _avgBenchmarkTime = ( (_avgBenchmarkTime * (_numOfBenchmarks-1)) + elapsed_seconds.count() ) / _numOfBenchmarks; + _avgBenchmarkTime = ((_avgBenchmarkTime * (_numOfBenchmarks - 1)) + + elapsed_seconds.count()) / _numOfBenchmarks; std::cout << " processData() " << name() << std::endl; std::cout << "avg elapsed time: " << _avgBenchmarkTime << "s\n"; std::cout << "num Benchmarks: " << _numOfBenchmarks << "\n"; @@ -171,4 +190,4 @@ std::vector DataPlane::textureData(){ return d; } -}// namespace openspace +} // namespace openspace diff --git a/modules/iswa/rendering/iswabasegroup.cpp b/modules/iswa/rendering/iswabasegroup.cpp index efe81edf7e..e1805de35d 100644 --- a/modules/iswa/rendering/iswabasegroup.cpp +++ b/modules/iswa/rendering/iswabasegroup.cpp @@ -108,12 +108,18 @@ std::shared_ptr > IswaBaseGroup::groupEvent() { void IswaBaseGroup::registerProperties(){ _enabled.onChange([this]{ LDEBUG("Group " + name() + " published enabledChanged"); - _groupEvent->publish("enabledChanged", ghoul::Dictionary({{"enabled", _enabled.value()}})); + _groupEvent->publish( + "enabledChanged", + ghoul::Dictionary({{"enabled", _enabled.value()}}) + ); }); _alpha.onChange([this]{ LDEBUG("Group " + name() + " published alphaChanged"); - _groupEvent->publish("alphaChanged", ghoul::Dictionary({{"alpha", _alpha.value()}})); + _groupEvent->publish( + "alphaChanged", + ghoul::Dictionary({{"alpha", _alpha.value()}}) + ); }); diff --git a/modules/iswa/rendering/iswacygnet.h b/modules/iswa/rendering/iswacygnet.h index b7fa75dc35..3857a49abc 100644 --- a/modules/iswa/rendering/iswacygnet.h +++ b/modules/iswa/rendering/iswacygnet.h @@ -118,7 +118,8 @@ protected: * this should be the data file. * @return true if update was successfull */ - virtual bool downloadTextureResource(double timestamp = OsEng.timeManager().time().j2000Seconds()) = 0; + virtual bool downloadTextureResource( + double timestamp = OsEng.timeManager().time().j2000Seconds()) = 0; virtual bool readyToRender() const = 0; /** * should set all uniforms needed to render diff --git a/modules/iswa/rendering/iswadatagroup.cpp b/modules/iswa/rendering/iswadatagroup.cpp index ed39c58bce..9b6dfaf0a0 100644 --- a/modules/iswa/rendering/iswadatagroup.cpp +++ b/modules/iswa/rendering/iswadatagroup.cpp @@ -122,12 +122,18 @@ void IswaDataGroup::registerProperties(){ _useLog.onChange([this]{ LDEBUG("Group " + name() + " published useLogChanged"); - _groupEvent->publish("useLogChanged", ghoul::Dictionary({{"useLog", _useLog.value()}})); + _groupEvent->publish( + "useLogChanged", + ghoul::Dictionary({{"useLog", _useLog.value()}}) + ); }); _useHistogram.onChange([this]{ LDEBUG("Group " + name() + " published useHistogramChanged"); - _groupEvent->publish("useHistogramChanged", ghoul::Dictionary({{"useHistogram", _useHistogram.value()}})); + _groupEvent->publish( + "useHistogramChanged", + ghoul::Dictionary({{"useHistogram", _useHistogram.value()}}) + ); }); //If autofiler is on, background values property should be hidden @@ -144,22 +150,34 @@ void IswaDataGroup::registerProperties(){ _backgroundValues.setVisibility(properties::Property::Visibility::All); //_backgroundValues.setVisible(true); } - _groupEvent->publish("autoFilterChanged", ghoul::Dictionary({{"autoFilter", _autoFilter.value()}})); + _groupEvent->publish( + "autoFilterChanged", + ghoul::Dictionary({{"autoFilter", _autoFilter.value()}}) + ); }); _normValues.onChange([this]{ LDEBUG("Group " + name() + " published normValuesChanged"); - _groupEvent->publish("normValuesChanged", ghoul::Dictionary({{"normValues", _normValues.value()}})); + _groupEvent->publish( + "normValuesChanged", + ghoul::Dictionary({{"normValues", _normValues.value()}}) + ); }); _backgroundValues.onChange([this]{ LDEBUG("Group " + name() + " published backgroundValuesChanged"); - _groupEvent->publish("backgroundValuesChanged", ghoul::Dictionary({{"backgroundValues", _backgroundValues.value()}})); + _groupEvent->publish( + "backgroundValuesChanged", + ghoul::Dictionary({{"backgroundValues", _backgroundValues.value()}}) + ); }); _transferFunctionsFile.onChange([this]{ LDEBUG("Group " + name() + " published transferFunctionsChanged"); - _groupEvent->publish("transferFunctionsChanged", ghoul::Dictionary({{"transferFunctions", _transferFunctionsFile.value()}})); + _groupEvent->publish( + "transferFunctionsChanged", + ghoul::Dictionary({{"transferFunctions", _transferFunctionsFile.value()}}) + ); }); _dataOptions.onChange([this]{ @@ -170,29 +188,32 @@ void IswaDataGroup::registerProperties(){ }); } -void IswaDataGroup::registerOptions(const std::vector& options){ - if(!_registered) +void IswaDataGroup::registerOptions( + const std::vector& options) +{ + if (!_registered) { registerProperties(); + } - if(_dataOptions.options().empty()){ - for(auto option : options){ + if (_dataOptions.options().empty()) { + for (auto option : options) { _dataOptions.addOption({option.value, option.description}); } _dataOptions.setValue(std::vector(1,0)); } } -void IswaDataGroup::createDataProcessor(){ - if(_type == typeid(DataPlane).name()){ +void IswaDataGroup::createDataProcessor() { + if (_type == typeid(DataPlane).name()) { _dataProcessor = std::make_shared(); - }else if(_type == typeid(DataSphere).name()){ + }else if (_type == typeid(DataSphere).name()) { _dataProcessor = std::make_shared(); - }else if(_type == typeid(KameleonPlane).name()){ + }else if (_type == typeid(KameleonPlane).name()) { _dataProcessor = std::make_shared(); } } -std::vector IswaDataGroup::dataOptionsValue(){ +std::vector IswaDataGroup::dataOptionsValue() { return _dataOptions.value(); } diff --git a/modules/iswa/rendering/iswadatagroup.h b/modules/iswa/rendering/iswadatagroup.h index 34543e734c..1ea58ab9b2 100644 --- a/modules/iswa/rendering/iswadatagroup.h +++ b/modules/iswa/rendering/iswadatagroup.h @@ -36,7 +36,8 @@ public: IswaDataGroup(std::string name, std::string type); ~IswaDataGroup(); - void registerOptions(const std::vector& options); + void registerOptions( + const std::vector& options); std::vector dataOptionsValue(); protected: diff --git a/modules/iswa/rendering/iswakameleongroup.cpp b/modules/iswa/rendering/iswakameleongroup.cpp index 5d6e0eeff6..303a4baa1b 100644 --- a/modules/iswa/rendering/iswakameleongroup.cpp +++ b/modules/iswa/rendering/iswakameleongroup.cpp @@ -66,14 +66,14 @@ IswaKameleonGroup::IswaKameleonGroup(std::string name, std::string type) registerProperties(); } -IswaKameleonGroup::~IswaKameleonGroup(){} +IswaKameleonGroup::~IswaKameleonGroup() {} -void IswaKameleonGroup::clearGroup(){ +void IswaKameleonGroup::clearGroup() { IswaBaseGroup::clearGroup(); clearFieldlines(); } -std::vector IswaKameleonGroup::fieldlineValue(){ +std::vector IswaKameleonGroup::fieldlineValue() { return _fieldlines.value(); } @@ -148,13 +148,18 @@ void IswaKameleonGroup::readFieldlinePaths(std::string indexFile) { } } -void IswaKameleonGroup::updateFieldlineSeeds(){ +void IswaKameleonGroup::updateFieldlineSeeds() { std::vector selectedOptions = _fieldlines.value(); - // SeedPath == map > - for (auto& seedPath: _fieldlineState) { + // SeedPath == map> + for (auto& seedPath : _fieldlineState) { // if this option was turned off - if (std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)==selectedOptions.end() && std::get<2>(seedPath.second)){ + auto it = std::find( + selectedOptions.begin(), + selectedOptions.end(), + seedPath.first + ); + if (it == selectedOptions.end() && std::get<2>(seedPath.second)) { LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); OsEng.scriptEngine().queueScript( "openspace.removeSceneGraphNode('" + std::get<0>(seedPath.second) + "')", @@ -162,17 +167,20 @@ void IswaKameleonGroup::updateFieldlineSeeds(){ ); std::get<2>(seedPath.second) = false; // if this option was turned on - } else if( std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)!=selectedOptions.end() && !std::get<2>(seedPath.second)) { + } else if (it != selectedOptions.end() && !std::get<2>(seedPath.second)) { LDEBUG("Created fieldlines: " + std::get<0>(seedPath.second)); - IswaManager::ref().createFieldline(std::get<0>(seedPath.second), _kameleonPath, std::get<1>(seedPath.second)); + IswaManager::ref().createFieldline( + std::get<0>(seedPath.second), + _kameleonPath, + std::get<1>(seedPath.second) + ); std::get<2>(seedPath.second) = true; } } } -void IswaKameleonGroup::clearFieldlines(){ - // SeedPath == map > - for (auto& seedPath: _fieldlineState) { +void IswaKameleonGroup::clearFieldlines() { + for (auto& seedPath : _fieldlineState) { if(std::get<2>(seedPath.second)){ LDEBUG("Removed fieldlines: " + std::get<0>(seedPath.second)); OsEng.scriptEngine().queueScript( @@ -184,7 +192,7 @@ void IswaKameleonGroup::clearFieldlines(){ } } -void IswaKameleonGroup::changeCdf(std::string path){ +void IswaKameleonGroup::changeCdf(std::string path) { _kameleonPath = path; clearFieldlines(); updateFieldlineSeeds(); diff --git a/modules/iswa/rendering/kameleonplane.cpp b/modules/iswa/rendering/kameleonplane.cpp index 12f0ecf14c..950af58866 100644 --- a/modules/iswa/rendering/kameleonplane.cpp +++ b/modules/iswa/rendering/kameleonplane.cpp @@ -164,7 +164,9 @@ void KameleonPlane::initialize() { updateFieldlineSeeds(); }); - std::dynamic_pointer_cast(_dataProcessor)->dimensions(_dimensions); + std::dynamic_pointer_cast(_dataProcessor)->dimensions( + _dimensions + ); _dataProcessor->addDataValues(_kwPath, _dataOptions); // if this datacygnet has added new values then reload texture // for the whole group, including this datacygnet, and return after. @@ -263,11 +265,19 @@ void KameleonPlane::setUniforms() { void KameleonPlane::updateFieldlineSeeds() { std::vector selectedOptions = _fieldlines.value(); - // SeedPath == map > - for (auto& seedPath: _fieldlineState) { + // SeedPath == map> + for (auto& seedPath : _fieldlineState) { // if this option was turned off - if (std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)==selectedOptions.end() && std::get<2>(seedPath.second)) { - if (OsEng.renderEngine().scene()->sceneGraphNode(std::get<0>(seedPath.second)) == nullptr) { + auto it = std::find( + selectedOptions.begin(), + selectedOptions.end(), + seedPath.first + ); + if (it == selectedOptions.end() && std::get<2>(seedPath.second)) { + SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode( + std::get<0>(seedPath.second) + ); + if (!n) { return; } @@ -278,12 +288,20 @@ void KameleonPlane::updateFieldlineSeeds() { ); std::get<2>(seedPath.second) = false; // if this option was turned on - } else if (std::find(selectedOptions.begin(), selectedOptions.end(), seedPath.first)!=selectedOptions.end() && !std::get<2>(seedPath.second)) { - if (OsEng.renderEngine().scene()->sceneGraphNode(std::get<0>(seedPath.second)) != nullptr) { + } else if (it != selectedOptions.end() && !std::get<2>(seedPath.second)) { + SceneGraphNode* n = OsEng.renderEngine().scene()->sceneGraphNode( + std::get<0>(seedPath.second) + ); + + if (n) { return; } LDEBUG("Created fieldlines: " + std::get<0>(seedPath.second)); - IswaManager::ref().createFieldline(std::get<0>(seedPath.second), _kwPath, std::get<1>(seedPath.second)); + IswaManager::ref().createFieldline( + std::get<0>(seedPath.second), + _kwPath, + std::get<1>(seedPath.second) + ); std::get<2>(seedPath.second) = true; } } @@ -321,7 +339,10 @@ void KameleonPlane::readFieldlinePaths(std::string indexFile) { i++; } } catch (const std::exception& e) { - LERROR("Error when reading json file with paths to seedpoints: " + std::string(e.what())); + LERROR( + "Error when reading json file with paths to seedpoints: " + + std::string(e.what()) + ); } } } @@ -332,7 +353,7 @@ void KameleonPlane::subscribeToGroup() { //Add additional Events specific to KameleonPlane auto groupEvent = _group->groupEvent(); - groupEvent->subscribe(name(), "resolutionChanged", [&](ghoul::Dictionary dict){ + groupEvent->subscribe(name(), "resolutionChanged", [&](ghoul::Dictionary dict) { LDEBUG(name() + " Event resolutionChanged"); float resolution; bool success = dict.getValue("resolution", resolution); @@ -341,7 +362,7 @@ void KameleonPlane::subscribeToGroup() { } }); - groupEvent->subscribe(name(), "cdfChanged", [&](ghoul::Dictionary dict){ + groupEvent->subscribe(name(), "cdfChanged", [&](ghoul::Dictionary dict) { LDEBUG(name() + " Event cdfChanged"); std::string path; bool success = dict.getValue("path", path); @@ -355,8 +376,8 @@ void KameleonPlane::subscribeToGroup() { void KameleonPlane::setDimensions() { // the cdf files has an offset of 0.5 in normali resolution. // with lower resolution the offset increases. - _data->offset = _origOffset - 0.5f*(100.0f/_resolution.value()); - _dimensions = glm::size3_t(_data->scale*((float)_resolution.value()/100.f)); + _data->offset = _origOffset - 0.5f* (100.f / _resolution.value()); + _dimensions = glm::size3_t(_data->scale * ((float)_resolution.value() / 100.f)); _dimensions[_cut] = 1; if (_cut == 0) { diff --git a/modules/iswa/rendering/kameleonplane.h b/modules/iswa/rendering/kameleonplane.h index 8fc3f3874c..d03160dd41 100644 --- a/modules/iswa/rendering/kameleonplane.h +++ b/modules/iswa/rendering/kameleonplane.h @@ -93,8 +93,10 @@ private: /** * _fieldlineState maps the checkbox value of each fieldline seedpoint file to a tuple - * containing information that is needed to either add or remove a fieldline from the scenegraph. - * this is the name, path to seedpoints file and a boolean to determine if it is active or inactive. + * containing information that is needed to either add or remove a fieldline from the + * scenegraph. + * This is the name, path to seedpoints file and a boolean to determine if it is + * active or inactive. */ std::map > _fieldlineState; std::string _fieldlineIndexFile; diff --git a/modules/iswa/rendering/screenspacecygnet.cpp b/modules/iswa/rendering/screenspacecygnet.cpp index 118db6e162..28959ffb73 100644 --- a/modules/iswa/rendering/screenspacecygnet.cpp +++ b/modules/iswa/rendering/screenspacecygnet.cpp @@ -53,7 +53,9 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); _lastUpdateOpenSpaceTime = _openSpaceTime; - _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + _realTime = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ); _lastUpdateRealTime = _realTime; _minRealTimeUpdateInterval = 100; @@ -67,16 +69,19 @@ ScreenSpaceCygnet::ScreenSpaceCygnet(const ghoul::Dictionary& dictionary) } -ScreenSpaceCygnet::~ScreenSpaceCygnet(){} +ScreenSpaceCygnet::~ScreenSpaceCygnet() {} -void ScreenSpaceCygnet::update(){ +void ScreenSpaceCygnet::update() { _openSpaceTime = OsEng.timeManager().time().j2000Seconds(); - _realTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + _realTime = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + ); - bool timeToUpdate = (fabs(_openSpaceTime-_lastUpdateOpenSpaceTime) >= _updateTime && - (_realTime.count()-_lastUpdateRealTime.count()) > _minRealTimeUpdateInterval); + bool timeToUpdate = + (fabs(_openSpaceTime-_lastUpdateOpenSpaceTime) >= _updateTime && + (_realTime.count()-_lastUpdateRealTime.count()) > _minRealTimeUpdateInterval); - if((OsEng.timeManager().time().timeJumped() || timeToUpdate )){ + if ((OsEng.timeManager().time().timeJumped() || timeToUpdate )) { _texturePath = IswaManager::ref().iswaUrl(_cygnetId); _lastUpdateRealTime = _realTime; _lastUpdateOpenSpaceTime = _openSpaceTime; diff --git a/modules/iswa/rendering/texturecygnet.cpp b/modules/iswa/rendering/texturecygnet.cpp index ea235dd086..b036fb71ff 100644 --- a/modules/iswa/rendering/texturecygnet.cpp +++ b/modules/iswa/rendering/texturecygnet.cpp @@ -50,7 +50,7 @@ bool TextureCygnet::updateTexture() { if (texture) { LDEBUG("Loaded texture from image iswa cygnet with id: '" << _data->id << "'"); texture->uploadTexture(); - // Textures of planets looks much smoother with AnisotropicMipMap rather than linear + // Textures of planets looks much smoother with AnisotropicMipMap texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear); _textures[0] = std::move(texture); } diff --git a/modules/iswa/rendering/texturecygnet.h b/modules/iswa/rendering/texturecygnet.h index a53b052cd2..d7a0050549 100644 --- a/modules/iswa/rendering/texturecygnet.h +++ b/modules/iswa/rendering/texturecygnet.h @@ -43,7 +43,8 @@ public: protected: bool updateTexture() override; - bool downloadTextureResource(double timestamp = OsEng.timeManager().time().j2000Seconds()) override; + bool downloadTextureResource( + double timestamp = OsEng.timeManager().time().j2000Seconds()) override; bool readyToRender() const override; bool updateTextureResource() override; diff --git a/modules/iswa/rendering/textureplane.cpp b/modules/iswa/rendering/textureplane.cpp index 4a4f0a31a9..74d3567190 100644 --- a/modules/iswa/rendering/textureplane.cpp +++ b/modules/iswa/rendering/textureplane.cpp @@ -83,9 +83,23 @@ bool TexturePlane::createGeometry() { glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(0)); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 6, + reinterpret_cast(0) + ); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(sizeof(GLfloat) * 4)); + glVertexAttribPointer( + 1, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(GLfloat) * 6, + reinterpret_cast(sizeof(GLfloat) * 4) + ); return true; } diff --git a/modules/iswa/util/dataprocessor.cpp b/modules/iswa/util/dataprocessor.cpp index 98663d863b..1fd42840dc 100644 --- a/modules/iswa/util/dataprocessor.cpp +++ b/modules/iswa/util/dataprocessor.cpp @@ -167,8 +167,18 @@ void DataProcessor::calculateFilterValues(std::vector selectedOptions) { filterMid = histogram->highestBinValue(_useHistogram); filterWidth = mean+histogram->binWidth(); - filterMid = normalizeWithStandardScore(filterMid, mean, standardDeviation, _normValues); - filterWidth = fabs(0.5-normalizeWithStandardScore(filterWidth, mean, standardDeviation, _normValues)); + filterMid = normalizeWithStandardScore( + filterMid, + mean, + standardDeviation, + _normValues + ); + filterWidth = fabs(0.5-normalizeWithStandardScore( + filterWidth, + mean, + standardDeviation, + _normValues) + ); } else { Histogram hist = _histograms[option]->equalize(); filterMid = hist.highestBinValue(true); @@ -208,13 +218,24 @@ void DataProcessor::add(std::vector>& optionValues, float oldMean = (1.0f/_numValues[i])*_sum[i]; _sum[i] += sum[i]; - _standardDeviation[i] = sqrt(pow(standardDeviation, 2) + pow(_standardDeviation[i], 2)); + _standardDeviation[i] = sqrt(pow(standardDeviation, 2) + + pow(_standardDeviation[i], 2)); _numValues[i] += numValues; mean = (1.0f/_numValues[i])*_sum[i]; - float min = normalizeWithStandardScore(_min[i], mean, _standardDeviation[i], _histNormValues); - float max = normalizeWithStandardScore(_max[i], mean, _standardDeviation[i], _histNormValues); + float min = normalizeWithStandardScore( + _min[i], + mean, + _standardDeviation[i], + _histNormValues + ); + float max = normalizeWithStandardScore( + _max[i], + mean, + _standardDeviation[i], + _histNormValues + ); if (!_histograms[i]) { _histograms[i] = std::make_shared(min, max, 512); @@ -225,20 +246,50 @@ void DataProcessor::add(std::vector>& optionValues, float histMax = _histograms[i]->maxValue(); int numBins = _histograms[i]->numBins(); - float unNormHistMin = unnormalizeWithStandardScore(histMin, oldMean, oldStandardDeviation, _histNormValues); - float unNormHistMax = unnormalizeWithStandardScore(histMax, oldMean, oldStandardDeviation, _histNormValues); + float unNormHistMin = unnormalizeWithStandardScore( + histMin, + oldMean, + oldStandardDeviation, + _histNormValues + ); + float unNormHistMax = unnormalizeWithStandardScore( + histMax, + oldMean, + oldStandardDeviation, + _histNormValues + ); //unnormalize histMin, histMax // min = std::min(min, histMin) std::shared_ptr newHist = std::make_shared( - std::min(min, normalizeWithStandardScore(unNormHistMin, mean, _standardDeviation[i], _histNormValues)), - std::min(max, normalizeWithStandardScore(unNormHistMax, mean, _standardDeviation[i], _histNormValues)), + std::min(min, normalizeWithStandardScore( + unNormHistMin, + mean, + _standardDeviation[i], + _histNormValues + )), + std::min(max, normalizeWithStandardScore( + unNormHistMax, + mean, + _standardDeviation[i], + _histNormValues + )), numBins ); for (int j = 0; j < numBins; j++) { value = j * (histMax-histMin)+histMin; - value = unnormalizeWithStandardScore(value, oldMean, oldStandardDeviation, _histNormValues); - _histograms[i]->add(normalizeWithStandardScore(value, mean, _standardDeviation[i], _histNormValues), histData[j]); + value = unnormalizeWithStandardScore( + value, + oldMean, + oldStandardDeviation, + _histNormValues + ); + _histograms[i]->add(normalizeWithStandardScore( + value, + mean, + _standardDeviation[i], + _histNormValues + ), histData[j]); } // _histograms[i]->changeRange(min, max); _histograms[i] = newHist; @@ -246,7 +297,12 @@ void DataProcessor::add(std::vector>& optionValues, for (int j = 0; j < numValues; j++) { value = values[j]; - _histograms[i]->add(normalizeWithStandardScore(value, mean, _standardDeviation[i], _histNormValues), 1); + _histograms[i]->add(normalizeWithStandardScore( + value, + mean, + _standardDeviation[i], + _histNormValues + ), 1); } _histograms[i]->generateEqualizer(); diff --git a/modules/iswa/util/dataprocessor.h b/modules/iswa/util/dataprocessor.h index 8c3dec76ac..d8b0ab897f 100644 --- a/modules/iswa/util/dataprocessor.h +++ b/modules/iswa/util/dataprocessor.h @@ -39,9 +39,12 @@ public: DataProcessor(); virtual ~DataProcessor(); - virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) = 0; - virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) = 0; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) = 0; + virtual std::vector readMetadata(std::string data, + glm::size3_t& dimensions) = 0; + virtual void addDataValues(std::string data, + properties::SelectionProperty& dataOptions) = 0; + virtual std::vector processData(std::string data, + properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) = 0; void useLog(bool useLog); void useHistogram(bool useHistogram); @@ -53,8 +56,10 @@ public: protected: float processDataPoint(float value, int option); - float normalizeWithStandardScore(float value, float mean, float sd, glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); - float unnormalizeWithStandardScore(float value, float mean, float sd, glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); + float normalizeWithStandardScore(float value, float mean, float sd, + glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); + float unnormalizeWithStandardScore(float value, float mean, float sd, + glm::vec2 normalizationValues = glm::vec2(1.0f, 1.0f)); void initializeVectors(int numOptions); void calculateFilterValues(std::vector selectedOptions); diff --git a/modules/iswa/util/dataprocessorjson.cpp b/modules/iswa/util/dataprocessorjson.cpp index 880b721af8..d56f81010c 100644 --- a/modules/iswa/util/dataprocessorjson.cpp +++ b/modules/iswa/util/dataprocessorjson.cpp @@ -40,22 +40,24 @@ DataProcessorJson::DataProcessorJson() DataProcessorJson::~DataProcessorJson() {} -std::vector DataProcessorJson::readMetadata(std::string data, glm::size3_t& dimensions){ +std::vector DataProcessorJson::readMetadata(std::string data, + glm::size3_t& dimensions) +{ std::vector options = std::vector(); - if(!data.empty()){ + if (!data.empty()) { json j = json::parse(data); json variables = j["variables"]; - for(json::iterator it = variables.begin(); it != variables.end(); ++it){ + for (json::iterator it = variables.begin(); it != variables.end(); ++it) { std::string option = it.key(); - if(option == "ep"){ + if (option == "ep") { json row = it.value(); json col = row.at(0); dimensions = glm::size3_t(col.size(), row.size(), 1); } - if(_coordinateVariables.find(option) == _coordinateVariables.end()){ + if (_coordinateVariables.find(option) == _coordinateVariables.end()) { options.push_back(option); } } @@ -63,11 +65,13 @@ std::vector DataProcessorJson::readMetadata(std::string data, glm:: return options; } -void DataProcessorJson::addDataValues(std::string data, properties::SelectionProperty& dataOptions){ +void DataProcessorJson::addDataValues(std::string data, + properties::SelectionProperty& dataOptions) +{ int numOptions = dataOptions.options().size(); initializeVectors(numOptions); - if(!data.empty()){ + if (!data.empty()) { json j = json::parse(data); json variables = j["variables"]; @@ -77,7 +81,7 @@ void DataProcessorJson::addDataValues(std::string data, properties::SelectionPro float value; - for(int i=0; i DataProcessorJson::processData(std::string data, std::vector dataOptions(numOptions, nullptr); for(int option : selectedOptions){ - dataOptions[option] = new float[dimensions.x*dimensions.y]{0.0f}; + dataOptions[option] = new float[dimensions.x*dimensions.y]{0.f}; json row = variables[options[option].description]; rowsize = row.size(); diff --git a/modules/iswa/util/dataprocessorjson.h b/modules/iswa/util/dataprocessorjson.h index 7a13281438..12ae5ef6b6 100644 --- a/modules/iswa/util/dataprocessorjson.h +++ b/modules/iswa/util/dataprocessorjson.h @@ -34,9 +34,12 @@ public: DataProcessorJson(); virtual ~DataProcessorJson(); - virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) override; - virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; + virtual std::vector readMetadata(std::string data, + glm::size3_t& dimensions) override; + virtual void addDataValues(std::string data, + properties::SelectionProperty& dataOptions) override; + virtual std::vector processData(std::string data, + properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; }; } // namespace openspace diff --git a/modules/iswa/util/dataprocessorkameleon.cpp b/modules/iswa/util/dataprocessorkameleon.cpp index 7864999e13..36c3b3f3b4 100644 --- a/modules/iswa/util/dataprocessorkameleon.cpp +++ b/modules/iswa/util/dataprocessorkameleon.cpp @@ -42,21 +42,25 @@ DataProcessorKameleon::DataProcessorKameleon() DataProcessorKameleon::~DataProcessorKameleon(){} -std::vector DataProcessorKameleon::readMetadata(std::string path, glm::size3_t& dimensions){ - - if(!path.empty()){ - if(path != _kwPath || !_kw){ - +std::vector DataProcessorKameleon::readMetadata(std::string path, + glm::size3_t& dimensions) +{ + if (!path.empty()) { + if (path != _kwPath || !_kw) { initializeKameleonWrapper(path); } std::vector opts = _kw->getVariables(); - opts.erase( std::remove_if( - opts.begin(), - opts.end(), - [this](std::string opt){ return (opt.size() > 3 || _coordinateVariables.find(opt) != _coordinateVariables.end());} + opts.erase( + std::remove_if( + opts.begin(), + opts.end(), + [this](std::string opt) { + return (opt.size() > 3 || + _coordinateVariables.find(opt) != _coordinateVariables.end()); + } ), - opts.end() + opts.end() ); return opts; } @@ -64,13 +68,16 @@ std::vector DataProcessorKameleon::readMetadata(std::string path, g return std::vector(); } -void DataProcessorKameleon::addDataValues(std::string path, properties::SelectionProperty& dataOptions){ +void DataProcessorKameleon::addDataValues(std::string path, + properties::SelectionProperty& dataOptions) +{ int numOptions = dataOptions.options().size(); initializeVectors(numOptions); - if(!path.empty()){ - if(path != _kwPath || !_kw) + if (!path.empty()) { + if (path != _kwPath || !_kw) { initializeKameleonWrapper(path); + } std::vector sum(numOptions, 0.0f); std::vector> optionValues(numOptions, std::vector()); @@ -81,11 +88,15 @@ void DataProcessorKameleon::addDataValues(std::string path, properties::Selectio float* values; float value; - for(int i=0; igetUniformSliceValues(options[i].description, _dimensions, 0.5f); + values = _kw->getUniformSliceValues( + options[i].description, + _dimensions, + 0.5f + ); - for(int j=0; j DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions, float slice){ +std::vector DataProcessorKameleon::processData(std::string path, + properties::SelectionProperty& dataOptions, + glm::size3_t& dimensions, + float slice) +{ _slice = slice; // _dimensions = dimensions; return processData(path, dataOptions, dimensions); } -std::vector DataProcessorKameleon::processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions){ +std::vector DataProcessorKameleon::processData(std::string path, + properties::SelectionProperty& dataOptions, + glm::size3_t& dimensions) +{ int numOptions = dataOptions.options().size(); - if(!path.empty()){ - if(path != _kwPath || !_kw) + if (!path.empty()) { + if (path != _kwPath || !_kw) { initializeKameleonWrapper(path); + } std::vector selectedOptions = dataOptions.value(); // int numSelected = selectedOptions.size(); @@ -122,10 +141,14 @@ std::vector DataProcessorKameleon::processData(std::string path, propert float value; std::vector dataOptions(numOptions, nullptr); - for(int option : selectedOptions){ - dataOptions[option] = _kw->getUniformSliceValues(options[option].description, dimensions, _slice); + for (int option : selectedOptions) { + dataOptions[option] = _kw->getUniformSliceValues( + options[option].description, + dimensions, + _slice + ); - for(int i=0; i DataProcessorKameleon::processData(std::string path, propert return std::vector(numOptions, nullptr); } +void DataProcessorKameleon::dimensions(glm::size3_t dimensions) { + _dimensions = dimensions; +} + void DataProcessorKameleon::initializeKameleonWrapper(std::string path){ const std::string& extension = ghoul::filesystem::File(absPath(path)).fileExtension(); if(FileSys.fileExists(absPath(path)) && extension == "cdf"){ diff --git a/modules/iswa/util/dataprocessorkameleon.h b/modules/iswa/util/dataprocessorkameleon.h index f7206bea11..85b9e26c85 100644 --- a/modules/iswa/util/dataprocessorkameleon.h +++ b/modules/iswa/util/dataprocessorkameleon.h @@ -35,11 +35,16 @@ public: DataProcessorKameleon(); ~DataProcessorKameleon(); - virtual std::vector readMetadata(std::string path, glm::size3_t& dimensions) override; - virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; - virtual std::vector processData(std::string path, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions, float slice); - void dimensions(glm::size3_t dimensions){_dimensions = dimensions;} + virtual std::vector readMetadata(std::string path, + glm::size3_t& dimensions) override; + virtual void addDataValues(std::string data, + properties::SelectionProperty& dataOptions) override; + virtual std::vector processData(std::string path, + properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; + virtual std::vector processData(std::string path, + properties::SelectionProperty& dataOptions, glm::size3_t& dimensions, + float slice); + void dimensions(glm::size3_t dimensions); private: void initializeKameleonWrapper(std::string kwPath); diff --git a/modules/iswa/util/dataprocessortext.cpp b/modules/iswa/util/dataprocessortext.cpp index 11f8f85bfc..a9e584a0f5 100644 --- a/modules/iswa/util/dataprocessortext.cpp +++ b/modules/iswa/util/dataprocessortext.cpp @@ -44,13 +44,16 @@ DataProcessorText::DataProcessorText() DataProcessorText::~DataProcessorText(){} -std::vector DataProcessorText::readMetadata(std::string data, glm::size3_t& dimensions){ +std::vector DataProcessorText::readMetadata(std::string data, + glm::size3_t& dimensions) +{ //The intresting part of the file looks like this: //# Output data: field with 61x61=3721 elements //# x y z N V_x B_x std::vector options = std::vector(); - std::string info = "# Output data: field with "; //The string where the interesting data begins + // The string where the interesting data begins + std::string info = "# Output data: field with "; if(!data.empty()){ std::string line; std::stringstream memorystream(data); @@ -85,15 +88,18 @@ std::vector DataProcessorText::readMetadata(std::string data, glm:: return options; } -void DataProcessorText::addDataValues(std::string data, properties::SelectionProperty& dataOptions){ +void DataProcessorText::addDataValues(std::string data, + properties::SelectionProperty& dataOptions) +{ int numOptions = dataOptions.options().size(); initializeVectors(numOptions); - if(!data.empty()){ + if (!data.empty()) { std::string line; std::stringstream memorystream(data); - std::vector sum(numOptions, 0.0f); //for standard diviation in the add() function + // for standard diviation in the add() function + std::vector sum(numOptions, 0.0f); std::vector> optionValues(numOptions, std::vector()); std::vector values; @@ -140,9 +146,11 @@ void DataProcessorText::addDataValues(std::string data, properties::SelectionPro } } -std::vector DataProcessorText::processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions){ - if(!data.empty()){ - +std::vector DataProcessorText::processData(std::string data, + properties::SelectionProperty& dataOptions, + glm::size3_t& dimensions) +{ + if (!data.empty()) { std::string line; std::stringstream memorystream(data); @@ -178,8 +186,9 @@ std::vector DataProcessorText::processData(std::string data, properties: // back_inserter(values) // ); + // +3 because options x, y and z in the file // copy( - // std::next( std::istream_iterator (ss), 3 ), //+3 because options x, y and z in the file + // std::next( std::istream_iterator (ss), 3 ), // std::istream_iterator (), // back_inserter(values) // ); diff --git a/modules/iswa/util/dataprocessortext.h b/modules/iswa/util/dataprocessortext.h index 6e67aee407..039e1038f0 100644 --- a/modules/iswa/util/dataprocessortext.h +++ b/modules/iswa/util/dataprocessortext.h @@ -34,9 +34,12 @@ public: DataProcessorText(); ~DataProcessorText(); - virtual std::vector readMetadata(std::string data, glm::size3_t& dimensions) override; - virtual void addDataValues(std::string data, properties::SelectionProperty& dataOptions) override; - virtual std::vector processData(std::string data, properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; + virtual std::vector readMetadata(std::string data, + glm::size3_t& dimensions) override; + virtual void addDataValues(std::string data, + properties::SelectionProperty& dataOptions) override; + virtual std::vector processData(std::string data, + properties::SelectionProperty& dataOptions, glm::size3_t& dimensions) override; private: // void initialize(int numOptions); diff --git a/modules/iswa/util/iswamanager.cpp b/modules/iswa/util/iswamanager.cpp index 60f58d2f5b..4177affd57 100644 --- a/modules/iswa/util/iswamanager.cpp +++ b/modules/iswa/util/iswamanager.cpp @@ -139,35 +139,39 @@ void IswaManager::addIswaCygnet(int id, std::string type, std::string group) { return; } - // This callback determines what geometry should be used and creates the right cygbet + // This callback determines what geometry should be used and creates + // the right cygnet auto metadataCallback = - [this, metaFuture](const DownloadManager::MemoryFile& file) { - //Create a string from downloaded file - std::string res; - res.append(file.buffer, file.size); - //add it to the metafuture object - metaFuture->json = res; + [this, metaFuture](const DownloadManager::MemoryFile& file) { + //Create a string from downloaded file + std::string res; + res.append(file.buffer, file.size); + //add it to the metafuture object + metaFuture->json = res; - //convert to json - json j = json::parse(res); + //convert to json + json j = json::parse(res); - // Check what kind of geometry here - if (j["Coordinate Type"].is_null()) { - metaFuture->geom = CygnetGeometry::Sphere; - createSphere(metaFuture); - } else if (j["Coordinate Type"] == "Cartesian") { - metaFuture->geom = CygnetGeometry::Plane; - createPlane(metaFuture); - } - LDEBUG("Download to memory finished"); - }; + // Check what kind of geometry here + if (j["Coordinate Type"].is_null()) { + metaFuture->geom = CygnetGeometry::Sphere; + createSphere(metaFuture); + } else if (j["Coordinate Type"] == "Cartesian") { + metaFuture->geom = CygnetGeometry::Plane; + createPlane(metaFuture); + } + LDEBUG("Download to memory finished"); + }; // Download metadata OsEng.downloadManager().fetchFile( _baseUrl + std::to_string(-id), metadataCallback, [id](const std::string& err) { - LDEBUG("Download to memory was aborted for data cygnet with id "+ std::to_string(id)+": " + err); + LDEBUG( + "Download to memory was aborted for data cygnet with id " + + std::to_string(id)+": " + err + ); } ); } @@ -177,7 +181,9 @@ void IswaManager::addKameleonCdf(std::string groupName, int pos) { // auto info = _cdfInformation[group][pos]; auto group = iswaGroup(groupName); if (group) { - std::dynamic_pointer_cast(group)->changeCdf(_cdfInformation[groupName][pos].path); + std::dynamic_pointer_cast(group)->changeCdf( + _cdfInformation[groupName][pos].path + ); return; } @@ -186,7 +192,9 @@ void IswaManager::addKameleonCdf(std::string groupName, int pos) { createKameleonPlane(_cdfInformation[groupName][pos], "x"); } -std::future IswaManager::fetchImageCygnet(int id, double timestamp) { +std::future IswaManager::fetchImageCygnet(int id, + double timestamp) +{ return std::move(OsEng.downloadManager().fetchFile( iswaUrl(id, timestamp, "image"), [id](const DownloadManager::MemoryFile&) { @@ -204,7 +212,9 @@ std::future IswaManager::fetchImageCygnet(int id, d ) ); } -std::future IswaManager::fetchDataCygnet(int id, double timestamp) { +std::future IswaManager::fetchDataCygnet(int id, + double timestamp) +{ return std::move(OsEng.downloadManager().fetchFile( iswaUrl(id, timestamp, "data"), [id](const DownloadManager::MemoryFile&) { @@ -227,7 +237,8 @@ std::string IswaManager::iswaUrl(int id, double timestamp, std::string type) { if (id < 0) { url = _baseUrl + type+"/" + std::to_string(-id) + "/"; } else { - url = "http://iswa3.ccmc.gsfc.nasa.gov/IswaSystemWebApp/iSWACygnetStreamer?window=-1&cygnetId="+ std::to_string(id) +"×tamp="; + url = "http://iswa3.ccmc.gsfc.nasa.gov/IswaSystemWebApp/iSWACygnetStreamer?" + "window=-1&cygnetId="+ std::to_string(id) +"×tamp="; } //std::string t = Time::ref().currentTimeUTC(); @@ -254,11 +265,20 @@ void IswaManager::registerGroup(std::string groupName, std::string type) { bool kameleonGroup = (type == typeid(KameleonPlane).name()); if (dataGroup) { - _groups.insert(std::pair>(groupName, std::make_shared(groupName, type))); + _groups.insert(std::pair>( + groupName, + std::make_shared(groupName, type)) + ); } else if (kameleonGroup) { - _groups.insert(std::pair>(groupName, std::make_shared(groupName, type))); + _groups.insert(std::pair>( + groupName, + std::make_shared(groupName, type)) + ); } else { - _groups.insert(std::pair>(groupName, std::make_shared(groupName, type))); + _groups.insert(std::pair>( + groupName, + std::make_shared(groupName, type)) + ); } } else if (!_groups[groupName]->isType(type)) { LWARNING("Can't add cygnet to groups with diffent type"); @@ -368,8 +388,10 @@ std::string IswaManager::jsonPlaneToLuaTable(std::shared_ptr dat std::string IswaManager::parseKWToLuaTable(CdfInfo info, std::string cut) { if (info.path != "") { - const std::string& extension = ghoul::filesystem::File(absPath(info.path)).fileExtension(); - if(extension == "cdf"){ + const std::string& extension = ghoul::filesystem::File( + absPath(info.path) + ).fileExtension(); + if(extension == "cdf") { KameleonWrapper kw = KameleonWrapper(absPath(info.path)); std::string parent = kw.getParent(); @@ -380,8 +402,13 @@ std::string IswaManager::parseKWToLuaTable(CdfInfo info, std::string cut) { glm::vec4 spatialScale; std::string coordinateType; - std::tuple gridUnits = kw.getGridUnits(); - if (std::get<0>(gridUnits) == "R" && std::get<1>(gridUnits) == "R" && std::get<2>(gridUnits) == "R") { + std::tuple gridUnits = + kw.getGridUnits(); + + if (std::get<0>(gridUnits) == "R" && + std::get<1>(gridUnits) == "R" && + std::get<2>(gridUnits) == "R") + { spatialScale.x = 6.371f; spatialScale.y = 6.371f; spatialScale.z = 6.371f; @@ -395,7 +422,7 @@ std::string IswaManager::parseKWToLuaTable(CdfInfo info, std::string cut) { } std::string table = "{" - "Name = '" +info.name+ "'," + "Name = '" + info.name + "'," "Parent = '" + parent + "', " "Renderable = {" "Type = 'KameleonPlane', " @@ -406,11 +433,11 @@ std::string IswaManager::parseKWToLuaTable(CdfInfo info, std::string cut) { "SpatialScale = " + std::to_string(spatialScale) + ", " "UpdateTime = 0, " "kwPath = '" + info.path + "' ," - "axisCut = '"+cut+"'," + "axisCut = '" + cut + "'," "CoordinateType = '" + coordinateType + "', " - "Group = '"+ info.group + "'," + "Group = '" + info.group + "'," // "Group = ''," - "fieldlineSeedsIndexFile = '"+info.fieldlineSeedsIndexFile+"'" + "fieldlineSeedsIndexFile = '" + info.fieldlineSeedsIndexFile + "'" "}" "}" ; @@ -480,7 +507,6 @@ void IswaManager::createScreenSpace(int id) { void IswaManager::createPlane(std::shared_ptr data) { // check if this plane already exist - std::string name = _type[data->type] + _geom[data->geom] + std::to_string(data->id); if (!data->group.empty()) { @@ -551,7 +577,9 @@ void IswaManager::createSphere(std::shared_ptr data) { } void IswaManager::createKameleonPlane(CdfInfo info, std::string cut) { - const std::string& extension = ghoul::filesystem::File(absPath(info.path)).fileExtension(); + const std::string& extension = ghoul::filesystem::File( + absPath(info.path) + ).fileExtension(); if (FileSys.fileExists(absPath(info.path)) && extension == "cdf") { if (!info.group.empty()) { std::string type = typeid(KameleonPlane).name(); @@ -646,7 +674,9 @@ void IswaManager::fillCygnetInfo(std::string jsonString) { jCygnet["cygnetUpdateInterval"], false }; - _cygnetInformation[jCygnet["cygnetID"]] = std::make_shared(info); + _cygnetInformation[jCygnet["cygnetID"]] = std::make_shared( + info + ); } } } diff --git a/modules/iswa/util/iswamanager.h b/modules/iswa/util/iswamanager.h index 814582e1ab..51acaf2f5b 100644 --- a/modules/iswa/util/iswamanager.h +++ b/modules/iswa/util/iswamanager.h @@ -92,7 +92,9 @@ struct MetadataFuture { }; -class IswaManager : public ghoul::Singleton, public properties::PropertyOwner { +class IswaManager : public ghoul::Singleton, + public properties::PropertyOwner +{ friend class ghoul::Singleton; public: @@ -108,7 +110,9 @@ public: std::future fetchImageCygnet(int id, double timestamp); std::future fetchDataCygnet(int id, double timestamp); - std::string iswaUrl(int id, double timestamp = OsEng.timeManager().time().j2000Seconds(), std::string type = "image"); + std::string iswaUrl(int id, + double timestamp = OsEng.timeManager().time().j2000Seconds(), + std::string type = "image"); std::shared_ptr iswaGroup(std::string name); diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index 4484d0bd7f..3b33dbde44 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -90,7 +90,9 @@ int iswa_addScreenSpaceCygnet(lua_State* L) { d.setValue("Type", "ScreenSpaceCygnet"); d.setValue("UpdateInterval", (float) updateInterval); - std::shared_ptr s( ScreenSpaceRenderable::createFromDictionary(d) ); + std::shared_ptr s( + ScreenSpaceRenderable::createFromDictionary(d) + ); OsEng.renderEngine().registerScreenSpaceRenderable(s); } return 0; @@ -140,7 +142,10 @@ int iswa_removeScrenSpaceCygnet(lua_State* L) { auto info = cygnetInformation[id]; info->selected = false; - std::string script = "openspace.unregisterScreenSpaceRenderable('" + cygnetInformation[id]->name + "');"; + std::string script = + "openspace.unregisterScreenSpaceRenderable('" + + cygnetInformation[id]->name + "');"; + OsEng.scriptEngine().queueScript( script, scripting::ScriptEngine::RemoteScripting::Yes diff --git a/modules/kameleon/include/kameleonwrapper.h b/modules/kameleon/include/kameleonwrapper.h index f178f9bd77..199a7b4706 100644 --- a/modules/kameleon/include/kameleonwrapper.h +++ b/modules/kameleon/include/kameleonwrapper.h @@ -90,38 +90,38 @@ public: void close(); float* getUniformSampledValues( - const std::string& var, + const std::string& var, const glm::size3_t& outDimensions); - float* getUniformSliceValues( - const std::string& var, + float* getUniformSliceValues( + const std::string& var, const glm::size3_t& outDimensions, const float& zSlice); float* getUniformSampledVectorValues( - const std::string& xVar, + const std::string& xVar, const std::string& yVar, - const std::string& zVar, + const std::string& zVar, const glm::size3_t& outDimensions); Fieldlines getClassifiedFieldLines( const std::string& xVar, - const std::string& yVar, + const std::string& yVar, const std::string& zVar, - const std::vector& seedPoints, + const std::vector& seedPoints, float stepSize); Fieldlines getFieldLines( const std::string& xVar, - const std::string& yVar, + const std::string& yVar, const std::string& zVar, - const std::vector& seedPoints, - float stepSize, + const std::vector& seedPoints, + float stepSize, const glm::vec4& color); Fieldlines getLorentzTrajectories( const std::vector& seedPoints, - const glm::vec4& color, + const glm::vec4& color, float stepsize); glm::vec3 getModelBarycenterOffset(); @@ -146,21 +146,21 @@ private: TraceLine traceCartesianFieldline( const std::string& xVar, const std::string& yVar, - const std::string& zVar, + const std::string& zVar, const glm::vec3& seedPoint, - float stepSize, - TraceDirection direction, + float stepSize, + TraceDirection direction, FieldlineEnd& end); TraceLine traceLorentzTrajectory( const glm::vec3& seedPoint, - float stepsize, + float stepsize, float eCharge); void getGridVariables(std::string& x, std::string& y, std::string& z); GridType getGridType( - const std::string& x, - const std::string& y, + const std::string& x, + const std::string& y, const std::string& z); Model getModelType(); glm::vec4 classifyFieldline(FieldlineEnd fEnd, FieldlineEnd bEnd); diff --git a/modules/kameleon/src/kameleonhelper.cpp b/modules/kameleon/src/kameleonhelper.cpp index ad3c6444aa..6d52f5d01a 100644 --- a/modules/kameleon/src/kameleonhelper.cpp +++ b/modules/kameleon/src/kameleonhelper.cpp @@ -100,10 +100,6 @@ double getTime(ccmc::Kameleon* kameleon) { break; } } - // else if (seqStartStr.length() < 19 && kameleon->doesAttributeExist("tim_crstart_cal")) { - // seqStartStr = - // kameleon->getGlobalAttribute("tim_crstart_cal").getAttributeString(); - // } } else if (kameleon->doesAttributeExist("tim_obsdate_cal")) { seqStartStr = kameleon->getGlobalAttribute("tim_obsdate_cal").getAttributeString(); diff --git a/modules/kameleon/src/kameleonwrapper.cpp b/modules/kameleon/src/kameleonwrapper.cpp index 4525dce784..cbd4fd1e67 100644 --- a/modules/kameleon/src/kameleonwrapper.cpp +++ b/modules/kameleon/src/kameleonwrapper.cpp @@ -131,12 +131,18 @@ bool KameleonWrapper::open(const std::string& filename) { LDEBUG("y:" << _yCoordVar); LDEBUG("z:" << _zCoordVar); - _xMin = _model->getVariableAttribute(_xCoordVar, "actual_min").getAttributeFloat(); - _xMax = _model->getVariableAttribute(_xCoordVar, "actual_max").getAttributeFloat(); - _yMin = _model->getVariableAttribute(_yCoordVar, "actual_min").getAttributeFloat(); - _yMax = _model->getVariableAttribute(_yCoordVar, "actual_max").getAttributeFloat(); - _zMin = _model->getVariableAttribute(_zCoordVar, "actual_min").getAttributeFloat(); - _zMax = _model->getVariableAttribute(_zCoordVar, "actual_max").getAttributeFloat(); + _xMin = + _model->getVariableAttribute(_xCoordVar, "actual_min").getAttributeFloat(); + _xMax = + _model->getVariableAttribute(_xCoordVar, "actual_max").getAttributeFloat(); + _yMin = + _model->getVariableAttribute(_yCoordVar, "actual_min").getAttributeFloat(); + _yMax = + _model->getVariableAttribute(_yCoordVar, "actual_max").getAttributeFloat(); + _zMin = + _model->getVariableAttribute(_zCoordVar, "actual_min").getAttributeFloat(); + _zMax = + _model->getVariableAttribute(_zCoordVar, "actual_max").getAttributeFloat(); /* _xMin = -200.0f; _xMax = 200.0f; @@ -146,12 +152,19 @@ bool KameleonWrapper::open(const std::string& filename) { _zMax = 200.0f;*/ - _xValidMin = _model->getVariableAttribute(_xCoordVar, "valid_min").getAttributeFloat(); - _xValidMax = _model->getVariableAttribute(_xCoordVar, "valid_max").getAttributeFloat(); - _yValidMin = _model->getVariableAttribute(_yCoordVar, "valid_min").getAttributeFloat(); - _yValidMax = _model->getVariableAttribute(_yCoordVar, "valid_max").getAttributeFloat(); - _zValidMin = _model->getVariableAttribute(_zCoordVar, "valid_min").getAttributeFloat(); - _zValidMax = _model->getVariableAttribute(_zCoordVar, "valid_max").getAttributeFloat(); + _xValidMin = + _model->getVariableAttribute(_xCoordVar, "valid_min").getAttributeFloat(); + _xValidMax = + _model->getVariableAttribute(_xCoordVar, "valid_max").getAttributeFloat(); + _yValidMin = + _model->getVariableAttribute(_yCoordVar, "valid_min").getAttributeFloat(); + _yValidMax = + _model->getVariableAttribute(_yCoordVar, "valid_max").getAttributeFloat(); + _zValidMin = + _model->getVariableAttribute(_zCoordVar, "valid_min").getAttributeFloat(); + _zValidMax = + _model->getVariableAttribute(_zCoordVar, "valid_max").getAttributeFloat(); + LDEBUG("_xMin: " << _xMin); LDEBUG("_xMax: " << _xMax); LDEBUG("_yMin: " << _yMin); @@ -186,14 +199,16 @@ void KameleonWrapper::close() { } float* KameleonWrapper::getUniformSampledValues( - const std::string& var, - const glm::size3_t& outDimensions) + const std::string& var, + const glm::size3_t& outDimensions) { assert(_model && _interpolator); assert(outDimensions.x > 0 && outDimensions.y > 0 && outDimensions.z > 0); LINFO("Loading variable " << var << " from CDF data with a uniform sampling"); - unsigned int size = static_cast(outDimensions.x*outDimensions.y*outDimensions.z); + unsigned int size = static_cast( + outDimensions.x * outDimensions.y * outDimensions.z + ); float* data = new float[size]; double* doubleData = new double[size]; @@ -223,20 +238,25 @@ float* KameleonWrapper::getUniformSampledValues( for (int x = 0; x < static_cast(outDimensions.x); ++x) { for (int y = 0; y < static_cast(outDimensions.y); ++y) { for (int z = 0; z < static_cast(outDimensions.z); ++z) { - unsigned int index = static_cast(x + y*outDimensions.x + z*outDimensions.x*outDimensions.y); + unsigned int index = static_cast( + x + y * outDimensions.x + z * outDimensions.x * outDimensions.y + ); if (_gridType == GridType::Spherical) { // Put r in the [0..sqrt(3)] range - double rNorm = sqrt(3.0) * static_cast(x) / static_cast(outDimensions.x - 1); + double rNorm = sqrt(3.0) * static_cast(x) / + static_cast(outDimensions.x - 1); // Put theta in the [0..PI] range - double thetaNorm = M_PI * static_cast(y) / static_cast(outDimensions.y - 1); + double thetaNorm = M_PI * static_cast(y) / + static_cast(outDimensions.y - 1); // Put phi in the [0..2PI] range - double phiNorm = 2.0 * M_PI * static_cast(z) / static_cast(outDimensions.z - 1); + double phiNorm = 2.0 * M_PI * static_cast(z) / + static_cast(outDimensions.z - 1); // Go to physical coordinates before sampling - double rPh = _xMin + rNorm*(_xMax-_xMin); + double rPh = _xMin + rNorm * (_xMax - _xMin); double thetaPh = thetaNorm; // phi range needs to be mapped to the slightly different model // range to avoid gaps in the data Subtract a small term to @@ -256,15 +276,15 @@ float* KameleonWrapper::getUniformSampledValues( // ENLIL CDF specific hacks! // Convert from meters to AU for interpolator rPh /= ccmc::constants::AU_in_meters; - // Convert from colatitude [0, pi] rad to latitude [-90, 90] degrees + // Convert from colatitude [0, pi] rad to latitude [-90, 90] deg thetaPh = -thetaPh*180.f/M_PI+90.f; // Convert from [0, 2pi] rad to [0, 360] degrees phiPh = phiPh*180.f/M_PI; // Sample value = _interpolator->interpolate( - var, - static_cast(rPh), - static_cast(thetaPh), + var, + static_cast(rPh), + static_cast(thetaPh), static_cast(phiPh)); // value = _interpolator->interpolate(var, rPh, phiPh, thetaPh); } @@ -308,7 +328,7 @@ float* KameleonWrapper::getUniformSampledValues( // if(i % 10 == 0) // std::cout << std::endl; //} - // + // // for(int i = 0; i < bins-1; ++i) { // // sum += histogram[i]; // // if(sum + histogram[i+1] > sumuntil) { @@ -360,16 +380,17 @@ float* KameleonWrapper::getUniformSampledValues( return data; } -float* KameleonWrapper::getUniformSliceValues( - const std::string& var, - const glm::size3_t& outDimensions, - const float& slice) +float* KameleonWrapper::getUniformSliceValues(const std::string& var, + const glm::size3_t& outDimensions, + const float& slice) { assert(_model && _interpolator); assert(outDimensions.x > 0 && outDimensions.y > 0 && outDimensions.z > 0); LINFO("Loading variable " << var << " from CDF data with a uniform sampling"); - unsigned int size = static_cast(outDimensions.x*outDimensions.y*outDimensions.z); + unsigned int size = static_cast( + outDimensions.x * outDimensions.y * outDimensions.z + ); float* data = new float[size]; double* doubleData = new double[size]; @@ -407,17 +428,22 @@ float* KameleonWrapper::getUniformSliceValues( float zi = (!zSlice)? z : slice; double value = 0; - unsigned int index = static_cast(x + y*outDimensions.x + z*outDimensions.x*outDimensions.y); - if(_gridType == GridType::Spherical) { - // int z = zSlice; + unsigned int index = static_cast( + x + y * outDimensions.x + z * outDimensions.x * outDimensions.y + ); + if (_gridType == GridType::Spherical) { + // int z = zSlice; // Put r in the [0..sqrt(3)] range - double rNorm = sqrt(3.0) * static_cast(xi) / static_cast(xDim); + double rNorm = sqrt(3.0) * static_cast(xi) / + static_cast(xDim); // Put theta in the [0..PI] range - double thetaNorm = M_PI * static_cast(yi) / static_cast(yDim); + double thetaNorm = M_PI * static_cast(yi) / + static_cast(yDim); // Put phi in the [0..2PI] range - double phiNorm = 2.0 * M_PI * static_cast(zi) / static_cast(zDim); + double phiNorm = 2.0 * M_PI * static_cast(zi) / + static_cast(zDim); // Go to physical coordinates before sampling double rPh = _xMin + rNorm * (_xMax-_xMin); @@ -439,17 +465,16 @@ float* KameleonWrapper::getUniformSliceValues( // ENLIL CDF specific hacks! // Convert from meters to AU for interpolator rPh /= ccmc::constants::AU_in_meters; - // Convert from colatitude [0, pi] rad to latitude [-90, 90] degrees - thetaPh = -thetaPh*180.f/M_PI+90.f; + // Convert from colatitude [0, pi] rad to [-90, 90] deg + thetaPh = -thetaPh * 180.f / M_PI + 90.f; // Convert from [0, 2pi] rad to [0, 360] degrees phiPh = phiPh*180.f/M_PI; // Sample value = _interpolator->interpolate( - var, - static_cast(rPh), - static_cast(phiPh), + var, + static_cast(rPh), + static_cast(phiPh), static_cast(thetaPh)); - // value = _interpolator->interpolate(var, rPh, phiPh, thetaPh); } } else { @@ -482,29 +507,27 @@ float* KameleonWrapper::getUniformSliceValues( } } } - // for(size_t i = 0; i < size; ++i) { - // double normalizedVal = (doubleData[i]-minValue)/(maxValue-minValue); - // data[i] = glm::clamp(normalizedVal, 0.0, 1.0); - // data[i] = 1; - // std::cout << minValue << ", " << maxValue << ", " << doubleData[i] << ", " << normalizedVal << ", " << data[i] << std::endl; - // } delete[] doubleData; return data; } -float* KameleonWrapper::getUniformSampledVectorValues( - const std::string& xVar, - const std::string& yVar, - const std::string& zVar, - const glm::size3_t& outDimensions) +float* KameleonWrapper::getUniformSampledVectorValues(const std::string& xVar, + const std::string& yVar, + const std::string& zVar, + const glm::size3_t& outDimensions) { assert(_model && _interpolator); assert(outDimensions.x > 0 && outDimensions.y > 0 && outDimensions.z > 0); - LINFO("Loading variables " << xVar << " " << yVar << " " << zVar << " from CDF data with a uniform sampling"); + LINFO( + "Loading variables " << xVar << " " << yVar << " " << zVar << + " from CDF data with a uniform sampling" + ); int channels = 4; - unsigned int size = static_cast(channels*outDimensions.x*outDimensions.y*outDimensions.z); + unsigned int size = static_cast( + channels * outDimensions.x * outDimensions.y * outDimensions.z + ); float* data = new float[size]; float varXMin = _model->getVariableAttribute(xVar, "actual_min").getAttributeFloat(); @@ -532,7 +555,10 @@ float* KameleonWrapper::getUniformSampledVectorValues( for (int y = 0; y < outDimensions.y; ++y) { for (int z = 0; z < outDimensions.z; ++z) { - unsigned int index = static_cast(x*channels + y*channels*outDimensions.x + z*channels*outDimensions.x*outDimensions.y); + unsigned int index = static_cast( + x * channels + y * channels * outDimensions.x + + z * channels * outDimensions.x * outDimensions.y + ); if (_gridType == GridType::Cartesian) { float xPos = _xMin + stepX*x; @@ -548,9 +574,13 @@ float* KameleonWrapper::getUniformSampledVectorValues( data[index] = (xValue-varXMin)/(varXMax-varXMin); // R data[index + 1] = (yValue-varYMin)/(varYMax-varYMin); // G data[index + 2] = (zValue-varZMin)/(varZMax-varZMin); // B - data[index + 3] = 1.0; // GL_RGB refuses to work. Workaround by doing a GL_RGBA with hardcoded alpha + // GL_RGB refuses to work. Workaround doing a GL_RGBA hardcoded alpha + data[index + 3] = 1.0; } else { - LERROR("Only cartesian grid supported for getUniformSampledVectorValues (for now)"); + LERROR( + "Only cartesian grid supported for " + "getUniformSampledVectorValues (for now)" + ); return data; } } @@ -561,14 +591,17 @@ float* KameleonWrapper::getUniformSampledVectorValues( } KameleonWrapper::Fieldlines KameleonWrapper::getClassifiedFieldLines( - const std::string& xVar, + const std::string& xVar, const std::string& yVar, const std::string& zVar, const std::vector& seedPoints, - float stepSize ) + float stepSize ) { assert(_model && _interpolator); - LINFO("Creating " << seedPoints.size() << " fieldlines from variables " << xVar << " " << yVar << " " << zVar); + LINFO( + "Creating " << seedPoints.size() << " fieldlines from variables " << + xVar << " " << yVar << " " << zVar + ); std::vector fLine, bLine; std::vector > fieldLines; @@ -577,8 +610,24 @@ KameleonWrapper::Fieldlines KameleonWrapper::getClassifiedFieldLines( if (_type == Model::BATSRUS) { for (glm::vec3 seedPoint : seedPoints) { - fLine = traceCartesianFieldline(xVar, yVar, zVar, seedPoint, stepSize, TraceDirection::FORWARD, forwardEnd); - bLine = traceCartesianFieldline(xVar, yVar, zVar, seedPoint, stepSize, TraceDirection::BACK, backEnd); + fLine = traceCartesianFieldline( + xVar, + yVar, + zVar, + seedPoint, + stepSize, + TraceDirection::FORWARD, + forwardEnd + ); + bLine = traceCartesianFieldline( + xVar, + yVar, + zVar, + seedPoint, + stepSize, + TraceDirection::BACK, + backEnd + ); bLine.erase(bLine.begin()); bLine.insert(bLine.begin(), fLine.rbegin(), fLine.rend()); @@ -601,16 +650,15 @@ KameleonWrapper::Fieldlines KameleonWrapper::getClassifiedFieldLines( return fieldLines; } -KameleonWrapper::Fieldlines KameleonWrapper::getFieldLines( - const std::string& xVar, - const std::string& yVar, - const std::string& zVar, - const std::vector& seedPoints, - float stepSize, - const glm::vec4& color ) +KameleonWrapper::Fieldlines KameleonWrapper::getFieldLines(const std::string& xVar, + const std::string& yVar, const std::string& zVar, + const std::vector& seedPoints, float stepSize, const glm::vec4& color) { assert(_model && _interpolator); - LINFO("Creating " << seedPoints.size() << " fieldlines from variables " << xVar << " " << yVar << " " << zVar); + LINFO( + "Creating " << seedPoints.size() << " fieldlines from variables " << + xVar << " " << yVar << " " << zVar + ); std::vector fLine, bLine; Fieldlines fieldLines; @@ -618,11 +666,27 @@ KameleonWrapper::Fieldlines KameleonWrapper::getFieldLines( if (_type == Model::BATSRUS) { for (glm::vec3 seedPoint : seedPoints) { - fLine = traceCartesianFieldline(xVar, yVar, zVar, seedPoint, stepSize, TraceDirection::FORWARD, forwardEnd); - bLine = traceCartesianFieldline(xVar, yVar, zVar, seedPoint, stepSize, TraceDirection::BACK, backEnd); + fLine = traceCartesianFieldline( + xVar, + yVar, + zVar, + seedPoint, + stepSize, + TraceDirection::FORWARD, + forwardEnd + ); + bLine = traceCartesianFieldline( + xVar, + yVar, + zVar, + seedPoint, + stepSize, + TraceDirection::BACK, + backEnd + ); bLine.erase(bLine.begin()); - bLine.insert(bLine.begin(), fLine.rbegin(), fLine.rend()); + bLine.insert(bLine.begin(), fLine.rbegin(), fLine.rend()); // write colors and convert positions to meter std::vector line; @@ -640,9 +704,7 @@ KameleonWrapper::Fieldlines KameleonWrapper::getFieldLines( } KameleonWrapper::Fieldlines KameleonWrapper::getLorentzTrajectories( - const std::vector& seedPoints, - const glm::vec4& /*color*/, - float stepsize) + const std::vector& seedPoints,const glm::vec4& /*color*/, float stepsize) { LINFO("Creating " << seedPoints.size() << " Lorentz force trajectories"); @@ -659,11 +721,19 @@ KameleonWrapper::Fieldlines KameleonWrapper::getLorentzTrajectories( // write colors and convert positions to meter std::vector trajectory; - for (glm::vec3 position : minusTraj) { - if (trajectory.size() < plusNum) // set positive trajectory to pink - trajectory.push_back(LinePoint(RE_TO_METER*position, glm::vec4(1, 0, 1, 1))); - else // set negative trajectory to cyan - trajectory.push_back(LinePoint(RE_TO_METER*position, glm::vec4(0, 1, 1, 1))); + for (glm::vec3 position : minusTraj) { + if (trajectory.size() < plusNum) { + // set positive trajectory to pink + trajectory.push_back( + LinePoint(RE_TO_METER*position, glm::vec4(1, 0, 1, 1)) + ); + } + else { + // set negative trajectory to cyan + trajectory.push_back( + LinePoint(RE_TO_METER*position, glm::vec4(0, 1, 1, 1)) + ); + } } trajectories.push_back(trajectory); } @@ -678,22 +748,24 @@ glm::vec3 KameleonWrapper::getModelBarycenterOffset() { } glm::vec3 offset; - offset.x = _xMin+(std::abs(_xMin)+std::abs(_xMax))/2.0f; - offset.y = _yMin+(std::abs(_yMin)+std::abs(_yMax))/2.0f; - offset.z = _zMin+(std::abs(_zMin)+std::abs(_zMax))/2.0f; + offset.x = _xMin + (std::abs(_xMin) + std::abs(_xMax)) / 2.0f; + offset.y = _yMin + (std::abs(_yMin) + std::abs(_yMax)) / 2.0f; + offset.z = _zMin + (std::abs(_zMin) + std::abs(_zMax)) / 2.0f; return offset; } -glm::vec4 KameleonWrapper::getModelBarycenterOffsetScaled(){ - std::tuple < std::string, std::string, std::string > gridUnits = getGridUnits(); +glm::vec4 KameleonWrapper::getModelBarycenterOffsetScaled() { + std::tuple gridUnits = getGridUnits(); glm::vec4 offset = glm::vec4(getModelBarycenterOffset(), 1.0); - if(std::get<0>(gridUnits) == "R" && std::get<1>(gridUnits) == "R" && std::get<2>(gridUnits) == "R"){ + if (std::get<0>(gridUnits) == "R" && + std::get<1>(gridUnits) == "R" && + std::get<2>(gridUnits) == "R") + { offset.x *= 6.371f; offset.y *= 6.371f; offset.z *= 6.371f; offset.w = 6; } - // else if(std::get<0>(t) == "m" && std::get<1>(t) == "radian" && std::get<2>(t) == "radian"){} return offset; } @@ -711,14 +783,20 @@ glm::vec3 KameleonWrapper::getModelScale() { glm::vec4 KameleonWrapper::getModelScaleScaled(){ std::tuple < std::string, std::string, std::string > gridUnits = getGridUnits(); glm::vec4 scale = glm::vec4(getModelScale(), 1.0); - if (std::get<0>(gridUnits) == "R" && std::get<1>(gridUnits) == "R" && std::get<2>(gridUnits) == "R") { + if (std::get<0>(gridUnits) == "R" && + std::get<1>(gridUnits) == "R" && + std::get<2>(gridUnits) == "R") + { // Earth radius scale.x *= 6.371f; scale.y *= 6.371f; scale.z *= 6.371f; scale.w = 6; } - else if (std::get<0>(gridUnits) == "m" && std::get<1>(gridUnits) == "radian" && std::get<2>(gridUnits) == "radian") { + else if (std::get<0>(gridUnits) == "m" && + std::get<1>(gridUnits) == "radian" && + std::get<2>(gridUnits) == "radian") + { // For spherical coordinate systems the radius is in meter scale.w = -log10(1.0f/_xMax); } @@ -756,13 +834,9 @@ KameleonWrapper::GridType KameleonWrapper::gridType() { } KameleonWrapper::TraceLine KameleonWrapper::traceCartesianFieldline( - const std::string& xVar, - const std::string& yVar, - const std::string& zVar, - const glm::vec3& seedPoint, - float stepSize, - TraceDirection direction, - FieldlineEnd& end) + const std::string& xVar, const std::string& yVar, const std::string& zVar, + const glm::vec3& seedPoint, float stepSize, TraceDirection direction, + FieldlineEnd& end) { glm::vec3 color, pos, k1, k2, k3, k4; @@ -781,7 +855,9 @@ KameleonWrapper::TraceLine KameleonWrapper::traceCartesianFieldline( // While we are inside the models boundries and not inside earth while ((pos.x < _xMax && pos.x > _xMin && pos.y < _yMax && pos.y > _yMin && - pos.z < _zMax && pos.z > _zMin) && !(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < 1.0)) { + pos.z < _zMax && pos.z > _zMin) && + !(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < 1.0)) + { // Save position. Model has +Z as up line.push_back(glm::vec3(pos.x, pos.z, pos.y)); @@ -790,25 +866,70 @@ KameleonWrapper::TraceLine KameleonWrapper::traceCartesianFieldline( k1.x = _interpolator->interpolate(xID, pos.x, pos.y, pos.z, stepX, stepY, stepZ); k1.y = _interpolator->interpolate(yID, pos.x, pos.y, pos.z); k1.z = _interpolator->interpolate(zID, pos.x, pos.y, pos.z); - k1 = (float)direction*glm::normalize(k1); + k1 = static_cast(direction) * glm::normalize(k1); stepX=stepX*stepSize; stepY=stepY*stepSize; stepZ=stepZ*stepSize; - k2.x = _interpolator->interpolate(xID, pos.x+(stepX/2.0f)*k1.x, pos.y+(stepY/2.0f)*k1.y, pos.z+(stepZ/2.0f)*k1.z); - k2.y = _interpolator->interpolate(yID, pos.x+(stepX/2.0f)*k1.x, pos.y+(stepY/2.0f)*k1.y, pos.z+(stepZ/2.0f)*k1.z); - k2.z = _interpolator->interpolate(zID, pos.x+(stepX/2.0f)*k1.x, pos.y+(stepY/2.0f)*k1.y, pos.z+(stepZ/2.0f)*k1.z); - k2 = (float)direction*glm::normalize(k2); - k3.x = _interpolator->interpolate(xID, pos.x+(stepX/2.0f)*k2.x, pos.y+(stepY/2.0f)*k2.y, pos.z+(stepZ/2.0f)*k2.z); - k3.y = _interpolator->interpolate(yID, pos.x+(stepX/2.0f)*k2.x, pos.y+(stepY/2.0f)*k2.y, pos.z+(stepZ/2.0f)*k2.z); - k3.z = _interpolator->interpolate(zID, pos.x+(stepX/2.0f)*k2.x, pos.y+(stepY/2.0f)*k2.y, pos.z+(stepZ/2.0f)*k2.z); - k3 = (float)direction*glm::normalize(k3); - k4.x = _interpolator->interpolate(xID, pos.x+stepX*k3.x, pos.y+stepY*k3.y, pos.z+stepZ*k3.z); - k4.y = _interpolator->interpolate(yID, pos.x+stepX*k3.x, pos.y+stepY*k3.y, pos.z+stepZ*k3.z); - k4.z = _interpolator->interpolate(zID, pos.x+stepX*k3.x, pos.y+stepY*k3.y, pos.z+stepZ*k3.z); - k4 = (float)direction*glm::normalize(k4); - pos.x = pos.x + (stepX/6.0f)*(k1.x + 2.0f*k2.x + 2.0f*k3.x + k4.x); - pos.y = pos.y + (stepY/6.0f)*(k1.y + 2.0f*k2.y + 2.0f*k3.y + k4.y); - pos.z = pos.z + (stepZ/6.0f)*(k1.z + 2.0f*k2.z + 2.0f*k3.z + k4.z); + k2.x = _interpolator->interpolate( + xID, + pos.x + (stepX / 2.0f) * k1.x, + pos.y + (stepY / 2.0f) * k1.y, + pos.z + (stepZ / 2.0f) * k1.z + ); + k2.y = _interpolator->interpolate( + yID, + pos.x + (stepX / 2.0f) * k1.x, + pos.y + (stepY / 2.0f) * k1.y, + pos.z + (stepZ / 2.0f) * k1.z + ); + k2.z = _interpolator->interpolate( + zID, + pos.x + (stepX / 2.0f) * k1.x, + pos.y + (stepY / 2.0f) * k1.y, + pos.z + (stepZ / 2.0f) * k1.z + ); + k2 = static_cast(direction) * glm::normalize(k2); + k3.x = _interpolator->interpolate( + xID, + pos.x + (stepX / 2.0f) * k2.x, + pos.y + (stepY / 2.0f) * k2.y, + pos.z + (stepZ / 2.0f) * k2.z + ); + k3.y = _interpolator->interpolate( + yID, + pos.x + (stepX / 2.0f) * k2.x, + pos.y + (stepY / 2.0f) * k2.y, + pos.z + (stepZ / 2.0f) * k2.z + ); + k3.z = _interpolator->interpolate( + zID, + pos.x + (stepX / 2.0f) * k2.x, + pos.y + (stepY / 2.0f) * k2.y, + pos.z + (stepZ / 2.0f) * k2.z + ); + k3 = static_cast(direction) * glm::normalize(k3); + k4.x = _interpolator->interpolate( + xID, + pos.x + stepX * k3.x, + pos.y + stepY * k3.y, + pos.z + stepZ * k3.z + ); + k4.y = _interpolator->interpolate( + yID, + pos.x + stepX * k3.x, + pos.y + stepY * k3.y, + pos.z + stepZ * k3.z + ); + k4.z = _interpolator->interpolate( + zID, + pos.x + stepX * k3.x, + pos.y + stepY * k3.y, + pos.z + stepZ * k3.z + ); + k4 = static_cast(direction) * glm::normalize(k4); + pos.x = pos.x + (stepX / 6.f) * (k1.x + 2.f * k2.x + 2.f * k3.x + k4.x); + pos.y = pos.y + (stepY / 6.f) * (k1.y + 2.f * k2.y + 2.f * k3.y + k4.y); + pos.z = pos.z + (stepZ / 6.f) * (k1.z + 2.f * k2.z + 2.f * k3.z + k4.z); ++numSteps; if (numSteps > maxSteps) { @@ -833,9 +954,7 @@ KameleonWrapper::TraceLine KameleonWrapper::traceCartesianFieldline( } KameleonWrapper::TraceLine KameleonWrapper::traceLorentzTrajectory( - const glm::vec3& seedPoint, - float stepsize, - float eCharge) + const glm::vec3& seedPoint, float stepsize, float eCharge) { glm::vec3 B, E, v0, k1, k2, k3, k4, sPos, tmpV; float stepX = stepsize, stepY = stepsize, stepZ = stepsize; @@ -857,8 +976,9 @@ KameleonWrapper::TraceLine KameleonWrapper::traceLorentzTrajectory( // While we are inside the models boundries and not inside earth while ((pos.x < _xMax && pos.x > _xMin && pos.y < _yMax && pos.y > _yMin && - pos.z < _zMax && pos.z > _zMin) && !(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < 1.0)) { - + pos.z < _zMax && pos.z > _zMin) && + !(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < 1.0)) + { // Save position. Model has +Z as up trajectory.push_back(glm::vec3(pos.x, pos.z, pos.y)); @@ -929,20 +1049,30 @@ KameleonWrapper::TraceLine KameleonWrapper::traceLorentzTrajectory( void KameleonWrapper::getGridVariables(std::string& x, std::string& y, std::string& z) { // get the grid system string - std::string gridSystem = _model->getGlobalAttribute("grid_system_1").getAttributeString(); + std::string gridSystem = + _model->getGlobalAttribute("grid_system_1").getAttributeString(); // remove leading and trailing brackets gridSystem = gridSystem.substr(1,gridSystem.length()-2); // remove all whitespaces - gridSystem.erase(remove_if(gridSystem.begin(), gridSystem.end(), isspace), gridSystem.end()); + gridSystem.erase( + remove_if( + gridSystem.begin(), + gridSystem.end(), + isspace), + gridSystem.end() + ); // replace all comma signs with whitespaces std::replace( gridSystem.begin(), gridSystem.end(), ',', ' '); // tokenize std::istringstream iss(gridSystem); - std::vector tokens{std::istream_iterator{iss},std::istream_iterator{}}; + std::vector tokens{ + std::istream_iterator{iss}, + std::istream_iterator{} + }; // validate if (tokens.size() != 3) LERROR("Something went wrong"); @@ -971,10 +1101,8 @@ void KameleonWrapper::getGridVariables(std::string& x, std::string& y, std::stri ); } -KameleonWrapper::GridType KameleonWrapper::getGridType( - const std::string& x, - const std::string& y, - const std::string& z) +KameleonWrapper::GridType KameleonWrapper::getGridType(const std::string& x, + const std::string& y, const std::string& z) { if (x == "x" && y == "y" && z == "z") { return GridType::Cartesian; @@ -988,7 +1116,8 @@ KameleonWrapper::GridType KameleonWrapper::getGridType( KameleonWrapper::Model KameleonWrapper::getModelType() { if(_kameleon->doesAttributeExist("model_name")) { - std::string modelName = (_kameleon->getGlobalAttribute("model_name")).getAttributeString(); + std::string modelName = + _kameleon->getGlobalAttribute("model_name").getAttributeString(); if (modelName == "open_ggcm" || modelName == "ucla_ggcm") { return Model::OpenGGCM; } else if (modelName == "batsrus") { @@ -1061,18 +1190,18 @@ std::string KameleonWrapper::getFrame() { } } -std::vector KameleonWrapper::getVariables(){ +std::vector KameleonWrapper::getVariables() { std::vector variableNames; int numVariables = _model->getNumberOfVariables(); - for(int i=0; igetVariableName(i));; } return variableNames; } -std::vector KameleonWrapper::getLoadedVariables(){ +std::vector KameleonWrapper::getLoadedVariables() { return _kameleon->getLoadedVariables(); } diff --git a/modules/kameleonvolume/kameleonvolumereader.cpp b/modules/kameleonvolume/kameleonvolumereader.cpp index d41af12646..5b644adf7d 100644 --- a/modules/kameleonvolume/kameleonvolumereader.cpp +++ b/modules/kameleonvolume/kameleonvolumereader.cpp @@ -78,7 +78,14 @@ std::unique_ptr> KameleonVolumeReader::readFloatVolume( const glm::vec3 & upperDomainBound) const { float min, max; - return readFloatVolume(dimensions, variable, lowerDomainBound, upperDomainBound, min, max); + return readFloatVolume( + dimensions, + variable, + lowerDomainBound, + upperDomainBound, + min, + max + ); } std::unique_ptr> KameleonVolumeReader::readFloatVolume( @@ -130,20 +137,30 @@ std::unique_ptr> KameleonVolumeReader::readFloatVolume( std::vector KameleonVolumeReader::gridVariableNames() const { // get the grid system string - std::string gridSystem = _model->getGlobalAttribute("grid_system_1").getAttributeString(); + std::string gridSystem = + _model->getGlobalAttribute("grid_system_1").getAttributeString(); // remove leading and trailing brackets gridSystem = gridSystem.substr(1, gridSystem.length() - 2); // remove all whitespaces - gridSystem.erase(remove_if(gridSystem.begin(), gridSystem.end(), isspace), gridSystem.end()); + gridSystem.erase( + remove_if( + gridSystem.begin(), + gridSystem.end(), + isspace), + gridSystem.end() + ); // replace all comma signs with whitespaces std::replace(gridSystem.begin(), gridSystem.end(), ',', ' '); // tokenize std::istringstream iss(gridSystem); - std::vector tokens{ std::istream_iterator{iss},std::istream_iterator{} }; + std::vector tokens{ + std::istream_iterator{iss}, + std::istream_iterator{} + }; // validate if (tokens.size() != 3) { @@ -199,18 +216,21 @@ std::vector KameleonVolumeReader::globalAttributeNames() const { return attributeNames; } -void KameleonVolumeReader::addAttributeToDictionary(ghoul::Dictionary& dictionary, const std::string& key, ccmc::Attribute& attr) { +void KameleonVolumeReader::addAttributeToDictionary(ghoul::Dictionary& dictionary, + const std::string& key, + ccmc::Attribute& attr) +{ ccmc::Attribute::AttributeType type = attr.getAttributeType(); switch (type) { - case ccmc::Attribute::AttributeType::FLOAT: - dictionary.setValue(key, attr.getAttributeFloat()); - return; - case ccmc::Attribute::AttributeType::INT: - dictionary.setValue(key, attr.getAttributeInt()); - return; - case ccmc::Attribute::AttributeType::STRING: - dictionary.setValue(key, attr.getAttributeString()); - return; + case ccmc::Attribute::AttributeType::FLOAT: + dictionary.setValue(key, attr.getAttributeFloat()); + return; + case ccmc::Attribute::AttributeType::INT: + dictionary.setValue(key, attr.getAttributeInt()); + return; + case ccmc::Attribute::AttributeType::STRING: + dictionary.setValue(key, attr.getAttributeString()); + return; } } @@ -226,15 +246,22 @@ ghoul::Dictionary KameleonVolumeReader::readMetaData() const { for (const std::string& variableName : variableNames()) { ghoul::Dictionary variableAttributesDictionary; for (const std::string& attributeName : varAttrNames) { - ccmc::Attribute attribute = _model->getVariableAttribute(variableName, attributeName); - addAttributeToDictionary(variableAttributesDictionary, attributeName, attribute); + ccmc::Attribute attribute = _model->getVariableAttribute( + variableName, + attributeName + ); + addAttributeToDictionary( + variableAttributesDictionary, + attributeName, + attribute + ); } variableDictionary.setValue(variableName, variableAttributesDictionary); } return { - {"globalAttributes", std::move(globalAttributesDictionary) }, - {"variableAttributes", std::move(variableDictionary) } + { "globalAttributes", std::move(globalAttributesDictionary) }, + { "variableAttributes", std::move(variableDictionary) } }; } diff --git a/modules/kameleonvolume/kameleonvolumereader.h b/modules/kameleonvolume/kameleonvolumereader.h index 17370df7cd..5e5bfbc48a 100644 --- a/modules/kameleonvolume/kameleonvolumereader.h +++ b/modules/kameleonvolume/kameleonvolumereader.h @@ -83,7 +83,9 @@ public: std::vector globalAttributeNames() const; private: - static void addAttributeToDictionary(ghoul::Dictionary& dictionary, const std::string& key, ccmc::Attribute& attr); + static void addAttributeToDictionary(ghoul::Dictionary& dictionary, + const std::string& key, ccmc::Attribute& attr); + std::string _path; ccmc::Kameleon _kameleon; ccmc::Model* _model; diff --git a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp index b317796e1e..ef6fe57e6d 100644 --- a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp +++ b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp @@ -326,7 +326,7 @@ void RenderableKameleonVolume::updateRaycasterModelTransform() { glm::vec3 scale = upperBoundingBoxBound - lowerBoundingBoxBound; glm::vec3 translation = (lowerBoundingBoxBound + upperBoundingBoxBound) * 0.5f; - glm::mat4 modelTransform = glm::translate(glm::mat4(1.0), translation); + glm::mat4 modelTransform = glm::translate(glm::mat4(1.0), translation); modelTransform = glm::scale(modelTransform, scale); _raycaster->setModelTransform(modelTransform); } @@ -338,7 +338,7 @@ bool RenderableKameleonVolume::cachingEnabled() { void RenderableKameleonVolume::load() { if (!FileSys.fileExists(_sourcePath)) { - LERROR("File " << _sourcePath << " does not exist."); + LERROR("File " << _sourcePath << " does not exist."); return; } if (!cachingEnabled()) { @@ -417,7 +417,7 @@ void RenderableKameleonVolume::loadCdf(const std::string& path) { } else { _gridType.setValue(static_cast(volume::VolumeGridType::Cartesian)); - } + } } ghoul::Dictionary dict = reader.readMetaData(); diff --git a/modules/multiresvolume/rendering/tsp.cpp b/modules/multiresvolume/rendering/tsp.cpp index e5b0946e88..b8c280775f 100644 --- a/modules/multiresvolume/rendering/tsp.cpp +++ b/modules/multiresvolume/rendering/tsp.cpp @@ -151,7 +151,7 @@ bool TSP::construct() { // Loop over the OTs (one per BST node) for (unsigned int OT = 0; OTtime. This is used internally for keeping - * track of both current simulation time and the time of the previously rendered frame. + * Updates sequencer with current time. This is used internally for + * keeping track of both current simulation time and the time of the previously + * rendered frame. */ void updateSequencer(const Time& time); /** @@ -98,7 +99,8 @@ public: std::pair getCurrentTarget(); /** - * Retrieves current target and (in the list) adjacent targets, the number to retrieve is user set + * Retrieves current target and (in the list) adjacent targets, the number to retrieve + * is user set */ std::pair> getIncidentTargetList(int range = 2); diff --git a/modules/touch/touchmodule.h b/modules/touch/touchmodule.h index f3466f58e5..48f6ef4b51 100644 --- a/modules/touch/touchmodule.h +++ b/modules/touch/touchmodule.h @@ -47,7 +47,8 @@ namespace openspace { TouchInteraction touch; TouchMarker markers; std::vector listOfContactPoints; - std::vector lastProcessed; // contains an id and the TuioPoint that was processed last frame + // contains an id and the TuioPoint that was processed last frame + std::vector lastProcessed; }; } // namespace openspace diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.h b/modules/toyvolume/rendering/toyvolumeraycaster.h index ac5eaa3569..a3ff865355 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.h +++ b/modules/toyvolume/rendering/toyvolumeraycaster.h @@ -50,10 +50,14 @@ public: virtual ~ToyVolumeRaycaster(); void initialize(); void deinitialize(); - void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - void postRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; + void renderEntryPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void renderExitPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void preRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + void postRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; std::string getBoundsVsPath() const override; std::string getBoundsFsPath() const override; diff --git a/modules/volume/lrucache.h b/modules/volume/lrucache.h index bbf1d590ce..ded1d13845 100644 --- a/modules/volume/lrucache.h +++ b/modules/volume/lrucache.h @@ -82,7 +82,9 @@ private: auto iter = _tracker.insert(_tracker.end(), key); _cache[key] = std::make_pair(value, iter); }; - ContainerType::iterator>> _cache; + ContainerType< + KeyType, std::pair::iterator> + > _cache; std::list _tracker; size_t _capacity; }; diff --git a/modules/volume/rawvolumewriter.inl b/modules/volume/rawvolumewriter.inl index 0e443e39ad..cad5fcfa1c 100644 --- a/modules/volume/rawvolumewriter.inl +++ b/modules/volume/rawvolumewriter.inl @@ -55,8 +55,9 @@ glm::uvec3 RawVolumeWriter::dimensions() const { } template -void RawVolumeWriter::write(const std::function& fn, - const std::function& onProgress) +void RawVolumeWriter::write( + const std::function& fn, + const std::function& onProgress) { glm::uvec3 dims = dimensions(); @@ -79,7 +80,10 @@ void RawVolumeWriter::write(const std::function(buffer.data()), bufferSize * sizeof(VoxelType)); + file.write( + reinterpret_cast(buffer.data()), + bufferSize * sizeof(VoxelType) + ); onProgress(static_cast(c + 1) / nChunks); } file.close(); diff --git a/modules/volume/rendering/basicvolumeraycaster.h b/modules/volume/rendering/basicvolumeraycaster.h index 4ff6580d49..544445d3dc 100644 --- a/modules/volume/rendering/basicvolumeraycaster.h +++ b/modules/volume/rendering/basicvolumeraycaster.h @@ -62,10 +62,14 @@ public: void initialize(); void deinitialize(); - void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - void postRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; + void renderEntryPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void renderExitPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void preRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + void postRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; bool cameraIsInside(const RenderData& data, glm::vec3& localPosition) override; std::string getBoundsVsPath() const override; diff --git a/modules/volume/rendering/renderabletimevaryingvolume.cpp b/modules/volume/rendering/renderabletimevaryingvolume.cpp index d80d4d4ab7..4829f6baf0 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.cpp +++ b/modules/volume/rendering/renderabletimevaryingvolume.cpp @@ -62,28 +62,114 @@ namespace { const char* KeyMaxValue = "MaxValue"; const char* KeyTime = "Time"; const float SecondsInOneDay = 60 * 60 * 24; + + static const openspace::properties::Property::PropertyInfo StepSizeInfo = { + "stepSize", + "Step Size", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo GridTypeInfo = { + "gridType", + "Grid Type", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo SecondsBeforeInfo = { + "secondsBefore", + "Seconds before", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo SecondsAfterInfo = { + "secondsAfter", + "Seconds after", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo SourceDirectoryInfo = { + "sourceDirectory", + "Source Directory", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo TransferFunctionInfo = { + "transferFunctionPath", + "Transfer Function Path", + "" + }; + + static const openspace::properties::Property::PropertyInfo TriggerTimeJumpInfo = { + "triggerTimeJump", + "Jump", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo JumpToTimestepInfo = { + "jumpToTimestep", + "Jump to timestep", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo CurrentTimeStepInfo = { + "currentTimestep", + "Current timestep", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo OpacityInfo = { + "opacity", + "Opacity", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo rNormalizationInfo = { + "rNormalization", + "Radius normalization", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo rUpperBoundInfo = { + "rUpperBound", + "Radius upper bound", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo lowerValueBoundInfo = { + "lowerValueBound", + "Lower value bound", + "" // @TODO Missing documentation + }; + + static const openspace::properties::Property::PropertyInfo upperValueBoundInfo = { + "upperValueBound", + "Upper value bound", + "" // @TODO Missing documentation + }; + } // namespace namespace openspace { namespace volume { -RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(const ghoul::Dictionary& dictionary) +RenderableTimeVaryingVolume::RenderableTimeVaryingVolume( + const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _clipPlanes(nullptr) - , _stepSize({ "stepSize", "Step Size", "" }, 0.02, 0.01, 1) - , _gridType({ "gridType", "Grid Type", "" }, properties::OptionProperty::DisplayType::Dropdown) - , _secondsBefore({ "secondsBefore", "Seconds before", "" }, 0.0, 0.01, SecondsInOneDay) - , _secondsAfter({ "secondsAfter", "Seconds after", "" }, 0.0, 0.01, SecondsInOneDay) - , _sourceDirectory({ "sourceDirectory", "Source Directory", "" }) - , _transferFunctionPath({"transferFunctionPath", "Transfer Function Path", "" }) - , _triggerTimeJump({"triggerTimeJump", "Jump", "" }) - , _jumpToTimestep({"jumpToTimestep", "Jump to timestep", "" }, 0, 0, 256) - , _currentTimestep({"currentTimestep", "Current timestep", "" }, 0, 0, 256) - , _opacity({"opacity", "Opacity", "" }, 10.0f, 0.0f, 50.0f) - , _rNormalization({"rNormalization", "Radius normalization", "" }, 0.0f, 0.0f, 2.0f) - , _rUpperBound({"rUpperBound", "Radius upper bound", "" }, 1.0f, 0.0f, 2.0f) - , _lowerValueBound({"lowerValueBound", "Lower value bound", "" }, 0.0f, 0.0f, 1000000.0f) - , _upperValueBound({"upperValueBound", "Upper value bound", "" }, 0.0f, 0.0f, 1000000.0f) + , _stepSize(StepSizeInfo, 0.02, 0.01, 1) + , _gridType(GridTypeInfo, properties::OptionProperty::DisplayType::Dropdown) + , _secondsBefore(SecondsBeforeInfo, 0.0, 0.01, SecondsInOneDay) + , _secondsAfter(SecondsAfterInfo, 0.0, 0.01, SecondsInOneDay) + , _sourceDirectory(SourceDirectoryInfo) + , _transferFunctionPath(TransferFunctionInfo) + , _triggerTimeJump(TriggerTimeJumpInfo) + , _jumpToTimestep(JumpToTimestepInfo, 0, 0, 256) + , _currentTimestep(CurrentTimeStepInfo, 0, 0, 256) + , _opacity(OpacityInfo, 10.0f, 0.0f, 50.0f) + , _rNormalization(rNormalizationInfo, 0.0f, 0.0f, 2.0f) + , _rUpperBound(rUpperBoundInfo, 1.0f, 0.0f, 2.0f) + , _lowerValueBound(lowerValueBoundInfo, 0.0f, 0.0f, 1000000.0f) + , _upperValueBound(upperValueBoundInfo, 0.0f, 0.0f, 1000000.0f) , _raycaster(nullptr) , _transferFunction(nullptr) { @@ -99,11 +185,12 @@ RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(const ghoul::Dictionary _upperValueBound = dictionary.value(KeyUpperValueBound); _transferFunction = std::make_shared(_transferFunctionPath); - _gridType.addOption(static_cast(volume::VolumeGridType::Cartesian), "Cartesian grid"); - _gridType.addOption(static_cast(volume::VolumeGridType::Spherical), "Spherical grid"); + _gridType.addOptions({ + { static_cast(volume::VolumeGridType::Cartesian), "Cartesian grid" }, + { static_cast(volume::VolumeGridType::Spherical), "Spherical grid" }, + }); _gridType.setValue(static_cast(volume::VolumeGridType::Cartesian)); - if (dictionary.hasValue(KeySecondsBefore)) { _secondsBefore = dictionary.value(KeySecondsBefore); } @@ -115,7 +202,9 @@ RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(const ghoul::Dictionary _clipPlanes->setName("clipPlanes"); if (dictionary.hasValue(KeyGridType)) { - VolumeGridType gridType = volume::parseGridType(dictionary.value(KeyGridType)); + VolumeGridType gridType = volume::parseGridType( + dictionary.value(KeyGridType) + ); _gridType = (gridType == VolumeGridType::Spherical) ? 1 : 0; } } @@ -146,7 +235,9 @@ void RenderableTimeVaryingVolume::initialize() { // TODO: defer loading of data to later. (separate thread or at least not when loading) for (auto& p : _volumeTimesteps) { Timestep& t = p.second; - std::string path = FileSys.pathByAppendingComponent(_sourceDirectory, t.baseName) + ".rawvolume"; + std::string path = FileSys.pathByAppendingComponent( + _sourceDirectory, t.baseName + ) + ".rawvolume"; RawVolumeReader reader(path, t.dimensions); t.rawVolume = reader.read(); @@ -168,13 +259,20 @@ void RenderableTimeVaryingVolume::initialize() { ghoul::opengl::Texture::WrappingMode::Clamp ); - t.texture->setPixelData(reinterpret_cast(data), ghoul::opengl::Texture::TakeOwnership::No); + t.texture->setPixelData( + reinterpret_cast(data), + ghoul::opengl::Texture::TakeOwnership::No + ); t.texture->uploadTexture(); } _clipPlanes->initialize(); _transferFunction->update(); - _raycaster = std::make_unique(nullptr, _transferFunction, _clipPlanes); + _raycaster = std::make_unique( + nullptr, + _transferFunction, + _clipPlanes + ); _raycaster->initialize(); OsEng.renderEngine().raycasterManager().attachRaycaster(*_raycaster.get()); auto onChange = [&](bool enabled) { @@ -194,7 +292,9 @@ void RenderableTimeVaryingVolume::initialize() { jumpToTimestep(_jumpToTimestep); }); - const int lastTimestep = (_volumeTimesteps.size() > 0) ? (_volumeTimesteps.size() - 1) : 0; + const int lastTimestep = (_volumeTimesteps.size() > 0) ? + (_volumeTimesteps.size() - 1) : + 0; _currentTimestep.setMaxValue(lastTimestep); _jumpToTimestep.setMaxValue(lastTimestep); @@ -211,16 +311,28 @@ void RenderableTimeVaryingVolume::initialize() { addProperty(_lowerValueBound); addProperty(_upperValueBound); - _raycaster->setGridType((_gridType.value() == 1) ? VolumeGridType::Spherical : VolumeGridType::Cartesian); + _raycaster->setGridType( + (_gridType.value() == 1) ? + VolumeGridType::Spherical : + VolumeGridType::Cartesian + ); _gridType.onChange([this] { - _raycaster->setGridType((_gridType.value() == 1) ? VolumeGridType::Spherical : VolumeGridType::Cartesian); + _raycaster->setGridType( + (_gridType.value() == 1) ? + VolumeGridType::Spherical : + VolumeGridType::Cartesian + ); }); } void RenderableTimeVaryingVolume::loadTimestepMetadata(const std::string& path) { ghoul::Dictionary dictionary = ghoul::lua::loadDictionaryFromFile(path); try { - documentation::testSpecificationAndThrow(TimestepDocumentation(), dictionary, "TimeVaryingVolumeTimestep"); + documentation::testSpecificationAndThrow( + TimestepDocumentation(), + dictionary, + "TimeVaryingVolumeTimestep" + ); } catch (const documentation::SpecificationError& e) { LERROR(e.message << e.component); return; @@ -243,6 +355,7 @@ void RenderableTimeVaryingVolume::loadTimestepMetadata(const std::string& path) } RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimestep() { + using TimeStep = RenderableTimeVaryingVolume::Timestep; if (_volumeTimesteps.size() == 0) { return nullptr; } @@ -252,14 +365,14 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimes auto currentTimestepIt = _volumeTimesteps.upper_bound(currentTime); if (currentTimestepIt == _volumeTimesteps.end()) { // No such timestep was found: show last timestep if it is within the time margin. - RenderableTimeVaryingVolume::Timestep* lastTimestep = &(_volumeTimesteps.rbegin()->second); + Timestep* lastTimestep = &(_volumeTimesteps.rbegin()->second); double threshold = lastTimestep->time + static_cast(_secondsAfter); return currentTime < threshold ? lastTimestep : nullptr; } if (currentTimestepIt == _volumeTimesteps.begin()) { // No such timestep was found: show first timestep if it is within the time margin. - RenderableTimeVaryingVolume::Timestep* firstTimestep = &(_volumeTimesteps.begin()->second); + Timestep* firstTimestep = &(_volumeTimesteps.begin()->second); double threshold = firstTimestep->time - static_cast(_secondsBefore); return currentTime >= threshold ? firstTimestep : nullptr; } @@ -269,7 +382,9 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimes return &(currentTimestepIt->second); } -int RenderableTimeVaryingVolume::timestepIndex(const RenderableTimeVaryingVolume::Timestep* t) const { +int RenderableTimeVaryingVolume::timestepIndex( + const RenderableTimeVaryingVolume::Timestep* t) const +{ if (!t) { return -1; } @@ -283,8 +398,12 @@ int RenderableTimeVaryingVolume::timestepIndex(const RenderableTimeVaryingVolume return -1; } -RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::timestepFromIndex(int target) { - if (target < 0) target = 0; +RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::timestepFromIndex( + int target) +{ + if (target < 0) { + target = 0; + } int index = 0; for (auto& it : _volumeTimesteps) { if (index == target) { @@ -310,7 +429,8 @@ void RenderableTimeVaryingVolume::update(const UpdateData& data) { if (t && t->texture) { if (_raycaster->gridType() == volume::VolumeGridType::Cartesian) { glm::dvec3 scale = t->upperDomainBound - t->lowerDomainBound; - glm::dvec3 translation = (t->lowerDomainBound + t->upperDomainBound) * 0.5f; + glm::dvec3 translation = + (t->lowerDomainBound + t->upperDomainBound) * 0.5f; glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), translation); glm::dmat4 scaleMatrix = glm::scale(glm::dmat4(1.0), scale); @@ -326,12 +446,16 @@ void RenderableTimeVaryingVolume::update(const UpdateData& data) { } _raycaster->setVolumeTexture(t->texture); - // Remap volume value to that TF value 0 is sampled for lowerValueBound, and 1 is sampled for upperLowerBound. - // This means that volume values = 0 need to be remapped to how localMin relates to the global range. - float zeroMap = (t->minValue - _lowerValueBound) / (_upperValueBound - _lowerValueBound); + // Remap volume value to that TF value 0 is sampled for lowerValueBound, and 1 + // is sampled for upperLowerBound. + // This means that volume values = 0 need to be remapped to how localMin + // relates to the global range. + float zeroMap = (t->minValue - _lowerValueBound) / + (_upperValueBound - _lowerValueBound); // Volume values = 1 are mapped to how localMax relates to the global range. - float oneMap = (t->maxValue - _lowerValueBound) / (_upperValueBound - _lowerValueBound); + float oneMap = (t->maxValue - _lowerValueBound) / + (_upperValueBound - _lowerValueBound); _raycaster->setValueRemapping(zeroMap, oneMap); } else { _raycaster->setVolumeTexture(nullptr); @@ -376,14 +500,14 @@ documentation::Documentation RenderableTimeVaryingVolume::Documentation() { KeyTransferFunction, new StringVerifier, Optional::No, - "Specifies the transfer function file path", + "Specifies the transfer function file path" }, { KeyLowerValueBound, new DoubleVerifier, Optional::No, "Specifies the lower value bound." - "This number will be mapped to 0 before uploadin to the GPU.", + "This number will be mapped to 0 before uploadin to the GPU." }, { KeyUpperValueBound, @@ -402,15 +526,16 @@ documentation::Documentation RenderableTimeVaryingVolume::Documentation() { KeySecondsBefore, new DoubleVerifier, Optional::Yes, - "Specifies the number of seconds to show the the first timestep before its actual time." - "The default value is 0.", + "Specifies the number of seconds to show the the first timestep before " + "its actual time. The default value is 0." }, { KeySecondsAfter, new DoubleVerifier, Optional::No, - "Specifies the number of seconds to show the the last timestep after its actual time", - }, + "Specifies the number of seconds to show the the last timestep after its " + "actual time" + } } }; } diff --git a/modules/volume/textureslicevolumereader.h b/modules/volume/textureslicevolumereader.h index f2c1a6daed..4c9af06ff8 100644 --- a/modules/volume/textureslicevolumereader.h +++ b/modules/volume/textureslicevolumereader.h @@ -41,7 +41,8 @@ class TextureSliceVolumeReader { public: using VoxelType = Type; - TextureSliceVolumeReader(std::vector paths, size_t sliceCacheMaxItems, size_t sliceCacheSize); + TextureSliceVolumeReader(std::vector paths, size_t sliceCacheMaxItems, + size_t sliceCacheSize); VoxelType get(const glm::ivec3& coordinates) const; virtual glm::ivec3 dimensions() const; void setPaths(const std::vector paths); diff --git a/modules/volume/textureslicevolumereader.inl b/modules/volume/textureslicevolumereader.inl index dcfa91a4b7..242ebba6d4 100644 --- a/modules/volume/textureslicevolumereader.inl +++ b/modules/volume/textureslicevolumereader.inl @@ -39,9 +39,10 @@ glm::ivec3 TextureSliceVolumeReader::dimensions() const { } template -TextureSliceVolumeReader::TextureSliceVolumeReader(std::vector paths, - size_t sliceCacheNIndices, - size_t sliceCacheCapacity) +TextureSliceVolumeReader::TextureSliceVolumeReader( + std::vector paths, + size_t sliceCacheNIndices, + size_t sliceCacheCapacity) : _initialized(false) , _paths(paths) , _cache(sliceCacheCapacity, sliceCacheNIndices) {} @@ -65,7 +66,9 @@ void TextureSliceVolumeReader::setPaths(const std::vector -ghoul::opengl::Texture& TextureSliceVolumeReader::getSlice(int sliceIndex) const { +ghoul::opengl::Texture& +TextureSliceVolumeReader::getSlice(int sliceIndex) const +{ ghoul_assert(_initialized, "Volume is not initialized"); ghoul_assert(sliceIndex >= 0 && sliceIndex < _paths.size(), "Slice index " + std::to_string(sliceIndex) + "is outside the range."); diff --git a/modules/volume/volumesampler.inl b/modules/volume/volumesampler.inl index 23bae64e5a..9f7a26d8be 100644 --- a/modules/volume/volumesampler.inl +++ b/modules/volume/volumesampler.inl @@ -26,23 +26,29 @@ namespace openspace { namespace volume { template -VolumeSampler::VolumeSampler(const VolumeType& volume, const glm::vec3& filterSize) { +VolumeSampler::VolumeSampler(const VolumeType& volume, + const glm::vec3& filterSize) +{ // Only accept filter sizes of size 1, 3, 5, 7... // Round down to closest odd number. - _filterSize = static_cast((filterSize - glm::vec3(1.0)) * glm::vec3(0.5)) * - glm::ivec3(2) + glm::ivec3(1); + _filterSize = static_cast( + (filterSize - glm::vec3(1.0)) * glm::vec3(0.5) + ) * glm::ivec3(2) + glm::ivec3(1); _volume = &volume; } template -typename VolumeType::VoxelType VolumeSampler::sample(const glm::vec3& position) const { +typename VolumeType::VoxelType VolumeSampler::sample( + const glm::vec3& position) const +{ glm::ivec3 flooredPos = static_cast(glm::floor(position)); glm::vec3 t = glm::fract(position); // t is now in interval [0, 1[ (never 1) glm::ivec3 minCoords = flooredPos - _filterSize / 2; // min coord to sample from - glm::ivec3 maxCoords = minCoords + _filterSize; // max coords to sample from, including interpolation. + // max coords to sample from, including interpolation. + glm::ivec3 maxCoords = minCoords + _filterSize; glm::ivec3 clampCeiling = _volume->dimensions() - glm::ivec3(1); typename VolumeType::VoxelType value; @@ -68,7 +74,11 @@ typename VolumeType::VoxelType VolumeSampler::sample(const glm::vec3 filterCoefficient *= t.z; } - glm::ivec3 clampedCoords = glm::clamp(sampleCoords, glm::ivec3(0), clampCeiling); + glm::ivec3 clampedCoords = glm::clamp( + sampleCoords, + glm::ivec3(0), + clampCeiling + ); value += filterCoefficient * _volume->get(clampedCoords); } diff --git a/src/engine/downloadmanager.cpp b/src/engine/downloadmanager.cpp index 019878987d..9f621fdb9c 100644 --- a/src/engine/downloadmanager.cpp +++ b/src/engine/downloadmanager.cpp @@ -347,7 +347,10 @@ DownloadManager::downloadRequestFiles( ++nFiles; #ifdef __APPLE__ // @TODO: Fix this so that the ifdef is not necessary anymore ---abock - std::string file = ghoul::filesystem::File(line, ghoul::filesystem::File::RawPath::Yes).filename(); + std::string file = ghoul::filesystem::File( + line, + ghoul::filesystem::File::RawPath::Yes + ).filename(); #else std::string file = ghoul::filesystem::File(line).filename(); #endif diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index b899e3b7ac..bec3001d95 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -321,15 +321,15 @@ void OpenSpaceEngine::create(int argc, char** argv, } const bool hasCacheCommandline = !commandlineArgumentPlaceholders.cacheFolder.empty(); - const bool hasCacheConfiguration = _engine->configurationManager().hasKeyAndValue( + const bool hasCacheConfig = _engine->configurationManager().hasKeyAndValue( ConfigurationManager::KeyPerSceneCache ); std::string cacheFolder = absPath("${CACHE}"); - if (hasCacheCommandline || hasCacheConfiguration) { + if (hasCacheCommandline || hasCacheConfig) { if (hasCacheCommandline) { cacheFolder = commandlineArgumentPlaceholders.cacheFolder; } - if (hasCacheConfiguration) { + if (hasCacheConfig) { std::string scene = _engine->configurationManager().value( ConfigurationManager::KeyConfigScene ); @@ -400,7 +400,9 @@ void OpenSpaceEngine::create(int argc, char** argv, } void OpenSpaceEngine::destroy() { - if (_engine->parallelConnection().status() != ParallelConnection::Status::Disconnected) { + if (_engine->parallelConnection().status() != + ParallelConnection::Status::Disconnected) + { _engine->parallelConnection().signalDisconnect(); } @@ -1369,8 +1371,8 @@ scripting::LuaLibrary OpenSpaceEngine::luaLibrary() { "toggleShutdown", &luascriptfunctions::toggleShutdown, "", - "Toggles the shutdown mode that will close the application after the count" - "down timer is reached" + "Toggles the shutdown mode that will close the application after the " + "count down timer is reached" }, { "writeDocumentation", diff --git a/src/engine/settingsengine.cpp b/src/engine/settingsengine.cpp index 458f0c5fd2..788ddb539d 100644 --- a/src/engine/settingsengine.cpp +++ b/src/engine/settingsengine.cpp @@ -61,7 +61,9 @@ void SettingsEngine::initialize() { // Load all matching files in the Scene // TODO: match regex with either with new ghoul readFiles or local code const std::string sceneDir = "${SCENE}"; - const std::vector scenes = ghoul::filesystem::Directory(sceneDir).readFiles(); + const std::vector scenes = ghoul::filesystem::Directory( + sceneDir + ).readFiles(); for (std::size_t i = 0; i < scenes.size(); ++i) { const std::size_t found = scenes[i].find_last_of("/\\"); diff --git a/src/engine/wrapper/sgctwindowwrapper.cpp b/src/engine/wrapper/sgctwindowwrapper.cpp index 6754293148..a4efb9856d 100644 --- a/src/engine/wrapper/sgctwindowwrapper.cpp +++ b/src/engine/wrapper/sgctwindowwrapper.cpp @@ -150,7 +150,8 @@ glm::ivec2 SGCTWindowWrapper::currentWindowResolution() const { } glm::ivec2 SGCTWindowWrapper::currentDrawBufferResolution() const { - sgct_core::Viewport* viewport = sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); + sgct_core::Viewport* viewport = + sgct::Engine::instance()->getCurrentWindowPtr()->getViewport(0); if (viewport != nullptr){ if (viewport->hasSubViewports() && viewport->getNonLinearProjectionPtr()) { int res = viewport->getNonLinearProjectionPtr()->getCubemapResolution(); @@ -242,7 +243,9 @@ bool SGCTWindowWrapper::isExternalControlConnected() const { return sgct::Engine::instance()->isExternalControlConnected(); } -void SGCTWindowWrapper::sendMessageToExternalControl(const std::vector& message) const { +void SGCTWindowWrapper::sendMessageToExternalControl( + const std::vector& message) const +{ sgct::Engine::instance()->sendMessageToExternalControl( message.data(), static_cast(message.size()) @@ -250,7 +253,8 @@ void SGCTWindowWrapper::sendMessageToExternalControl(const std::vector& me } bool SGCTWindowWrapper::isSimpleRendering() const { - return (sgct::Engine::instance()->getCurrentRenderTarget() != sgct::Engine::NonLinearBuffer); + return (sgct::Engine::instance()->getCurrentRenderTarget() != + sgct::Engine::NonLinearBuffer); } void SGCTWindowWrapper::takeScreenshot(bool applyWarping) const { diff --git a/src/interaction/keybindingmanager.cpp b/src/interaction/keybindingmanager.cpp index c9f56fe3cf..231d278846 100644 --- a/src/interaction/keybindingmanager.cpp +++ b/src/interaction/keybindingmanager.cpp @@ -38,12 +38,6 @@ #include -namespace { - const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/main.hbs"; - const char* KeybindingTemplateFilename = "${OPENSPACE_DATA}/web/keybindings/keybinding.hbs"; - const char* JsFilename = "${OPENSPACE_DATA}/web/keybindings/script.js"; -} // namespace - #include "keybindingmanager_lua.inl" namespace openspace::interaction { @@ -53,14 +47,15 @@ KeyBindingManager::KeyBindingManager() "Documentation", "keybindings", { - { "keybindingTemplate", KeybindingTemplateFilename }, - { "mainTemplate", MainTemplateFilename } + { "keybindingTemplate", "${OPENSPACE_DATA}/web/keybindings/keybinding.hbs" }, + { "mainTemplate", "${OPENSPACE_DATA}/web/keybindings/main.hbs" } }, - JsFilename + "${OPENSPACE_DATA}/web/keybindings/script.js" ) { } -void KeyBindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { +void KeyBindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) +{ if (action == KeyAction::Press || action == KeyAction::Repeat) { // iterate over key bindings std::pair::iterator, @@ -122,7 +117,8 @@ std::string KeyBindingManager::generateJson() const { json << "{"; json << "\"key\": \"" << std::to_string(p.first) << "\","; json << "\"script\": \"" << p.second.command << "\","; - json << "\"remoteScripting\": " << (p.second.synchronization ? "true," : "false,"); + json << "\"remoteScripting\": " + << (p.second.synchronization ? "true," : "false,"); json << "\"documentation\": \"" << escapedJson(p.second.documentation) << "\""; json << "}"; } diff --git a/src/interaction/keyframenavigator.cpp b/src/interaction/keyframenavigator.cpp index 4d92bda1ee..66a40bf3cc 100644 --- a/src/interaction/keyframenavigator.cpp +++ b/src/interaction/keyframenavigator.cpp @@ -44,8 +44,10 @@ void KeyframeNavigator::updateCamera(Camera& camera) { return; } - const Keyframe* nextKeyframe = _cameraPoseTimeline.firstKeyframeAfter(now); - const Keyframe* prevKeyframe = _cameraPoseTimeline.lastKeyframeBefore(now); + const Keyframe* nextKeyframe = + _cameraPoseTimeline.firstKeyframeAfter(now); + const Keyframe* prevKeyframe = + _cameraPoseTimeline.lastKeyframeBefore(now); double nextTime = 0; double prevTime = 0; double t = 0; @@ -84,14 +86,23 @@ void KeyframeNavigator::updateCamera(Camera& camera) { glm::dquat prevKeyframeCameraRotation = prevPose.rotation; glm::dquat nextKeyframeCameraRotation = nextPose.rotation; - // Transform position and rotation based on focus node rotation (if following rotation) + // Transform position and rotation based on focus node rotation + // (if following rotation) if (prevPose.followFocusNodeRotation) { - prevKeyframeCameraRotation = glm::dquat(prevFocusNode->worldRotationMatrix() * glm::dmat3(glm::dquat(prevPose.rotation))); - prevKeyframeCameraPosition = prevFocusNode->worldRotationMatrix() * prevPose.position; + prevKeyframeCameraRotation = glm::dquat( + prevFocusNode->worldRotationMatrix() * + glm::dmat3(glm::dquat(prevPose.rotation)) + ); + prevKeyframeCameraPosition = prevFocusNode->worldRotationMatrix() * + prevPose.position; } if (nextPose.followFocusNodeRotation) { - nextKeyframeCameraRotation = glm::dquat(nextFocusNode->worldRotationMatrix() * glm::dmat3(glm::dquat(nextPose.rotation))); - nextKeyframeCameraPosition = nextFocusNode->worldRotationMatrix() * nextPose.position; + nextKeyframeCameraRotation = glm::dquat( + nextFocusNode->worldRotationMatrix() * + glm::dmat3(glm::dquat(nextPose.rotation)) + ); + nextKeyframeCameraPosition = nextFocusNode->worldRotationMatrix() * + nextPose.position; } // Transform position based on focus node position @@ -99,15 +110,20 @@ void KeyframeNavigator::updateCamera(Camera& camera) { nextKeyframeCameraPosition += nextFocusNode->worldPosition(); // Linear interpolation - camera.setPositionVec3(prevKeyframeCameraPosition * (1 - t) + nextKeyframeCameraPosition * t); - camera.setRotation(glm::slerp(prevKeyframeCameraRotation, nextKeyframeCameraRotation, t)); + camera.setPositionVec3( + prevKeyframeCameraPosition * (1 - t) + nextKeyframeCameraPosition * t + ); + camera.setRotation( + glm::slerp(prevKeyframeCameraRotation, nextKeyframeCameraRotation, t) + ); } Timeline& KeyframeNavigator::timeline() { return _cameraPoseTimeline; } -void KeyframeNavigator::addKeyframe(double timestamp, KeyframeNavigator::CameraPose pose) { +void KeyframeNavigator::addKeyframe(double timestamp, KeyframeNavigator::CameraPose pose) +{ timeline().addKeyframe(timestamp, pose); } diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index 08c4373dac..e370b8268c 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -75,7 +75,9 @@ NavigationHandler::NavigationHandler() _origin.onChange([this]() { SceneGraphNode* node = sceneGraphNode(_origin.value()); if (!node) { - LWARNING("Could not find a node in scenegraph called '" << _origin.value() << "'"); + LWARNING( + "Could not find a node in scenegraph called '" << _origin.value() << "'" + ); return; } setFocusNode(node); @@ -165,7 +167,9 @@ glm::dvec3 NavigationHandler::focusNodeToCameraVector() const { } glm::quat NavigationHandler::focusNodeToCameraRotation() const { - glm::dmat4 invWorldRotation = glm::dmat4(glm::inverse(focusNode()->worldRotationMatrix())); + glm::dmat4 invWorldRotation = glm::dmat4( + glm::inverse(focusNode()->worldRotationMatrix()) + ); return glm::quat(invWorldRotation) * glm::quat(_camera->rotationQuaternion()); } @@ -189,11 +193,13 @@ void NavigationHandler::mouseScrollWheelCallback(double pos) { _inputState->mouseScrollWheelCallback(pos); } -void NavigationHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { +void NavigationHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) +{ _inputState->keyboardCallback(key, modifier, action); } -void NavigationHandler::setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict) { +void NavigationHandler::setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict) +{ bool readSuccessful = true; std::string focus; @@ -255,7 +261,8 @@ void NavigationHandler::saveCameraStateToFile(const std::string& filepath) { glm::dquat q = _camera->rotationQuaternion(); ofs << "return {" << std::endl; - ofs << " " << KeyFocus << " = " << "\"" << focusNode()->name() << "\"" << "," << std::endl; + ofs << " " << KeyFocus << " = " << "\"" << focusNode()->name() << "\"" + << "," << std::endl; ofs << " " << KeyPosition << " = {" << std::to_string(p.x) << ", " << std::to_string(p.y) << ", " diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index 550c3abfef..38c5180af7 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -585,7 +585,8 @@ void ParallelConnection::initializationMessageReceived(){ std::cout << "initialization message recieved queue" << std::endl; queueMessage(InitializationCompleted, buffer); - //we also need to force a time jump just to ensure that the server and client are synced + // we also need to force a time jump just to ensure that the server and client are + // synced _initializationTimejumpRequired.store(true); } @@ -614,11 +615,13 @@ double ParallelConnection::latencyStandardDeviation() const { accumulatedLatencyDiff += diff; accumulatedLatencyDiffSquared += diff*diff; } - double expectedLatencyDiffSquared = accumulatedLatencyDiffSquared / _latencyDiffs.size(); + double expectedLatencyDiffSquared = accumulatedLatencyDiffSquared / + _latencyDiffs.size(); double expectedLatencyDiff = accumulatedLatencyDiff / _latencyDiffs.size(); // V(X) = E(x^2) - E(x)^2 - double latencyVariance = expectedLatencyDiffSquared - expectedLatencyDiff*expectedLatencyDiff; + double latencyVariance = expectedLatencyDiffSquared - + expectedLatencyDiff*expectedLatencyDiff; return std::sqrt(latencyVariance); } @@ -834,7 +837,9 @@ void ParallelConnection::nConnectionsMessageReceived(const std::vector& me -//void ParallelConnection::initializationRequestMessageReceived(const std::vector& message){ +//void ParallelConnection::initializationRequestMessageReceived( + // const std::vector& message +// { /* //get current state as scripts std::vector scripts; @@ -846,7 +851,9 @@ void ParallelConnection::nConnectionsMessageReceived(const std::vector& me for(state_it = _currentState.begin(); state_it != _currentState.end(); ++state_it){ - scripts.push_back(scriptFromPropertyAndValue(state_it->first, state_it->second)); + scripts.push_back( + scriptFromPropertyAndValue(state_it->first, state_it->second) + ); } } @@ -888,14 +895,26 @@ void ParallelConnection::nConnectionsMessageReceived(const std::vector& me writeHeader(buffer, MessageTypes::Initialization); //write client ID to receive init message - buffer.insert(buffer.end(), reinterpret_cast(&requesterID), reinterpret_cast(&requesterID) + sizeof(uint32_t)); + buffer.insert( + buffer.end(), + reinterpret_cast(&requesterID), + reinterpret_cast(&requesterID) + sizeof(uint32_t) + ); //write total size of data chunk uint32_t totlen = static_cast(scriptbuffer.size()); - buffer.insert(buffer.end(), reinterpret_cast(&totlen), reinterpret_cast(&totlen) + sizeof(uint32_t)); + buffer.insert( + buffer.end(), + reinterpret_cast(&totlen), + reinterpret_cast(&totlen) + sizeof(uint32_t) + ); //write number of scripts - buffer.insert(buffer.end(), reinterpret_cast(&numscripts), reinterpret_cast(&numscripts) + sizeof(uint16_t)); + buffer.insert( + buffer.end(), + reinterpret_cast(&numscripts), + reinterpret_cast(&numscripts) + sizeof(uint16_t) + ); //write all scripts buffer.insert(buffer.end(), scriptbuffer.begin(), scriptbuffer.end()); @@ -1152,7 +1171,8 @@ void ParallelConnection::sendCameraKeyframe() { datamessagestructures::CameraKeyframe kf; kf._position = OsEng.navigationHandler().focusNodeToCameraVector(); - kf._followNodeRotation = OsEng.navigationHandler().orbitalNavigator().followingNodeRotation(); + kf._followNodeRotation = + OsEng.navigationHandler().orbitalNavigator().followingNodeRotation(); if (kf._followNodeRotation) { kf._position = glm::inverse(focusNode->worldRotationMatrix()) * kf._position; kf._rotation = OsEng.navigationHandler().focusNodeToCameraRotation(); diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index 1250a300a9..a7921bd387 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -214,7 +214,10 @@ void PerformanceManager::outputLogs() { for (int16_t n = 0; n < layout->nFunctionEntries; n++) { const auto function = layout->functionEntries[n]; const std::string filename = formatLogName(function.name); - std::ofstream out = std::ofstream(absPath(filename), std::ofstream::out | std::ofstream::app); + std::ofstream out = std::ofstream( + absPath(filename), + std::ofstream::out | std::ofstream::app + ); // Comma separate data for (size_t i = writeStart; i < PerformanceLayout::NumberValues; i++) { @@ -230,7 +233,10 @@ void PerformanceManager::outputLogs() { // Open file const std::string filename = formatLogName(node.name); - std::ofstream out = std::ofstream(absPath(filename), std::ofstream::out | std::ofstream::app); + std::ofstream out = std::ofstream( + absPath(filename), + std::ofstream::out | std::ofstream::app + ); // Comma separate data for (size_t i = writeStart; i < PerformanceLayout::NumberValues; i++) { @@ -390,7 +396,8 @@ void PerformanceManager::storeScenePerformanceMeasurements( #endif SceneGraphNode::PerformanceRecord r = node->performanceRecord(); - PerformanceLayout::SceneGraphPerformanceLayout& entry = layout->sceneGraphEntries[i]; + PerformanceLayout::SceneGraphPerformanceLayout& entry = + layout->sceneGraphEntries[i]; // Covert nano to microseconds const float micro = 1000.f; @@ -407,28 +414,32 @@ void PerformanceManager::storeScenePerformanceMeasurements( std::next(std::begin(entry.updateTranslation)), std::end(entry.updateTranslation) ); - entry.updateTranslation[PerformanceLayout::NumberValues - 1] = r.updateTimeTranslation / micro; + entry.updateTranslation[PerformanceLayout::NumberValues - 1] = + r.updateTimeTranslation / micro; std::rotate( std::begin(entry.updateRotation), std::next(std::begin(entry.updateRotation)), std::end(entry.updateRotation) ); - entry.updateRotation[PerformanceLayout::NumberValues - 1] = r.updateTimeRotation / micro; + entry.updateRotation[PerformanceLayout::NumberValues - 1] = + r.updateTimeRotation / micro; std::rotate( std::begin(entry.updateScaling), std::next(std::begin(entry.updateScaling)), std::end(entry.updateScaling) ); - entry.updateScaling[PerformanceLayout::NumberValues - 1] = r.updateTimeScaling / micro; + entry.updateScaling[PerformanceLayout::NumberValues - 1] = + r.updateTimeScaling / micro; std::rotate( std::begin(entry.updateRenderable), std::next(std::begin(entry.updateRenderable)), std::end(entry.updateRenderable) ); - entry.updateRenderable[PerformanceLayout::NumberValues - 1] = r.updateTimeRenderable / micro; + entry.updateRenderable[PerformanceLayout::NumberValues - 1] = + r.updateTimeRenderable / micro; } _performanceMemory->releaseLock(); diff --git a/src/properties/scalar/wcharproperty.cpp b/src/properties/scalar/wcharproperty.cpp index 75bc573f2e..11691ed4e7 100644 --- a/src/properties/scalar/wcharproperty.cpp +++ b/src/properties/scalar/wcharproperty.cpp @@ -33,32 +33,32 @@ using std::numeric_limits; namespace openspace::properties { -// #define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ -// [](lua_State* state, bool& success) -> TYPE { \ -// success = (lua_isnumber(state, -1) == 1); \ -// if (success) { \ -// return static_cast(lua_tonumber(state, -1)); \ -// } \ -// else { \ -// return DEFAULT_VALUE; \ -// } \ +// #define DEFAULT_FROM_LUA_LAMBDA(TYPE, DEFAULT_VALUE) \ +// [](lua_State* state, bool& success) -> TYPE { \ +// success = (lua_isnumber(state, -1) == 1); \ +// if (success) { \ +// return static_cast(lua_tonumber(state, -1)); \ +// } \ +// else { \ +// return DEFAULT_VALUE; \ +// } \ // } -// #define DEFAULT_TO_LUA_LAMBDA(TYPE) \ -// [](lua_State* state, TYPE value) -> bool { \ -// lua_pushnumber(state, static_cast(value)); \ -// return true; \ +// #define DEFAULT_TO_LUA_LAMBDA(TYPE) \ +// [](lua_State* state, TYPE value) -> bool { \ +// lua_pushnumber(state, static_cast(value)); \ +// return true; \ // } -// #define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ -// [](std::string val, bool& success) -> TYPE { \ -// std::stringstream s(val); \ -// TYPE v; \ -// s >> v; \ -// success = !s.fail(); \ -// if (success) { \ -// return v; \ -// } \ +// #define DEFAULT_FROM_STRING_LAMBDA(TYPE, DEFAULT_VALUE) \ +// [](std::string val, bool& success) -> TYPE { \ +// std::stringstream s(val); \ +// TYPE v; \ +// s >> v; \ +// success = !s.fail(); \ +// if (success) { \ +// return v; \ +// } \ // } //REGISTER_NUMERICALPROPERTY_SOURCE(WCharProperty, wchar_t, wchar_t(0), diff --git a/src/query/query.cpp b/src/query/query.cpp index 6663895128..7ce43a5bc3 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -1,4 +1,4 @@ - /***************************************************************************************** +/***************************************************************************************** * * * OpenSpace * * * diff --git a/src/rendering/abufferrenderer.cpp b/src/rendering/abufferrenderer.cpp index ee7bc8a4fb..ba13ab46c3 100644 --- a/src/rendering/abufferrenderer.cpp +++ b/src/rendering/abufferrenderer.cpp @@ -364,9 +364,15 @@ void ABufferRenderer::preRaycast(const RaycasterTask& raycasterTask) { glm::vec3 localCameraPosition; bool cameraIsInside = raycaster.cameraIsInside(renderData, localCameraPosition); int uniformIndex = raycastData.id + 1; // uniforms are indexed from 1 (not from 0) - _resolveProgram->setUniform("insideRaycaster" + std::to_string(uniformIndex), cameraIsInside); + _resolveProgram->setUniform( + "insideRaycaster" + std::to_string(uniformIndex), + cameraIsInside + ); if (cameraIsInside) { - _resolveProgram->setUniform("cameraPosInRaycaster" + std::to_string(uniformIndex), localCameraPosition); + _resolveProgram->setUniform( + "cameraPosInRaycaster" + std::to_string(uniformIndex), + localCameraPosition + ); } } @@ -550,7 +556,9 @@ void ABufferRenderer::updateRaycastData() { OsEng.renderEngine().raycasterManager().raycasters(); std::map namespaceIndices; - int nextId = 0; // raycaster ids are positive integers starting at 0. (for raycasters, fragment type is id+1) + // raycaster ids are positive integers starting at 0. (for raycasters, + // fragment type is id+1) + int nextId = 0; int nextNamespaceIndex = 0; for (auto &raycaster : raycasters) { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 211f970b48..e0e633c579 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -45,10 +45,12 @@ namespace { const char* _loggerCat = "FramebufferRenderer"; const char* ExitFragmentShaderPath = "${SHADERS}/framebuffer/exitframebuffer.frag"; - const char* RaycastFragmentShaderPath = "${SHADERS}/framebuffer/raycastframebuffer.frag"; + const char* RaycastFragmentShaderPath = + "${SHADERS}/framebuffer/raycastframebuffer.frag"; const char* GetEntryInsidePath = "${SHADERS}/framebuffer/inside.glsl"; const char* GetEntryOutsidePath = "${SHADERS}/framebuffer/outside.glsl"; - const char* RenderFragmentShaderPath = "${SHADERS}/framebuffer/renderframebuffer.frag"; + const char* RenderFragmentShaderPath = + "${SHADERS}/framebuffer/renderframebuffer.frag"; } // namespace namespace openspace { diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index c4e52442fe..446202a96e 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -63,8 +63,8 @@ documentation::Documentation Renderable::Documentation() { KeyType, new StringAnnotationVerifier("A valid Renderable created by a factory"), Optional::No, - "This key specifies the type of Renderable that gets created. It has to be one" - "of the valid Renderables that are available for creation (see the " + "This key specifies the type of Renderable that gets created. It has to be " + "one of the valid Renderables that are available for creation (see the " "FactoryDocumentation for a list of possible Renderables), which depends on " "the configration of the application" }, diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index b7660d1f8e..52960f58b5 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -232,13 +232,15 @@ RenderEngine::RenderEngine() if (!_performanceManager) { std::string loggingDir = "${BASE_PATH}"; - const std::string KeyDir = ConfigurationManager::KeyLogging + "." + ConfigurationManager::PartLogDir; + const std::string KeyDir = ConfigurationManager::KeyLogging + "." + + ConfigurationManager::PartLogDir; if (OsEng.configurationManager().hasKey(KeyDir)) { loggingDir = OsEng.configurationManager().value(KeyDir); } std::string prefix = "PM-"; - const std::string KeyPrefix = ConfigurationManager::KeyLogging + "." + ConfigurationManager::PartLogPerformancePrefix; + const std::string KeyPrefix = ConfigurationManager::KeyLogging + "." + + ConfigurationManager::PartLogPerformancePrefix; if (OsEng.configurationManager().hasKey(KeyPrefix)) { prefix = OsEng.configurationManager().value(KeyPrefix); } @@ -821,13 +823,15 @@ scripting::LuaLibrary RenderEngine::luaLibrary() { "registerScreenSpaceRenderable", &luascriptfunctions::registerScreenSpaceRenderable, "table", - "Will create a ScreenSpaceRenderable from a lua Table and register it in the RenderEngine" + "Will create a ScreenSpaceRenderable from a lua Table and register it in " + "the RenderEngine" }, { "unregisterScreenSpaceRenderable", &luascriptfunctions::unregisterScreenSpaceRenderable, "string", - "Given a ScreenSpaceRenderable name this script will remove it from the renderengine" + "Given a ScreenSpaceRenderable name this script will remove it from the " + "renderengine" }, }, }; @@ -1048,8 +1052,8 @@ void RenderEngine::renderInformation() { // static const glm::vec4 nextMissionColor(0.7, 0.3, 0.3, 1); // //static const glm::vec4 missionProgressColor(0.4, 1.0, 1.0, 1); // static const glm::vec4 currentMissionColor(0.0, 0.5, 0.5, 1); - // static const glm::vec4 missionProgressColor = currentMissionColor;// (0.4, 1.0, 1.0, 1); - // // static const glm::vec4 currentLeafMissionColor = missionProgressColor; + // static const glm::vec4 missionProgressColor = currentMissionColor; + // // static const glm::vec4 currentLeafMissionColor = missionProgressColor; // static const glm::vec4 nonCurrentMissionColor(0.3, 0.3, 0.3, 1); // // Add spacing @@ -1060,15 +1064,27 @@ void RenderEngine::renderInformation() { // if (phaseTrace.size()) { // const MissionPhase& phase = phaseTrace.back().get(); // std::string title = "Current Mission Phase: " + phase.name(); - // RenderFontCr(*_fontInfo, penPosition, missionProgressColor, title.c_str()); + // RenderFontCr( + // *_fontInfo, + // penPosition, + // missionProgressColor, + // title.c_str() + // ); // double remaining = phase.timeRange().end - currentTime; - // float t = static_cast(1.0 - remaining / phase.timeRange().duration()); + // float t = static_cast( + // 1.0 - remaining / phase.timeRange().duration() + // ); // std::string progress = progressToStr(25, t); // //RenderFontCr(*_fontInfo, penPosition, missionProgressColor, // // "%.0f s %s %.1f %%", remaining, progress.c_str(), t * 100); // } // else { - // RenderFontCr(*_fontInfo, penPosition, nextMissionColor, "Next Mission:"); + // RenderFontCr( + // *_fontInfo, + // penPosition, + // nextMissionColor, + // "Next Mission:" + // ); // double remaining = mission.timeRange().start - currentTime; // RenderFontCr(*_fontInfo, penPosition, nextMissionColor, // "%.0f s", remaining); @@ -1090,7 +1106,9 @@ void RenderEngine::renderInformation() { // penPosition.x += depth * pixelIndentation; // if (isCurrentPhase) { // double remaining = phase->timeRange().end - currentTime; - // float t = static_cast(1.0 - remaining / phase->timeRange().duration()); + // float t = static_cast( + // 1.0 - remaining / phase->timeRange().duration() + // ); // std::string progress = progressToStr(25, t); // RenderFontCr(*_fontInfo, penPosition, currentMissionColor, // "%s %s %.1f %%", @@ -1100,14 +1118,22 @@ void RenderEngine::renderInformation() { // ); // } // else { - // RenderFontCr(*_fontInfo, penPosition, nonCurrentMissionColor, phase->name().c_str()); + // RenderFontCr( + // *_fontInfo, + // penPosition, + // nonCurrentMissionColor, + // phase->name().c_str() + // ); // } // penPosition.x -= depth * pixelIndentation; // if (isCurrentPhase || showAllPhases) { - // // phases are sorted increasingly by start time, and will be popped - // // last-in-first-out from the stack, so add them in reversed order. - // int indexLastPhase = static_cast(phase->phases().size()) - 1; + // // phases are sorted increasingly by start time, and will be + // // popped last-in-first-out from the stack, so add them in + // // reversed order. + // int indexLastPhase = static_cast( + // phase->phases().size() + // ) - 1; // for (int i = indexLastPhase; 0 <= i; --i) { // S.push({ &phase->phases()[i], depth + 1 }); // } @@ -1126,9 +1152,19 @@ void RenderEngine::renderInformation() { if (hasNewHorizons) { try { double lt; - glm::dvec3 p = - SpiceManager::ref().targetPosition("PLUTO", "NEW HORIZONS", "GALACTIC", {}, currentTime, lt); - psc nhPos = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); + glm::dvec3 p = SpiceManager::ref().targetPosition( + "PLUTO", + "NEW HORIZONS", + "GALACTIC", + {}, + currentTime, + lt + ); + psc nhPos = PowerScaledCoordinate::CreatePowerScaledCoordinate( + p.x, + p.y, + p.z + ); float a, b; glm::dvec3 radii; SpiceManager::ref().getValue("PLUTO", "RADII", radii); @@ -1150,13 +1186,16 @@ void RenderEngine::renderInformation() { } } - double remaining = openspace::ImageSequencer::ref().getNextCaptureTime() - currentTime; - float t = static_cast(1.0 - remaining / openspace::ImageSequencer::ref().getIntervalLength()); + double remaining = openspace::ImageSequencer::ref().getNextCaptureTime() - + currentTime; + float t = static_cast( + 1.0 - remaining / openspace::ImageSequencer::ref().getIntervalLength() + ); std::string str = SpiceManager::ref().dateFromEphemerisTime( ImageSequencer::ref().getNextCaptureTime(), "YYYY MON DD HR:MN:SC" - ); + ); glm::vec4 active(0.6, 1, 0.00, 1); glm::vec4 brigther_active(0.9, 1, 0.75, 1); @@ -1185,8 +1224,10 @@ void RenderEngine::renderInformation() { str.c_str() ); } - std::pair nextTarget = ImageSequencer::ref().getNextTarget(); - std::pair currentTarget = ImageSequencer::ref().getCurrentTarget(); + std::pair nextTarget = + ImageSequencer::ref().getNextTarget(); + std::pair currentTarget = + ImageSequencer::ref().getCurrentTarget(); if (currentTarget.first > 0.0) { int timeleft = static_cast(nextTarget.first - currentTime); @@ -1216,34 +1257,10 @@ void RenderEngine::renderInformation() { hh.c_str(), mm.c_str(), ss.c_str() ); -#if 0 -// Why is it (2) in the original? ---abock - //std::pair> incidentTargets = ImageSequencer::ref().getIncidentTargetList(0); - //std::pair> incidentTargets = ImageSequencer::ref().getIncidentTargetList(2); - std::string space; - glm::vec4 color; - size_t isize = incidentTargets.second.size(); - for (size_t p = 0; p < isize; p++) { - double t = static_cast(p + 1) / static_cast(isize + 1); - t = (p > isize / 2) ? 1 - t : t; - t += 0.3; - color = (p == isize / 2) ? targetColor : glm::vec4(t, t, t, 1); - - RenderFont(*_fontInfo, - penPosition, - color, - "%s%s", - space.c_str(), incidentTargets.second[p].c_str() - ); - - - for (int k = 0; k < incidentTargets.second[p].size() + 2; k++) - space += " "; - } -#endif penPosition.y -= _fontInfo->height(); - std::map activeMap = ImageSequencer::ref().getActiveInstruments(); + std::map activeMap = + ImageSequencer::ref().getActiveInstruments(); glm::vec4 firing(0.58 - t, 1 - t, 1 - t, 1); glm::vec4 notFiring(0.5, 0.5, 0.5, 1); diff --git a/src/rendering/renderengine_lua.inl b/src/rendering/renderengine_lua.inl index fa97cab86d..3efd03bc06 100644 --- a/src/rendering/renderengine_lua.inl +++ b/src/rendering/renderengine_lua.inl @@ -114,7 +114,9 @@ int registerScreenSpaceRenderable(lua_State* L) { return 0; } - std::shared_ptr s( ScreenSpaceRenderable::createFromDictionary(d) ); + std::shared_ptr s( + ScreenSpaceRenderable::createFromDictionary(d) + ); OsEng.renderEngine().registerScreenSpaceRenderable(s); return 1; @@ -130,9 +132,14 @@ int unregisterScreenSpaceRenderable(lua_State* L) { std::string name = luaL_checkstring(L, -1); - std::shared_ptr s = OsEng.renderEngine().screenSpaceRenderable(name); + std::shared_ptr s = OsEng.renderEngine().screenSpaceRenderable( + name + ); if (!s) { - LERRORC("unregisterScreenSpaceRenderable", errorLocation(L) << "Could not find ScreenSpaceRenderable '" << name << "'"); + LERRORC( + "unregisterScreenSpaceRenderable", + errorLocation(L) << "Could not find ScreenSpaceRenderable '" << name << "'" + ); return 0; } diff --git a/src/rendering/transferfunction.cpp b/src/rendering/transferfunction.cpp index 54a8c08dde..5541f8c116 100644 --- a/src/rendering/transferfunction.cpp +++ b/src/rendering/transferfunction.cpp @@ -40,14 +40,13 @@ namespace { const char* _loggerCat = "TransferFunction"; - ghoul::opengl::Texture::FilterMode filtermode = ghoul::opengl::Texture::FilterMode::Linear; - ghoul::opengl::Texture::WrappingMode wrappingmode = ghoul::opengl::Texture::WrappingMode::ClampToEdge; - - bool hasExtension (std::string const &filepath, std::string const &extension) - { + // @TODO Replace with Filesystem::File extension + bool hasExtension(const std::string& filepath, const std::string& extension) { std::string ending = "." + extension; if (filepath.length() > ending.length()) { - return (0 == filepath.compare (filepath.length() - ending.length(), ending.length(), ending)); + return (0 == filepath.compare( + filepath.length() - ending.length(), + ending.length(), ending)); } else { return false; } @@ -57,7 +56,10 @@ namespace { namespace openspace { -TransferFunction::TransferFunction(const std::string& filepath, TfChangedCallback tfChangedCallback) : _filepath(filepath) { +TransferFunction::TransferFunction(const std::string& filepath, + TfChangedCallback tfChangedCallback) + : _filepath(filepath) +{ setPath(filepath); setCallback(tfChangedCallback); } @@ -72,7 +74,10 @@ void TransferFunction::setPath(const std::string& filepath) { _file = nullptr; } _filepath = f; - _file = std::make_unique(filepath, ghoul::filesystem::File::RawPath::Yes); + _file = std::make_unique( + filepath, + ghoul::filesystem::File::RawPath::Yes + ); _needsUpdate = true; _file->setCallback([this](const ghoul::filesystem::File&) { _needsUpdate = true; @@ -163,8 +168,8 @@ void TransferFunction::setTextureFromTxt() { transferFunction[i] = 0.0f; } - size_t lowerIndex = static_cast(floorf(lower*static_cast(width-1))); - size_t upperIndex = static_cast(floorf(upper*static_cast(width-1))); + size_t lowerIndex = static_cast(floorf(lower * static_cast(width-1))); + size_t upperIndex = static_cast(floorf(upper * static_cast(width-1))); auto prevKey = mappingKeys.begin(); auto currentKey = prevKey + 1; @@ -187,21 +192,27 @@ void TransferFunction::setTextureFromTxt() { size_t position = 4*i + channel; // Interpolate linearly between prev and next mapping key - float value = - ((*prevKey).color[channel]*(1.f-weight) + (*currentKey).color[channel]*weight)/255.f; + float value = ((*prevKey).color[channel] * (1.f - weight) + + (*currentKey).color[channel] * weight) / 255.f; transferFunction[position] = value; } } // no need to deallocate transferFunction. Ownership is transferred to the Texture. - _texture = std::make_unique(transferFunction, - glm::size3_t(width,1,1),ghoul::opengl::Texture::Format::RGBA, - GL_RGBA, GL_FLOAT, filtermode, wrappingmode); + _texture = std::make_unique( + transferFunction, + glm::size3_t(width, 1, 1), + ghoul::opengl::Texture::Format::RGBA, + GL_RGBA, + GL_FLOAT, + ghoul::opengl::Texture::FilterMode::Linear, + ghoul::opengl::Texture::WrappingMode::ClampToEdge + ); } void TransferFunction::setTextureFromImage() { _texture = ghoul::io::TextureReader::ref().loadTexture(_filepath); - _texture->setWrapping(wrappingmode); + _texture->setWrapping(ghoul::opengl::Texture::WrappingMode::ClampToEdge); } glm::vec4 TransferFunction::sample(size_t offset) { diff --git a/src/scene/rotation.cpp b/src/scene/rotation.cpp index f1209576f6..f08f226966 100644 --- a/src/scene/rotation.cpp +++ b/src/scene/rotation.cpp @@ -57,7 +57,9 @@ documentation::Documentation Rotation::Documentation() { }; } -std::unique_ptr Rotation::createFromDictionary(const ghoul::Dictionary& dictionary) { +std::unique_ptr Rotation::createFromDictionary( + const ghoul::Dictionary& dictionary) +{ documentation::testSpecificationAndThrow(Documentation(), dictionary, "Rotation"); std::string rotationType = dictionary.value(KeyType); diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index cbf29e5d46..3adaf90ea7 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -63,18 +63,6 @@ namespace { const char* _loggerCat = "Scene"; - //const char* _moduleExtension = ".mod"; - //const char* _commonModuleToken = "${COMMON_MODULE}"; - - //const char* KeyCamera = "Camera"; - //const char* KeyFocusObject = "Focus"; - //const char* KeyPositionObject = "Position"; - //const char* KeyViewOffset = "Offset"; - - const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/properties/main.hbs"; - const char* PropertyOwnerTemplateFilename = "${OPENSPACE_DATA}/web/properties/propertyowner.hbs"; - const char* PropertyTemplateFilename = "${OPENSPACE_DATA}/web/properties/property.hbs"; - const char* JsFilename = "${OPENSPACE_DATA}/web/properties/script.js"; } // namespace namespace openspace { @@ -84,11 +72,20 @@ Scene::Scene() "Documented", "propertyOwners", { - { "mainTemplate", MainTemplateFilename }, - { "propertyOwnerTemplate", PropertyOwnerTemplateFilename }, - { "propertyTemplate", PropertyTemplateFilename } + { + "mainTemplate", + "${OPENSPACE_DATA}/web/properties/main.hbs" + }, + { + "propertyOwnerTemplate", + "${OPENSPACE_DATA}/web/properties/propertyowner.hbs" + }, + { + "propertyTemplate", + "${OPENSPACE_DATA}/web/properties/property.hbs" + } }, - JsFilename + "${OPENSPACE_DATA}/web/properties/script.js" ) {} @@ -128,7 +125,11 @@ void Scene::removeNode(SceneGraphNode* node, UpdateDependencies updateDeps) { // Remove the node and all its children. node->traversePostOrder([this](SceneGraphNode* n) { _topologicallySortedNodes.erase( - std::remove(_topologicallySortedNodes.begin(), _topologicallySortedNodes.end(), n), + std::remove( + _topologicallySortedNodes.begin(), + _topologicallySortedNodes.end(), + n + ), _topologicallySortedNodes.end() ); _nodesByName.erase(n->name()); @@ -155,7 +156,10 @@ void Scene::sortTopologically() { ); _circularNodes.clear(); - ghoul_assert(_topologicallySortedNodes.size() == _nodesByName.size(), "Number of scene graph nodes is inconsistent"); + ghoul_assert( + _topologicallySortedNodes.size() == _nodesByName.size(), + "Number of scene graph nodes is inconsistent" + ); if (_topologicallySortedNodes.empty()) { return; @@ -204,7 +208,10 @@ void Scene::sortTopologically() { } } if (inDegrees.size() > 0) { - LERROR("The scene contains circular dependencies. " << inDegrees.size() << " nodes will be disabled."); + LERROR( + "The scene contains circular dependencies. " << + inDegrees.size() << " nodes will be disabled." + ); } for (auto it : inDegrees) { @@ -429,7 +436,8 @@ scripting::LuaLibrary Scene::luaLibrary() { }; } -Scene::InvalidSceneError::InvalidSceneError(const std::string& error, const std::string& comp) +Scene::InvalidSceneError::InvalidSceneError(const std::string& error, + const std::string& comp) : ghoul::RuntimeError(error, comp) {} diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index 4d1110ed85..da01fbe96f 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -147,7 +147,6 @@ int setPropertyCall_single(properties::Property* prop, std::string uri, lua_Stat //ensure properties are synced over parallel connection std::string value; prop->getStringValue(value); - //OsEng.parallelConnection().scriptMessage(prop->fullyQualifiedIdentifier(), value); } return 0; @@ -358,7 +357,10 @@ int addSceneGraphNode(lua_State* L) { } SceneLoader loader; - SceneGraphNode* importedNode = loader.importNodeDictionary(*OsEng.renderEngine().scene(), d); + SceneGraphNode* importedNode = loader.importNodeDictionary( + *OsEng.renderEngine().scene(), + d + ); importedNode->initialize(); return 1; diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index edcf312764..54b55850a9 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -72,7 +72,9 @@ const std::string SceneGraphNode::KeyParentName = "Parent"; const std::string SceneGraphNode::KeyDependencies = "Dependencies"; const std::string SceneGraphNode::KeyTag = "Tag"; -std::unique_ptr SceneGraphNode::createFromDictionary(const ghoul::Dictionary& dictionary){ +std::unique_ptr SceneGraphNode::createFromDictionary( + const ghoul::Dictionary& dictionary) +{ openspace::documentation::testSpecificationAndThrow( SceneGraphNode::Documentation(), dictionary, @@ -315,7 +317,11 @@ void SceneGraphNode::update(const UpdateData& data) { } void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { - const psc thisPositionPSC = psc::CreatePowerScaledCoordinate(_worldPositionCached.x, _worldPositionCached.y, _worldPositionCached.z); + const psc thisPositionPSC = psc::CreatePowerScaledCoordinate( + _worldPositionCached.x, + _worldPositionCached.y, + _worldPositionCached.z + ); RenderData newData = { data.camera, @@ -359,7 +365,8 @@ void SceneGraphNode::setParent(SceneGraphNode& parent, UpdateScene updateScene) ghoul_assert(_parent != nullptr, "Node must be attached to a parent"); ghoul_assert( !updateScene || _scene == parent._scene, - "For the scene to be updated, this object must belong to the same scene as the parent" + "For the scene to be updated, this object must belong to the same scene as " + "the parent" ); ghoul_assert( !updateScene || _parent->_scene == parent._scene, @@ -373,7 +380,9 @@ void SceneGraphNode::setParent(SceneGraphNode& parent, UpdateScene updateScene) } } -void SceneGraphNode::attachChild(std::unique_ptr child, UpdateScene updateScene) { +void SceneGraphNode::attachChild(std::unique_ptr child, + UpdateScene updateScene) +{ ghoul_assert(child->parent() == nullptr, "Child may not already have a parent"); child->_parent = this; @@ -388,8 +397,13 @@ void SceneGraphNode::attachChild(std::unique_ptr child, UpdateSc } } -std::unique_ptr SceneGraphNode::detachChild(SceneGraphNode& child, UpdateScene updateScene) { - ghoul_assert(child._dependentNodes.empty(), "Nodes cannot depend on a node being detached"); +std::unique_ptr SceneGraphNode::detachChild(SceneGraphNode& child, + UpdateScene updateScene) +{ + ghoul_assert( + child._dependentNodes.empty(), + "Nodes cannot depend on a node being detached" + ); ghoul_assert(child._parent != nullptr, "Node must be attached to a parent"); // Update of deps is deffered to the removal of the node from the scene @@ -425,7 +439,8 @@ void SceneGraphNode::addDependency(SceneGraphNode& dependency, UpdateScene updat } } -void SceneGraphNode::removeDependency(SceneGraphNode& dependency, UpdateScene updateScene) { +void SceneGraphNode::removeDependency(SceneGraphNode& dependency, UpdateScene updateScene) +{ dependency._dependentNodes.erase(std::remove_if( dependency._dependentNodes.begin(), dependency._dependentNodes.end(), @@ -463,7 +478,9 @@ void SceneGraphNode::clearDependencies(UpdateScene updateScene) { } } -void SceneGraphNode::setDependencies(const std::vector& dependencies, UpdateScene updateScene) { +void SceneGraphNode::setDependencies(const std::vector& dependencies, + UpdateScene updateScene) +{ clearDependencies(UpdateScene::No); _dependencies = dependencies; @@ -672,9 +689,6 @@ void SceneGraphNode::updateCamera(Camera* camera) const{ camera->setPosition(target); camera->setFocusPosition(origin); - - //printf("target: %f, %f, %f, %f\n", target.vec4().x, target.vec4().y, target.vec4().z, target.vec4().w); - } } // namespace openspace diff --git a/src/scene/scenelicensewriter.cpp b/src/scene/scenelicensewriter.cpp index 4b16d49366..c2a0958ae3 100644 --- a/src/scene/scenelicensewriter.cpp +++ b/src/scene/scenelicensewriter.cpp @@ -28,7 +28,8 @@ namespace { const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/scenelicense/main.hbs"; - const char* SceneLicenseTemplateFilename = "${OPENSPACE_DATA}/web/scenelicense/scenelicense.hbs"; + const char* SceneLicenseTemplateFilename = + "${OPENSPACE_DATA}/web/scenelicense/scenelicense.hbs"; const char* JsFilename = "${OPENSPACE_DATA}/web/scenelicense/script.js"; } // namespace diff --git a/src/scene/sceneloader.cpp b/src/scene/sceneloader.cpp index fb93bf8a78..af4cb04efb 100644 --- a/src/scene/sceneloader.cpp +++ b/src/scene/sceneloader.cpp @@ -81,11 +81,17 @@ std::unique_ptr SceneLoader::loadScene(const std::string& path) { } ghoul::lua::loadDictionaryFromFile(absScenePath, sceneDictionary, state); - documentation::testSpecificationAndThrow(Scene::Documentation(), sceneDictionary, "Scene"); + documentation::testSpecificationAndThrow( + Scene::Documentation(), + sceneDictionary, + "Scene" + ); std::string relativeSceneDirectory = "."; sceneDictionary.getValue(KeyPathScene, relativeSceneDirectory); - std::string modulesPath = FileSys.absPath(sceneDirectory + FileSys.PathSeparator + relativeSceneDirectory); + std::string modulesPath = FileSys.absPath( + sceneDirectory + FileSys.PathSeparator + relativeSceneDirectory + ); ghoul::Dictionary moduleDictionary; sceneDictionary.getValue(KeyModules, moduleDictionary); @@ -181,7 +187,9 @@ SceneLoader::importDirectory(Scene& scene, const std::string& path) { return { addLoadedNodes(scene, std::move(nodes.first)), nodes.second }; } -SceneGraphNode* SceneLoader::importNodeDictionary(Scene& scene, const ghoul::Dictionary& dict) { +SceneGraphNode* SceneLoader::importNodeDictionary(Scene& scene, + const ghoul::Dictionary& dict) +{ std::vector loadedNodes; loadedNodes.push_back(loadNode(dict)); std::vector nodes = addLoadedNodes(scene, std::move(loadedNodes)); @@ -229,11 +237,13 @@ SceneLoader::loadDirectory( return {}; } std::string moduleName = path.substr(pos + 1); - std::string moduleFile = FileSys.pathByAppendingComponent(path, moduleName) + ModuleExtension; + std::string moduleFile = FileSys.pathByAppendingComponent(path, moduleName) + + ModuleExtension; if (FileSys.fileExists(moduleFile)) { // TODO: Get rid of changing the working directory (global state is bad) -- emiax - // This requires refactoring all renderables to not use relative paths in constructors. + // This requires refactoring all renderables to not use relative paths in + // constructors. // For now, no need to reset the directory here as it is done from the outside // function calling this method FileSys.setCurrentDirectory(ghoul::filesystem::Directory(path)); @@ -242,7 +252,8 @@ SceneLoader::loadDirectory( std::vector nodes = loadModule(moduleFile, luaState); std::vector licenses; - std::string licenseFile = FileSys.pathByAppendingComponent(path, moduleName) + LicenseExtension; + std::string licenseFile = FileSys.pathByAppendingComponent(path, moduleName) + + LicenseExtension; if (FileSys.fileExists(licenseFile)) { licenses = loadLicense(licenseFile, moduleName); } @@ -288,7 +299,9 @@ SceneLoader::LoadedNode SceneLoader::loadNode(const ghoul::Dictionary& dictionar std::string nodeName = dictionary.value(KeyName); std::string parentName = dictionary.value(KeyParentName); - std::unique_ptr node = SceneGraphNode::createFromDictionary(dictionary); + std::unique_ptr node = SceneGraphNode::createFromDictionary( + dictionary + ); if (dictionary.hasKey(SceneGraphNode::KeyDependencies)) { if (!dictionary.hasValue(SceneGraphNode::KeyDependencies)) { @@ -307,7 +320,9 @@ SceneLoader::LoadedNode SceneLoader::loadNode(const ghoul::Dictionary& dictionar } -std::vector SceneLoader::loadModule(const std::string& path, lua_State* luaState) { +std::vector SceneLoader::loadModule(const std::string& path, + lua_State* luaState) +{ ghoul::Dictionary moduleDictionary; try { ghoul::lua::loadDictionaryFromFile(path, moduleDictionary, luaState); @@ -344,13 +359,18 @@ std::vector SceneLoader::loadModule(const std::string& } } catch (ghoul::RuntimeError& e) { - LERROR("Failed loading node from " << path << ": " << e.message << ", " << e.component); + LERROR( + "Failed loading node from " << path << ": " << + e.message << ", " << e.component + ); } } return loadedNodes; } -std::vector SceneLoader::loadLicense(const std::string& path, std::string module) { +std::vector SceneLoader::loadLicense(const std::string& path, + std::string module) +{ ghoul::Dictionary licenseDictionary; try { ghoul::lua::loadDictionaryFromFile(path, licenseDictionary); @@ -363,7 +383,9 @@ std::vector SceneLoader::loadLicense(const std::string& path, std: return { license }; } -std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vector&& loadedNodes) { +std::vector SceneLoader::addLoadedNodes(Scene& scene, + std::vector&& loadedNodes) +{ std::map existingNodes = scene.nodesByName(); std::map addedNodes; @@ -406,7 +428,10 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect SceneGraphNode* parent = findNode(parentName); if (!parent) { - LERROR("Could not find parent '" + parentName + "' for '" + loadedNode.name + "'"); + LERROR( + "Could not find parent '" + parentName + "' for '" + + loadedNode.name + "'" + ); badNodes.push_back(std::move(loadedNode.node)); continue; } @@ -416,7 +441,10 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect for (const auto& depName : dependencyNames) { SceneGraphNode* dep = findNode(depName); if (!dep) { - LERROR("Could not find dependency '" + depName + "' for '" + loadedNode.name + "'"); + LERROR( + "Could not find dependency '" + depName + "' for '" + + loadedNode.name + "'" + ); foundAllDeps = false; continue; } @@ -437,7 +465,8 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect } } - // Remove all bad nodes (parent or deps missing) and all their children and dependent nodes. + // Remove all bad nodes (parent or deps missing) and all their children and dependent + // nodes. // Use unsorted set `visited` to avoid infinite loop in case of circular deps. std::unordered_set visited; for (size_t i = 0; i < badNodes.size(); i++) { @@ -451,7 +480,9 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect if (visited.count(d) == 0) { visited.insert(d); if (parent) { - badNodes.push_back(parent->detachChild(*d, SceneGraphNode::UpdateScene::No)); + badNodes.push_back( + parent->detachChild(*d, SceneGraphNode::UpdateScene::No) + ); } } } @@ -459,7 +490,10 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect // Warn for nodes that lack connection to the root. for (auto& node : addedNodes) { if (!node.second->scene()) { - LWARNING("Node '" << node.first << "' is not connected to the root and will not be added to the scene"); + LWARNING( + "Node '" << node.first << "' is not connected to the root and will " << + "not be added to the scene" + ); } } @@ -473,10 +507,16 @@ std::vector SceneLoader::addLoadedNodes(Scene& scene, std::vect // Return a vector of all added nodes. std::vector addedNodesVector; - std::transform(addedNodes.begin(), addedNodes.end(), std::back_inserter(addedNodesVector), [] (auto& pair) { - return pair.second; - }); + std::transform( + addedNodes.begin(), + addedNodes.end(), + std::back_inserter(addedNodesVector), + [](auto& pair) { + return pair.second; + } + ); return addedNodesVector; } -} + +} // namespace openspace diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index 7ff6c829a4..c8a93bbc5f 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -44,10 +44,6 @@ namespace { const char* _loggerCat = "ScriptEngine"; const int TableOffset = -3; // -1 (top) -1 (first argument) -1 (second argument) - - const char* MainTemplateFilename = "${OPENSPACE_DATA}/web/luascripting/main.hbs"; - const char* ScriptingTemplateFilename = "${OPENSPACE_DATA}/web/luascripting/scripting.hbs"; - const char* JsFilename = "${OPENSPACE_DATA}/web/luascripting/script.js"; } // namespace namespace openspace::scripting { @@ -59,10 +55,16 @@ ScriptEngine::ScriptEngine() "Script Documentation", "scripting", { - { "mainTemplate", MainTemplateFilename }, - { "scriptingTemplate", ScriptingTemplateFilename } + { + "mainTemplate", + "${OPENSPACE_DATA}/web/luascripting/main.hbs" + }, + { + "scriptingTemplate", + "${OPENSPACE_DATA}/web/luascripting/scripting.hbs" + } }, - JsFilename + "${OPENSPACE_DATA}/web/luascripting/script.js" ) {} @@ -199,103 +201,6 @@ bool ScriptEngine::runScriptFile(const std::string& filename) { return true; } -/*bool ScriptEngine::shouldScriptBeSent(const std::string& library, const std::string& function) { - std::set::const_iterator libit; - for (libit = _registeredLibraries.cbegin(); - libit != _registeredLibraries.cend(); - ++libit){ - if (libit->name.compare(library) == 0){ - break; - } - } - - std::vector::const_iterator funcit; - //library was found - if (libit != _registeredLibraries.cend()){ - for (funcit = libit->functions.cbegin(); - funcit != libit->functions.cend(); - ++funcit){ - //function was found! - if (funcit->name.compare(function) == 0){ - //is the function of a type that should be shared via parallel connection? - return funcit->parallelShared; - } - } - } - - return false; -}*/ - -/*void ScriptEngine::cacheScript(const std::string &library, const std::string &function, const std::string &script){ - _cachedScriptsMutex.lock(); - _cachedScripts[library][function] = script; - _cachedScriptsMutex.unlock(); -} - -std::vector ScriptEngine::cachedScripts(){ - _cachedScriptsMutex.lock(); - - std::vector retVal; - std::map>::const_iterator outerIt; - std::map::const_iterator innerIt; - for(outerIt = _cachedScripts.cbegin(); - outerIt != _cachedScripts.cend(); - ++outerIt){ - for(innerIt = outerIt->second.cbegin(); - innerIt != outerIt->second.cend(); - ++innerIt){ - retVal.push_back(innerIt->second); - } - } - - _cachedScriptsMutex.unlock(); - - return retVal; -}*/ - -/* -bool ScriptEngine::parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script){ - - //"deconstruct the script to find library and function name - //assuming a script looks like: "openspace.library.function()" - //or openspace.funcion() - std::string sub; - library.clear(); - function.clear(); - //find first "." - std::size_t pos = script.find("."); - - if (pos != std::string::npos){ - //strip "openspace." - sub = script.substr(pos + 1, script.size()); - pos = sub.find("."); - //one more "." was found, if the "." comes before first "(" we have a library name - if (pos != std::string::npos && pos < sub.find("(")){ - //assing library name - library = sub.substr(0, pos); - //strip "library." - sub = sub.substr(pos + 1, sub.size()); - - pos = sub.find("("); - if (pos != std::string::npos && pos > 0){ - //strip the () and we're left with function name - function = sub.substr(0, pos); - } - } - else{ - //no more "." was found, we have the case of "openspace.funcion()" - pos = sub.find("("); - if (pos != std::string::npos && pos > 0){ - //strip the () and we're left with function name - function = sub.substr(0, pos); - } - } - } - - //if we found a function all is good - return !function.empty(); -} -*/ bool ScriptEngine::isLibraryNameAllowed(lua_State* state, const std::string& name) { bool result = false; lua_getglobal(state, OpenSpaceLibraryName.c_str()); @@ -345,7 +250,9 @@ bool ScriptEngine::isLibraryNameAllowed(lua_State* state, const std::string& nam return result; } -void ScriptEngine::addLibraryFunctions(lua_State* state, LuaLibrary& library, bool replace) { +void ScriptEngine::addLibraryFunctions(lua_State* state, LuaLibrary& library, + bool replace) +{ ghoul_assert(state, "State must not be nullptr"); for (LuaLibrary::Function p : library.functions) { if (!replace) { @@ -750,13 +657,18 @@ void ScriptEngine::postsync(bool) { } } -void ScriptEngine::queueScript(const std::string &script, ScriptEngine::RemoteScripting remoteScripting){ +void ScriptEngine::queueScript(const std::string &script, + ScriptEngine::RemoteScripting remoteScripting) +{ if (script.empty()) { return; } _mutex.lock(); - _queuedScripts.insert(_queuedScripts.begin(), std::make_pair(script, remoteScripting)); + _queuedScripts.insert( + _queuedScripts.begin(), + std::make_pair(script, remoteScripting) + ); _mutex.unlock(); } diff --git a/src/util/camera.cpp b/src/util/camera.cpp index e41a0b872b..f86cbacfe2 100644 --- a/src/util/camera.cpp +++ b/src/util/camera.cpp @@ -35,7 +35,7 @@ namespace openspace { ////////////////////////////////////////////////////////////////////////////////////// - // CAMERA // + // CAMERA // ////////////////////////////////////////////////////////////////////////////////////// namespace { @@ -176,7 +176,9 @@ namespace openspace { const Camera::Mat4& Camera::viewRotationMatrix() const { if (_cachedViewRotationMatrix.isDirty) { - _cachedViewRotationMatrix.datum = glm::mat4_cast(glm::inverse(static_cast(_rotation))); + _cachedViewRotationMatrix.datum = glm::mat4_cast( + glm::inverse(static_cast(_rotation)) + ); } return _cachedViewRotationMatrix.datum; } @@ -223,7 +225,7 @@ namespace openspace { } ////////////////////////////////////////////////////////////////////////////////////// - // SGCT INTERNAL // + // SGCT INTERNAL // ////////////////////////////////////////////////////////////////////////////////////// Camera::SgctInternal::SgctInternal() : _viewMatrix() diff --git a/src/util/histogram.cpp b/src/util/histogram.cpp index a0538e63f7..ca3410c070 100644 --- a/src/util/histogram.cpp +++ b/src/util/histogram.cpp @@ -114,8 +114,11 @@ bool Histogram::add(float value, float repeat) { return false; } - float normalizedValue = (value - _minValue) / (_maxValue - _minValue); // [0.0, 1.0] - int binIndex = std::min( static_cast(floor(normalizedValue * _numBins)), _numBins - 1.0f ); // [0, _numBins - 1] + float normalizedValue = (value - _minValue) / (_maxValue - _minValue); // [0.0, 1.0] + int binIndex = std::min( + static_cast(floor(normalizedValue * _numBins)), + _numBins - 1.f + ); // [0, _numBins - 1] _data[binIndex] += repeat; _numValues += repeat; @@ -133,8 +136,12 @@ void Histogram::changeRange(float minValue, float maxValue){\ float* newData = new float[_numBins]{0.0}; for(int i=0; i<_numBins; i++){ float unNormalizedValue = i*(oldMax-oldMin)+oldMin; - float normalizedValue = (unNormalizedValue - _minValue) / (_maxValue - _minValue); // [0.0, 1.0] - int binIndex = std::min( static_cast(floor(normalizedValue * _numBins)), _numBins - 1.0f ); // [0, _numBins - 1] + float normalizedValue = (unNormalizedValue - _minValue) / + (_maxValue - _minValue); // [0.0, 1.0] + int binIndex = std::min( + static_cast(floor(normalizedValue * _numBins)), + _numBins - 1.f + ); // [0, _numBins - 1] newData[binIndex] = oldData[i]; } @@ -148,13 +155,13 @@ void Histogram::changeRange(float minValue, float maxValue){\ } bool Histogram::add(const Histogram& histogram) { - if (_minValue == histogram.minValue() && _maxValue == histogram.maxValue() && _numBins == histogram.numBins()) { - + if (_minValue == histogram.minValue() && + _maxValue == histogram.maxValue() && + _numBins == histogram.numBins()) + { const float* data = histogram.data(); for (int i = 0; i < _numBins; i++) { - _data[i] += data[i]; - } _numValues += histogram._numValues; return true; @@ -278,7 +285,11 @@ Histogram Histogram::equalize(){ */ float Histogram::equalize(float value){ // if (value < _minValue || value > _maxValue) { - // LWARNING("Equalized value is is not within domain of histogram. min: " + std::to_string(_minValue) + " max: " + std::to_string(_maxValue) + " val: " + std::to_string(value)); + // LWARNING( + // "Equalized value is is not within domain of histogram. min: " + + // std::to_string(_minValue) + " max: " + std::to_string(_maxValue) + + // " val: " + std::to_string(value) + // ); // } float normalizedValue = (value-_minValue)/(_maxValue-_minValue); int bin = floor(normalizedValue * _numBins); @@ -293,15 +304,14 @@ float Histogram::entropy(){ float entropy = 0.f; for (int i = 0; i < _numBins; ++i) { if (_data[i] != 0) { - entropy -= (static_cast(_data[i])/_numValues) * log2(static_cast(_data[i])/_numValues); + entropy -= (static_cast(_data[i])/_numValues) * + log2(static_cast(_data[i])/_numValues); } } return entropy; } void Histogram::print() const { - // std::cout << "number of bins: " << _numBins << std::endl - // << "range: " << _minValue << " - " << _maxValue << std::endl << std::endl; for (int i = 0; i < _numBins; i++) { float low = _minValue + float(i) / _numBins * (_maxValue - _minValue); float high = low + (_maxValue - _minValue) / float(_numBins); @@ -342,7 +352,8 @@ float Histogram::highestBinValue(bool equalized, int overBins){ if (!equalized) { - float low = _minValue + static_cast(highestBin) / _numBins * (_maxValue - _minValue); + float low = _minValue + static_cast(highestBin) / + _numBins * (_maxValue - _minValue); float high = low + (_maxValue - _minValue) / static_cast(_numBins); return (high+low)/2.0; } else { @@ -355,4 +366,4 @@ float Histogram::binWidth() { return (_maxValue-_minValue) / _numBins; } -} +} // namespace openspace diff --git a/src/util/progressbar.cpp b/src/util/progressbar.cpp index 14ec9f879c..6d9859cd36 100644 --- a/src/util/progressbar.cpp +++ b/src/util/progressbar.cpp @@ -50,7 +50,8 @@ void ProgressBar::print(int current) { int spWidth = _width - pos + 2; _stream << "[" << std::setfill('=') << std::setw(eqWidth) << ">" << std::setfill(' ') << std::setw(spWidth) - << "] " << std::setfill(' ') << std::setw(3) << iprogress << " % \r" << std::flush; + << "] " << std::setfill(' ') << std::setw(3) << iprogress << " % \r" + << std::flush; } _previous = iprogress; }; diff --git a/src/util/spicemanager.cpp b/src/util/spicemanager.cpp index ae27937026..cd4fb99845 100644 --- a/src/util/spicemanager.cpp +++ b/src/util/spicemanager.cpp @@ -509,10 +509,11 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target, if (!targetHasCoverage && !observerHasCoverage) { if (_useExceptions) { throw SpiceException( - format("Neither target '{}' nor observer '{}' has SPK coverage at time {}", - target, - observer, - ephemerisTime + format( + "Neither target '{}' nor observer '{}' has SPK coverage at time {}", + target, + observer, + ephemerisTime ) ); } @@ -1128,7 +1129,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram if (_useExceptions) { // no coverage throw SpiceException(format( - "No data available for the transform matrix from '{}' to '{}' at any time", + "No data available for transform matrix from '{}' to '{}' at any time", fromFrame, toFrame )); } diff --git a/src/util/spicemanager_lua.inl b/src/util/spicemanager_lua.inl index 1c22d98640..010e3ee6d4 100644 --- a/src/util/spicemanager_lua.inl +++ b/src/util/spicemanager_lua.inl @@ -17,7 +17,7 @@ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ diff --git a/src/util/taskloader.cpp b/src/util/taskloader.cpp index c6780c5e55..009156c856 100644 --- a/src/util/taskloader.cpp +++ b/src/util/taskloader.cpp @@ -39,7 +39,9 @@ namespace { namespace openspace { -std::vector> TaskLoader::tasksFromDictionary(const ghoul::Dictionary& tasksDictionary) { +std::vector> TaskLoader::tasksFromDictionary( + const ghoul::Dictionary& tasksDictionary) +{ std::vector> tasks; std::vector keys = tasksDictionary.keys(); for (const std::string& key : keys) { diff --git a/src/util/timemanager.cpp b/src/util/timemanager.cpp index 3ba6a5eac9..1f4b3565a6 100644 --- a/src/util/timemanager.cpp +++ b/src/util/timemanager.cpp @@ -50,11 +50,20 @@ void TimeManager::consumeKeyframes(double dt) { double now = OsEng.windowWrapper().applicationTime(); const std::deque>& keyframes = _timeline.keyframes(); - auto firstFutureKeyframe = std::lower_bound(keyframes.begin(), keyframes.end(), now, &compareKeyframeTimeWithTime); + auto firstFutureKeyframe = std::lower_bound( + keyframes.begin(), + keyframes.end(), + now, + &compareKeyframeTimeWithTime + ); - bool consumingTimeJump = std::find_if(keyframes.begin(), firstFutureKeyframe, [] (const Keyframe