Merge remote-tracking branch 'origin/master' into feature/profile-gui

# Conflicts:
#	data/profiles/apollo8.profile
#	data/profiles/apollo_sites.profile
#	data/profiles/asteroids.profile
#	data/profiles/dawn.profile
#	data/profiles/default.profile
#	data/profiles/default_full.profile
#	data/profiles/gaia.profile
#	data/profiles/insight.profile
#	data/profiles/juno.profile
#	data/profiles/mars.profile
#	data/profiles/messenger.profile
#	data/profiles/newhorizons.profile
#	data/profiles/osirisrex.profile
#	data/profiles/rosetta.profile
#	data/profiles/touch.profile
#	data/profiles/voyager.profile
This commit is contained in:
Alexander Bock
2020-10-13 16:32:58 +02:00
29 changed files with 1041 additions and 1049 deletions

View File

@@ -28,15 +28,16 @@ asset.onInitialize(function ()
end
helper.setCurrentSlide(deck, 1)
openspace.bindKey("RIGHT", "nextSlide()", "Next slide", "Next slide", "/Slides")
openspace.bindKey("LEFT", "previousSlide()", "Previous slide", "Previous slide", "/Slides")
openspace.bindKey("UP", "toggleSlides()", "Toggle slides", "Toggle slides", "/Slides")
openspace.bindKey("KP_6", "nextSlide()", "Next slide", "Next slide", "/Slides")
openspace.bindKey("KP_4", "previousSlide()", "Previous slide", "Previous slide", "/Slides")
openspace.bindKey("KP_0", "toggleSlides()", "Toggle slides", "Toggle slides", "/Slides")
end)
asset.onDeinitialize(function()
openspace.clearKey("RIGHT")
openspace.clearKey("LEFT")
openspace.clearKey("KP_6")
openspace.clearKey("KP_4")
openspace.clearKey("KP_0")
helper.removeDeck(deck)
end)

View File

@@ -17,6 +17,11 @@ local CharonTrailBarycentric = {
Period = 6.38723,
Resolution = 1000
},
Tag = {
"moonTrail_solarSystem",
"moonTrail_dwarf",
"moonTrail_pluto",
"moonTrail_minor" },
GUI = {
Name = "Charon Barycentric Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -21,6 +21,7 @@ local Hydra = {
SegmentsPerPatch = 64,
Layers = {}
},
Tag = { "moon_solarSystem", "moon_dwarf", "moon_pluto" },
GUI = {
Path = "/Solar System/Dwarf Planets/Pluto"
}
@@ -40,6 +41,11 @@ local HydraTrail = {
Period = 38.20177,
Resolution = 1000
},
Tag = {
"moonTrail_solarSystem",
"moonTrail_dwarf",
"moonTrail_pluto",
"moonTrail_minor" },
GUI = {
Name = "Hydra Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -21,6 +21,7 @@ local Kerberos = {
SegmentsPerPatch = 64,
Layers = {}
},
Tag = { "moon_solarSystem", "moon_dwarf", "moon_pluto" },
GUI = {
Path = "/Solar System/Dwarf Planets/Pluto"
}
@@ -40,6 +41,11 @@ local KerberosTrail = {
Period = 32.16756,
Resolution = 1000
},
Tag = {
"moonTrail_solarSystem",
"moonTrail_dwarf",
"moonTrail_pluto",
"moonTrail_minor" },
GUI = {
Name = "Hydra Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -21,6 +21,7 @@ local Nix = {
SegmentsPerPatch = 64,
Layers = {}
},
Tag = { "moon_solarSystem", "moon_dwarf", "moon_pluto" },
GUI = {
Path = "/Solar System/Dwarf Planets/Pluto"
}
@@ -40,6 +41,11 @@ local NixTrail = {
Period = 24.85463,
Resolution = 1000
},
Tag = {
"moonTrail_solarSystem",
"moonTrail_dwarf",
"moonTrail_pluto",
"moonTrail_minor" },
GUI = {
Name = "Nix Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -21,6 +21,7 @@ local Styx = {
SegmentsPerPatch = 64,
Layers = {}
},
Tag = { "moon_solarSystem", "moon_dwarf", "moon_pluto" },
GUI = {
Path = "/Solar System/Dwarf Planets/Pluto"
}
@@ -40,6 +41,11 @@ local StyxTrail = {
Period = 20.16155,
Resolution = 1000
},
Tag = {
"moonTrail_solarSystem",
"moonTrail_dwarf",
"moonTrail_pluto",
"moonTrail_minor" },
GUI = {
Name = "Styx Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -17,6 +17,7 @@ local PlutoTrailBarycentric = {
Period = 6.38723,
Resolution = 1000
},
Tag = { "planetTrail_solarSystem", "planetTrail_dwarf" },
GUI = {
Name = "Pluto Barycentric Trail",
Path = "/Solar System/Dwarf Planets/Pluto"

View File

@@ -279,7 +279,6 @@ local initializeAndAddNodes = function()
}
}
table.insert(nodes, issTrail)
return { iss, parentNode, issTrail }
end
@@ -289,8 +288,16 @@ asset.onInitialize(function ()
openspace.addSceneGraphNode(node)
end
openspace.setPropertyValueSingle("Scene.ISSparentNode.Rotation.yAxis-InvertObject", true)
end)
asset.onDeinitialize(function ()
for i=1, #nodes do
openspace.removeSceneGraphNode(nodes[#nodes + 1 - i].Identifier)
end
end)
asset.meta = {
Name = "ISS",

View File

@@ -144,30 +144,12 @@ openspace.setPropertyValueSingle("RenderEngine.ShowCamera", not isEnabled)]],
}
}
local DeltaTimeKeys
asset.onInitialize(function()
sceneHelper.bindKeys(Keybindings)
DeltaTimeKeys = sceneHelper.setDeltaTimeKeys({
-- 1 2 3 4 5 6 7 8 9 0
--------------------------------------------------------------------------------------------------------------------------
-- 1s 2s 5s 10s 30s 1m 2m 5m 10m 30m
1, 2, 5, 10, 30, 60, 120, 300, 600, 1800,
-- 1h 2h 3h 6h 12h 1d 2d 4d 1w 2w
3600, 7200, 10800, 21600, 43200, 86400, 172800, 345600, 604800, 1209600,
-- 1mo 2mo 3mo 6mo 1yr 2y 5y 10y 20y 50y
2592000, 5184000, 7776000, 15552000, 31536000, 63072000, 157680000, 315360000, 630720000, 1576800000
})
-- OBS: One month (1mo) is approximated by 30 days.
end)
asset.onDeinitialize(function ()
sceneHelper.unbindKeys(Keybindings)
sceneHelper.unbindKeys(DeltaTimeKeys)
end)
asset.export("DefaultKeybindings", Keybindings)
asset.export("DefaultDeltaTimeKeys", DeltaTimeKeys)

View File

@@ -31,42 +31,6 @@ local unbindKeys = function(keys)
end
asset.export("unbindKeys", unbindKeys)
local deltaTimeKeys = {}
local setDeltaTimeKeys = function(t)
local Keys = {
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'Shift+1', 'Shift+2', 'Shift+3', 'Shift+4', 'Shift+5', 'Shift+6', 'Shift+7', 'Shift+8', 'Shift+9', 'Shift+0',
'Ctrl+1', 'Ctrl+2', 'Ctrl+3', 'Ctrl+4', 'Ctrl+5', 'Ctrl+6', 'Ctrl+7', 'Ctrl+8', 'Ctrl+9', 'Ctrl+0',
'Alt+1', 'Alt+2', 'Alt+3', 'Alt+4', 'Alt+5', 'Alt+6', 'Alt+7', 'Alt+8', 'Alt+9', 'Alt+0'
}
if #t > #Keys then
openspace.printError("Error settings delta time keys: Too many delta times (" .. #t .. ")")
return
end
unbindKeys(deltaTimeKeys)
result = {}
for i, v in ipairs(t) do
openspace.bindKeyLocal(
Keys[i],
'openspace.time.interpolateDeltaTime(' .. v .. ")",
'Setting the simulation speed to ' .. v .. ' seconds per realtime second',
'Set sim speed ' .. v,
'/Simulation Speed'
)
table.insert(result, Keys[i])
end
deltaTimeKeys = result
return result
end
asset.export("setDeltaTimeKeys", setDeltaTimeKeys)
--shortcut function
local function has_value (tab, val)
for index, value in ipairs(tab) do

View File

@@ -3,7 +3,7 @@ asset.require('./static_server')
local guiCustomization = asset.require('customization/gui')
-- Select which commit hashes to use for the frontend and backend
local frontendHash = "d85b4022813caafb0fdde18bea2c2f51768816fa"
local frontendHash = "6b5ac33a77fff6f46088c1fffdaf04d59ec5bb5f"
local dataProvider = "data.openspaceproject.com/files/webgui"
local frontend = asset.syncedResource({

View File

@@ -1,9 +1,9 @@
local dataFolder = "${BASE}/modules/exoplanets"
local dataFolder = "D:/dev/exoplanets data config"
return {
{
Type = "ExoplanetsCsvToBinTask",
InputCSV = dataFolder .. "/exoplanets.csv",
Type = "ExoplanetsDataPreparationTask",
InputDataFile = dataFolder .. "/exoplanets_data_composite.csv",
InputSPECK = "${SYNC}/http/digitaluniverse_exoplanets_speck/1/expl.speck",
TeffToBvFile = "${SYNC}/http/exoplanets_data/1/teff_bv.txt",
OutputBIN = dataFolder .. "/exoplanets_data.bin",

View File

@@ -62,10 +62,14 @@ public:
std::string documentation = "", std::string name = "", std::string guiPath = "");
void removeKeyBinding(const std::string& key);
void removeKeyBinding(const KeyWithModifier& key);
std::vector<std::pair<KeyWithModifier, KeyInformation>> keyBinding(
const std::string& key) const;
std::vector<std::pair<KeyWithModifier, KeyInformation>> keyBinding(
const KeyWithModifier& key) const;
static scripting::LuaLibrary luaLibrary();
void keyboardCallback(Key key, KeyModifier modifier, KeyAction action);

View File

@@ -0,0 +1,44 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_CORE___COORDINATECONVERSION___H__
#define __OPENSPACE_CORE___COORDINATECONVERSION___H__
#include <ghoul/glm.h>
namespace openspace {
/**
* Converts from ICRS coordinates to galactic cartesian coordinates.
* \param ra Right ascension, given in decimal degrees
* \param dec Declination, given in decimal degrees
* \param distance The distance, or radius, to the position given in any unit.
* \return A position in galactic cartesian coordinates, given in the same unit as the
* distance parameter.
*/
glm::dvec3 icrsToGalacticCartesian(float ra, float dec, double distance);
} // namespace openspace
#endif // __OPENSPACE_CORE___COORDINATECONVERSION___H__

View File

@@ -25,6 +25,9 @@
#ifndef __OPENSPACE_CORE___TIMEMANAGER___H__
#define __OPENSPACE_CORE___TIMEMANAGER___H__
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <openspace/util/keys.h>
#include <openspace/util/syncdata.h>
#include <openspace/util/time.h>
#include <openspace/util/timeline.h>
@@ -33,14 +36,6 @@
#include <utility>
#include <vector>
#include <deque>
#include <functional>
#include <openspace/util/timeline.h>
#include <openspace/util/time.h>
#include <openspace/util/syncdata.h>
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/scalar/floatproperty.h>
namespace openspace {
struct TimeKeyframeData {
@@ -130,6 +125,9 @@ private:
TimeKeyframeData interpolate(const Keyframe<TimeKeyframeData>& past,
const Keyframe<TimeKeyframeData>& future, double time);
void addDeltaTimesKeybindings();
void clearDeltaTimesKeybindings();
Timeline<TimeKeyframeData> _timeline;
SyncData<Time> _currentTime;
SyncData<Time> _integrateFromTime;
@@ -142,8 +140,9 @@ private:
double _lastDeltaTime = 0.0;
double _lastTargetDeltaTime = 0.0;
std::vector<double> _deltaTimeSteps;
bool _deltaTimeStepsChanged = false;
std::vector<double> _deltaTimeSteps;
std::vector<KeyWithModifier> _deltaTimeStepKeybindings;
properties::FloatProperty _defaultTimeInterpolationDuration;
properties::FloatProperty _defaultDeltaTimeInterpolationDuration;

View File

@@ -28,7 +28,7 @@ set(HEADER_FILES
${CMAKE_CURRENT_SOURCE_DIR}/exoplanetshelper.h
${CMAKE_CURRENT_SOURCE_DIR}/exoplanetsmodule.h
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableorbitdisc.h
${CMAKE_CURRENT_SOURCE_DIR}/tasks/exoplanetscsvtobintask.h
${CMAKE_CURRENT_SOURCE_DIR}/tasks/exoplanetsdatapreparationtask.h
)
source_group("Header Files" FILES ${HEADER_FILES})
@@ -37,7 +37,7 @@ set(SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/exoplanetsmodule.cpp
${CMAKE_CURRENT_SOURCE_DIR}/exoplanetsmodule_lua.inl
${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableorbitdisc.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tasks/exoplanetscsvtobintask.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tasks/exoplanetsdatapreparationtask.cpp
)
source_group("Source Files" FILES ${SOURCE_FILES})

View File

@@ -24,103 +24,150 @@
#include <modules/exoplanets/exoplanetshelper.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/fmt.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/transform.hpp>
#include <string_view>
#include <fstream>
#include <sstream>
namespace {
constexpr const char* _loggerCat = "ExoplanetsModule";
constexpr const char* BvColormapPath = "${SYNC}/http/stars_colormap/2/colorbv.cmap";
}
namespace openspace::exoplanets {
std::string_view speckStarName(std::string_view csvName) {
if (csvName == "HD 1237") { return "GJ 3021"; }
if (csvName == "MOA-2009-BLG-387L") { return "MOA 2009-BLG-387L"; }
if (csvName == "HD 126614 A") { return "HD 126614"; }
if (csvName == "epsilon Ret") { return "HD 27442"; }
if (csvName == "PH-1") { return "PH1"; }
if (csvName == "gamma Leo A") { return "gam 1 Leo"; }
if (csvName == "OGLE-2007-BLG-368L") { return "OGLE 2007-BLG-368L"; }
if (csvName == "alpha Ari") { return "alf Ari"; }
if (csvName == "mu Ara") { return "HD 160691"; }
if (csvName == "OGLE-05-169L") { return "OGLE 2005-BLG-169L"; }
if (csvName == "tau Gru") { return "HD 216435"; }
if (csvName == "iota Hor") { return "HR 810"; }
if (csvName == "OGLE-05-071L") { return "OGLE 2005-BLG-71L"; }
if (csvName == "OGLE235-MOA53") { return "OGLE 2003-BLG-235L"; }
if (csvName == "OGLE-2005-BLG-169L") { return "OGLE 2005-BLG-169L"; }
if (csvName == "OGLE-2005-BLG-071L") { return "OGLE 2005-BLG-71L"; }
if (csvName == "OGLE-2003-BLG-235L") { return "OGLE 2003-BLG-235L"; }
if (csvName == "MOA-2008-BLG-310L") { return "MOA 2008-BLG-310L"; }
if (csvName == "KIC 11442793") { return "KOI-351"; }
if (csvName == "OGLE-2006-BLG-109L") { return "OGLE 2006-BLG-109L"; }
if (csvName == "HD 137388") { return "HD 137388 A"; }
if (csvName == "kappa CrB") { return "kap CrB"; }
if (csvName == "XO-2") { return "XO-2 N"; }
if (csvName == "epsilon Tau") { return "eps Tau"; }
if (csvName == "epsilon Eri") { return "eps Eri"; }
if (csvName == "Kepler-448") { return "KOI-12"; }
if (csvName == "omega Ser") { return "ome Ser"; }
if (csvName == "MOA-2010-BLG-477L") { return "MOA 2010-BLG-477L"; }
if (csvName == "GJ 176") { return "HD 285968"; }
if (csvName == "HIP 2247") { return "BD-17 63"; }
if (csvName == "MOA-2009-BLG-266L") { return "MOA 2009-BLG-266L"; }
if (csvName == "Kepler-89") { return "KOI-94"; }
if (csvName == "iota Dra") { return "HIP 75458"; }
if (csvName == "iot Dra") { return "HIP 75458"; }
if (csvName == "MOA-2007-BLG-400L") { return "MOA 2007-BLG-400L"; }
if (csvName == "upsilon And") { return "ups And"; }
if (csvName == "OGLE-2011-BLG-0251") { return "OGLE 2011-BLG-251L"; }
if (csvName == "OGLE-05-390L") { return "OGLE 2005-BLG-390L"; }
if (csvName == "Kepler-420") { return "KOI-1257"; }
if (csvName == "beta Pic") { return "bet Pic"; }
if (csvName == "gamma Cep") { return "gam Cep"; }
if (csvName == "OGLE-2011-BLG-0251L") { return "OGLE 2011-BLG-251L"; }
if (csvName == "OGLE-2005-BLG-390L") { return "OGLE 2005-BLG-390L"; }
if (csvName == "MOA-2007-BLG-192L") { return "MOA 2007-BLG-192L"; }
if (csvName == "MOA-2009-BLG-319L") { return "MOA 2009-BLG-319L"; }
if (csvName == "omicron CrB") { return "omi CrB"; }
if (csvName == "beta Gem") { return "HD 62509"; }
if (csvName == "epsilon CrB") { return "eps CrB"; }
if (csvName == "omicron UMa") { return "omi UMa"; }
if (csvName == "HD 142022") { return "HD 142022 A"; }
return csvName;
}
std::string_view csvStarName(std::string_view name) {
if (name == "GJ 3021") { return "HD 1237"; }
if (name == "MOA 2009-BLG-387L") { return "MOA-2009-BLG-387L"; }
if (name == "HD 126614") { return "HD 126614 A"; }
if (name == "HD 27442") { return "epsilon Ret"; }
if (name == "PH1") { return "PH-1"; }
if (name == "gam 1 Leo") { return "gamma Leo A"; }
if (name == "OGLE 2007-BLG-368L") { return "OGLE-2007-BLG-368L"; }
if (name == "alf Ari") { return "alpha Ari"; }
if (name == "HD 160691") { return "mu Ara"; }
if (name == "OGLE 2005-BLG-169L") { return "OGLE-05-169L"; }
if (name == "HD 216435") { return "tau Gru"; }
if (name == "HR 810") { return "iota Hor"; }
if (name == "OGLE 2005-BLG-71L") { return "OGLE-05-071L"; }
if (name == "OGLE 2003-BLG-235L") { return "OGLE235-MOA53"; }
if (name == "OGLE 2005-BLG-169L") { return "OGLE-2005-BLG-169L"; }
if (name == "OGLE 2005-BLG-71L") { return "OGLE-2005-BLG-071L"; }
if (name == "OGLE 2003-BLG-235L") { return "OGLE-2003-BLG-235L"; }
if (name == "MOA 2008-BLG-310L") { return "MOA-2008-BLG-310L"; }
if (name == "KOI-351") { return "KIC 11442793"; }
if (name == "OGLE 2006-BLG-109L") { return "OGLE-2006-BLG-109L"; }
if (name == "HD 137388 A") { return "HD 137388"; }
if (name == "kap CrB") { return "kappa CrB"; }
if (name == "XO-2 N") { return "XO-2"; }
if (name == "eps Tau") { return "epsilon Tau"; }
if (name == "eps Eri") { return "epsilon Eri"; }
if (name == "KOI-12") { return "Kepler-448"; }
if (name == "ome Ser") { return "omega Ser"; }
if (name == "MOA 2010-BLG-477L") { return "MOA-2010-BLG-477L"; }
if (name == "HD 285968") { return "GJ 176"; }
if (name == "BD-17 63") { return "HIP 2247"; }
if (name == "MOA 2009-BLG-266L") { return "MOA-2009-BLG-266L"; }
if (name == "KOI-94") { return "Kepler-89"; }
if (name == "HIP 75458") { return "iota Dra"; }
if (name == "HIP 75458") { return "iot Dra"; }
if (name == "MOA 2007-BLG-400L") { return "MOA-2007-BLG-400L"; }
if (name == "ups And") { return "upsilon And"; }
if (name == "OGLE 2011-BLG-251L") { return "OGLE-2011-BLG-0251"; }
if (name == "OGLE 2005-BLG-390L") { return "OGLE-05-390L"; }
if (name == "KOI-1257") { return "Kepler-420"; }
if (name == "bet Pic") { return "beta Pic"; }
if (name == "gam Cep") { return "gamma Cep"; }
if (name == "OGLE 2011-BLG-251L") { return "OGLE-2011-BLG-0251L"; }
if (name == "OGLE 2005-BLG-390L") { return "OGLE-2005-BLG-390L"; }
if (name == "MOA 2007-BLG-192L") { return "MOA-2007-BLG-192L"; }
if (name == "MOA 2009-BLG-319L") { return "MOA-2009-BLG-319L"; }
if (name == "omi CrB") { return "omicron CrB"; }
if (name == "HD 62509") { return "beta Gem"; }
if (name == "eps CrB") { return "epsilon CrB"; }
if (name == "omi UMa") { return "omicron UMa"; }
if (name == "HD 142022 A") { return "HD 142022"; }
return name;
}
std::string starColor(float bv) {
std::ifstream colorMap(absPath(BvColormapPath), std::ios::in);
if (!colorMap.good()) {
LERROR(fmt::format(
"Failed to open colormap data file: '{}'",
absPath(BvColormapPath)
));
return "";
}
const int t = static_cast<int>(round(((bv + 0.4) / (2.0 + 0.4)) * 255));
std::string color;
for (int i = 0; i < t + 12; i++) {
getline(colorMap, color);
}
colorMap.close();
std::istringstream colorStream(color);
std::string r, g, b;
getline(colorStream, r, ' ');
getline(colorStream, g, ' ');
getline(colorStream, b, ' ');
return fmt::format("{{ {}, {}, {} }}", r, g, b);
}
glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom, float omega) {
// Exoplanet defined inclination changed to be used as Kepler defined inclination
const glm::dvec3 ascendingNodeAxisRot = glm::dvec3(0.0, 0.0, 1.0);
const glm::dvec3 inclinationAxisRot = glm::dvec3(1.0, 0.0, 0.0);
const glm::dvec3 argPeriapsisAxisRot = glm::dvec3(0.0, 0.0, 1.0);
const double asc = glm::radians(bigom);
const double inc = glm::radians(i);
const double per = glm::radians(omega);
const glm::dmat4 orbitPlaneRotation =
glm::rotate(asc, glm::dvec3(ascendingNodeAxisRot)) *
glm::rotate(inc, glm::dvec3(inclinationAxisRot)) *
glm::rotate(per, glm::dvec3(argPeriapsisAxisRot));
return orbitPlaneRotation;
}
// Rotate the original coordinate system (where x is pointing to First Point of Aries)
// so that x is pointing from star to the sun.
// Modified from "http://www.opengl-tutorial.org/intermediate-tutorials/
// tutorial-17-quaternions/ #how-do-i-find-the-rotation-between-2-vectors"
glm::dmat3 exoplanetSystemRotation(glm::dvec3 start, glm::dvec3 end) {
glm::quat rotationQuat;
glm::dvec3 rotationAxis;
const float cosTheta = static_cast<float>(glm::dot(start, end));
constexpr float Epsilon = 1E-3f;
if (cosTheta < -1.f + Epsilon) {
// special case when vectors in opposite directions:
// there is no "ideal" rotation axis
// So guess one; any will do as long as it's perpendicular to start vector
rotationAxis = glm::cross(glm::dvec3(0.0, 0.0, 1.0), start);
if (glm::length2(rotationAxis) < 0.01f) {
// bad luck, they were parallel, try again!
rotationAxis = glm::cross(glm::dvec3(1.0, 0.0, 0.0), start);
}
rotationAxis = glm::normalize(rotationAxis);
rotationQuat = glm::quat(glm::radians(180.f), rotationAxis);
return glm::dmat3(glm::toMat4(rotationQuat));
}
rotationAxis = glm::cross(start, end);
const float s = sqrt((1.f + cosTheta) * 2.f);
const float invs = 1.f / s;
rotationQuat = glm::quat(
s * 0.5f,
static_cast<float>(rotationAxis.x * invs),
static_cast<float>(rotationAxis.y * invs),
static_cast<float>(rotationAxis.z * invs)
);
return glm::dmat3(glm::toMat4(rotationQuat));
}
std::string createIdentifier(std::string name) {
std::replace(name.begin(), name.end(), ' ', '_');
return name;
}

View File

@@ -25,6 +25,7 @@
#ifndef __OPENSPACE_MODULE_EXOPLANETS___EXOPLANET_HELPER___H__
#define __OPENSPACE_MODULE_EXOPLANETS___EXOPLANET_HELPER___H__
#include <ghoul/glm.h>
#include <string>
namespace openspace::exoplanets {
@@ -33,42 +34,33 @@ struct Exoplanet {
float a; // Orbital semi-major axis in AU
double aUpper; // Upper uncertainty of orbital semi-major axis
double aLower; // Lower uncertainty of orbital semi-major axis
double ua; // Uncertainty of orbital semi-major axis
float bigOm; // Longitude of ascending node in degrees
float bigOmUpper; // Upper uncertainty of longitude of ascending node
float bigOmLower; // Lower uncertainty of longitude of ascending node
float uBigOm; // Uncertainty of longitude of ascending node
float bigOmega; // Longitude of ascending node in degrees
float bigOmegaUpper; // Upper uncertainty of longitude of ascending node
float bigOmegaLower; // Lower uncertainty of longitude of ascending node
bool binary; // Star known to be binary?
float bmv; // B V color
float ecc; // Orbital eccentricity
float eccUpper; // Upper uncertainty of orbital eccentricity
float eccLower; // Lower uncertainty of orbital eccentricity
float uEcc; // Uncertainty of orbital eccentricity
float i; // Orbital inclination in degrees (for transiting systems only)
float iUpper; // Upper uncertainty of orbital inclination
float iLower; // Lower uncertainty of orbital inclination
float ui; // Uncertainty of orbital inclination
int nComp; // Number of planetary companions known
float om; // Argument of periastron in degrees
float omUpper; // Upper uncertainty of argument of periastron
float omLower; // Lower uncertainty of argument of periastron
float uOm; // Uncertainty of argument of periastron
float omega; // Argument of periastron in degrees
float omegaUpper; // Upper uncertainty of argument of periastron
float omegaLower; // Lower uncertainty of argument of periastron
double per; // Orbital period in days
float perUpper; // Upper uncertainty of period
float perLower; // Lower uncertainty of period
float uPer; // Uncertainty of period
double r; // Radius of the planet in Jupiter radii
double rUpper; // Upper uncertainty of radius of the planet
double rLower; // Lower uncertainty of radius of the planet
double ur; // Uncertainty of radius of the planet
float rStar; // Estimated radius of the star in solar radii
float rStarUpper; // Upper uncertainty of estimated star radius
float rStarLower; // Lower uncertainty of estimated star radius
float urStar; // Uncertainty of estimated star radius
double tt; // Epoch of transit center in HJD-2440000
float ttUpper; // Upper uncertainty of epoch of transit center
float ttLower; // Lower uncertainty of epoch of transit center
float uTt; // Uncertainty of epoch of transit center
float positionX; // Star position's X-coordinate in parsec
float positionY; // Star position's Y-coordinate in parsec
float positionZ; // Star position's Z-coordinate in parsec
@@ -80,6 +72,18 @@ std::string_view speckStarName(std::string_view name);
// Convert speck-file specific names to the corresponding name in the csv data file
std::string_view csvStarName(std::string_view name);
// Compute star color in RGB from b-v color index
std::string starColor(float bv);
glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom, float omega);
// Rotate the original coordinate system (where x is pointing to First Point of Aries)
// so that x is pointing from star to the sun.
glm::dmat3 exoplanetSystemRotation(glm::dvec3 start, glm::dvec3 end);
// Create an identifier without whitespaces
std::string createIdentifier(std::string name);
} // namespace openspace::exoplanets
#endif // __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSMODULE___H__

View File

@@ -25,7 +25,7 @@
#include <modules/exoplanets/exoplanetsmodule.h>
#include <modules/exoplanets/rendering/renderableorbitdisc.h>
#include <modules/exoplanets/tasks/exoplanetscsvtobintask.h>
#include <modules/exoplanets/tasks/exoplanetsdatapreparationtask.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/interaction/navigationhandler.h>
@@ -52,9 +52,9 @@ scripting::LuaLibrary ExoplanetsModule::luaLibrary() const {
"addExoplanetSystem",
&exoplanets::luascriptfunctions::addExoplanetSystem,
{},
"string",
"Add the exoplanet system specified by the input string, including "
"information about the host star and planets."
"string or list of strings",
"Add one or multiple exoplanet systems to the scene, as specified by the "
"input. An input string should be the name of the system host star."
},
{
"removeExoplanetSystem",
@@ -70,6 +70,13 @@ scripting::LuaLibrary ExoplanetsModule::luaLibrary() const {
"",
"Prints a list with the names of all exoplanet systems that can be added to "
"the scene graph to the OpenSpace Log. "
},
{
"getListOfExoplanets",
&exoplanets::luascriptfunctions::getListOfExoplanets,
{},
"",
"Gets a list with the names of all exoplanet systems, that can be used by a GUI."
}
};
@@ -80,13 +87,13 @@ void ExoplanetsModule::internalInitialize(const ghoul::Dictionary&) {
auto fTask = FactoryManager::ref().factory<Task>();
auto fRenderable = FactoryManager::ref().factory<Renderable>();
ghoul_assert(fTask, "No task factory existed");
fTask->registerClass<ExoplanetsCsvToBinTask>("ExoplanetsCsvToBinTask");
fTask->registerClass<ExoplanetsDataPreparationTask>("ExoplanetsDataPreparationTask");
fRenderable->registerClass<RenderableOrbitDisc>("RenderableOrbitDisc");
}
std::vector<documentation::Documentation> ExoplanetsModule::documentations() const {
return {
ExoplanetsCsvToBinTask::documentation()
ExoplanetsDataPreparationTask::documentation()
};
}

View File

@@ -62,93 +62,7 @@ constexpr const char* StarTextureFile = "${SYNC}/http/exoplanets_textures/1/sun.
constexpr const char* DiscTextureFile =
"${SYNC}/http/exoplanets_textures/1/disc_texture.png";
constexpr const char* BvColormapPath = "${SYNC}/http/stars_colormap/2/colorbv.cmap";
std::string starColor(float bv, std::ifstream& colormap) {
const int t = static_cast<int>(round(((bv + 0.4) / (2.0 + 0.4)) * 255));
std::string color;
for (int i = 0; i < t + 12; i++) {
getline(colormap, color);
}
colormap.close();
std::istringstream colorStream(color);
std::string r, g, b;
getline(colorStream, r, ' ');
getline(colorStream, g, ' ');
getline(colorStream, b, ' ');
return fmt::format("{{ {}, {}, {} }}", r, g, b);
}
glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom, float om) {
// Exoplanet defined inclination changed to be used as Kepler defined inclination
const glm::dvec3 ascendingNodeAxisRot = glm::dvec3(0.0, 0.0, 1.0);
const glm::dvec3 inclinationAxisRot = glm::dvec3(1.0, 0.0, 0.0);
const glm::dvec3 argPeriapsisAxisRot = glm::dvec3(0.0, 0.0, 1.0);
const double asc = glm::radians(bigom);
const double inc = glm::radians(i);
const double per = glm::radians(om);
const glm::dmat4 orbitPlaneRotation =
glm::rotate(asc, glm::dvec3(ascendingNodeAxisRot)) *
glm::rotate(inc, glm::dvec3(inclinationAxisRot)) *
glm::rotate(per, glm::dvec3(argPeriapsisAxisRot));
return orbitPlaneRotation;
}
// Rotate the original coordinate system (where x is pointing to First Point of Aries)
// so that x is pointing from star to the sun.
// Modified from "http://www.opengl-tutorial.org/intermediate-tutorials/
// tutorial-17-quaternions/ #how-do-i-find-the-rotation-between-2-vectors"
glm::dmat3 exoplanetSystemRotation(glm::dvec3 start, glm::dvec3 end) {
glm::quat rotationQuat;
glm::dvec3 rotationAxis;
const float cosTheta = static_cast<float>(glm::dot(start, end));
constexpr float Epsilon = 1E-3f;
if (cosTheta < -1.f + Epsilon) {
// special case when vectors in opposite directions:
// there is no "ideal" rotation axis
// So guess one; any will do as long as it's perpendicular to start vector
rotationAxis = glm::cross(glm::dvec3(0.0, 0.0, 1.0), start);
if (length2(rotationAxis) < 0.01f) {
// bad luck, they were parallel, try again!
rotationAxis = glm::cross(glm::dvec3(1.0, 0.0, 0.0), start);
}
rotationAxis = glm::normalize(rotationAxis);
rotationQuat = glm::quat(glm::radians(180.f), rotationAxis);
return glm::dmat3(toMat4(rotationQuat));
}
rotationAxis = glm::cross(start, end);
const float s = sqrt((1.f + cosTheta) * 2.f);
const float invs = 1.f / s;
rotationQuat = glm::quat(
s * 0.5f,
rotationAxis.x * invs,
rotationAxis.y * invs,
rotationAxis.z * invs
);
return glm::dmat3(glm::toMat4(rotationQuat));
}
// Create an identifier without whitespaces
std::string createIdentifier(std::string name) {
std::replace(name.begin(), name.end(), ' ', '_');
return name;
}
int addExoplanetSystem(lua_State* L) {
const int StringLocation = -1;
const std::string starName = luaL_checkstring(L, StringLocation);
void createExoplanetSystem(std::string_view starName) {
// If user have given name as in EOD, change it to speck-name
const std::string starNameSpeck = std::string(speckStarName(starName));
@@ -157,21 +71,28 @@ int addExoplanetSystem(lua_State* L) {
SceneGraphNode* existingStarNode = sceneGraphNode(starIdentifier);
if (existingStarNode) {
return ghoul::lua::luaError(
L,
"Adding of exoplanet system failed. The system has already been added."
);
LERROR(fmt::format(
"Adding of exoplanet system '{}' failed. The system has already been added.",
starName
));
return;
}
std::ifstream data(absPath(ExoplanetsDataPath), std::ios::in | std::ios::binary);
if (!data.good()) {
return ghoul::lua::luaError(L, "Failed to open exoplanets data file");
LERROR(fmt::format(
"Failed to open exoplanets data file: '{}'", absPath(ExoplanetsDataPath)
));
return;
}
std::ifstream lut(absPath(LookUpTablePath));
if (!lut.good()) {
return ghoul::lua::luaError(L, "Failed to open exoplanets look-up table file");
LERROR(fmt::format(
"Failed to open exoplanets look-up table: '{}'", absPath(LookUpTablePath)
));
return;
}
// 1. search lut for the starname and return the corresponding location
@@ -207,19 +128,18 @@ int addExoplanetSystem(lua_State* L) {
lut.close();
if (!found) {
return ghoul::lua::luaError(
L,
"No star with the provided name was found."
);
LERROR(fmt::format("No star with the provided name was found: '{}'", starName));
return;
}
bool notEnoughData = std::isnan(p.positionX) || std::isnan(p.a) || std::isnan(p.per);
if (notEnoughData) {
return ghoul::lua::luaError(
L,
"Insufficient data available for representing the exoplanet system."
);
LERROR(fmt::format(
"Insufficient data available for representing the exoplanet system: '{}'",
starName
));
return;
}
const glm::dvec3 starPosition = glm::dvec3(
@@ -263,41 +183,47 @@ int addExoplanetSystem(lua_State* L) {
starToSunVec.z
);
// Star renderable globe, if we have a radius
// Star renderable globe, if we have a radius and bv color index
std::string starGlobeRenderableString;
const float starRadius = p.rStar;
if (!std::isnan(starRadius)) {
std::ifstream colorMap(absPath(BvColormapPath), std::ios::in);
if (!std::isnan(p.rStar)) {
const float radiusInMeter =
p.rStar * static_cast<float>(distanceconstants::SolarRadius);
if (!colorMap.good()) {
return ghoul::lua::luaError(L, "Failed to open colormap data file");
std::string layers = "";
if (!std::isnan(p.bmv)) {
// @TODO (emmbr, 2020-10-12) should also check the bv value for the siblings.
// The data on the planets is derived from different sources, so while this
// planet has a nan value, another might not
const std::string color = starColor(p.bmv);
if (color.empty()) {
LERROR("Error occurred when computing star color");
return;
}
layers = "ColorLayers = {"
"{"
"Identifier = 'StarColor',"
"Type = 'SolidColor',"
"Color = " + color + ","
"BlendMode = 'Normal',"
"Enabled = true"
"},"
"{"
"Identifier = 'StarTexture',"
"FilePath = openspace.absPath('" + StarTextureFile + "'),"
"BlendMode = 'Color',"
"Enabled = true"
"}"
"}";
}
const std::string color = starColor(p.bmv, colorMap);
const float radiusInMeter = starRadius * static_cast<float>(distanceconstants::SolarRadius);
starGlobeRenderableString = "Renderable = {"
"Type = 'RenderableGlobe',"
"Radii = " + std::to_string(radiusInMeter) + ","
"SegmentsPerPatch = 64,"
"PerformShading = false,"
"Layers = {"
"ColorLayers = {"
"{"
"Identifier = 'StarColor',"
"Type = 'SolidColor',"
"Color = " + color + ","
"BlendMode = 'Normal',"
"Enabled = true"
"},"
"{"
"Identifier = 'StarTexture',"
"FilePath = openspace.absPath('" + StarTextureFile +"'),"
"BlendMode = 'Color',"
"Enabled = true"
"}"
"}"
"}"
"Layers = {" + layers + "}"
"},";
}
@@ -315,6 +241,7 @@ int addExoplanetSystem(lua_State* L) {
"Position = " + ghoul::to_string(starPosition) + ""
"}"
"},"
"Tag = {'exoplanet_system'},"
"GUI = {"
"Name = '" + starNameSpeck + " (Star)',"
"Path = '" + guiPath + "'"
@@ -323,7 +250,7 @@ int addExoplanetSystem(lua_State* L) {
openspace::global::scriptEngine.queueScript(
"openspace.addSceneGraphNode(" + starParent + ");",
openspace::scripting::ScriptEngine::RemoteScripting::Yes
scripting::ScriptEngine::RemoteScripting::Yes
);
// Planets
@@ -337,11 +264,11 @@ int addExoplanetSystem(lua_State* L) {
if (std::isnan(planet.i)) {
planet.i = 90.f;
}
if (std::isnan(planet.bigOm)) {
planet.bigOm = 180.f;
if (std::isnan(planet.bigOmega)) {
planet.bigOmega = 180.f;
}
if (std::isnan(planet.om)) {
planet.om = 90.f;
if (std::isnan(planet.omega)) {
planet.omega = 90.f;
}
Time epoch;
std::string sEpoch;
@@ -385,8 +312,8 @@ int addExoplanetSystem(lua_State* L) {
"Eccentricity = " + std::to_string(planet.ecc) + "," //ECC
"SemiMajorAxis = " + std::to_string(semiMajorAxisInKm) + ","
"Inclination = " + std::to_string(planet.i) + "," //I
"AscendingNode = " + std::to_string(planet.bigOm) + "," //BIGOM
"ArgumentOfPeriapsis = " + std::to_string(planet.om) + "," //OM
"AscendingNode = " + std::to_string(planet.bigOmega) + "," //BIGOM
"ArgumentOfPeriapsis = " + std::to_string(planet.omega) + "," //OM
"MeanAnomaly = 0.0,"
"Epoch = '" + sEpoch + "'," //TT. JD to YYYY MM DD hh:mm:ss
"Period = " + std::to_string(period) + ""
@@ -423,7 +350,7 @@ int addExoplanetSystem(lua_State* L) {
openspace::global::scriptEngine.queueScript(
"openspace.addSceneGraphNode(" + planetNode + ");",
openspace::scripting::ScriptEngine::RemoteScripting::Yes
scripting::ScriptEngine::RemoteScripting::Yes
);
const std::string planetTrailNode = "{"
@@ -455,8 +382,8 @@ int addExoplanetSystem(lua_State* L) {
// Get the orbit plane of the planet trail orbit from the KeplerTranslation
const glm::dmat4 orbitPlaneRotationMatrix = computeOrbitPlaneRotationMatrix(
planet.i,
planet.bigOm,
planet.om
planet.bigOmega,
planet.omega
);
const glm::dmat3 rotation = orbitPlaneRotationMatrix;
@@ -489,15 +416,49 @@ int addExoplanetSystem(lua_State* L) {
openspace::global::scriptEngine.queueScript(
"openspace.addSceneGraphNode(" + discNode + ");",
openspace::scripting::ScriptEngine::RemoteScripting::Yes
scripting::ScriptEngine::RemoteScripting::Yes
);
}
}
}
int addExoplanetSystem(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::addExoplanetSystem");
const int t = lua_type(L, 1);
if (t == LUA_TSTRING) {
// The user provided a single name
const std::string& starName = ghoul::lua::value<std::string>(L, 1);
createExoplanetSystem(starName);
}
else if (t == LUA_TTABLE) {
// A list of names was provided
ghoul::Dictionary d;
ghoul::lua::luaDictionaryFromState(L, d);
for (size_t i = 1; i <= d.size(); ++i) {
if (!d.hasKeyAndValue<std::string>(std::to_string(i))) {
return ghoul::lua::luaError(
L, fmt::format("List item {} is of invalid type", i)
);
}
const std::string& starName = d.value<std::string>(std::to_string(i));
createExoplanetSystem(starName);
}
lua_pop(L, 1);
}
else {
return ghoul::lua::luaError(L, "Invalid input");
}
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
int removeExoplanetSystem(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::removeExoplanetSystem");
const int StringLocation = -1;
const std::string starName = luaL_checkstring(L, StringLocation);
const std::string starNameSpeck = std::string(speckStarName(starName));
@@ -511,32 +472,25 @@ int removeExoplanetSystem(lua_State* L) {
return 0;
}
int listAvailableExoplanetSystems(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::listAvailableExoplanetSystems");
std::ifstream file(absPath(LookUpTablePath));
if (!file.good()) {
return ghoul::lua::luaError(
L,
fmt::format("Failed to open file '{}'", LookUpTablePath)
);
}
std::vector<std::string> readHostStarNames(std::ifstream& lookupTableFile) {
std::vector<std::string> names;
// As of 2020 there are about 4000 confirmed exoplanets, so use this number
// as a guess for the vector size
const int nExoplanetsGuess = 4000;
names.reserve(nExoplanetsGuess);
std::string line;
while (getline(file, line)) {
// Read number of lines
int nExoplanets = 0;
while (getline(lookupTableFile, line)) {
++nExoplanets;
}
lookupTableFile.clear();
lookupTableFile.seekg(0);
names.reserve(nExoplanets);
while (getline(lookupTableFile, line)) {
std::stringstream ss(line);
std::string name;
getline(ss, name, ',');
// Remove the last two characters, that specify the planet
name = name.substr(0, name.size() - 2);
names.push_back(name);
}
@@ -544,6 +498,44 @@ int listAvailableExoplanetSystems(lua_State* L) {
std::sort(names.begin(), names.end());
names.erase(std::unique(names.begin(), names.end()), names.end());
return names;
}
int getListOfExoplanets(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::getListOfExoplanets");
std::ifstream file(absPath(LookUpTablePath));
if (!file.good()) {
return ghoul::lua::luaError(
L, fmt::format("Failed to open file '{}'", LookUpTablePath
));
}
std::vector<std::string> names = readHostStarNames(file);
lua_newtable(L);
int number = 1;
for (const std::string& s : names) {
lua_pushstring(L, s.c_str());
lua_rawseti(L, -2, number);
++number;
}
return 1;
}
int listAvailableExoplanetSystems(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::listAvailableExoplanetSystems");
std::ifstream file(absPath(LookUpTablePath));
if (!file.good()) {
return ghoul::lua::luaError(
L, fmt::format("Failed to open file '{}'", LookUpTablePath
));
}
std::vector<std::string> names = readHostStarNames(file);
std::string output;
for (auto it = names.begin(); it != names.end(); ++it) {
if (it != names.end()) {
@@ -553,8 +545,7 @@ int listAvailableExoplanetSystems(lua_State* L) {
LINFO(fmt::format(
"There is data available for the following {} exoplanet systems: {}",
names.size(),
output
names.size(), output
));
return 0;

View File

@@ -1,706 +0,0 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/exoplanets/tasks/exoplanetscsvtobintask.h>
#include <modules/exoplanets/exoplanetshelper.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/fmt.h>
#include <ghoul/glm.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/dictionary.h>
#include <charconv>
#include <fstream>
namespace {
constexpr const char* KeyInputCsv = "InputCSV";
constexpr const char* KeyInputSpeck = "InputSPECK";
constexpr const char* KeyOutputBin = "OutputBIN";
constexpr const char* KeyOutputLut = "OutputLUT";
constexpr const char* KeyTeffToBv = "TeffToBvFile";
constexpr const char* _loggerCat = "CsvToBinTask";
} // namespace
namespace openspace::exoplanets {
ExoplanetsCsvToBinTask::ExoplanetsCsvToBinTask(const ghoul::Dictionary& dictionary) {
openspace::documentation::testSpecificationAndThrow(
documentation(),
dictionary,
"ExoplanetsCsvToBinTask"
);
_inputCsvPath = absPath(dictionary.value<std::string>(KeyInputCsv));
_inputSpeckPath = absPath(dictionary.value<std::string>(KeyInputSpeck));
_outputBinPath = absPath(dictionary.value<std::string>(KeyOutputBin));
_outputLutPath = absPath(dictionary.value<std::string>(KeyOutputLut));
_teffToBvFilePath = absPath(dictionary.value<std::string>(KeyTeffToBv));
}
std::string ExoplanetsCsvToBinTask::description() {
return fmt::format(
"Extract metadata from csv-file '{}' and write as bin to '{}'",
_inputCsvPath,
_outputBinPath
);
}
void ExoplanetsCsvToBinTask::perform(const Task::ProgressCallback& progressCallback) {
std::ifstream csvFile(_inputCsvPath);
if (!csvFile.good()) {
LERROR(fmt::format("Failed to open CSV file '{}'", _inputCsvPath));
return;
}
std::ofstream binFile(_outputBinPath, std::ios::out | std::ios::binary);
std::ofstream lutFile(_outputLutPath);
int version = 1;
binFile.write(reinterpret_cast<char*>(&version), sizeof(int));
std::string planetRow;
getline(csvFile, planetRow); // The first line, containing the data names
int total = 0;
while (getline(csvFile, planetRow)) {
++total;
}
csvFile.clear();
csvFile.seekg(0);
getline(csvFile, planetRow); // The first line, containing the data names
LINFOC("CSVTOBIN", fmt::format("Loading {} stars", total));
auto readFloatData = [](const std::string& str) -> float {
#ifdef WIN32
float result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return NAN;
#else
// clang is missing float support for std::from_chars
return !str.empty() ? std::stof(str.c_str(), nullptr) : NAN;
#endif
};
auto readDoubleData = [](const std::string& str) -> double {
#ifdef WIN32
double result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return NAN;
#else
// clang is missing double support for std::from_chars
return !str.empty() ? std::stod(str.c_str(), nullptr) : NAN;
#endif
};
auto readIntegerData = [](const std::string& str) -> int {
int result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return -1;
};
Exoplanet p;
std::string data;
int count = 0;
while (getline(csvFile, planetRow)) {
++count;
progressCallback(static_cast<float>(count) / static_cast<float>(total));
std::istringstream lineStream(planetRow);
getline(lineStream, data, ','); // A
p.a = readFloatData(data);
getline(lineStream, data, ','); // AUPPER
p.aUpper = readDoubleData(data);
getline(lineStream, data, ','); // ALOWER
p.aLower = readDoubleData(data);
getline(lineStream, data, ','); // UA
p.ua = readDoubleData(data);
getline(lineStream, data, ','); // AREF
getline(lineStream, data, ','); // AURL
getline(lineStream, data, ','); // AR
getline(lineStream, data, ','); // ARUPPER
getline(lineStream, data, ','); // ARLOWER
getline(lineStream, data, ','); // UAR
getline(lineStream, data, ','); // ARREF
getline(lineStream, data, ','); // ARURL
getline(lineStream, data, ','); // ASTROMETRY
getline(lineStream, data, ','); // B
getline(lineStream, data, ','); // BUPPER
getline(lineStream, data, ','); // BLOWER
getline(lineStream, data, ','); // UB
getline(lineStream, data, ','); // BREF
getline(lineStream, data, ','); // BURL
getline(lineStream, data, ','); // BIGOM
p.bigOm = readFloatData(data);
getline(lineStream, data, ','); // BIGOMUPPER
p.bigOmUpper = readFloatData(data);
getline(lineStream, data, ','); // BIGOMLOWER
p.bigOmLower = readFloatData(data);
getline(lineStream, data, ','); // UBIGOM
p.uBigOm = readFloatData(data);
getline(lineStream, data, ','); // BIGOMREF
getline(lineStream, data, ','); // BIGOMURL
getline(lineStream, data, ','); // BINARY
p.binary = static_cast<bool>(readIntegerData(data));
getline(lineStream, data, ','); // BINARYREF
getline(lineStream, data, ','); // BINARYURL
getline(lineStream, data, ','); // BMV
p.bmv = readFloatData(data);
getline(lineStream, data, ','); // CHI2
getline(lineStream, data, ','); // COMP
std::string component = data;
getline(lineStream, data, ','); // DATE
getline(lineStream, data, ','); // DEC
getline(lineStream, data, ','); // DEC_STRING
getline(lineStream, data, ','); // DENSITY
getline(lineStream, data, ','); // DENSITYUPPER
getline(lineStream, data, ','); // DENSITYLOWER
getline(lineStream, data, ','); // UDENSITY
getline(lineStream, data, ','); // DENSITYREF
getline(lineStream, data, ','); // DENSITYURL
getline(lineStream, data, ','); // DEPTH
getline(lineStream, data, ','); // DEPTHUPPER
getline(lineStream, data, ','); // DEPTHLOWER
getline(lineStream, data, ','); // UDEPTH
getline(lineStream, data, ','); // DEPTHREF
getline(lineStream, data, ','); // DEPTHURL
getline(lineStream, data, ','); // DIST
getline(lineStream, data, ','); // DISTUPPER
getline(lineStream, data, ','); // DISTLOWER
getline(lineStream, data, ','); // UDIST
getline(lineStream, data, ','); // DISTREF
getline(lineStream, data, ','); // DISTURL
getline(lineStream, data, ','); // DR
getline(lineStream, data, ','); // DRUPPER
getline(lineStream, data, ','); // DRLOWER
getline(lineStream, data, ','); // UDR
getline(lineStream, data, ','); // DRREF
getline(lineStream, data, ','); // DRURL
getline(lineStream, data, ','); // DVDT
getline(lineStream, data, ','); // DVDTUPPER
getline(lineStream, data, ','); // DVDTLOWER
getline(lineStream, data, ','); // UDVDT
getline(lineStream, data, ','); // DVDTREF
getline(lineStream, data, ','); // DVDTURL
getline(lineStream, data, ','); // EANAME
getline(lineStream, data, ','); // EAURL
getline(lineStream, data, ','); // ECC
p.ecc = readFloatData(data);
getline(lineStream, data, ','); // ECCUPPER
p.eccUpper = readFloatData(data);
getline(lineStream, data, ','); // ECCLOWER
p.eccLower = readFloatData(data);
getline(lineStream, data, ','); // UECC
p.uEcc = readFloatData(data);
getline(lineStream, data, ','); // ECCREF
getline(lineStream, data, ','); // ECCURL
getline(lineStream, data, ','); // EOD
getline(lineStream, data, ','); // ETDNAME
getline(lineStream, data, ','); // ETDURL
getline(lineStream, data, ','); // FE
getline(lineStream, data, ','); // FEUPPER
getline(lineStream, data, ','); // FELOWER
getline(lineStream, data, ','); // UFE
getline(lineStream, data, ','); // FEREF
getline(lineStream, data, ','); // FEURL
getline(lineStream, data, ','); // FIRSTREF
getline(lineStream, data, ','); // FIRSTURL
getline(lineStream, data, ','); // FREEZE_ECC
getline(lineStream, data, ','); // GAMMA
getline(lineStream, data, ','); // GAMMAUPPER
getline(lineStream, data, ','); // GAMMALOWER
getline(lineStream, data, ','); // UGAMMA
getline(lineStream, data, ','); // GAMMAREF
getline(lineStream, data, ','); // GAMMAURL
getline(lineStream, data, ','); // GL
getline(lineStream, data, ','); // GRAVITY
getline(lineStream, data, ','); // GRAVITYUPPER
getline(lineStream, data, ','); // GRAVITYLOWER
getline(lineStream, data, ','); // UGRAVITY
getline(lineStream, data, ','); // GRAVITYREF
getline(lineStream, data, ','); // GRAVITYURL
getline(lineStream, data, ','); // H
getline(lineStream, data, ','); // HD
getline(lineStream, data, ','); // HIPP
getline(lineStream, data, ','); // HR
getline(lineStream, data, ','); // I
p.i = readFloatData(data);
getline(lineStream, data, ','); // IUPPER
p.iUpper = readFloatData(data);
getline(lineStream, data, ','); // ILOWER
p.iLower = readFloatData(data);
getline(lineStream, data, ','); // UI
p.ui = readFloatData(data);
getline(lineStream, data, ','); // IREF
getline(lineStream, data, ','); // IURL
getline(lineStream, data, ','); // IMAGING
getline(lineStream, data, ','); // J
getline(lineStream, data, ','); // JSNAME
getline(lineStream, data, ','); // EPEURL
getline(lineStream, data, ','); // K
getline(lineStream, data, ','); // KUPPER
getline(lineStream, data, ','); // KLOWER
getline(lineStream, data, ','); // UK
getline(lineStream, data, ','); // KREF
getline(lineStream, data, ','); // KURL
getline(lineStream, data, ','); // KOI
getline(lineStream, data, ','); // KS
getline(lineStream, data, ','); // KP
getline(lineStream, data, ','); // LAMBDA
getline(lineStream, data, ','); // LAMBDAUPPER
getline(lineStream, data, ','); // LAMBDALOWER
getline(lineStream, data, ','); // ULAMBDA
getline(lineStream, data, ','); // LAMBDAREF
getline(lineStream, data, ','); // LAMBDAURL
getline(lineStream, data, ','); // LOGG
getline(lineStream, data, ','); // LOGGUPPER
getline(lineStream, data, ','); // LOGGLOWER
getline(lineStream, data, ','); // ULOGG
getline(lineStream, data, ','); // LOGGREF
getline(lineStream, data, ','); // LOGGURL;
getline(lineStream, data, ','); // MASS
getline(lineStream, data, ','); // MASSUPPER
getline(lineStream, data, ','); // MASSLOWER
getline(lineStream, data, ','); // UMASS
getline(lineStream, data, ','); // MASSREF
getline(lineStream, data, ','); // MASSURL
getline(lineStream, data, ','); // MICROLENSING
getline(lineStream, data, ','); // MSINI
getline(lineStream, data, ','); // MSINIUPPER
getline(lineStream, data, ','); // MSINILOWER
getline(lineStream, data, ','); // UMSINI
getline(lineStream, data, ','); // MSINIREF
getline(lineStream, data, ','); // MSINIURL
getline(lineStream, data, ','); // MSTAR
getline(lineStream, data, ','); // MSTARUPPER
getline(lineStream, data, ','); // MSTARLOWER
getline(lineStream, data, ','); // UMSTAR
getline(lineStream, data, ','); // MSTARREF
getline(lineStream, data, ','); // MSTARURL
getline(lineStream, data, ','); // MULT
getline(lineStream, data, ','); // NAME
getline(lineStream, data, ','); // NCOMP
p.nComp = readIntegerData(data);
getline(lineStream, data, ','); // NOBS
getline(lineStream, data, ','); // OM
p.om = readFloatData(data);
getline(lineStream, data, ','); // OMUPPER
p.omUpper = readFloatData(data);
getline(lineStream, data, ','); // OMLOWER
p.omLower = readFloatData(data);
getline(lineStream, data, ','); // UOM
p.uOm = readFloatData(data);
getline(lineStream, data, ','); // OMREF
getline(lineStream, data, ','); // OMURL
getline(lineStream, data, ','); // ORBREF
getline(lineStream, data, ','); // ORBURL
getline(lineStream, data, ','); // OTHERNAME
getline(lineStream, data, ','); // PAR
getline(lineStream, data, ','); // PARUPPER
getline(lineStream, data, ','); // PARLOWER
getline(lineStream, data, ','); // UPAR
getline(lineStream, data, ','); // PER
p.per = readDoubleData(data);
getline(lineStream, data, ','); // PERUPPER
p.perUpper = readFloatData(data);
getline(lineStream, data, ','); // PERLOWER
p.perLower = readFloatData(data);
getline(lineStream, data, ','); // UPER
p.uPer = readFloatData(data);
getline(lineStream, data, ','); // PERREF
getline(lineStream, data, ','); // PERURL
getline(lineStream, data, ','); // PLANETDISCMETH
getline(lineStream, data, ','); // R
p.r = readDoubleData(data);
getline(lineStream, data, ','); // RUPPER
p.rUpper = readDoubleData(data);
getline(lineStream, data, ','); // RLOWER
p.rLower = readDoubleData(data);
getline(lineStream, data, ','); //UR
p.ur = readDoubleData(data);
getline(lineStream, data, ','); // RREF
getline(lineStream, data, ','); // RURL
getline(lineStream, data, ','); // RA
getline(lineStream, data, ','); // RA_STRING
getline(lineStream, data, ','); // RHK
getline(lineStream, data, ','); // RHOSTAR
getline(lineStream, data, ','); // RHOSTARUPPER
getline(lineStream, data, ','); // RHOSTARLOWER
getline(lineStream, data, ','); // URHOSTAR
getline(lineStream, data, ','); // RHOSTARREF
getline(lineStream, data, ','); // RHOSTARURL
getline(lineStream, data, ','); // RMS
getline(lineStream, data, ','); // RR
getline(lineStream, data, ','); // RRUPPER
getline(lineStream, data, ','); // RRLOWER
getline(lineStream, data, ','); // URR
getline(lineStream, data, ','); // RRREF
getline(lineStream, data, ','); // RRURL
getline(lineStream, data, ','); // RSTAR
p.rStar = readFloatData(data);
getline(lineStream, data, ','); // RSTARUPPER
p.rStarUpper = readFloatData(data);
getline(lineStream, data, ','); // RSTARLOWER
p.rStarLower = readFloatData(data);
getline(lineStream, data, ','); // URSTAR
p.urStar = readFloatData(data);
getline(lineStream, data, ','); // RSTARREF
getline(lineStream, data, ','); // RSTARURL
getline(lineStream, data, ','); // SAO
getline(lineStream, data, ','); // SE
getline(lineStream, data, ','); // SEREF
getline(lineStream, data, ','); // SEURL
getline(lineStream, data, ','); // SEDEPTHJ
getline(lineStream, data, ','); // SEDEPTHJUPPER
getline(lineStream, data, ','); // SEDEPTHJLOWER
getline(lineStream, data, ','); // USEDEPTHJ
getline(lineStream, data, ','); // SEDEPTHJREF
getline(lineStream, data, ','); // SEDEPTHJURL
getline(lineStream, data, ','); // SEDEPTHH
getline(lineStream, data, ','); // SEDEPTHHUPPER
getline(lineStream, data, ','); // SEDEPTHHLOWER
getline(lineStream, data, ','); // USEDEPTHH
getline(lineStream, data, ','); // SEDEPTHHREF
getline(lineStream, data, ','); // SEDEPTHHURL
getline(lineStream, data, ','); // SEDEPTHKS
getline(lineStream, data, ','); // SEDEPTHKSUPPER
getline(lineStream, data, ','); // SEDEPTHKSLOWER
getline(lineStream, data, ','); // USEDEPTHKS
getline(lineStream, data, ','); // SEDEPTHKSREF
getline(lineStream, data, ','); // SEDEPTHKSURL
getline(lineStream, data, ','); // SEDEPTHKP
getline(lineStream, data, ','); // SEDEPTHKPUPPER
getline(lineStream, data, ','); // SEDEPTHKPLOWER
getline(lineStream, data, ','); // USEDEPTHKP
getline(lineStream, data, ','); // SEDEPTHKPREF
getline(lineStream, data, ','); // SEDEPTHKPURL
getline(lineStream, data, ','); // SEDEPTH36
getline(lineStream, data, ','); // SEDEPTH36UPPER
getline(lineStream, data, ','); // SEDEPTH36LOWER
getline(lineStream, data, ','); // USEDEPTH36
getline(lineStream, data, ','); // SEDEPTH36REFx
getline(lineStream, data, ','); // SEDEPTH36URLx
getline(lineStream, data, ','); // SEDEPTH45
getline(lineStream, data, ','); // SEDEPTH45UPPER
getline(lineStream, data, ','); // SEDEPTH45LOWER
getline(lineStream, data, ','); // USEDEPTH45
getline(lineStream, data, ','); // SEDEPTH45REF
getline(lineStream, data, ','); // SEDEPTH45URL
getline(lineStream, data, ','); // SEDEPTH58
getline(lineStream, data, ','); // SEDEPTH58UPPER
getline(lineStream, data, ','); // SEDEPTH58LOWER
getline(lineStream, data, ','); // USEDEPTH58
getline(lineStream, data, ','); // EDEPTH58REF
getline(lineStream, data, ','); // SEDEPTH58URL
getline(lineStream, data, ','); // SEDEPTH80
getline(lineStream, data, ','); // SEDEPTH80UPPER
getline(lineStream, data, ','); // SEDEPTH80LOWER
getline(lineStream, data, ','); // USEDEPTH80
getline(lineStream, data, ','); // SEDEPTH80REF
getline(lineStream, data, ','); // SEDEPTH80URL
getline(lineStream, data, ','); // SEP
getline(lineStream, data, ','); // SEPUPPER
getline(lineStream, data, ','); // SEPLOWER
getline(lineStream, data, ','); // USEP
getline(lineStream, data, ','); // SEPREF
getline(lineStream, data, ','); // SEPURL
getline(lineStream, data, ','); // SET
getline(lineStream, data, ','); // SETUPPER
getline(lineStream, data, ','); // SETLOWER
getline(lineStream, data, ','); // USET
getline(lineStream, data, ','); // SETREF
getline(lineStream, data, ','); // SETURL
getline(lineStream, data, ','); // SHK
getline(lineStream, data, ','); // SIMBADNAME
getline(lineStream, data, ','); // SIMBADURL
getline(lineStream, data, ','); // SPECREF
getline(lineStream, data, ','); // SPECURL
getline(lineStream, data, ','); // STAR
std::string speckStarname = std::string(speckStarName(data));
glm::vec3 position = starPosition(speckStarname);
p.positionX = position[0];
p.positionY = position[1];
p.positionZ = position[2];
getline(lineStream, data, ','); // STARDISCMETH
getline(lineStream, data, ','); // T0
getline(lineStream, data, ','); // T0UPPER
getline(lineStream, data, ','); // T0LOWER
getline(lineStream, data, ','); // UT0
getline(lineStream, data, ','); // T0REF
getline(lineStream, data, ','); // T0URL
getline(lineStream, data, ','); // T14
getline(lineStream, data, ','); // T14UPPER
getline(lineStream, data, ','); // T14LOWER
getline(lineStream, data, ','); // UT14
getline(lineStream, data, ','); // T14REF
getline(lineStream, data, ','); // T14URL
getline(lineStream, data, ','); // TEFF
float teff = readFloatData(data);
getline(lineStream, data, ','); // TEFFUPPER
getline(lineStream, data, ','); // TEFFLOWER
getline(lineStream, data, ','); // UTEFF
getline(lineStream, data, ','); // TEFFREF
getline(lineStream, data, ','); // TEFFURL
getline(lineStream, data, ','); // TIMING
getline(lineStream, data, ','); // TRANSIT
getline(lineStream, data, ','); // TRANSITREF
getline(lineStream, data, ','); // TRANSITURL
getline(lineStream, data, ','); // TREND
getline(lineStream, data, ','); // TT
p.tt = readDoubleData(data);
getline(lineStream, data, ','); // TTUPPER
p.ttUpper = readFloatData(data);
getline(lineStream, data, ','); // TTLOWER
p.ttLower = readFloatData(data);
getline(lineStream, data, ','); // UTT
p.uTt = readFloatData(data);
getline(lineStream, data, ','); // TTREF
getline(lineStream, data, ','); // TTURL
getline(lineStream, data, ','); // V
getline(lineStream, data, ','); // VREF
getline(lineStream, data, ','); // VURL
getline(lineStream, data, ','); // VSINI
getline(lineStream, data, ','); // VSINIUPPER
getline(lineStream, data, ','); // VSINILOWER
getline(lineStream, data, ','); // UVSINI
getline(lineStream, data, ','); // VSINIREF
getline(lineStream, data, ','); // VSINIURL
getline(lineStream, data, ','); // KEPID
bool isKeplerObject = false;
if (!data.empty()) {
isKeplerObject = true;
}
getline(lineStream, data); // KDE
if (!isKeplerObject) {
// calculate B-V from Teff if not exsisting
if (std::isnan(p.bmv)) {
p.bmv = bvFromTeff(teff);
}
// create look-up table
long pos = static_cast<long>(binFile.tellp());
std::string planetName = speckStarname + " " + component;
lutFile << planetName << "," << pos << std::endl;
binFile.write(reinterpret_cast<char*>(&p), sizeof(Exoplanet));
}
}
progressCallback(1.f);
}
glm::vec3 ExoplanetsCsvToBinTask::starPosition(const std::string& starName) {
std::ifstream exoplanetsFile(_inputSpeckPath);
if (!exoplanetsFile) {
LERROR(fmt::format("Error opening file expl.speck"));
}
glm::vec3 position{ NAN };
std::string line;
while (getline(exoplanetsFile, line)) {
bool shouldSkipLine = (
line.empty() || line[0] == '#' || line.substr(0, 7) == "datavar" ||
line.substr(0, 10) == "texturevar" || line.substr(0, 7) == "texture"
);
if (shouldSkipLine) {
continue;
}
std::string data;
std::string name;
std::istringstream linestream(line);
getline(linestream, data, '#');
getline(linestream, name);
name.erase(0, 1);
std::string coord;
if (name == starName) {
std::stringstream dataStream(data);
getline(dataStream, coord, ' ');
position[0] = std::stof(coord.c_str(), nullptr);
getline(dataStream, coord, ' ');
position[1] = std::stof(coord.c_str(), nullptr);
getline(dataStream, coord, ' ');
position[2] = std::stof(coord.c_str(), nullptr);
break;
}
}
// Apply transformation matrix to pos
glm::dmat4 _transformationMatrix = glm::dmat4(1.0);
glm::vec3 transformedPosition = glm::vec3(
_transformationMatrix * glm::dvec4(position, 1.0)
);
return transformedPosition;
}
float ExoplanetsCsvToBinTask::bvFromTeff(float teff) {
if (std::isnan(teff)) {
return NAN;
}
std::ifstream teffToBvFile(_teffToBvFilePath);
if (!teffToBvFile.good()) {
LERROR(fmt::format("Failed to open teff_bv.txt file"));
return NAN;
}
float bv = 0.f;
float bvUpper = 0.f;
float bvLower = 0.f;
float teffLower, teffUpper;
std::string row, teffString, bvString;
while (getline(teffToBvFile, row)) {
std::istringstream lineStream(row);
getline(lineStream, teffString, ',');
getline(lineStream, bvString);
float teffCurrent = std::stof(teffString.c_str(), nullptr);
float bvCurrent = std::stof(bvString.c_str(), nullptr);
if (teff > teffCurrent) {
teffLower = teffCurrent;
bvLower = bvCurrent;
}
else {
teffUpper = teffCurrent;
bvUpper = bvCurrent;
if (bvLower == 0.f) {
bv = 2.f;
}
else {
float bvDiff = (bvUpper - bvLower);
float teffDiff = (teffUpper - teffLower);
bv = ((bvDiff * (teff - teffLower)) / teffDiff) + bvLower;
}
break;
}
}
return bv;
}
documentation::Documentation ExoplanetsCsvToBinTask::documentation() {
using namespace documentation;
return {
"ExoplanetsCsvToBinTask",
"exoplanets_csv_to_bin_task",
{
{
"Type",
new StringEqualVerifier("ExoplanetsCsvToBinTask"),
Optional::No,
""
},
{
KeyInputCsv,
new StringAnnotationVerifier("A file path to a csv file"),
Optional::No,
"The csv file to extract data from"
},
{
KeyInputSpeck,
new StringAnnotationVerifier("A file path to a speck file"),
Optional::No,
"The speck file with star locations"
},
{
KeyOutputBin,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The bin file to export data into"
},
{
KeyOutputLut,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The txt file to write look-up table into"
},
{
KeyTeffToBv,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The path to a teff to bv conversion file"
}
}
};
}
} // namespace openspace::exoplanets

View File

@@ -0,0 +1,449 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/exoplanets/tasks/exoplanetsdatapreparationtask.h>
#include <modules/exoplanets/exoplanetshelper.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/util/coordinateconversion.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/fmt.h>
#include <ghoul/glm.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/dictionary.h>
#include <charconv>
#include <fstream>
namespace {
constexpr const char* KeyInputDataFile = "InputDataFile";
constexpr const char* KeyInputSpeck = "InputSPECK";
constexpr const char* KeyOutputBin = "OutputBIN";
constexpr const char* KeyOutputLut = "OutputLUT";
constexpr const char* KeyTeffToBv = "TeffToBvFile";
constexpr const char* _loggerCat = "ExoplanetsDataPreparationTask";
} // namespace
namespace openspace::exoplanets {
ExoplanetsDataPreparationTask::ExoplanetsDataPreparationTask(const ghoul::Dictionary& dictionary) {
openspace::documentation::testSpecificationAndThrow(
documentation(),
dictionary,
"ExoplanetsDataPreparationTask"
);
_inputDataPath = absPath(dictionary.value<std::string>(KeyInputDataFile));
_inputSpeckPath = absPath(dictionary.value<std::string>(KeyInputSpeck));
_outputBinPath = absPath(dictionary.value<std::string>(KeyOutputBin));
_outputLutPath = absPath(dictionary.value<std::string>(KeyOutputLut));
_teffToBvFilePath = absPath(dictionary.value<std::string>(KeyTeffToBv));
}
std::string ExoplanetsDataPreparationTask::description() {
return fmt::format(
"Extract data about exoplanets from file '{}' and write as bin to '{}'. The data "
"file should be a csv version of the Planetary Systems Composite Data from the "
"NASA exoplanets archive (https://exoplanetarchive.ipac.caltech.edu/).",
_inputDataPath, _outputBinPath
);
}
void ExoplanetsDataPreparationTask::perform(const Task::ProgressCallback& progressCallback) {
std::ifstream inputDataFile(_inputDataPath);
if (!inputDataFile.good()) {
LERROR(fmt::format("Failed to open input file '{}'", _inputDataPath));
return;
}
std::ofstream binFile(_outputBinPath, std::ios::out | std::ios::binary);
std::ofstream lutFile(_outputLutPath);
int version = 1;
binFile.write(reinterpret_cast<char*>(&version), sizeof(int));
std::string planetRow;
getline(inputDataFile, planetRow); // The first line, containing the data names
// Read column names into a vector, for later access
std::vector<std::string> columnNames;
std::stringstream sStream(planetRow);
std::string colName;
while (getline(sStream, colName, ',')) {
columnNames.push_back(colName);
}
// Read total number of items
int total = 0;
while (getline(inputDataFile, planetRow)) {
++total;
}
inputDataFile.clear();
inputDataFile.seekg(0);
getline(inputDataFile, planetRow); // The first line, containing the data names
LINFO(fmt::format("Loading {} exoplanets", total));
auto readFloatData = [](const std::string& str) -> float {
#ifdef WIN32
float result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return std::numeric_limits<float>::quiet_NaN();
#else
// clang is missing float support for std::from_chars
return !str.empty() ? std::stof(str.c_str(), nullptr) : NAN;
#endif
};
auto readDoubleData = [](const std::string& str) -> double {
#ifdef WIN32
double result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return std::numeric_limits<double>::quiet_NaN();
#else
// clang is missing double support for std::from_chars
return !str.empty() ? std::stod(str.c_str(), nullptr) : NAN;
#endif
};
auto readIntegerData = [](const std::string& str) -> int {
int result;
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc()) {
return result;
}
return -1;
};
auto readStringData = [](const std::string& str) -> std::string {
std::string result = str;
result.erase(std::remove(result.begin(), result.end(), '\"'), result.end());
return result;
};
Exoplanet p;
std::string data;
int exoplanetCount = 0;
while (getline(inputDataFile, planetRow)) {
++exoplanetCount;
progressCallback(static_cast<float>(exoplanetCount) / static_cast<float>(total));
std::string component;
std::string speckStarname;
float ra = std::numeric_limits<float>::quiet_NaN(); // decimal degrees
float dec = std::numeric_limits<float>::quiet_NaN(); // decimal degrees
float distanceInParsec = std::numeric_limits<float>::quiet_NaN();
std::istringstream lineStream(planetRow);
int columnIndex = 0;
while (getline(lineStream, data, ',')) {
const std::string& column = columnNames[columnIndex];
columnIndex++;
if (column == "pl_letter") {
component = readStringData(data);
}
// Orbital semi-major axis
else if (column == "pl_orbsmax") {
p.a = readFloatData(data);
}
else if (column == "pl_orbsmaxerr1") {
p.aUpper = readDoubleData(data);
}
else if (column == "pl_orbsmaxerr2") {
p.aLower = -readDoubleData(data);
}
// Orbital eccentricity
else if (column == "pl_orbeccen") {
p.ecc = readFloatData(data);
}
else if (column == "pl_orbeccenerr1") {
p.eccUpper = readFloatData(data);
}
else if (column == "pl_orbeccenerr2") {
p.eccLower = -readFloatData(data);
}
// Orbital inclination
else if (column == "pl_orbincl") {
p.i = readFloatData(data);
}
else if (column == "pl_orbinclerr1") {
p.iUpper = readFloatData(data);
}
else if (column == "pl_orbinclerr2") {
p.iLower = -readFloatData(data);
}
// Argument of periastron
else if (column == "pl_orblper") {
p.omega = readFloatData(data);
}
else if (column == "pl_orblpererr1") {
p.omegaUpper = readFloatData(data);
}
else if (column == "pl_orblpererr2") {
p.omegaLower = -readFloatData(data);
}
// Orbital period
else if (column == "pl_orbper") {
p.per = readDoubleData(data);
}
else if (column == "pl_orbpererr1") {
p.perUpper = readFloatData(data);
}
else if (column == "pl_orbpererr2") {
p.perLower = -readFloatData(data);
}
// Radius of the planet (Jupiter radii)
else if (column == "pl_radj") {
p.r = readDoubleData(data);
}
else if (column == "pl_radjerr1") {
p.rUpper = readDoubleData(data);
}
else if (column == "pl_radjerr2") {
p.rLower = -readDoubleData(data);
}
// Time of transit midpoint
else if (column == "pl_tranmid") {
p.tt = readDoubleData(data);
}
else if (column == "pl_tranmiderr1") {
p.ttUpper = readFloatData(data);
}
else if (column == "pl_tranmiderr2") {
p.ttLower = -readFloatData(data);
}
// Star - name and position
else if (column == "hostname") {
std::string name = readStringData(data);
speckStarname = std::string(speckStarName(name));
glm::vec3 position = starPosition(speckStarname);
p.positionX = position[0];
p.positionY = position[1];
p.positionZ = position[2];
}
else if (column == "ra") {
ra = readFloatData(data);
}
else if (column == "dec") {
dec = readFloatData(data);
}
else if (column == "sy_dist") {
distanceInParsec = readFloatData(data);
}
// Star radius
else if (column == "st_rad") {
p.rStar = readFloatData(data);
}
else if (column == "st_raderr1") {
p.rStarUpper = readFloatData(data);
}
else if (column == "st_raderr2") {
p.rStarLower = -readFloatData(data);
}
// Color of star (B-V color index computed from star's effective temperature)
else if (column == "st_teff") {
float teff = readFloatData(data);
p.bmv = bvFromTeff(teff);
}
// Is the planet orbiting a binary system?
else if (column == "cb_flag") {
p.binary = static_cast<bool>(readIntegerData(data));
}
// Number of planets in the system
else if (column == "sy_pnum") {
p.nComp = readIntegerData(data);
}
}
// @TODO (emmbr 2020-10-05) Currently, the dataset has no information about the
// longitude of the ascending node, but maybe it might in the future
p.bigOmega = std::numeric_limits<float>::quiet_NaN();
p.bigOmegaUpper = std::numeric_limits<float>::quiet_NaN();
p.bigOmegaLower = std::numeric_limits<float>::quiet_NaN();
bool foundPositionFromSpeck = !std::isnan(p.positionX);
bool hasDistance = !std::isnan(distanceInParsec);
bool hasIcrsCoords = !std::isnan(ra) && !std::isnan(dec) && hasDistance;
if (!foundPositionFromSpeck && hasIcrsCoords) {
glm::dvec3 pos = icrsToGalacticCartesian(ra, dec, distanceInParsec);
p.positionX = static_cast<float>(pos.x);
p.positionY = static_cast<float>(pos.y);
p.positionZ = static_cast<float>(pos.z);
}
// Create look-up table
long pos = static_cast<long>(binFile.tellp());
std::string planetName = speckStarname + " " + component;
lutFile << planetName << "," << pos << std::endl;
binFile.write(reinterpret_cast<char*>(&p), sizeof(Exoplanet));
}
progressCallback(1.f);
}
glm::vec3 ExoplanetsDataPreparationTask::starPosition(const std::string& starName) {
std::ifstream exoplanetsFile(_inputSpeckPath);
if (!exoplanetsFile) {
LERROR(fmt::format("Error opening file expl.speck"));
}
glm::vec3 position{ std::numeric_limits<float>::quiet_NaN() };
std::string line;
while (getline(exoplanetsFile, line)) {
bool shouldSkipLine = (
line.empty() || line[0] == '#' || line.substr(0, 7) == "datavar" ||
line.substr(0, 10) == "texturevar" || line.substr(0, 7) == "texture"
);
if (shouldSkipLine) {
continue;
}
std::string data;
std::string name;
std::istringstream linestream(line);
getline(linestream, data, '#');
getline(linestream, name);
name.erase(0, 1);
std::string coord;
if (name == starName) {
std::stringstream dataStream(data);
getline(dataStream, coord, ' ');
position[0] = std::stof(coord.c_str(), nullptr);
getline(dataStream, coord, ' ');
position[1] = std::stof(coord.c_str(), nullptr);
getline(dataStream, coord, ' ');
position[2] = std::stof(coord.c_str(), nullptr);
break;
}
}
return position;
}
float ExoplanetsDataPreparationTask::bvFromTeff(float teff) {
if (std::isnan(teff)) {
return std::numeric_limits<float>::quiet_NaN();
}
std::ifstream teffToBvFile(_teffToBvFilePath);
if (!teffToBvFile.good()) {
LERROR(fmt::format("Failed to open teff_bv.txt file"));
return std::numeric_limits<float>::quiet_NaN();
}
float bv = 0.f;
float bvUpper = 0.f;
float bvLower = 0.f;
float teffLower, teffUpper;
std::string row, teffString, bvString;
while (getline(teffToBvFile, row)) {
std::istringstream lineStream(row);
getline(lineStream, teffString, ',');
getline(lineStream, bvString);
float teffCurrent = std::stof(teffString.c_str(), nullptr);
float bvCurrent = std::stof(bvString.c_str(), nullptr);
if (teff > teffCurrent) {
teffLower = teffCurrent;
bvLower = bvCurrent;
}
else {
teffUpper = teffCurrent;
bvUpper = bvCurrent;
if (bvLower == 0.f) {
bv = 2.f;
}
else {
float bvDiff = (bvUpper - bvLower);
float teffDiff = (teffUpper - teffLower);
bv = ((bvDiff * (teff - teffLower)) / teffDiff) + bvLower;
}
break;
}
}
return bv;
}
documentation::Documentation ExoplanetsDataPreparationTask::documentation() {
using namespace documentation;
return {
"ExoplanetsDataPreparationTask",
"exoplanets_data_preparation_task",
{
{
"Type",
new StringEqualVerifier("ExoplanetsDataPreparationTask"),
Optional::No,
""
},
{
KeyInputDataFile,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The csv file to extract data from"
},
{
KeyInputSpeck,
new StringAnnotationVerifier("A file path to a speck file"),
Optional::No,
"The speck file with star locations"
},
{
KeyOutputBin,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The bin file to export data into"
},
{
KeyOutputLut,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The txt file to write look-up table into"
},
{
KeyTeffToBv,
new StringAnnotationVerifier("A valid filepath"),
Optional::No,
"The path to a teff to bv conversion file"
}
}
};
}
} // namespace openspace::exoplanets

View File

@@ -22,8 +22,8 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSCSVTOBINTASK___H__
#define __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSCSVTOBINTASK___H__
#ifndef __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSDATAPREPARATIONTASK___H__
#define __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSDATAPREPARATIONTASK___H__
#include <openspace/properties/vector/vec3property.h>
#include <openspace/util/task.h>
@@ -31,15 +31,15 @@
namespace openspace::exoplanets {
class ExoplanetsCsvToBinTask : public Task {
class ExoplanetsDataPreparationTask : public Task {
public:
ExoplanetsCsvToBinTask(const ghoul::Dictionary& dictionary);
ExoplanetsDataPreparationTask(const ghoul::Dictionary& dictionary);
std::string description() override;
void perform(const Task::ProgressCallback& progressCallback) override;
static documentation::Documentation documentation();
private:
std::string _inputCsvPath;
std::string _inputDataPath;
std::string _inputSpeckPath;
std::string _outputBinPath;
std::string _outputLutPath;
@@ -53,4 +53,4 @@ private:
} // namespace openspace::exoplanets
#endif // __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSCSVTOBINTASK___H__
#endif // __OPENSPACE_MODULE_EXOPLANETS___EXOPLANETSDATAPREPARATIONTASK___H__

View File

@@ -171,6 +171,7 @@ set(OPENSPACE_SOURCE
${OPENSPACE_BASE_DIR}/src/util/blockplaneintersectiongeometry.cpp
${OPENSPACE_BASE_DIR}/src/util/boxgeometry.cpp
${OPENSPACE_BASE_DIR}/src/util/camera.cpp
${OPENSPACE_BASE_DIR}/src/util/coordinateconversion.cpp
${OPENSPACE_BASE_DIR}/src/util/distanceconversion.cpp
${OPENSPACE_BASE_DIR}/src/util/factorymanager.cpp
${OPENSPACE_BASE_DIR}/src/util/httprequest.cpp
@@ -359,6 +360,7 @@ set(OPENSPACE_HEADER
${OPENSPACE_BASE_DIR}/include/openspace/util/concurrentjobmanager.inl
${OPENSPACE_BASE_DIR}/include/openspace/util/concurrentqueue.h
${OPENSPACE_BASE_DIR}/include/openspace/util/concurrentqueue.inl
${OPENSPACE_BASE_DIR}/include/openspace/util/coordinateconversion.h
${OPENSPACE_BASE_DIR}/include/openspace/util/distanceconstants.h
${OPENSPACE_BASE_DIR}/include/openspace/util/distanceconversion.h
${OPENSPACE_BASE_DIR}/include/openspace/util/factorymanager.h

View File

@@ -134,18 +134,21 @@ void KeybindingManager::bindKey(Key key, KeyModifier modifier, std::string luaCo
}
void KeybindingManager::removeKeyBinding(const std::string& key) {
// Erase-remove idiom does not work for std::multimap so we have to do this on foot
KeyWithModifier k = stringToKey(key);
removeKeyBinding(k);
}
void KeybindingManager::removeKeyBinding(const KeyWithModifier& key) {
// Erase-remove idiom does not work for std::multimap so we have to do this on foot
for (auto it = _keyLua.begin(); it != _keyLua.end(); ) {
// If the current iterator is the key that we are looking for, delete it
// (std::multimap::erase will return the iterator to the next element for us)
if (it->first == k) {
if (it->first == key) {
it = _keyLua.erase(it);
}
else {
// We if it is not, we continue iteration
// If it is not, we continue iteration
++it;
}
}
@@ -153,11 +156,17 @@ void KeybindingManager::removeKeyBinding(const std::string& key) {
std::vector<std::pair<KeyWithModifier, KeybindingManager::KeyInformation>>
KeybindingManager::keyBinding(const std::string& key) const
{
KeyWithModifier k = stringToKey(key);
return keyBinding(k);
}
std::vector<std::pair<KeyWithModifier, KeybindingManager::KeyInformation>>
KeybindingManager::keyBinding(const KeyWithModifier& key) const
{
std::vector<std::pair<KeyWithModifier, KeyInformation>> result;
KeyWithModifier k = stringToKey(key);
auto itRange = _keyLua.equal_range(k);
auto itRange = _keyLua.equal_range(key);
for (auto it = itRange.first; it != itRange.second; ++it) {
result.emplace_back(it->first, it->second);
}

View File

@@ -0,0 +1,49 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/util/coordinateconversion.h>
namespace openspace {
glm::dvec3 icrsToGalacticCartesian(float ra, float dec, double distance) {
// Convert to Galactic Coordinates from ICRS right ascension and declination
// https://gea.esac.esa.int/archive/documentation/GDR2/Data_processing/
// chap_cu3ast/sec_cu3ast_intro/ssec_cu3ast_intro_tansforms.html#SSS1
const glm::dmat3 conversionMatrix = glm::dmat3({
-0.0548755604162154, 0.4941094278755837, -0.8676661490190047, // col 0
-0.8734370902348850, -0.4448296299600112, -0.1980763734312015, // col 1
-0.4838350155487132, 0.7469822444972189, 0.4559837761750669 // col 2
});
glm::dvec3 rICRS = glm::dvec3(
cos(glm::radians(ra)) * cos(glm::radians(dec)),
sin(glm::radians(ra)) * cos(glm::radians(dec)),
sin(glm::radians(dec))
);
glm::dvec3 rGalactic = conversionMatrix * rICRS; // on the unit sphere
return distance * rGalactic;
}
} // namespace openspace

View File

@@ -59,7 +59,6 @@ bool hasKeyModifier(KeyModifier lhs, KeyModifier rhs) {
static_cast<std::underlying_type_t<KeyModifier>>(rhs);
}
KeyModifier operator|(KeyModifier lhs, KeyModifier rhs) {
return static_cast<KeyModifier>(
static_cast<std::underlying_type_t<KeyModifier>>(lhs) |
@@ -91,7 +90,6 @@ KeyWithModifier stringToKey(std::string str) {
}
Key k = itKey->second;
KeyModifier m = KeyModifier::NoModifier;
std::for_each(
tokens.begin(),

View File

@@ -26,12 +26,16 @@
#include <openspace/engine/globals.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/interaction/keybindingmanager.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/util/keys.h>
#include <openspace/util/timeline.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/profiling.h>
namespace {
constexpr const char* _loggerCat = "TimeManager";
// Properties for time interpolation
// These are used when setting the time from lua time interpolation functions,
// when called without arguments.
@@ -65,6 +69,8 @@ namespace {
"The default duration taken to transition to the unpaused state, "
"when interpolating"
};
constexpr const char* DeltaTimeStepsKeybindsGuiPath = "/Delta Time Steps";
}
namespace openspace {
@@ -397,8 +403,8 @@ void TimeManager::setDeltaTimeSteps(std::vector<double> deltaTimes) {
std::vector<double> negatives;
negatives.reserve(deltaTimes.size());
std::transform(
deltaTimes.begin(),
deltaTimes.end(),
deltaTimes.begin(),
deltaTimes.end(),
std::back_inserter(negatives),
[](double d) { return -d; }
);
@@ -411,6 +417,111 @@ void TimeManager::setDeltaTimeSteps(std::vector<double> deltaTimes) {
_deltaTimeSteps = std::move(deltaTimes);
_deltaTimeStepsChanged = true;
addDeltaTimesKeybindings();
}
void TimeManager::addDeltaTimesKeybindings() {
constexpr const std::array<Key, 10> Keys = {
Key::Num1,
Key::Num2,
Key::Num3,
Key::Num4,
Key::Num5,
Key::Num6,
Key::Num7,
Key::Num8,
Key::Num9,
Key::Num0
};
clearDeltaTimesKeybindings();
_deltaTimeStepKeybindings.reserve(_deltaTimeSteps.size());
// Find positive delta time steps
std::vector<double> steps;
const int nStepsGuess = static_cast<int>(std::floor(_deltaTimeSteps.size() * 0.5f));
steps.reserve(nStepsGuess);
std::copy_if(
_deltaTimeSteps.begin(),
_deltaTimeSteps.end(),
std::back_inserter(steps),
[](double value) { return value >= 0.0; }
);
const int nKeys = static_cast<int>(Keys.size());
const int nSteps = static_cast<int>(steps.size());
const int maxIterations = (nSteps >= nKeys) ? nKeys : nSteps;
auto addDeltaTimeKeybind = [this](Key key, KeyModifier mod, double step) {
const std::string s = fmt::format("{:.0f}", step);
global::keybindingManager.bindKeyLocal(
key,
mod,
fmt::format("openspace.time.interpolateDeltaTime({})", s),
fmt::format(
"Setting the simulation speed to {} seconds per realtime second", s
),
fmt::format("Set Simulation Speed: {}", s),
DeltaTimeStepsKeybindsGuiPath
);
_deltaTimeStepKeybindings.push_back(KeyWithModifier{ key, mod });
};
// For each key, add upp to three keybinds (no modifier, then SHIFT and then CTRL),
// plus inverted version of each time step one using the ALT modifier
for (int i = 0; i < maxIterations; ++i) {
const Key key = Keys[i];
addDeltaTimeKeybind(key, KeyModifier::NoModifier, steps[i]);
addDeltaTimeKeybind(key, KeyModifier::Alt, -steps[i]);
if (nSteps > nKeys) {
const int index = nKeys + i;
addDeltaTimeKeybind(key, KeyModifier::Shift, steps[index]);
KeyModifier mod = KeyModifier::Shift | KeyModifier::Alt;
addDeltaTimeKeybind(key, mod, -steps[index]);
}
if (nSteps > 2 * nKeys) {
const int index = 2 * nKeys + i;
addDeltaTimeKeybind(key, KeyModifier::Control, steps[index]);
KeyModifier mod = KeyModifier::Control | KeyModifier::Alt;
addDeltaTimeKeybind(key, mod, -steps[index]);
}
}
LINFO("Added keybindings for specified delta time steps.");
const int maxKeyBinds = 3 * nKeys;
if (nSteps > maxKeyBinds) {
LWARNING(fmt::format(
"Error settings delta time keys: Too many delta times, so not all could be "
"mapped to a key. Total: {} steps, which is {} more than the number of "
"available keybindings.",
nSteps, nSteps - maxKeyBinds
));
}
}
void TimeManager::clearDeltaTimesKeybindings() {
for (const KeyWithModifier& kb : _deltaTimeStepKeybindings) {
// Check if there are multiple keys bound to the same key
auto bindings = global::keybindingManager.keyBinding(kb);
if (bindings.size() > 1) {
std::string names;
for (auto& b : bindings) {
names += fmt::format("'{}' ", b.second.name);
}
LWARNING(fmt::format(
"Updating keybindings for new delta time steps: More than one action "
"was bound to key '{}'. The following keybindings are removed: {}",
ghoul::to_string(kb), names
));
}
global::keybindingManager.removeKeyBinding(kb);
}
_deltaTimeStepKeybindings.clear();
}
size_t TimeManager::nKeyframes() const {
@@ -446,7 +557,7 @@ TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCa
return handle;
}
TimeManager::CallbackHandle
TimeManager::CallbackHandle
TimeManager::addDeltaTimeStepsChangeCallback(TimeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
@@ -677,7 +788,7 @@ void TimeManager::setPreviousDeltaTimeStep() {
}
void TimeManager::interpolateNextDeltaTimeStep(double durationSeconds) {
if (!hasNextDeltaTimeStep())
if (!hasNextDeltaTimeStep())
return;
double nextDeltaTime = nextDeltaTimeStep().value();