Pass through the code to address clang-tidy linting (#3083)

This commit is contained in:
Alexander Bock
2024-03-17 00:58:50 +01:00
committed by GitHub
parent 75681d1d4c
commit 2759c00e4b
457 changed files with 6639 additions and 6519 deletions
+23 -25
View File
@@ -46,14 +46,14 @@ void Camera::setPose(CameraPose pose) {
void Camera::setPositionVec3(glm::dvec3 pos) {
if (!glm::any(glm::isnan(pos))) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_position = std::move(pos);
_cachedCombinedViewMatrix.isDirty = true;
}
}
void Camera::setRotation(glm::dquat rotation) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_rotation = std::move(rotation);
_cachedViewDirection.isDirty = true;
_cachedLookupVector.isDirty = true;
@@ -62,14 +62,14 @@ void Camera::setRotation(glm::dquat rotation) {
}
void Camera::setScaling(float scaling) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_scaling = scaling;
_cachedViewScaleMatrix.isDirty = true;
_cachedCombinedViewMatrix.isDirty = true;
}
void Camera::setMaxFov(float fov) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_maxFov = fov;
_cachedSinMaxFov.isDirty = true;
}
@@ -78,9 +78,9 @@ void Camera::setParent(SceneGraphNode* parent) {
_parent = parent;
}
void Camera::rotate(glm::dquat rotation) {
std::lock_guard _lock(_mutex);
_rotation = std::move(rotation) * static_cast<glm::dquat>(_rotation);
void Camera::rotate(const glm::dquat& rotation) {
const std::lock_guard _lock(_mutex);
_rotation = rotation * static_cast<glm::dquat>(_rotation);
_cachedViewDirection.isDirty = true;
_cachedLookupVector.isDirty = true;
@@ -93,19 +93,19 @@ const glm::dvec3& Camera::positionVec3() const {
}
glm::dvec3 Camera::eyePositionVec3() const {
glm::dvec4 eyeInEyeSpace(0.0, 0.0, 0.0, 1.0);
constexpr glm::dvec4 EyeInEyeSpace = glm::dvec4(0.0, 0.0, 0.0, 1.0);
glm::dmat4 invViewMatrix = glm::inverse(sgctInternal.viewMatrix());
glm::dmat4 invRotationMatrix = glm::mat4_cast(static_cast<glm::dquat>(_rotation));
glm::dmat4 invTranslationMatrix = glm::translate(
const glm::dmat4 invViewMat = glm::inverse(sgctInternal.viewMatrix());
const glm::dmat4 invRotationMat = glm::mat4_cast(static_cast<glm::dquat>(_rotation));
const glm::dmat4 invTranslationMat = glm::translate(
glm::dmat4(1.0),
static_cast<glm::dvec3>(_position)
);
glm::dmat4 invViewScale = glm::inverse(viewScaleMatrix());
const glm::dmat4 invViewScale = glm::inverse(viewScaleMatrix());
glm::dvec4 eyeInWorldSpace = invTranslationMatrix * invRotationMatrix *
invViewScale * invViewMatrix * eyeInEyeSpace;
const glm::dvec4 eyeInWorldSpace = invTranslationMat * invRotationMat *
invViewScale * invViewMat * EyeInEyeSpace;
return glm::dvec3(eyeInWorldSpace.x, eyeInWorldSpace.y, eyeInWorldSpace.z);
}
@@ -145,7 +145,7 @@ float Camera::maxFov() const {
float Camera::sinMaxFov() const {
if (_cachedSinMaxFov.isDirty) {
_cachedSinMaxFov.datum = sin(_maxFov);
_cachedSinMaxFov.datum = std::sin(_maxFov);
_cachedSinMaxFov.isDirty = true;
}
return _cachedSinMaxFov.datum;
@@ -216,8 +216,8 @@ void Camera::invalidateCache() {
void Camera::serialize(std::ostream& os) const {
const glm::dvec3 p = positionVec3();
const glm::dquat q = rotationQuaternion();
os << p.x << " " << p.y << " " << p.z << std::endl;
os << q.x << " " << q.y << " " << q.z << " " << q.w << std::endl;
os << p.x << " " << p.y << " " << p.z << '\n';
os << q.x << " " << q.y << " " << q.z << " " << q.w << '\n';
}
void Camera::deserialize(std::istream& is) {
@@ -236,20 +236,20 @@ Camera::SgctInternal::SgctInternal(const SgctInternal& o)
{}
void Camera::SgctInternal::setSceneMatrix(glm::mat4 sceneMatrix) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_sceneMatrix = std::move(sceneMatrix);
}
void Camera::SgctInternal::setViewMatrix(glm::mat4 viewMatrix) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_viewMatrix = std::move(viewMatrix);
_cachedViewProjectionMatrix.isDirty = true;
}
void Camera::SgctInternal::setProjectionMatrix(glm::mat4 projectionMatrix) {
std::lock_guard _lock(_mutex);
const std::lock_guard _lock(_mutex);
_projectionMatrix = std::move(projectionMatrix);
_cachedViewProjectionMatrix.isDirty = true;
@@ -268,11 +268,9 @@ const glm::mat4& Camera::SgctInternal::projectionMatrix() const {
}
const glm::mat4& Camera::SgctInternal::viewProjectionMatrix() const {
//if (_cachedViewProjectionMatrix.isDirty) {
std::lock_guard _lock(_mutex);
_cachedViewProjectionMatrix.datum = _projectionMatrix * _viewMatrix;
_cachedViewProjectionMatrix.isDirty = false;
//}
const std::lock_guard _lock(_mutex);
_cachedViewProjectionMatrix.datum = _projectionMatrix * _viewMatrix;
_cachedViewProjectionMatrix.isDirty = false;
return _cachedViewProjectionMatrix.datum;
}
+6 -6
View File
@@ -50,7 +50,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional<DataMapping> s
ghoul_assert(std::filesystem::exists(filePath), "File must exist");
auto readFloatData = [](const std::string& str) -> float {
float result;
float result = 0.f;
#ifdef WIN32
auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc() && std::isfinite(result)) {
@@ -60,7 +60,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional<DataMapping> s
#else // ^^^^ WIN32 // !WIN32 vvvv
// clang is missing float support for std::from_chars
try {
result = std::stof(str.c_str(), nullptr);
result = std::stof(str, nullptr);
if (std::isfinite(result)) {
return result;
}
@@ -96,7 +96,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional<DataMapping> s
int nameColumn = -1;
int nDataColumns = 0;
bool hasExcludeColumns = specs.has_value() && (*specs).hasExcludeColumns();
const bool hasExcludeColumns = specs.has_value() && specs->hasExcludeColumns();
std::vector<size_t> skipColumns;
if (hasExcludeColumns) {
skipColumns.reserve((*specs).excludeColumns.size());
@@ -161,7 +161,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional<DataMapping> s
const std::string& strValue = row[i];
// For now, all values are converted to float
float value = readFloatData(strValue);
const float value = readFloatData(strValue);
if (i == xColumn) {
entry.position.x = value;
@@ -182,8 +182,8 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional<DataMapping> s
}
}
glm::vec3 positive = glm::abs(entry.position);
float max = glm::compMax(positive);
const glm::vec3 positive = glm::abs(entry.position);
const float max = glm::compMax(positive);
if (max > res.maxPositionComponent) {
res.maxPositionComponent = max;
}
+49 -52
View File
@@ -118,19 +118,19 @@ namespace data {
Dataset loadFile(std::filesystem::path path, std::optional<DataMapping> specs) {
ghoul_assert(std::filesystem::exists(path), "File must exist");
std::ifstream file(path);
const std::ifstream file = std::ifstream(path);
if (!file.good()) {
throw ghoul::RuntimeError(fmt::format("Failed to open data file '{}'", path));
}
std::string extension = ghoul::toLowerCase(path.extension().string());
const std::string extension = ghoul::toLowerCase(path.extension().string());
Dataset res;
if (extension == ".csv") {
res = csv::loadCsvFile(path, specs);
res = csv::loadCsvFile(path, std::move(specs));
}
else if (extension == ".speck") {
res = speck::loadSpeckFile(path, specs);
res = speck::loadSpeckFile(path, std::move(specs));
}
else {
LERRORC("DataLoader", fmt::format(
@@ -142,15 +142,15 @@ Dataset loadFile(std::filesystem::path path, std::optional<DataMapping> specs) {
return res;
}
std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
std::ifstream file(path, std::ios::binary);
std::optional<Dataset> loadCachedFile(const std::filesystem::path& path) {
std::ifstream file = std::ifstream(path, std::ios::binary);
if (!file.good()) {
return std::nullopt;
}
Dataset result;
int8_t fileVersion;
int8_t fileVersion = 0;
file.read(reinterpret_cast<char*>(&fileVersion), sizeof(int8_t));
if (fileVersion != DataCacheFileVersion) {
// Incompatible version and we won't be able to read the file
@@ -159,17 +159,17 @@ std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
//
// Read variables
uint16_t nVariables;
uint16_t nVariables = 0;
file.read(reinterpret_cast<char*>(&nVariables), sizeof(uint16_t));
result.variables.resize(nVariables);
for (int i = 0; i < nVariables; i += 1) {
Dataset::Variable var;
int16_t idx;
int16_t idx = 0;
file.read(reinterpret_cast<char*>(&idx), sizeof(int16_t));
var.index = idx;
uint16_t len;
uint16_t len = 0;
file.read(reinterpret_cast<char*>(&len), sizeof(uint16_t));
var.name.resize(len);
file.read(var.name.data(), len);
@@ -179,17 +179,17 @@ std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
//
// Read textures
uint16_t nTextures;
uint16_t nTextures = 0;
file.read(reinterpret_cast<char*>(&nTextures), sizeof(uint16_t));
result.textures.resize(nTextures);
for (int i = 0; i < nTextures; i += 1) {
Dataset::Texture tex;
int16_t idx;
int16_t idx = 0;
file.read(reinterpret_cast<char*>(&idx), sizeof(int16_t));
tex.index = idx;
uint16_t len;
uint16_t len = 0;
file.read(reinterpret_cast<char*>(&len), sizeof(uint16_t));
tex.file.resize(len);
file.read(tex.file.data(), len);
@@ -199,17 +199,17 @@ std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
//
// Read indices
int16_t texDataIdx;
int16_t texDataIdx = 0;
file.read(reinterpret_cast<char*>(&texDataIdx), sizeof(int16_t));
result.textureDataIndex = texDataIdx;
int16_t oriDataIdx;
int16_t oriDataIdx = 0;
file.read(reinterpret_cast<char*>(&oriDataIdx), sizeof(int16_t));
result.orientationDataIndex = oriDataIdx;
//
// Read entries
uint64_t nEntries;
uint64_t nEntries = 0;
file.read(reinterpret_cast<char*>(&nEntries), sizeof(uint64_t));
result.entries.reserve(nEntries);
for (uint64_t i = 0; i < nEntries; i += 1) {
@@ -218,12 +218,12 @@ std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
file.read(reinterpret_cast<char*>(&e.position.y), sizeof(float));
file.read(reinterpret_cast<char*>(&e.position.z), sizeof(float));
uint16_t nValues;
uint16_t nValues = 0;
file.read(reinterpret_cast<char*>(&nValues), sizeof(uint16_t));
e.data.resize(nValues);
file.read(reinterpret_cast<char*>(e.data.data()), nValues * sizeof(float));
uint16_t len;
uint16_t len = 0;
file.read(reinterpret_cast<char*>(&len), sizeof(uint16_t));
if (len > 0) {
std::string comment;
@@ -237,15 +237,15 @@ std::optional<Dataset> loadCachedFile(std::filesystem::path path) {
//
// Read max data point variable
float max;
float max = 0.f;
file.read(reinterpret_cast<char*>(&max), sizeof(float));
result.maxPositionComponent = max;
return result;
}
void saveCachedFile(const Dataset& dataset, std::filesystem::path path) {
std::ofstream file(path, std::ofstream::binary);
void saveCachedFile(const Dataset& dataset, const std::filesystem::path& path) {
std::ofstream file = std::ofstream(path, std::ofstream::binary);
file.write(reinterpret_cast<const char*>(&DataCacheFileVersion), sizeof(int8_t));
@@ -330,12 +330,10 @@ void saveCachedFile(const Dataset& dataset, std::filesystem::path path) {
);
}
Dataset loadFileWithCache(std::filesystem::path filePath,
std::optional<DataMapping> specs)
{
Dataset loadFileWithCache(std::filesystem::path path, std::optional<DataMapping> specs) {
return internalLoadFileWithCache<Dataset>(
filePath,
specs,
std::move(path),
std::move(specs),
&loadFile,
&loadCachedFile,
&saveCachedFile
@@ -349,12 +347,12 @@ namespace label {
Labelset loadFile(std::filesystem::path path, std::optional<DataMapping>) {
ghoul_assert(std::filesystem::exists(path), "File must exist");
std::ifstream file(path);
const std::ifstream file = std::ifstream(path);
if (!file.good()) {
throw ghoul::RuntimeError(fmt::format("Failed to open dataset file '{}'", path));
}
std::string extension = ghoul::toLowerCase(path.extension().string());
const std::string extension = ghoul::toLowerCase(path.extension().string());
Labelset res;
if (extension == ".label") {
@@ -370,13 +368,13 @@ Labelset loadFile(std::filesystem::path path, std::optional<DataMapping>) {
return res;
}
std::optional<Labelset> loadCachedFile(std::filesystem::path path) {
std::optional<Labelset> loadCachedFile(const std::filesystem::path& path) {
std::ifstream file(path, std::ios::binary);
if (!file.good()) {
return std::nullopt;
}
int8_t fileVersion;
int8_t fileVersion = 0;
file.read(reinterpret_cast<char*>(&fileVersion), sizeof(int8_t));
if (fileVersion != LabelCacheFileVersion) {
// Incompatible version and we won't be able to read the file
@@ -385,11 +383,11 @@ std::optional<Labelset> loadCachedFile(std::filesystem::path path) {
Labelset result;
int16_t textColorIdx;
int16_t textColorIdx = 0;
file.read(reinterpret_cast<char*>(&textColorIdx), sizeof(int16_t));
result.textColorIndex = textColorIdx;
uint32_t nEntries;
uint32_t nEntries = 0;
file.read(reinterpret_cast<char*>(&nEntries), sizeof(uint32_t));
result.entries.reserve(nEntries);
for (unsigned int i = 0; i < nEntries; i += 1) {
@@ -399,13 +397,13 @@ std::optional<Labelset> loadCachedFile(std::filesystem::path path) {
file.read(reinterpret_cast<char*>(&e.position.z), sizeof(float));
// Identifier
uint8_t idLen;
uint8_t idLen = 0;
file.read(reinterpret_cast<char*>(&idLen), sizeof(uint8_t));
e.identifier.resize(idLen);
file.read(e.identifier.data(), idLen);
// Text
uint16_t len;
uint16_t len = 0;
file.read(reinterpret_cast<char*>(&len), sizeof(uint16_t));
e.text.resize(len);
file.read(e.text.data(), len);
@@ -416,8 +414,8 @@ std::optional<Labelset> loadCachedFile(std::filesystem::path path) {
return result;
}
void saveCachedFile(const Labelset& labelset, std::filesystem::path path) {
std::ofstream file(path, std::ofstream::binary);
void saveCachedFile(const Labelset& labelset, const std::filesystem::path& path) {
std::ofstream file = std::ofstream(path, std::ofstream::binary);
file.write(reinterpret_cast<const char*>(&LabelCacheFileVersion), sizeof(int8_t));
@@ -453,7 +451,7 @@ void saveCachedFile(const Labelset& labelset, std::filesystem::path path) {
Labelset loadFileWithCache(std::filesystem::path filePath) {
return internalLoadFileWithCache<Labelset>(
filePath,
std::move(filePath),
std::nullopt,
&loadFile,
&loadCachedFile,
@@ -485,12 +483,12 @@ namespace color {
ColorMap loadFile(std::filesystem::path path, std::optional<DataMapping>) {
ghoul_assert(std::filesystem::exists(path), "File must exist");
std::ifstream file(path);
const std::ifstream file = std::ifstream(path);
if (!file.good()) {
throw ghoul::RuntimeError(fmt::format("Failed to open colormap file '{}'", path));
}
std::string extension = ghoul::toLowerCase(path.extension().string());
const std::string extension = ghoul::toLowerCase(path.extension().string());
ColorMap res;
if (extension == ".cmap") {
@@ -506,13 +504,13 @@ ColorMap loadFile(std::filesystem::path path, std::optional<DataMapping>) {
return res;
}
std::optional<ColorMap> loadCachedFile(std::filesystem::path path) {
std::optional<ColorMap> loadCachedFile(const std::filesystem::path& path) {
std::ifstream file(path, std::ios::binary);
if (!file.good()) {
return std::nullopt;
}
int8_t fileVersion;
int8_t fileVersion = 0;
file.read(reinterpret_cast<char*>(&fileVersion), sizeof(int8_t));
if (fileVersion != ColorCacheFileVersion) {
// Incompatible version and we won't be able to read the file
@@ -521,7 +519,7 @@ std::optional<ColorMap> loadCachedFile(std::filesystem::path path) {
ColorMap result;
uint32_t nColors;
uint32_t nColors = 0;
file.read(reinterpret_cast<char*>(&nColors), sizeof(uint32_t));
result.entries.reserve(nColors);
for (unsigned int i = 0; i < nColors; i += 1) {
@@ -571,8 +569,8 @@ std::optional<ColorMap> loadCachedFile(std::filesystem::path path) {
return result;
}
void saveCachedFile(const ColorMap& colorMap, std::filesystem::path path) {
std::ofstream file(path, std::ofstream::binary);
void saveCachedFile(const ColorMap& colorMap, const std::filesystem::path& path) {
std::ofstream file = std::ofstream(path, std::ofstream::binary);
file.write(reinterpret_cast<const char*>(&ColorCacheFileVersion), sizeof(int8_t));
@@ -610,10 +608,9 @@ void saveCachedFile(const ColorMap& colorMap, std::filesystem::path path) {
file.write(reinterpret_cast<const char*>(&nanColor.w), sizeof(float));
}
ColorMap loadFileWithCache(std::filesystem::path path)
{
ColorMap loadFileWithCache(std::filesystem::path path) {
return internalLoadFileWithCache<ColorMap>(
path,
std::move(path),
std::nullopt,
&loadFile,
&loadCachedFile,
@@ -637,7 +634,7 @@ int Dataset::index(std::string_view variableName) const {
}
bool Dataset::normalizeVariable(std::string_view variableName) {
int idx = index(variableName);
const int idx = index(variableName);
if (idx == -1) {
// We didn't find the variable that was specified
@@ -647,7 +644,7 @@ bool Dataset::normalizeVariable(std::string_view variableName) {
float minValue = std::numeric_limits<float>::max();
float maxValue = -std::numeric_limits<float>::max();
for (Dataset::Entry& e : entries) {
float value = e.data[idx];
const float value = e.data[idx];
if (std::isnan(value)) {
continue;
}
@@ -656,7 +653,7 @@ bool Dataset::normalizeVariable(std::string_view variableName) {
}
for (Dataset::Entry& e : entries) {
float value = e.data[idx];
const float value = e.data[idx];
if (std::isnan(value)) {
continue;
}
@@ -681,7 +678,7 @@ glm::vec2 Dataset::findValueRange(int variableIndex) const {
float maxValue = -std::numeric_limits<float>::max();
for (const Dataset::Entry& e : entries) {
if (!e.data.empty()) {
float value = e.data[variableIndex];
const float value = e.data[variableIndex];
if (std::isnan(value)) {
continue;
}
@@ -698,7 +695,7 @@ glm::vec2 Dataset::findValueRange(int variableIndex) const {
}
glm::vec2 Dataset::findValueRange(std::string_view variableName) const {
int idx = index(variableName);
const int idx = index(variableName);
if (idx == -1) {
// We didn't find the variable that was specified
+1 -1
View File
@@ -144,7 +144,7 @@ bool DataMapping::isExcludeColumn(std::string_view column) const {
std::string generateHashString(const DataMapping& dm) {
std::string a;
for (std::string_view c : dm.excludeColumns) {
for (const std::string_view c : dm.excludeColumns) {
a += c;
}
unsigned int excludeColumnsHash = ghoul::hashCRC32(a);
+6 -6
View File
@@ -273,8 +273,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional<DataMapping> spe
str >> entry.position.x >> entry.position.y >> entry.position.z;
allZero &= (entry.position == glm::vec3(0.0));
glm::vec3 positive = glm::abs(entry.position);
float max = glm::compMax(positive);
const glm::vec3 positive = glm::abs(entry.position);
const float max = glm::compMax(positive);
if (max > res.maxPositionComponent) {
res.maxPositionComponent = max;
}
@@ -304,8 +304,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional<DataMapping> spe
// Check if value corresponds to a missing value
if (specs.has_value() && specs->missingDataValue.has_value()) {
float missingDataValue = specs->missingDataValue.value();
float diff = std::abs(entry.data[i] - missingDataValue);
const float missingDataValue = specs->missingDataValue.value();
const float diff = std::abs(entry.data[i] - missingDataValue);
if (diff < std::numeric_limits<float>::epsilon()) {
entry.data[i] = std::numeric_limits<float>::quiet_NaN();
}
@@ -455,7 +455,7 @@ Labelset loadLabelFile(std::filesystem::path path) {
// optional arument with identifier
// Remove the 'id' text
rest = rest.substr(std::string_view("id ").size());
size_t index = rest.find("text");
const size_t index = rest.find("text");
entry.identifier = rest.substr(0, index - 1);
// update the rest, remove the identifier
@@ -493,7 +493,7 @@ Labelset loadLabelFile(std::filesystem::path path) {
ColorMap loadCmapFile(std::filesystem::path path) {
ghoul_assert(std::filesystem::exists(path), "File must exist");
std::ifstream file(path);
std::ifstream file = std::ifstream(path);
if (!file.good()) {
throw ghoul::RuntimeError(fmt::format(
"Failed to open color map file '{}'", path
+5 -5
View File
@@ -221,7 +221,7 @@ TestResult testSpecification(const Documentation& documentation,
for (const auto& p : documentation.entries) {
if (p.key == DocumentationEntry::Wildcard) {
for (std::string_view key : dictionary.keys()) {
for (const std::string_view key : dictionary.keys()) {
applyVerifier(*(p.verifier), std::string(key));
}
}
@@ -237,14 +237,14 @@ TestResult testSpecification(const Documentation& documentation,
// Remove duplicate offenders that might occur if multiple rules apply to a single
// key and more than one of these rules are broken
std::set<TestResult::Offense, OffenseCompare> uniqueOffenders(
const std::set<TestResult::Offense, OffenseCompare> uniqueOffenders(
result.offenses.begin(), result.offenses.end()
);
result.offenses = std::vector<TestResult::Offense>(
uniqueOffenders.begin(), uniqueOffenders.end()
);
// Remove duplicate warnings. This should normally not happen, but we want to be sure
std::set<TestResult::Warning, WarningCompare> uniqueWarnings(
const std::set<TestResult::Warning, WarningCompare> uniqueWarnings(
result.warnings.begin(), result.warnings.end()
);
result.warnings = std::vector<TestResult::Warning>(
@@ -258,9 +258,9 @@ void testSpecificationAndThrow(const Documentation& documentation,
const ghoul::Dictionary& dictionary, std::string component)
{
// Perform testing against the documentation/specification
TestResult testResult = testSpecification(documentation, dictionary);
const TestResult testResult = testSpecification(documentation, dictionary);
if (!testResult.success) {
throw SpecificationError(testResult, component);
throw SpecificationError(testResult, std::move(component));
}
}
+175 -143
View File
@@ -138,9 +138,9 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict,
if (dict.hasKey(key)) {
if (dict.hasValue<double>(key)) {
// If we have a double value, we need to check if it is integer
double value = dict.value<double>(key);
double intPart;
bool isInt = modf(value, &intPart) == 0.0;
const double value = dict.value<double>(key);
double intPart = 0.0;
const bool isInt = modf(value, &intPart) == 0.0;
if (isInt) {
TestResult res;
res.success = true;
@@ -149,10 +149,11 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict,
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -160,20 +161,22 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict,
// If we don't have a double value, we cannot have an int value
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::MissingKey;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::MissingKey
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -195,12 +198,15 @@ TestResult StringVerifier::operator()(const ghoul::Dictionary& dictionary,
return res;
}
std::string value = dictionary.value<std::string>(key);
const std::string value = dictionary.value<std::string>(key);
if (value.empty() && _mustBeNotEmpty) {
res.success = false;
res.offenses.push_back({
key, TestResult::Offense::Reason::Verification, "value must not be empty"
});
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification,
.explanation = "value must not be empty"
};
res.offenses.push_back(std::move(o));
}
return res;
}
@@ -223,15 +229,16 @@ TestResult IdentifierVerifier::operator()(const ghoul::Dictionary& dict,
return res;
}
std::string identifier = dict.value<std::string>(key);
size_t pos = identifier.find_first_of(" \t\n\r.");
const std::string identifier = dict.value<std::string>(key);
const size_t pos = identifier.find_first_of(" \t\n\r.");
if (pos != std::string::npos) {
res.success = false;
TestResult::Offense off;
off.offender = key;
off.reason = TestResult::Offense::Reason::Verification;
off.explanation = "Identifier contained illegal character";
res.offenses.push_back(off);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification,
.explanation = "Identifier contained illegal character"
};
res.offenses.push_back(std::move(o));
}
return res;
}
@@ -254,14 +261,15 @@ TestResult FileVerifier::operator()(const ghoul::Dictionary& dict,
return res;
}
std::string file = dict.value<std::string>(key);
const std::string file = dict.value<std::string>(key);
if (!std::filesystem::exists(file) || !std::filesystem::is_regular_file(file)) {
res.success = false;
TestResult::Offense off;
off.offender = key;
off.reason = TestResult::Offense::Reason::Verification;
off.explanation = "File did not exist";
res.offenses.push_back(off);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification,
.explanation = "File did not exist"
};
res.offenses.push_back(std::move(o));
}
return res;
}
@@ -280,14 +288,15 @@ TestResult DirectoryVerifier::operator()(const ghoul::Dictionary& dict,
return res;
}
std::string dir = dict.value<std::string>(key);
const std::string dir = dict.value<std::string>(key);
if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
res.success = false;
TestResult::Offense off;
off.offender = key;
off.reason = TestResult::Offense::Reason::Verification;
off.explanation = "Directory did not exist";
res.offenses.push_back(off);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification,
.explanation = "Directory did not exist"
};
res.offenses.push_back(std::move(o));
}
return res;
}
@@ -306,8 +315,8 @@ TestResult DateTimeVerifier::operator()(const ghoul::Dictionary& dict,
return res;
}
std::string dateTime = dict.value<std::string>(key);
std::string format = "%Y %m %d %H:%M:%S"; // YYYY MM DD hh:mm:ss
const std::string dateTime = dict.value<std::string>(key);
const std::string format = "%Y %m %d %H:%M:%S"; // YYYY MM DD hh:mm:ss
std::tm t = {};
std::istringstream ss(dateTime);
@@ -316,11 +325,12 @@ TestResult DateTimeVerifier::operator()(const ghoul::Dictionary& dict,
// first check format (automatically checks if valid time)
if (ss.fail()) {
res.success = false;
TestResult::Offense off;
off.offender = key;
off.reason = TestResult::Offense::Reason::Verification;
off.explanation = "Not a valid format, should be: YYYY MM DD hh:mm:ss";
res.offenses.push_back(off);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification,
.explanation = "Not a valid format, should be: YYYY MM DD hh:mm:ss"
};
res.offenses.push_back(std::move(o));
}
return res;
}
@@ -337,36 +347,39 @@ TestResult Color3Verifier::operator()(const ghoul::Dictionary& dictionary,
return res;
}
glm::dvec3 values = dictionary.value<glm::dvec3>(key);
const glm::dvec3 values = dictionary.value<glm::dvec3>(key);
if (values.x < 0.0 || values.x > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".x";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".x",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
if (values.y < 0.0 || values.y > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".y";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".y",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
if (values.z < 0.0 || values.z > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".z";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".z",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
return res;
}
std::string Color3Verifier::type() const {
return std::string("Color3");
return "Color3";
}
TestResult Color4Verifier::operator()(const ghoul::Dictionary& dictionary,
@@ -377,44 +390,48 @@ TestResult Color4Verifier::operator()(const ghoul::Dictionary& dictionary,
return res;
}
glm::dvec4 values = dictionary.value<glm::dvec4>(key);
const glm::dvec4 values = dictionary.value<glm::dvec4>(key);
if (values.x < 0.0 || values.x > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".x";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".x",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
if (values.y < 0.0 || values.y > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".y";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".y",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
if (values.z < 0.0 || values.z > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".z";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".z",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
if (values.w < 0.0 || values.w > 1.0) {
res.success = false;
TestResult::Offense o;
o.offender = key + ".a";
o.reason = TestResult::Offense::Reason::Verification;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key + ".a",
.reason = TestResult::Offense::Reason::Verification
};
res.offenses.push_back(std::move(o));
}
return res;
}
std::string Color4Verifier::type() const {
return std::string("Color4");
return "Color4";
}
template <>
@@ -429,9 +446,9 @@ TestResult TemplateVerifier<glm::ivec2>::operator()(const ghoul::Dictionary& dic
else {
if (dict.hasKey(key)) {
if (dict.hasValue<glm::dvec2>(key)) {
glm::dvec2 value = dict.value<glm::dvec2>(key);
const glm::dvec2 value = dict.value<glm::dvec2>(key);
glm::dvec2 intPart;
glm::bvec2 isInt = glm::bvec2(
const glm::bvec2 isInt = glm::bvec2(
modf(value.x, &intPart.x) == 0.0,
modf(value.y, &intPart.y) == 0.0
);
@@ -443,30 +460,33 @@ TestResult TemplateVerifier<glm::ivec2>::operator()(const ghoul::Dictionary& dic
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::MissingKey;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::MissingKey
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -484,9 +504,9 @@ TestResult TemplateVerifier<glm::ivec3>::operator()(const ghoul::Dictionary& dic
else {
if (dict.hasKey(key)) {
if (dict.hasValue<glm::dvec3>(key)) {
glm::dvec3 value = dict.value<glm::dvec3>(key);
const glm::dvec3 value = dict.value<glm::dvec3>(key);
glm::dvec3 intPart;
glm::bvec3 isInt = glm::bvec3(
const glm::bvec3 isInt = glm::bvec3(
modf(value.x, &intPart.x) == 0.0,
modf(value.y, &intPart.y) == 0.0,
modf(value.z, &intPart.z) == 0.0
@@ -499,30 +519,33 @@ TestResult TemplateVerifier<glm::ivec3>::operator()(const ghoul::Dictionary& dic
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::MissingKey;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::MissingKey
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -540,46 +563,50 @@ TestResult TemplateVerifier<glm::ivec4>::operator()(const ghoul::Dictionary& dic
else {
if (dict.hasKey(key)) {
if (dict.hasValue<glm::dvec4>(key)) {
glm::dvec4 value = dict.value<glm::dvec4>(key);
const glm::dvec4 value = dict.value<glm::dvec4>(key);
glm::dvec4 intPart;
glm::bvec4 isInt = glm::bvec4(
const glm::bvec4 isInt = glm::bvec4(
modf(value.x, &intPart.x) == 0.0,
modf(value.y, &intPart.y) == 0.0,
modf(value.z, &intPart.z) == 0.0,
modf(value.w, &intPart.w) == 0.0
);
if (isInt.x && isInt.y && isInt.z && isInt.w) {
TestResult res;
res.success = true;
TestResult res = {
.success = true
};
return res;
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::MissingKey;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::MissingKey
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -593,8 +620,8 @@ TestResult TableVerifier::operator()(const ghoul::Dictionary& dictionary,
const std::string& key) const
{
if (dictionary.hasValue<Type>(key)) {
ghoul::Dictionary d = dictionary.value<ghoul::Dictionary>(key);
Documentation doc = { .entries = documentations };
const ghoul::Dictionary d = dictionary.value<ghoul::Dictionary>(key);
const Documentation doc = { .entries = documentations };
TestResult res = testSpecification(doc, d);
// Add the 'key' as a prefix to make the new offender a fully qualified identifer
@@ -613,19 +640,21 @@ TestResult TableVerifier::operator()(const ghoul::Dictionary& dictionary,
if (dictionary.hasKey(key)) {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::WrongType;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::WrongType
};
res.offenses.push_back(std::move(o));
return res;
}
else {
TestResult res;
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::MissingKey;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::MissingKey
};
res.offenses.push_back(std::move(o));
return res;
}
}
@@ -676,14 +705,15 @@ TestResult ReferencingVerifier::operator()(const ghoul::Dictionary& dictionary,
if (it == docs.end()) {
res.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::UnknownIdentifier;
res.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::UnknownIdentifier
};
res.offenses.push_back(std::move(o));
return res;
}
ghoul::Dictionary d = dictionary.value<ghoul::Dictionary>(key);
const ghoul::Dictionary d = dictionary.value<ghoul::Dictionary>(key);
TestResult r = testSpecification(*it, d);
// Add the 'key' as a prefix to make the offender a fully qualified identifer
@@ -708,7 +738,7 @@ std::string ReferencingVerifier::documentation() const {
}
OrVerifier::OrVerifier(
const std::vector<std::variant<Verifier*, std::shared_ptr<Verifier>>> values_)
const std::vector<std::variant<Verifier*, std::shared_ptr<Verifier>>>& values_)
{
ghoul_assert(!values_.empty(), "values must not be empty");
for (const std::variant<Verifier*, std::shared_ptr<Verifier>>& v : values_) {
@@ -741,17 +771,19 @@ TestResult OrVerifier::operator()(const ghoul::Dictionary& dictionary,
);
if (success) {
TestResult r;
r.success = true;
TestResult r = {
.success = true
};
return r;
}
else {
TestResult r;
r.success = false;
TestResult::Offense o;
o.offender = key;
o.reason = TestResult::Offense::Reason::Verification;
r.offenses.push_back(o);
TestResult::Offense o = {
.offender = key,
.reason = TestResult::Offense::Reason::Verification
};
r.offenses.push_back(std::move(o));
return r;
}
}
+13 -11
View File
@@ -340,8 +340,8 @@ ghoul::Dictionary Configuration::createDictionary() {
res.setValue("GlobalCustomizationScripts", globalCustomizationScriptsDict);
ghoul::Dictionary fontsDict;
for (auto it = fonts.begin(); it != fonts.end(); it++) {
fontsDict.setValue(it->first, it->second);
for (const auto& [name, path] : fonts) {
fontsDict.setValue(name, path);
}
res.setValue("Fonts", fontsDict);
@@ -413,8 +413,8 @@ ghoul::Dictionary Configuration::createDictionary() {
res.setValue("LayerServer", layerServerToString(layerServer));
ghoul::Dictionary moduleConfigurationsDict;
for (auto it = moduleConfigurations.begin(); it != moduleConfigurations.end(); it++) {
moduleConfigurationsDict.setValue(it->first, it->second);
for (const auto& [key, value] : moduleConfigurations) {
moduleConfigurationsDict.setValue(key, value);
}
res.setValue("ModuleConfigurations", moduleConfigurationsDict);
@@ -447,7 +447,7 @@ ghoul::Dictionary Configuration::createDictionary() {
static_cast<int>(openGLDebugContext.identifierFilters[i].identifier)
);
openGLDebugContextDict.setValue(std::to_string(i), identifierFilterDict);
identifierFiltersDict.setValue(std::to_string(i), identifierFilterDict);
}
}
openGLDebugContextDict.setValue("IdentifierFilters", identifierFiltersDict);
@@ -486,7 +486,7 @@ void parseLuaState(Configuration& configuration) {
// Shorten the rest of this function
Configuration& c = configuration;
LuaState& s = c.state;
const LuaState& s = c.state;
// The sgctConfigNameInitialized is a bit special
lua_getglobal(s, "sgctconfiginitializeString");
@@ -503,7 +503,9 @@ void parseLuaState(Configuration& configuration) {
// We go through all of the entries and lift them from global scope into the table on
// the stack so that we can create a ghoul::Dictionary from this new table
documentation::Documentation doc = codegen::doc<Parameters>("core_configuration");
const documentation::Documentation doc = codegen::doc<Parameters>(
"core_configuration"
);
for (const documentation::DocumentationEntry& e : doc.entries) {
lua_pushstring(s, e.key.c_str());
lua_getglobal(s, e.key.c_str());
@@ -544,7 +546,7 @@ void parseLuaState(Configuration& configuration) {
c.isPrintingEvents = p.printEvents.value_or(c.isPrintingEvents);
if (p.consoleKey.has_value()) {
KeyWithModifier km = stringToKey(*p.consoleKey);
const KeyWithModifier km = stringToKey(*p.consoleKey);
if (km.modifier != KeyModifier::None) {
throw ghoul::RuntimeError(fmt::format(
"Console key '{}' must be a 'bare' key and cannot contain any modifiers",
@@ -680,7 +682,7 @@ std::filesystem::path findConfiguration(const std::string& filename) {
}
// Otherwise, we traverse the directory tree up
std::filesystem::path nextDirectory = directory.parent_path();
const std::filesystem::path nextDirectory = directory.parent_path();
if (directory == nextDirectory) {
// We have reached the root of the file system and did not find the file
@@ -702,7 +704,7 @@ Configuration loadConfigurationFromFile(const std::filesystem::path& configurati
Configuration result;
// Injecting the resolution of the primary screen into the Lua state
std::string script = fmt::format(
const std::string script = fmt::format(
"ScreenResolution = {{ x = {}, y = {} }}",
primaryMonitorResolution.x, primaryMonitorResolution.y
);
@@ -719,7 +721,7 @@ Configuration loadConfigurationFromFile(const std::filesystem::path& configurati
parseLuaState(result);
if (std::filesystem::is_regular_file(settingsFile)) {
Settings settings = loadSettings(settingsFile);
const Settings settings = loadSettings(settingsFile);
patchConfiguration(result, settings);
}
+10 -10
View File
@@ -46,13 +46,13 @@ namespace {
};
size_t writeData(void* ptr, size_t size, size_t nmemb, FILE* stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
const size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
size_t writeMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t realsize = size * nmemb;
auto mem = static_cast<openspace::DownloadManager::MemoryFile*>(userp);
const size_t realsize = size * nmemb;
auto* mem = static_cast<openspace::DownloadManager::MemoryFile*>(userp);
// @TODO(abock): Remove this and replace mem->buffer with std::vector<char>
mem->buffer = reinterpret_cast<char*>(
@@ -128,7 +128,7 @@ std::shared_ptr<DownloadManager::FileFuture> DownloadManager::downloadFile(
FailOnError failOnError,
unsigned int timeout_secs,
DownloadFinishedCallback finishedCallback,
DownloadProgressCallback progressCallback)
DownloadProgressCallback progressCallback) const
{
if (!overrideFile && std::filesystem::is_regular_file(file)) {
return nullptr;
@@ -184,7 +184,7 @@ std::shared_ptr<DownloadManager::FileFuture> DownloadManager::downloadFile(
#endif
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
CURLcode res = curl_easy_perform(curl);
const CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
@@ -192,7 +192,7 @@ std::shared_ptr<DownloadManager::FileFuture> DownloadManager::downloadFile(
future->isFinished = true;
}
else {
long rescode;
long rescode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rescode);
future->errorMessage = fmt::format(
"{}. HTTP code: {}", curl_easy_strerror(res), rescode
@@ -256,7 +256,7 @@ std::future<DownloadManager::MemoryFile> DownloadManager::fetchFile(
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
// ask for the content-type
char* ct;
char* ct = nullptr;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if (res == CURLE_OK) {
std::string extension = std::string(ct);
@@ -293,8 +293,8 @@ std::future<DownloadManager::MemoryFile> DownloadManager::fetchFile(
return std::async(std::launch::async, downloadFunction);
}
void DownloadManager::getFileExtension(const std::string& url,
RequestFinishedCallback finishedCallback)
void DownloadManager::fileExtension(const std::string& url,
RequestFinishedCallback finishedCallback) const
{
auto requestFunction = [url, finishedCb = std::move(finishedCallback)]() {
CURL* curl = curl_easy_init();
@@ -304,7 +304,7 @@ void DownloadManager::getFileExtension(const std::string& url,
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
CURLcode res = curl_easy_perform(curl);
if (CURLE_OK == res) {
char* ct;
char* ct = nullptr;
// ask for the content-type
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if ((res == CURLE_OK) && ct && finishedCb) {
+11 -11
View File
@@ -98,25 +98,25 @@ documentation::Documentation LogFactoryDocumentation() {
std::unique_ptr<ghoul::logging::Log> createLog(const ghoul::Dictionary& dictionary) {
const Parameters p = codegen::bake<Parameters>(dictionary);
std::filesystem::path filename = absPath(p.file);
bool append = p.append.value_or(true);
int nLogRotation = p.logRotation.value_or(0);
bool timeStamp = p.timeStamping.value_or(true);
bool dateStamp = p.dateStamping.value_or(true);
bool categoryStamp = p.categoryStamping.value_or(true);
bool logLevelStamp = p.logLevelStamping.value_or(true);
ghoul::logging::LogLevel level = codegen::map<ghoul::logging::LogLevel>(
const std::filesystem::path filename = absPath(p.file);
const bool append = p.append.value_or(true);
const int nLogRotation = p.logRotation.value_or(0);
const bool timeStamp = p.timeStamping.value_or(true);
const bool dateStamp = p.dateStamping.value_or(true);
const bool categoryStamp = p.categoryStamping.value_or(true);
const bool logLevelStamp = p.logLevelStamping.value_or(true);
const ghoul::logging::LogLevel level = codegen::map<ghoul::logging::LogLevel>(
p.logLevel.value_or(Parameters::LogLevel::AllLogging)
);
switch (p.type) {
case Parameters::Type::Html:
{
std::vector<std::string> cssFiles{
const std::vector<std::string> cssFiles = {
absPath(BootstrapPath).string(),
absPath(CssPath).string()
};
std::vector<std::string> jsFiles{ absPath(JsPath).string() };
const std::vector<std::string> jsFiles = { absPath(JsPath).string() };
return std::make_unique<ghoul::logging::HTMLLog>(
filename.string(),
@@ -142,7 +142,7 @@ std::unique_ptr<ghoul::logging::Log> createLog(const ghoul::Dictionary& dictiona
level
);
default:
throw new ghoul::MissingCaseException();
throw ghoul::MissingCaseException();
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ void ModuleEngine::initialize(
{
ZoneScoped;
std::vector<OpenSpaceModule*> modules = AllModules();
const std::vector<OpenSpaceModule*> modules = AllModules();
std::vector<std::string> moduleNames;
moduleNames.reserve(modules.size());
+50 -41
View File
@@ -178,11 +178,17 @@ namespace {
}
void resetPropertyChangeFlags() {
using namespace openspace;
ZoneScoped;
std::vector<openspace::SceneGraphNode*> nodes =
openspace::global::renderEngine->scene()->allSceneGraphNodes();
for (openspace::SceneGraphNode* n : nodes) {
Scene* scene = global::renderEngine->scene();
if (!scene) {
return;
}
const std::vector<SceneGraphNode*> nodes = scene->allSceneGraphNodes();
for (SceneGraphNode* n : nodes) {
resetPropertyChangeFlagsOfSubowners(n);
}
}
@@ -300,10 +306,10 @@ void OpenSpaceEngine::initialize() {
ghoul::logging::LogManager::deinitialize();
}
ghoul::logging::LogLevel level = ghoul::from_string<ghoul::logging::LogLevel>(
const ghoul::logging::LogLevel level = ghoul::from_string<ghoul::logging::LogLevel>(
global::configuration->logging.level
);
bool immediateFlush = global::configuration->logging.forceImmediateFlush;
const bool immediateFlush = global::configuration->logging.forceImmediateFlush;
using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush;
ghoul::logging::LogManager::initialize(level, ImmediateFlush(immediateFlush));
@@ -341,9 +347,9 @@ void OpenSpaceEngine::initialize() {
while (rot > 0) {
// Move all of the existing logs one position up
std::filesystem::path file = absPath(global::configuration->scriptLog);
std::string fname = file.stem().string();
std::string ext = file.extension().string();
const std::filesystem::path file = absPath(global::configuration->scriptLog);
const std::string fname = file.stem().string();
const std::string ext = file.extension().string();
std::filesystem::path newCandidate = file;
newCandidate.replace_filename(fmt::format("{}-{}{}", fname, rot, ext));
@@ -393,10 +399,10 @@ void OpenSpaceEngine::initialize() {
// Process profile file
std::filesystem::path profile;
if (!std::filesystem::is_regular_file(global::configuration->profile)) {
std::filesystem::path userCandidate = absPath(fmt::format(
const std::filesystem::path userCandidate = absPath(fmt::format(
"${{USER_PROFILES}}/{}.profile", global::configuration->profile
));
std::filesystem::path profileCandidate = absPath(fmt::format(
const std::filesystem::path profileCandidate = absPath(fmt::format(
"${{PROFILES}}/{}.profile", global::configuration->profile
));
@@ -432,7 +438,7 @@ void OpenSpaceEngine::initialize() {
for (OpenSpaceModule* module : global::moduleEngine->modules()) {
global::scriptEngine->addLibrary(module->luaLibrary());
for (scripting::LuaLibrary& l : module->luaLibraries()) {
for (const scripting::LuaLibrary& l : module->luaLibraries()) {
global::scriptEngine->addLibrary(l);
}
}
@@ -472,7 +478,7 @@ void OpenSpaceEngine::initializeGL() {
SysCap.detectCapabilities();
using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity;
Verbosity verbosity = ghoul::from_string<Verbosity>(
const Verbosity verbosity = ghoul::from_string<Verbosity>(
global::configuration->logging.capabilitiesVerbosity
);
SysCap.logCapabilities(verbosity);
@@ -483,7 +489,7 @@ void OpenSpaceEngine::initializeGL() {
}
// Check the required OpenGL versions of the registered modules
ghoul::systemcapabilities::Version version =
const ghoul::systemcapabilities::Version version =
global::moduleEngine->requiredOpenGLVersion();
LINFO(fmt::format("Required OpenGL version: {}", ghoul::to_string(version)));
@@ -558,7 +564,7 @@ void OpenSpaceEngine::initializeGL() {
if (debugActive) {
using namespace ghoul::opengl::debug;
bool synchronous = global::configuration->openGLDebugContext.isSynchronous;
const bool synchronous = global::configuration->openGLDebugContext.isSynchronous;
setDebugOutput(DebugOutput(debugActive), SynchronousOutput(synchronous));
for (const Configuration::OpenGLDebugContext::IdentifierFilter& f :
@@ -586,7 +592,7 @@ void OpenSpaceEngine::initializeGL() {
ghoul::opengl::debug::setDebugCallback(
[](Source source, Type type, Severity severity, unsigned int id,
std::string message)
const std::string& message)
{
const std::string s = ghoul::to_string(source);
const std::string t = ghoul::to_string(type);
@@ -681,7 +687,9 @@ void OpenSpaceEngine::initializeGL() {
if (global::configuration->isLoggingOpenGLCalls) {
using namespace ghoul::logging;
LogLevel lvl = ghoul::from_string<LogLevel>(global::configuration->logging.level);
const LogLevel lvl = ghoul::from_string<LogLevel>(
global::configuration->logging.level
);
if (lvl > LogLevel::Trace) {
LWARNING(
"Logging OpenGL calls is enabled, but the selected log level does "
@@ -751,11 +759,11 @@ void OpenSpaceEngine::loadAssets() {
std::unique_ptr<SceneInitializer> sceneInitializer;
if (global::configuration->useMultithreadedInitialization) {
unsigned int nAvailableThreads = std::min(
const unsigned int nAvailableThreads = std::min(
std::thread::hardware_concurrency() - 1,
4u
);
unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads;
const unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads;
sceneInitializer = std::make_unique<MultiThreadedSceneInitializer>(nThreads);
}
else {
@@ -895,7 +903,7 @@ void OpenSpaceEngine::runGlobalCustomizationScripts() {
ZoneScoped;
LINFO("Running Global initialization scripts");
ghoul::lua::LuaState state;
const ghoul::lua::LuaState state;
global::scriptEngine->initializeLuaState(state);
for (const std::string& script : global::configuration->globalCustomizationScripts) {
@@ -929,7 +937,7 @@ void OpenSpaceEngine::loadFonts() {
}
LDEBUG(fmt::format("Registering font '{}' with key '{}'", fontName, key));
bool success = global::fontManager->registerFontPath(key, fontName);
const bool success = global::fontManager->registerFontPath(key, fontName);
if (!success) {
LERROR(fmt::format(
@@ -1023,7 +1031,7 @@ void OpenSpaceEngine::preSynchronization() {
global::windowDelegate->setSynchronization(false);
}
bool master = global::windowDelegate->isMaster();
const bool master = global::windowDelegate->isMaster();
global::syncEngine->preSynchronization(SyncEngine::IsMaster(master));
if (master) {
@@ -1034,10 +1042,10 @@ void OpenSpaceEngine::preSynchronization() {
global::timeManager->preSynchronization(dt);
std::vector<std::string> scheduledScripts = global::scriptScheduler->progressTo(
const std::vector<std::string> schedScripts = global::scriptScheduler->progressTo(
global::timeManager->time().j2000Seconds()
);
for (const std::string& script : scheduledScripts) {
for (const std::string& script : schedScripts) {
global::scriptEngine->queueScript(
script,
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
@@ -1088,7 +1096,7 @@ void OpenSpaceEngine::postSynchronizationPreDraw() {
TracyGpuZone("postSynchronizationPreDraw");
LTRACE("OpenSpaceEngine::postSynchronizationPreDraw(begin)");
bool master = global::windowDelegate->isMaster();
const bool master = global::windowDelegate->isMaster();
global::syncEngine->postSynchronization(SyncEngine::IsMaster(master));
if (_shutdown.inShutdown) {
@@ -1259,8 +1267,8 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio
}
if (!global::configuration->isConsoleDisabled) {
bool isConsoleConsumed = global::luaConsole->keyboardCallback(key, mod, action);
if (isConsoleConsumed) {
const bool isConsumed = global::luaConsole->keyboardCallback(key, mod, action);
if (isConsumed) {
return;
}
}
@@ -1280,7 +1288,7 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier,
ZoneScoped;
for (const global::callback::CharacterCallback& func : *global::callback::character) {
bool isConsumed = func(codepoint, modifier, isGuiWindow);
const bool isConsumed = func(codepoint, modifier, isGuiWindow);
if (isConsumed) {
return;
}
@@ -1327,7 +1335,8 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action
// Check if the user clicked on one of the 'buttons' the RenderEngine is drawing.
// Only handle the clicks if we are in a GUI window
if (action == MouseAction::Press && isGuiWindow) {
bool isConsumed = global::renderEngine->mouseActivationCallback(_mousePosition);
const bool isConsumed =
global::renderEngine->mouseActivationCallback(_mousePosition);
if (isConsumed) {
return;
}
@@ -1373,7 +1382,7 @@ void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY,
using F = global::callback::MouseScrollWheelCallback;
for (const F& func : *global::callback::mouseScrollWheel) {
bool isConsumed = func(posX, posY, isGuiWindow);
const bool isConsumed = func(posX, posY, isGuiWindow);
if (isConsumed) {
return;
}
@@ -1387,7 +1396,7 @@ void OpenSpaceEngine::touchDetectionCallback(TouchInput input) {
ZoneScoped;
for (const std::function<bool(TouchInput)>& func : *global::callback::touchDetected) {
bool isConsumed = func(input);
const bool isConsumed = func(input);
if (isConsumed) {
return;
}
@@ -1398,7 +1407,7 @@ void OpenSpaceEngine::touchUpdateCallback(TouchInput input) {
ZoneScoped;
for (const std::function<bool(TouchInput)>& func : *global::callback::touchUpdated) {
bool isConsumed = func(input);
const bool isConsumed = func(input);
if (isConsumed) {
return;
}
@@ -1414,11 +1423,11 @@ void OpenSpaceEngine::touchExitCallback(TouchInput input) {
}
void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) {
ghoul::lua::LuaState s(ghoul::lua::LuaState::IncludeStandardLibrary::Yes);
std::filesystem::path absolutePath = absPath("${SCRIPTS}/drag_drop_handler.lua");
int status = luaL_loadfile(s, absolutePath.string().c_str());
const ghoul::lua::LuaState s(ghoul::lua::LuaState::IncludeStandardLibrary::Yes);
const std::filesystem::path path = absPath("${SCRIPTS}/drag_drop_handler.lua");
int status = luaL_loadfile(s, path.string().c_str());
if (status != LUA_OK) {
std::string error = lua_tostring(s, -1);
const std::string error = lua_tostring(s, -1);
LERROR(error);
return;
}
@@ -1427,7 +1436,7 @@ void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) {
lua_setglobal(s, "filename");
std::string basename = file.filename().string();
ghoul::lua::push(s, basename);
ghoul::lua::push(s, std::move(basename));
lua_setglobal(s, "basename");
std::string extension = file.extension().string();
@@ -1438,7 +1447,7 @@ void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) {
status = lua_pcall(s, 0, 1, 0);
if (status != LUA_OK) {
std::string error = lua_tostring(s, -1);
const std::string error = lua_tostring(s, -1);
LERROR(error);
return;
}
@@ -1450,7 +1459,7 @@ void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) {
std::string script = ghoul::lua::value<std::string>(s);
global::scriptEngine->queueScript(
script,
std::move(script),
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
scripting::ScriptEngine::ShouldSendToRemote::Yes
);
@@ -1526,7 +1535,7 @@ void OpenSpaceEngine::resetMode() {
OpenSpaceEngine::CallbackHandle OpenSpaceEngine::addModeChangeCallback(
ModeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_modeChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
@@ -1652,12 +1661,12 @@ void setCameraFromProfile(const Profile& p) {
checkNodeExists(node.anchor);
NodeCameraStateSpec spec = {
NodeCameraStateSpec spc = {
.identifier = node.anchor,
.height = node.height,
.useTargetUpDirection = true
};
global::navigationHandler->setCameraFromNodeSpecNextFrame(spec);
global::navigationHandler->setCameraFromNodeSpecNextFrame(std::move(spc));
}
},
p.camera.value()
+9 -7
View File
@@ -100,8 +100,8 @@ namespace version1 {
std::filesystem::path findSettings(const std::string& filename) {
// Right now the settings file lives next to the openspace.cfg file
std::filesystem::path path = findConfiguration();
std::filesystem::path result = path.parent_path() / filename;
const std::filesystem::path path = findConfiguration();
const std::filesystem::path result = path.parent_path() / filename;
return result;
}
@@ -110,10 +110,12 @@ Settings loadSettings(const std::filesystem::path& filename) {
return Settings();
}
std::ifstream f(filename);
std::stringstream buffer;
buffer << f.rdbuf();
std::string contents = buffer.str();
{
const std::ifstream f = std::ifstream(filename);
buffer << f.rdbuf();
}
const std::string contents = buffer.str();
nlohmann::json setting = nlohmann::json::parse(contents);
if (setting.empty()) {
@@ -186,8 +188,8 @@ void saveSettings(const Settings& settings, const std::filesystem::path& filenam
json["mrf"] = mrf;
}
std::string content = json.dump(2);
std::ofstream f(filename);
std::ofstream f = std::ofstream(filename);
const std::string content = json.dump(2);
f << content;
}
+1 -1
View File
@@ -74,7 +74,7 @@ void log(int i, [[ maybe_unused ]] const EventProfileLoadingFinished& e) {
void log(int i, const EventApplicationShutdown& e) {
ghoul_assert(e.type == EventApplicationShutdown::Type, "Wrong type");
std::string t = [](EventApplicationShutdown::State state) {
const std::string t = [](EventApplicationShutdown::State state) {
switch (state) {
case EventApplicationShutdown::State::Started: return "started";
case EventApplicationShutdown::State::Aborted: return "aborted";
+4 -4
View File
@@ -80,14 +80,14 @@ void EventEngine::registerEventTopic(size_t topicId, events::Event::Type type,
{
TopicInfo ti;
ti.id = topicId;
ti.callback = callback;
ti.callback = std::move(callback);
_eventTopics[type].push_back(ti);
}
void EventEngine::unregisterEventAction(events::Event::Type type,
const std::string& identifier,
std::optional<ghoul::Dictionary> filter)
const std::optional<ghoul::Dictionary>& filter)
{
const auto it = _eventActions.find(type);
if (it != _eventActions.end()) {
@@ -204,7 +204,7 @@ void EventEngine::triggerActions() const {
while (e) {
const auto it = _eventActions.find(e->type);
if (it != _eventActions.end()) {
ghoul::Dictionary params = toParameter(*e);
const ghoul::Dictionary params = toParameter(*e);
for (const ActionInfo& ai : it->second) {
if (ai.isEnabled &&
(!ai.filter.has_value() || params.isSubset(*ai.filter)))
@@ -235,7 +235,7 @@ void EventEngine::triggerTopics() const {
const auto it = _eventTopics.find(e->type);
if (it != _eventTopics.end()) {
ghoul::Dictionary params = toParameter(*e);
const ghoul::Dictionary params = toParameter(*e);
for (const TopicInfo& ti : it->second) {
ti.callback(params);
}
+2 -2
View File
@@ -101,14 +101,14 @@ void ActionManager::triggerAction(const std::string& identifier,
if (!shouldBeSynchronized || a.isLocal) {
global::scriptEngine->queueScript(
script,
std::move(script),
scripting::ScriptEngine::ShouldBeSynchronized::No,
scripting::ScriptEngine::ShouldSendToRemote::No
);
}
else {
global::scriptEngine->queueScript(
script,
std::move(script),
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
scripting::ScriptEngine::ShouldSendToRemote::Yes
);
+1 -1
View File
@@ -84,7 +84,7 @@ void CameraInteractionStates::resetVelocities() {
_globalRollState.velocity.setHard({ 0.0, 0.0 });
}
bool CameraInteractionStates::hasNonZeroVelocities(bool checkOnlyMovement) {
bool CameraInteractionStates::hasNonZeroVelocities(bool checkOnlyMovement) const {
glm::dvec2 sum = glm::dvec2(0.0);
sum += globalRotationVelocity();
sum += truckMovementVelocity();
+10 -10
View File
@@ -47,7 +47,7 @@ void JoystickCameraStates::updateStateFromInput(
const JoystickInputStates& joystickInputStates,
double deltaTime)
{
OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
if (mode == OpenSpaceEngine::Mode::CameraPath ||
mode == OpenSpaceEngine::Mode::SessionRecordingPlayback)
{
@@ -71,7 +71,7 @@ void JoystickCameraStates::updateStateFromInput(
continue;
}
int nAxes = joystickInputStates.numAxes(joystickInputState.name);
const int nAxes = joystickInputStates.numAxes(joystickInputState.name);
for (int i = 0;
i < std::min(nAxes, static_cast<int>(joystick->axisMapping.size()));
i++)
@@ -81,7 +81,7 @@ void JoystickCameraStates::updateStateFromInput(
continue;
}
float rawValue = joystickInputStates.axis(joystickInputState.name, i);
const float rawValue = joystickInputStates.axis(joystickInputState.name, i);
float value = rawValue;
if (t.isSticky) {
@@ -162,7 +162,7 @@ void JoystickCameraStates::updateStateFromInput(
localRotation.second.y += value;
break;
case AxisType::Property:
std::string script = fmt::format(
const std::string script = fmt::format(
"openspace.setPropertyValue('{}', {});",
t.propertyUri, value
);
@@ -176,11 +176,11 @@ void JoystickCameraStates::updateStateFromInput(
}
}
int nButtons = joystickInputStates.numButtons(joystickInputState.name);
const int nButtons = joystickInputStates.numButtons(joystickInputState.name);
for (int i = 0; i < nButtons; i++) {
auto itRange = joystick->buttonMapping.equal_range(i);
for (auto it = itRange.first; it != itRange.second; it++) {
bool active = global::joystickInputStates->button(
const bool active = global::joystickInputStates->button(
joystickInputState.name,
i,
it->second.action
@@ -237,7 +237,7 @@ void JoystickCameraStates::updateStateFromInput(
}
}
void JoystickCameraStates::setAxisMapping(std::string joystickName,
void JoystickCameraStates::setAxisMapping(const std::string& joystickName,
int axis, AxisType mapping,
AxisInvert shouldInvert,
JoystickType joystickType,
@@ -267,7 +267,7 @@ void JoystickCameraStates::setAxisMapping(std::string joystickName,
global::joystickInputStates->axis(joystickName, axis);
}
void JoystickCameraStates::setAxisMappingProperty(std::string joystickName,
void JoystickCameraStates::setAxisMappingProperty(const std::string& joystickName,
int axis,
std::string propertyUri,
float min, float max,
@@ -287,7 +287,7 @@ void JoystickCameraStates::setAxisMappingProperty(std::string joystickName,
joystickCameraState->axisMapping[axis].type = AxisType::Property;
joystickCameraState->axisMapping[axis].invert = shouldInvert;
joystickCameraState->axisMapping[axis].propertyUri = propertyUri;
joystickCameraState->axisMapping[axis].propertyUri = std::move(propertyUri);
joystickCameraState->axisMapping[axis].minValue = min;
joystickCameraState->axisMapping[axis].maxValue = max;
joystickCameraState->axisMapping[axis].isRemote = isRemote;
@@ -431,7 +431,7 @@ JoystickCameraStates::findOrAddJoystickCameraState(const std::string& joystickNa
JoystickCameraState* joystick = joystickCameraState(joystickName);
if (!joystick) {
if (_joystickCameraStates.size() < JoystickInputStates::MaxNumJoysticks) {
_joystickCameraStates.push_back(JoystickCameraState());
_joystickCameraStates.emplace_back();
joystick = &_joystickCameraStates.back();
joystick->joystickName = joystickName;
}
+20 -29
View File
@@ -44,9 +44,9 @@ int JoystickInputStates::numAxes(const std::string& joystickName) const {
return maxNumAxes;
}
for (auto it = begin(); it < end(); it++) {
if (it->name == joystickName) {
return it->nAxes;
for (const JoystickInputState& state : *this) {
if (state.name == joystickName) {
return state.nAxes;
}
}
return -1;
@@ -55,19 +55,20 @@ int JoystickInputStates::numAxes(const std::string& joystickName) const {
int JoystickInputStates::numButtons(const std::string& joystickName) const {
if (joystickName.empty()) {
int maxNumButtons = -1;
for (auto it = begin(); it < end(); it++) {
if (it->nButtons > maxNumButtons) {
maxNumButtons = it->nButtons;
for (const JoystickInputState& state : *this) {
if (state.nButtons > maxNumButtons) {
maxNumButtons = state.nButtons;
}
}
return maxNumButtons;
}
for (auto it = begin(); it < end(); it++) {
if (it->name == joystickName) {
return it->nButtons;
for (const JoystickInputState& state : *this) {
if (state.name == joystickName) {
return state.nButtons;
}
}
return -1;
}
@@ -75,7 +76,7 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const
ghoul_precondition(axis >= 0, "axis must be 0 or positive");
if (joystickName.empty()) {
float res = std::accumulate(
const float res = std::accumulate(
begin(),
end(),
0.f,
@@ -93,18 +94,13 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const
return res;
}
const JoystickInputState* state = nullptr;
for (auto it = begin(); it < end(); it++) {
if (it->name == joystickName) {
state = &(*it);
for (const JoystickInputState& state : *this) {
if (state.name == joystickName) {
return state.axes[axis];
}
}
if (!state) {
return 0.f;
}
return state->axes[axis];
return 0.f;
}
bool JoystickInputStates::button(const std::string& joystickName, int button,
@@ -113,7 +109,7 @@ bool JoystickInputStates::button(const std::string& joystickName, int button,
ghoul_precondition(button >= 0, "button must be 0 or positive");
if (joystickName.empty()) {
bool res = std::any_of(
const bool res = std::any_of(
begin(),
end(),
[button, action](const JoystickInputState& state) {
@@ -123,18 +119,13 @@ bool JoystickInputStates::button(const std::string& joystickName, int button,
return res;
}
const JoystickInputState* state = nullptr;
for (auto it = begin(); it < end(); it++) {
if (it->name == joystickName) {
state = &(*it);
for (const JoystickInputState& state : *this) {
if (state.name == joystickName) {
return state.isConnected ? (state.buttons[button] == action) : false;
}
}
if (!state) {
return false;
}
return state->isConnected ? (state->buttons[button] == action) : false;
return false;
}
} // namespace openspace::interaction
+1 -3
View File
@@ -38,8 +38,6 @@
namespace openspace::interaction {
KeybindingManager::KeybindingManager() {}
void KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)
{
if (action == KeyAction::Press || action == KeyAction::Repeat) {
@@ -78,7 +76,7 @@ void KeybindingManager::bindKey(Key key, KeyModifier modifier, std::string actio
#endif // WIN32
ghoul_assert(!action.empty(), "Action must not be empty");
KeyWithModifier km = { key, modifier };
const KeyWithModifier km = { key, modifier };
_keyLua.insert({ km, std::move(action) });
}
+27 -24
View File
@@ -38,32 +38,35 @@ MouseCameraStates::MouseCameraStates(double sensitivity, double velocityScaleFac
: CameraInteractionStates(sensitivity, velocityScaleFactor)
{}
void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputState,
const KeyboardInputState& keyboardinputState,
void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseState,
const KeyboardInputState& keyboardState,
double deltaTime)
{
MouseButton primary =
const MouseButton primary =
_isMouseButtonInverted ? MouseButton::Button2 : MouseButton::Button1;
MouseButton secondary =
const MouseButton secondary =
_isMouseButtonInverted ? MouseButton::Button1 : MouseButton::Button2;
glm::dvec2 mousePosition = mouseinputState.mousePosition();
const glm::dvec2 mousePosition = mouseState.mousePosition();
bool primaryPressed = mouseinputState.isMouseButtonPressed(primary);
bool secondaryPressed = mouseinputState.isMouseButtonPressed(secondary);
bool button3Pressed = mouseinputState.isMouseButtonPressed(MouseButton::Button3);
bool keyCtrlPressed = keyboardinputState.isKeyPressed(Key::LeftControl) ||
keyboardinputState.isKeyPressed(Key::RightControl);
bool keyShiftPressed = keyboardinputState.isKeyPressed(Key::LeftShift) ||
keyboardinputState.isKeyPressed(Key::RightShift);
bool keyAltPressed = keyboardinputState.isKeyPressed(Key::LeftAlt) ||
keyboardinputState.isKeyPressed(Key::RightAlt);
const bool primaryPressed = mouseState.isMouseButtonPressed(primary);
const bool secondaryPressed = mouseState.isMouseButtonPressed(secondary);
const bool button3Pressed = mouseState.isMouseButtonPressed(MouseButton::Button3);
const bool keyCtrlPressed =
keyboardState.isKeyPressed(Key::LeftControl) ||
keyboardState.isKeyPressed(Key::RightControl);
const bool keyShiftPressed =
keyboardState.isKeyPressed(Key::LeftShift) ||
keyboardState.isKeyPressed(Key::RightShift);
const bool keyAltPressed =
keyboardState.isKeyPressed(Key::LeftAlt) ||
keyboardState.isKeyPressed(Key::RightAlt);
// Update the mouse states
if (primaryPressed && !keyShiftPressed && !keyAltPressed) {
if (keyCtrlPressed) {
glm::dvec2 mousePositionDelta = _localRotationState.previousPosition -
mousePosition;
const glm::dvec2 mousePositionDelta =
_localRotationState.previousPosition - mousePosition;
_localRotationState.velocity.set(
mousePositionDelta * _sensitivity,
deltaTime
@@ -73,8 +76,8 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt
_globalRotationState.velocity.decelerate(deltaTime);
}
else {
glm::dvec2 mousePositionDelta = _globalRotationState.previousPosition -
mousePosition;
const glm::dvec2 mousePositionDelta =
_globalRotationState.previousPosition - mousePosition;
_globalRotationState.velocity.set(
mousePositionDelta * _sensitivity,
deltaTime
@@ -92,14 +95,14 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt
_globalRotationState.velocity.decelerate(deltaTime);
}
if (secondaryPressed || (keyAltPressed && primaryPressed)) {
glm::dvec2 mousePositionDelta = _truckMovementState.previousPosition -
mousePosition;
const glm::dvec2 mousePositionDelta =
_truckMovementState.previousPosition - mousePosition;
double sensitivity = _sensitivity;
if (keyboardinputState.isKeyPressed(Key::Z)) {
if (keyboardState.isKeyPressed(Key::Z)) {
sensitivity *= SENSITIVITY_ADJUSTMENT_INCREASE;
}
else if (keyboardinputState.isKeyPressed(Key::X)) {
else if (keyboardState.isKeyPressed(Key::X)) {
sensitivity *= SENSITIVITY_ADJUSTMENT_DECREASE;
}
@@ -114,7 +117,7 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt
}
if (button3Pressed || (keyShiftPressed && primaryPressed)) {
if (keyCtrlPressed) {
glm::dvec2 mousePositionDelta = _localRollState.previousPosition -
const glm::dvec2 mousePositionDelta = _localRollState.previousPosition -
mousePosition;
_localRollState.velocity.set(
mousePositionDelta * _sensitivity,
@@ -125,7 +128,7 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt
_globalRollState.velocity.decelerate(deltaTime);
}
else {
glm::dvec2 mousePositionDelta = _globalRollState.previousPosition -
const glm::dvec2 mousePositionDelta = _globalRollState.previousPosition -
mousePosition;
_globalRollState.velocity.set(
mousePositionDelta * _sensitivity,
+146 -151
View File
@@ -120,9 +120,6 @@ SessionRecording::SessionRecording(bool isGlobal)
}
}
SessionRecording::~SessionRecording() {
}
void SessionRecording::deinitialize() {
stopRecording();
stopPlayback();
@@ -132,7 +129,9 @@ void SessionRecording::setRecordDataFormat(DataMode dataMode) {
_recordingDataMode = dataMode;
}
bool SessionRecording::hasFileExtension(std::string filename, std::string extension) {
bool SessionRecording::hasFileExtension(const std::string& filename,
const std::string& extension)
{
if (filename.length() <= extension.length()) {
return false;
}
@@ -142,12 +141,12 @@ bool SessionRecording::hasFileExtension(std::string filename, std::string extens
}
bool SessionRecording::isPath(std::string& filename) {
size_t unixDelimiter = filename.find("/");
size_t windowsDelimiter = filename.find("\\");
const size_t unixDelimiter = filename.find('/');
const size_t windowsDelimiter = filename.find('\\');
return (unixDelimiter != std::string::npos || windowsDelimiter != std::string::npos);
}
void SessionRecording::removeTrailingPathSlashes(std::string& filename) {
void SessionRecording::removeTrailingPathSlashes(std::string& filename) const {
while (filename.substr(filename.length() - 1, 1) == "/") {
filename.pop_back();
}
@@ -219,7 +218,7 @@ bool SessionRecording::startRecording(const std::string& filename) {
std::filesystem::create_directories(absPath("${RECORDINGS}"));
}
bool recordingFileOK = handleRecordingFile(filename);
const bool recordingFileOK = handleRecordingFile(filename);
if (recordingFileOK) {
_state = SessionState::Recording;
@@ -260,17 +259,17 @@ bool SessionRecording::startRecording(const std::string& filename) {
}
void SessionRecording::recordCurrentTimePauseState() {
bool isPaused = global::timeManager->isPaused();
const bool isPaused = global::timeManager->isPaused();
std::string initialTimePausedCommand = "openspace.time.setPause(" +
std::string(isPaused ? "true" : "false") + ")";
saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand);
saveScriptKeyframeToPropertiesBaseline(std::move(initialTimePausedCommand));
}
void SessionRecording::recordCurrentTimeRate() {
std::string initialTimeRateCommand = fmt::format(
"openspace.time.setDeltaTime({})", global::timeManager->targetDeltaTime()
);
saveScriptKeyframeToPropertiesBaseline(initialTimeRateCommand);
saveScriptKeyframeToPropertiesBaseline(std::move(initialTimeRateCommand));
}
void SessionRecording::stopRecording() {
@@ -300,8 +299,8 @@ void SessionRecording::stopRecording() {
std::move(kf.position),
std::move(kf.rotation),
std::move(kf.focusNode),
std::move(kf.followFocusNodeRotation),
std::move(kf.scale)
kf.followFocusNodeRotation,
kf.scale
);
saveSingleKeyframeCamera(
kfMsg,
@@ -390,7 +389,7 @@ bool SessionRecording::startPlayback(std::string& filename,
// Open in ASCII first
_playbackFile.open(_playbackFilename, std::ifstream::in);
// Read header
std::string readBackHeaderString = readHeaderElement(
const std::string readBackHeaderString = readHeaderElement(
_playbackFile,
FileHeaderTitle.length()
);
@@ -419,7 +418,7 @@ bool SessionRecording::startPlayback(std::string& filename,
// past the header, version, and data type
_playbackFile.close();
_playbackFile.open(_playbackFilename, std::ifstream::in | std::ios::binary);
size_t headerSize = FileHeaderTitle.length() + FileHeaderVersionLength
const size_t headerSize = FileHeaderTitle.length() + FileHeaderVersionLength
+ sizeof(DataFormatBinaryTag) + sizeof('\n');
std::vector<char> hBuffer;
hBuffer.resize(headerSize);
@@ -456,7 +455,7 @@ bool SessionRecording::startPlayback(std::string& filename,
return false;
}
bool canTriggerPlayback = global::openSpaceEngine->setMode(
const bool canTriggerPlayback = global::openSpaceEngine->setMode(
OpenSpaceEngine::Mode::SessionRecordingPlayback
);
@@ -512,7 +511,7 @@ bool SessionRecording::initializePlayback_timeline() {
return false;
}
if (_playbackForceSimTimeAtStart) {
Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps;
const Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps;
global::timeManager->setTimeNextFrame(Time(times.timeSim));
_saveRenderingCurrentRecordedTime = times.timeRec;
}
@@ -640,9 +639,9 @@ void SessionRecording::cleanUpPlayback() {
ghoul_assert(camera != nullptr, "Camera must not be nullptr");
Scene* scene = camera->parent()->scene();
if (!_timeline.empty()) {
unsigned int p =
const unsigned int p =
_timeline[_idxTimeline_cameraPtrPrev].idxIntoKeyframeTypeArray;
if (_keyframesCamera.size() > 0) {
if (!_keyframesCamera.empty()) {
const SceneGraphNode* n = scene->sceneGraphNode(
_keyframesCamera[p].focusNode
);
@@ -728,7 +727,7 @@ void SessionRecording::saveStringToFile(const std::string& s,
std::ofstream& file)
{
size_t strLen = s.size();
size_t writeSize_bytes = sizeof(size_t);
const size_t writeSize_bytes = sizeof(size_t);
idx = 0;
unsigned char const *p = reinterpret_cast<unsigned char const*>(&strLen);
@@ -740,18 +739,18 @@ void SessionRecording::saveStringToFile(const std::string& s,
}
bool SessionRecording::hasCameraChangedFromPrev(
datamessagestructures::CameraKeyframe kfNew)
const datamessagestructures::CameraKeyframe& kfNew)
{
constexpr double threshold = 1e-2;
bool hasChanged = false;
glm::dvec3 positionDiff = kfNew._position - _prevRecordedCameraKeyframe._position;
if (glm::length(positionDiff) > threshold) {
const glm::dvec3 position = kfNew._position - _prevRecordedCameraKeyframe._position;
if (glm::length(position) > threshold) {
hasChanged = true;
}
double rotationDiff = dot(kfNew._rotation, _prevRecordedCameraKeyframe._rotation);
if (std::abs(rotationDiff - 1.0) > threshold) {
const double rotation = dot(kfNew._rotation, _prevRecordedCameraKeyframe._rotation);
if (std::abs(rotation - 1.0) > threshold) {
hasChanged = true;
}
@@ -759,10 +758,12 @@ bool SessionRecording::hasCameraChangedFromPrev(
return hasChanged;
}
SessionRecording::Timestamps SessionRecording::generateCurrentTimestamp3(double kfTime) {
SessionRecording::Timestamps SessionRecording::generateCurrentTimestamp3(
double keyframeTime) const
{
return {
kfTime,
kfTime - _timestampRecordStarted,
keyframeTime,
keyframeTime - _timestampRecordStarted,
global::timeManager->time().j2000Seconds()
};
}
@@ -780,7 +781,7 @@ void SessionRecording::saveCameraKeyframeToTimeline() {
Timestamps times = generateCurrentTimestamp3(kf._timestamp);
interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf));
addKeyframe(times, pbFrame, _recordingEntryNum++);
addKeyframe(std::move(times), std::move(pbFrame), _recordingEntryNum++);
}
void SessionRecording::saveHeaderBinary(Timestamps& times,
@@ -825,7 +826,7 @@ void SessionRecording::saveCameraKeyframeAscii(Timestamps& times,
{
if (_addModelMatrixinAscii) {
SceneGraphNode* node = sceneGraphNode(kf._focusNode);
glm::dmat4 modelTransform = node->modelTransform();
const glm::dmat4 modelTransform = node->modelTransform();
file << HeaderCommentAscii << ' ' << ghoul::to_string(modelTransform) << '\n';
}
@@ -838,11 +839,11 @@ void SessionRecording::saveCameraKeyframeAscii(Timestamps& times,
void SessionRecording::saveTimeKeyframeToTimeline() {
// Create a time keyframe, then call to populate it with current time props
datamessagestructures::TimeKeyframe kf =
const datamessagestructures::TimeKeyframe kf =
datamessagestructures::generateTimeKeyframe();
Timestamps times = generateCurrentTimestamp3(kf._timestamp);
addKeyframe(times, kf, _recordingEntryNum++);
addKeyframe(std::move(times), kf, _recordingEntryNum++);
}
void SessionRecording::saveTimeKeyframeBinary(Timestamps& times,
@@ -869,33 +870,28 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times,
}
void SessionRecording::saveScriptKeyframeToTimeline(std::string script) {
if (doesStartWithSubstring(script, scriptReturnPrefix)) {
if (script.starts_with(scriptReturnPrefix)) {
script = script.substr(scriptReturnPrefix.length());
}
for (std::string reject : _scriptRejects) {
if (doesStartWithSubstring(script, reject)) {
for (const std::string& reject : _scriptRejects) {
if (script.starts_with(reject)) {
return;
}
}
trimCommandsFromScriptIfFound(script);
replaceCommandsFromScriptIfFound(script);
datamessagestructures::ScriptMessage sm
const datamessagestructures::ScriptMessage sm
= datamessagestructures::generateScriptMessage(script);
Timestamps times = generateCurrentTimestamp3(sm._timestamp);
addKeyframe(times, sm._script, _playbackLineNum);
}
bool SessionRecording::doesStartWithSubstring(const std::string& s,
const std::string& matchSubstr)
{
return s.substr(0, matchSubstr.length()) == matchSubstr;
addKeyframe(std::move(times), sm._script, _playbackLineNum);
}
void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script) {
Timestamps times =
generateCurrentTimestamp3(global::windowDelegate->applicationTime());
size_t indexIntoScriptKeyframesFromMainTimeline =
const Timestamps times = generateCurrentTimestamp3(
global::windowDelegate->applicationTime()
);
const size_t indexIntoScriptKeyframesFromMainTimeline =
_keyframesSavePropertiesBaseline_scripts.size();
_keyframesSavePropertiesBaseline_scripts.push_back(std::move(script));
addKeyframeToTimeline(
@@ -908,7 +904,7 @@ void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script
}
void SessionRecording::trimCommandsFromScriptIfFound(std::string& script) {
for (std::string trimSnippet : _scriptsToBeTrimmed) {
for (const std::string& trimSnippet : _scriptsToBeTrimmed) {
auto findIdx = script.find(trimSnippet);
if (findIdx != std::string::npos) {
auto findClosingParens = script.find_first_of(')', findIdx);
@@ -918,7 +914,7 @@ void SessionRecording::trimCommandsFromScriptIfFound(std::string& script) {
}
void SessionRecording::replaceCommandsFromScriptIfFound(std::string& script) {
for (ScriptSubstringReplace replacementSnippet : _scriptsToBeReplaced) {
for (const ScriptSubstringReplace& replacementSnippet : _scriptsToBeReplaced) {
auto findIdx = script.find(replacementSnippet.substringFound);
if (findIdx != std::string::npos) {
script.erase(findIdx, replacementSnippet.substringFound.length());
@@ -950,24 +946,24 @@ void SessionRecording::saveScriptKeyframeAscii(Timestamps& times,
// Erase all \r (from windows newline), and all \n from line endings and replace with
// ';' so that lua will treat them as separate lines. This is done in order to treat
// a multi-line script as a single line in the file.
size_t startPos = sm._script.find("\r", 0);
size_t startPos = sm._script.find('\r', 0);
while (startPos != std::string::npos) {
sm._script.erase(startPos, 1);
startPos = sm._script.find("\r", startPos);
startPos = sm._script.find('\r', startPos);
}
startPos = sm._script.find("\n", 0);
startPos = sm._script.find('\n', 0);
while (startPos != std::string::npos) {
sm._script.replace(startPos, 1, ";");
startPos = sm._script.find("\n", startPos);
startPos = sm._script.find('\n', startPos);
}
sm.write(keyframeLine);
saveKeyframeToFile(keyframeLine.str(), file);
}
void SessionRecording::savePropertyBaseline(properties::Property& prop) {
std::string propIdentifier = prop.fullyQualifiedIdentifier();
const std::string propIdentifier = prop.fullyQualifiedIdentifier();
if (isPropertyAllowedForBaseline(propIdentifier)) {
bool isPropAlreadySaved = (
const bool isPropAlreadySaved = (
std::find(
_propertyBaselinesSaved.begin(),
_propertyBaselinesSaved.end(),
@@ -976,7 +972,7 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) {
!= _propertyBaselinesSaved.end()
);
if (!isPropAlreadySaved) {
std::string initialScriptCommand = fmt::format(
const std::string initialScriptCommand = fmt::format(
"openspace.setPropertyValueSingle(\"{}\", {})",
propIdentifier, prop.stringValue()
);
@@ -987,8 +983,8 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) {
}
bool SessionRecording::isPropertyAllowedForBaseline(const std::string& propString) {
for (std::string reject : _propertyBaselineRejects) {
if (doesStartWithSubstring(propString, reject)) {
for (const std::string& reject : _propertyBaselineRejects) {
if (propString.starts_with(reject)) {
return false;
}
}
@@ -1035,15 +1031,15 @@ void SessionRecording::render() {
constexpr std::string_view FontName = "Mono";
constexpr float FontSizeFrameinfo = 32.f;
std::shared_ptr<ghoul::fontrendering::Font> font =
const std::shared_ptr<ghoul::fontrendering::Font> font =
global::fontManager->font(FontName, FontSizeFrameinfo);
glm::vec2 res = global::renderEngine->fontResolution();
const glm::vec2 res = global::renderEngine->fontResolution();
glm::vec2 penPosition = glm::vec2(
res.x / 2 - 150.f,
res.y / 4
);
std::string text1 = std::to_string(currentTime());
const std::string text1 = std::to_string(currentTime());
ghoul::fontrendering::RenderFont(
*font,
penPosition,
@@ -1051,7 +1047,7 @@ void SessionRecording::render() {
glm::vec4(1.f),
ghoul::fontrendering::CrDirection::Down
);
std::string text2 = fmt::format(
const std::string text2 = fmt::format(
"Scale: {}", global::navigationHandler->camera()->scaling()
);
ghoul::fontrendering::RenderFont(*font, penPosition, text2, glm::vec4(1.f));
@@ -1251,7 +1247,7 @@ bool SessionRecording::playbackCamera() {
_playbackLineNum
);
interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf));
const interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf));
if (success) {
success = addKeyframe(
{times.timeOs, times.timeRec, times.timeSim},
@@ -1269,7 +1265,7 @@ bool SessionRecording::convertCamera(std::stringstream& inStream, DataMode mode,
Timestamps times;
datamessagestructures::CameraKeyframe kf;
bool success = readSingleKeyframeCamera(
const bool success = readSingleKeyframeCamera(
kf,
times,
mode,
@@ -1353,13 +1349,11 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times,
bool SessionRecording::readCameraKeyframeAscii(Timestamps& times,
datamessagestructures::CameraKeyframe& kf,
std::string currentParsingLine,
const std::string& currentParsingLine,
int lineN)
{
std::string rotationFollowing;
std::istringstream iss = std::istringstream(currentParsingLine);
std::string entryType;
std::istringstream iss(currentParsingLine);
iss >> entryType;
iss >> times.timeOs >> times.timeRec >> times.timeSim;
kf.read(iss);
@@ -1404,7 +1398,7 @@ bool SessionRecording::convertTimeChange(std::stringstream& inStream, DataMode m
Timestamps times;
datamessagestructures::TimeKeyframe kf;
bool success = readSingleKeyframeTime(
const bool success = readSingleKeyframeTime(
kf,
times,
mode,
@@ -1484,7 +1478,7 @@ bool SessionRecording::readTimeKeyframeBinary(Timestamps& times,
bool SessionRecording::readTimeKeyframeAscii(Timestamps& times,
datamessagestructures::TimeKeyframe& kf,
std::string currentParsingLine,
const std::string& currentParsingLine,
int lineN)
{
std::string entryType;
@@ -1504,18 +1498,18 @@ bool SessionRecording::readTimeKeyframeAscii(Timestamps& times,
}
std::string SessionRecording::readHeaderElement(std::ifstream& stream,
size_t readLen_chars)
size_t readLenChars)
{
std::vector<char> readTemp(readLen_chars);
stream.read(&readTemp[0], readLen_chars);
std::vector<char> readTemp(readLenChars);
stream.read(readTemp.data(), readLenChars);
return std::string(readTemp.begin(), readTemp.end());
}
std::string SessionRecording::readHeaderElement(std::stringstream& stream,
size_t readLen_chars)
size_t readLenChars)
{
std::vector<char> readTemp(readLen_chars);
stream.read(&readTemp[0], readLen_chars);
std::vector<char> readTemp = std::vector<char>(readLenChars);
stream.read(readTemp.data(), readLenChars);
return std::string(readTemp.begin(), readTemp.end());
}
@@ -1545,7 +1539,7 @@ bool SessionRecording::playbackScript() {
}
void SessionRecording::populateListofLoadedSceneGraphNodes() {
std::vector<SceneGraphNode*> nodes =
const std::vector<SceneGraphNode*> nodes =
global::renderEngine->scene()->allSceneGraphNodes();
for (SceneGraphNode* n : nodes) {
_loadedNodes.push_back(n->identifier());
@@ -1557,16 +1551,15 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) {
s.erase(0, scriptReturnPrefix.length());
}
// This works for both setPropertyValue and setPropertyValueSingle
bool containsSetPropertyVal = (s.rfind("openspace.setPropertyValue", 0) == 0);
bool containsParensStart = (s.find("(") != std::string::npos);
const bool containsSetPropertyVal = (s.rfind("openspace.setPropertyValue", 0) == 0);
const bool containsParensStart = (s.find('(') != std::string::npos);
if (containsSetPropertyVal && containsParensStart) {
std::string subjectOfSetProp = isolateTermFromQuotes(s.substr(s.find("(") + 1));
std::string subjectOfSetProp = isolateTermFromQuotes(s.substr(s.find('(') + 1));
if (checkForScenegraphNodeAccessNav(subjectOfSetProp)) {
size_t commaPos = s.find(",");
const size_t commaPos = s.find(',');
std::string navNode = isolateTermFromQuotes(s.substr(commaPos + 1));
if (navNode != "nil") {
std::vector<std::string>::iterator it =
std::find(_loadedNodes.begin(), _loadedNodes.end(), navNode);
auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), navNode);
if (it == _loadedNodes.end()) {
LWARNING(fmt::format(
"Playback file contains a property setting of navigation using "
@@ -1578,7 +1571,7 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) {
else if (checkForScenegraphNodeAccessScene(subjectOfSetProp)) {
std::string found = extractScenegraphNodeFromScene(subjectOfSetProp);
if (!found.empty()) {
std::vector<properties::Property*> matchHits =
const std::vector<properties::Property*> matchHits =
global::renderEngine->scene()->propertiesMatchingRegex(
subjectOfSetProp
);
@@ -1593,17 +1586,17 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) {
}
}
bool SessionRecording::checkForScenegraphNodeAccessScene(std::string& s) {
bool SessionRecording::checkForScenegraphNodeAccessScene(const std::string& s) {
const std::string scene = "Scene.";
return (s.find(scene) != std::string::npos);
}
std::string SessionRecording::extractScenegraphNodeFromScene(std::string& s) {
std::string SessionRecording::extractScenegraphNodeFromScene(const std::string& s) {
const std::string scene = "Scene.";
std::string extracted;
size_t posScene = s.find(scene);
const size_t posScene = s.find(scene);
if (posScene != std::string::npos) {
size_t posDot = s.find(".", posScene + scene.length() + 1);
const size_t posDot = s.find('.', posScene + scene.length() + 1);
if (posDot > posScene && posDot != std::string::npos) {
extracted = s.substr(posScene + scene.length(), posDot -
(posScene + scene.length()));
@@ -1614,9 +1607,9 @@ std::string SessionRecording::extractScenegraphNodeFromScene(std::string& s) {
bool SessionRecording::checkForScenegraphNodeAccessNav(std::string& navTerm) {
const std::string nextTerm = "NavigationHandler.OrbitalNavigator.";
size_t posNav = navTerm.find(nextTerm);
const size_t posNav = navTerm.find(nextTerm);
if (posNav != std::string::npos) {
for (std::string accessName : _navScriptsUsingNodes) {
for (const std::string& accessName : _navScriptsUsingNodes) {
if (navTerm.find(accessName) != std::string::npos) {
return true;
}
@@ -1634,14 +1627,14 @@ std::string SessionRecording::isolateTermFromQuotes(std::string s) {
while (possibleQuotes.find(s.front()) != std::string::npos) {
s.erase(0, 1);
}
for (char q : possibleQuotes) {
for (const char q : possibleQuotes) {
if (s.find(q) != std::string::npos) {
s = s.substr(0, s.find(q));
return s;
}
}
//If no quotes found, remove other possible characters from end
std::string unwantedChars = " );";
const std::string unwantedChars = " );";
while (!s.empty() && (unwantedChars.find(s.back()) != std::string::npos)) {
s.pop_back();
}
@@ -1654,10 +1647,10 @@ void SessionRecording::eraseSpacesFromString(std::string& s) {
std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) {
std::string result;
char quote = s.at(0);
const char quote = s.at(0);
// Handle either ' or " marks
if (quote == '\'' || quote == '\"') {
size_t quoteCount = std::count(s.begin(), s.end(), quote);
const size_t quoteCount = std::count(s.begin(), s.end(), quote);
// Must be an opening and closing quote char
if (quoteCount == 2) {
result = s.substr(1, s.rfind(quote) - 1);
@@ -1666,18 +1659,20 @@ std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) {
return result;
}
bool SessionRecording::checkIfInitialFocusNodeIsLoaded(unsigned int camIdx1) {
if (_keyframesCamera.size() > 0) {
std::string startFocusNode
= _keyframesCamera[_timeline[camIdx1].idxIntoKeyframeTypeArray].focusNode;
auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), startFocusNode);
if (it == _loadedNodes.end()) {
LERROR(fmt::format(
"Playback file requires scenegraph node '{}', which is "
"not currently loaded", startFocusNode
));
return false;
}
bool SessionRecording::checkIfInitialFocusNodeIsLoaded(unsigned int firstCamIndex) {
if (_keyframesCamera.empty()) {
return true;
}
std::string startFocusNode =
_keyframesCamera[_timeline[firstCamIndex].idxIntoKeyframeTypeArray].focusNode;
auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), startFocusNode);
if (it == _loadedNodes.end()) {
LERROR(fmt::format(
"Playback file requires scenegraph node '{}', which is "
"not currently loaded", startFocusNode
));
return false;
}
return true;
}
@@ -1690,7 +1685,7 @@ bool SessionRecording::convertScript(std::stringstream& inStream, DataMode mode,
Timestamps times;
datamessagestructures::ScriptMessage kf;
bool success = readSingleKeyframeScript(
const bool success = readSingleKeyframeScript(
kf,
times,
mode,
@@ -1774,7 +1769,8 @@ bool SessionRecording::readScriptKeyframeBinary(Timestamps& times,
bool SessionRecording::readScriptKeyframeAscii(Timestamps& times,
datamessagestructures::ScriptMessage& kf,
std::string currentParsingLine, int lineN)
const std::string& currentParsingLine,
int lineN)
{
std::string entryType;
std::istringstream iss(currentParsingLine);
@@ -1819,7 +1815,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps,
interaction::KeyframeNavigator::CameraPose keyframe,
int lineNum)
{
size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size();
const size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size();
_keyframesCamera.push_back(std::move(keyframe));
return addKeyframeToTimeline(
_timeline,
@@ -1834,7 +1830,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps,
datamessagestructures::TimeKeyframe keyframe,
int lineNum)
{
size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size();
const size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size();
_keyframesTime.push_back(std::move(keyframe));
return addKeyframeToTimeline(
_timeline,
@@ -1849,7 +1845,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps,
std::string scriptToQueue,
int lineNum)
{
size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size();
const size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size();
_keyframesScript.push_back(std::move(scriptToQueue));
return addKeyframeToTimeline(
_timeline,
@@ -1863,14 +1859,14 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps,
void SessionRecording::moveAheadInTime() {
using namespace std::chrono;
bool playbackPaused = (_state == SessionState::PlaybackPaused);
const bool playbackPaused = (_state == SessionState::PlaybackPaused);
if (playbackPaused) {
_playbackPauseOffset
+= global::windowDelegate->applicationTime() - _previousTime;
}
_previousTime = global::windowDelegate->applicationTime();
double currTime = currentTime();
const double currTime = currentTime();
lookForNonCameraKeyframesThatHaveComeDue(currTime);
updateCameraWithOrWithoutNewKeyframes(currTime);
// Unfortunately the first frame is sometimes rendered because globebrowsing reports
@@ -1922,12 +1918,11 @@ void SessionRecording::updateCameraWithOrWithoutNewKeyframes(double currTime) {
return;
}
bool didFindFutureCameraKeyframes = findNextFutureCameraIndex(currTime);
bool isPrevAtFirstKeyframe = (_idxTimeline_cameraPtrPrev ==
_idxTimeline_cameraFirstInTimeline);
bool isFirstTimelineCameraKeyframeInFuture = (currTime <
_cameraFirstInTimeline_timestamp);
const bool didFindFutureCameraKeyframes = findNextFutureCameraIndex(currTime);
const bool isPrevAtFirstKeyframe =
(_idxTimeline_cameraPtrPrev == _idxTimeline_cameraFirstInTimeline);
const bool isFirstTimelineCameraKeyframeInFuture =
(currTime < _cameraFirstInTimeline_timestamp);
if (! (isPrevAtFirstKeyframe && isFirstTimelineCameraKeyframeInFuture)) {
processCameraKeyframe(currTime);
@@ -1938,8 +1933,8 @@ void SessionRecording::updateCameraWithOrWithoutNewKeyframes(double currTime) {
}
bool SessionRecording::isTimeToHandleNextNonCameraKeyframe(double currTime) {
bool isNonCameraPlaybackActive = (_playbackActive_time || _playbackActive_script);
return (currTime > getNextTimestamp()) && isNonCameraPlaybackActive;
const bool nonCameraPlaybackActive = (_playbackActive_time || _playbackActive_script);
return (currTime > getNextTimestamp()) && nonCameraPlaybackActive;
}
bool SessionRecording::findNextFutureCameraIndex(double currTime) {
@@ -1951,9 +1946,9 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) {
}
if (doesTimelineEntryContainCamera(seekAheadIndex)) {
unsigned int indexIntoCameraKeyframes =
const unsigned int indexIntoCameraKeyframes =
_timeline[seekAheadIndex].idxIntoKeyframeTypeArray;
double seekAheadKeyframeTimestamp
const double seekAheadKeyframeTimestamp
= appropriateTimestamp(_timeline[seekAheadIndex].t3stamps);
if (indexIntoCameraKeyframes >= (_keyframesCamera.size() - 1)) {
@@ -1973,7 +1968,7 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) {
}
}
double interpolationUpperBoundTimestamp =
const double interpolationUpperBoundTimestamp =
appropriateTimestamp(_timeline[_idxTimeline_cameraPtrNext].t3stamps);
if ((currTime > interpolationUpperBoundTimestamp) && _hasHitEndOfCameraKeyframes)
{
@@ -2033,8 +2028,8 @@ bool SessionRecording::processCameraKeyframe(double now) {
interaction::KeyframeNavigator::CameraPose nextPose;
interaction::KeyframeNavigator::CameraPose prevPose;
unsigned int prevIdx;
unsigned int nextIdx;
unsigned int prevIdx = 0;
unsigned int nextIdx = 0;
if (!_playbackActive_camera) {
return false;
}
@@ -2049,19 +2044,16 @@ bool SessionRecording::processCameraKeyframe(double now) {
}
// getPrevTimestamp();
double prevTime = appropriateTimestamp(
const double prevTime = appropriateTimestamp(
_timeline[_idxTimeline_cameraPtrPrev].t3stamps
);
// getNextTimestamp();
double nextTime = appropriateTimestamp(
const double nextTime = appropriateTimestamp(
_timeline[_idxTimeline_cameraPtrNext].t3stamps
);
double t;
if ((nextTime - prevTime) < 1e-7) {
t = 0;
}
else {
double t = 0.0;
if ((nextTime - prevTime) >= 1e-7) {
t = (now - prevTime) / (nextTime - prevTime);
}
@@ -2098,7 +2090,7 @@ bool SessionRecording::processScriptKeyframe() {
return false;
}
else {
std::string nextScript = nextKeyframeObj(
const std::string nextScript = nextKeyframeObj(
_idxScript,
_keyframesScript,
([this]() { signalPlaybackFinishedForComponent(RecordedType::Script); })
@@ -2176,14 +2168,14 @@ void SessionRecording::saveKeyframeToFileBinary(unsigned char* buffer,
file.write(reinterpret_cast<char*>(buffer), size);
}
void SessionRecording::saveKeyframeToFile(std::string entry, std::ofstream& file) {
file << std::move(entry) << std::endl;
void SessionRecording::saveKeyframeToFile(const std::string& entry, std::ofstream& file) {
file << entry << '\n';
}
SessionRecording::CallbackHandle SessionRecording::addStateChangeCallback(
StateChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_stateChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
@@ -2222,7 +2214,7 @@ std::vector<std::string> SessionRecording::playbackList() const {
DWORD attributes = GetFileAttributes(e.path().string().c_str());
bool isHidden = attributes & FILE_ATTRIBUTE_HIDDEN;
#else
bool isHidden = filename.find(".") == 0;
const bool isHidden = filename.find('.') == 0;
#endif // WIN32
if (!isHidden) {
// Don't add hidden files
@@ -2238,7 +2230,7 @@ void SessionRecording::readPlaybackHeader_stream(std::stringstream& conversionIn
std::string& version, DataMode& mode)
{
// Read header
std::string readBackHeaderString = readHeaderElement(
const std::string readBackHeaderString = readHeaderElement(
conversionInStream,
FileHeaderTitle.length()
);
@@ -2261,13 +2253,15 @@ void SessionRecording::readPlaybackHeader_stream(std::stringstream& conversionIn
readHeaderElement(conversionInStream, 1);
}
SessionRecording::DataMode SessionRecording::readModeFromHeader(std::string filename) {
DataMode mode;
SessionRecording::DataMode SessionRecording::readModeFromHeader(
const std::string& filename)
{
DataMode mode = DataMode::Unknown;
std::ifstream inputFile;
// Open in ASCII first
inputFile.open(filename, std::ifstream::in);
// Read header
std::string readBackHeaderString = readHeaderElement(
const std::string readBackHeaderString = readHeaderElement(
inputFile,
FileHeaderTitle.length()
);
@@ -2300,7 +2294,7 @@ void SessionRecording::readFileIntoStringStream(std::string filename,
));
}
DataMode mode = readModeFromHeader(conversionInFilename.string());
const DataMode mode = readModeFromHeader(conversionInFilename.string());
stream.str("");
stream.clear();
@@ -2321,7 +2315,8 @@ void SessionRecording::readFileIntoStringStream(std::string filename,
}
void SessionRecording::convertFileRelativePath(std::string filenameRelative) {
convertFile(absPath(filenameRelative).string());
const std::filesystem::path path = absPath(std::move(filenameRelative));
convertFile(path.string());
}
std::string SessionRecording::convertFile(std::string filename, int depth) {
@@ -2335,14 +2330,14 @@ std::string SessionRecording::convertFile(std::string filename, int depth) {
std::string newFilename = filename;
try {
readFileIntoStringStream(filename, conversionInFile, conversionInStream);
DataMode mode;
DataMode mode = DataMode::Unknown;
std::string fileVersion;
readPlaybackHeader_stream(
conversionInStream,
fileVersion,
mode
);
int conversionLineNum = 1;
const int conversionLineNum = 1;
// If this instance of the SessionRecording class isn't the instance with the
// correct version of the file to be converted, then call getLegacy() to recurse
@@ -2554,7 +2549,7 @@ bool SessionRecording::convertEntries(std::string& inFilename,
std::string SessionRecording::getLegacyConversionResult(std::string filename, int depth) {
SessionRecording_legacy_0085 legacy;
return legacy.convertFile(filename, depth);
return legacy.convertFile(std::move(filename), depth);
}
std::string SessionRecording_legacy_0085::getLegacyConversionResult(std::string filename,
@@ -2579,15 +2574,15 @@ std::string SessionRecording::targetFileFormatVersion() {
return std::string(FileHeaderVersion);
}
std::string SessionRecording::determineConversionOutFilename(const std::string filename,
std::string SessionRecording::determineConversionOutFilename(const std::string& filename,
DataMode mode)
{
std::string filenameSansExtension = filename;
std::string fileExtension = (mode == DataMode::Binary) ?
const std::string fileExtension = (mode == DataMode::Binary) ?
FileExtensionBinary : FileExtensionAscii;
if (filename.find_last_of(".") != std::string::npos) {
filenameSansExtension = filename.substr(0, filename.find_last_of("."));
if (filename.find_last_of('.') != std::string::npos) {
filenameSansExtension = filename.substr(0, filename.find_last_of('.'));
}
filenameSansExtension += "_" + fileFormatVersion() + "-" + targetFileFormatVersion();
return filenameSansExtension + fileExtension;
@@ -2602,7 +2597,7 @@ bool SessionRecording_legacy_0085::convertScript(std::stringstream& inStream,
Timestamps times;
ScriptMessage_legacy_0085 kf;
bool success = readSingleKeyframeScript(
const bool success = readSingleKeyframeScript(
kf,
times,
mode,
@@ -62,9 +62,7 @@ ConvertRecFileVersionTask::ConvertRecFileVersionTask(const ghoul::Dictionary& di
}
ConvertRecFileVersionTask::~ConvertRecFileVersionTask() {
if (sessRec != nullptr) {
delete sessRec;
}
delete sessRec;
}
std::string ConvertRecFileVersionTask::description() {
@@ -80,11 +78,11 @@ void ConvertRecFileVersionTask::perform(const Task::ProgressCallback&) {
}
void ConvertRecFileVersionTask::convert() {
bool hasBinaryFileExtension = sessRec->hasFileExtension(
const bool hasBinaryFileExtension = SessionRecording::hasFileExtension(
_inFilename,
SessionRecording::FileExtensionBinary
);
bool hasAsciiFileExtension = sessRec->hasFileExtension(
const bool hasAsciiFileExtension = SessionRecording::hasFileExtension(
_inFilename,
SessionRecording::FileExtensionAscii
);
+41 -38
View File
@@ -38,6 +38,17 @@ namespace {
constexpr std::string_view KeyInFilePath = "InputFilePath";
constexpr std::string_view KeyOutFilePath = "OutputFilePath";
std::string addFileSuffix(const std::string& filePath, const std::string& suffix) {
const size_t lastdot = filePath.find_last_of('.');
const std::string extension = filePath.substr(0, lastdot);
if (lastdot == std::string::npos) {
return filePath + suffix;
}
else {
return filePath.substr(0, lastdot) + suffix + extension;
}
}
} // namespace
namespace openspace::interaction {
@@ -66,9 +77,7 @@ ConvertRecFormatTask::ConvertRecFormatTask(const ghoul::Dictionary& dictionary)
ConvertRecFormatTask::~ConvertRecFormatTask() {
_iFile.close();
_oFile.close();
if (sessRec != nullptr) {
delete sessRec;
}
delete sessRec;
}
std::string ConvertRecFormatTask::description() {
@@ -92,7 +101,8 @@ void ConvertRecFormatTask::perform(const Task::ProgressCallback&) {
}
void ConvertRecFormatTask::convert() {
std::string expectedFileExtension_in, expectedFileExtension_out;
std::string expectedFileExtension_in;
std::string expectedFileExtension_out;
std::string currentFormat;
if (_fileFormatType == SessionRecording::DataMode::Binary) {
currentFormat = "binary";
@@ -185,23 +195,21 @@ void ConvertRecFormatTask::determineFormatType() {
void ConvertRecFormatTask::convertToAscii() {
SessionRecording::Timestamps times;
datamessagestructures::CameraKeyframe ckf;
datamessagestructures::TimeKeyframe tkf;
datamessagestructures::ScriptMessage skf;
datamessagestructures::TimeKeyframe tkf;
datamessagestructures::ScriptMessage skf;
int lineNum = 1;
_oFile.open(_outFilePath, std::ifstream::app);
char tmpType = SessionRecording::DataFormatAsciiTag;
const char tmpType = SessionRecording::DataFormatAsciiTag;
_oFile.write(&tmpType, 1);
_oFile.write("\n", 1);
bool fileReadOk = true;
while (fileReadOk) {
unsigned char frameType = readFromPlayback<unsigned char>(_iFile);
while (true) {
const unsigned char frameType = readFromPlayback<unsigned char>(_iFile);
// Check if have reached EOF
if (!_iFile) {
LINFO(fmt::format(
"Finished converting {} entries from file '{}'", lineNum - 1, _inFilePath
));
fileReadOk = false;
break;
}
@@ -210,20 +218,29 @@ void ConvertRecFormatTask::convertToAscii() {
if (frameType == SessionRecording::HeaderCameraBinary) {
sessRec->readCameraKeyframeBinary(times, ckf, _iFile, lineNum);
sessRec->saveHeaderAscii(times, SessionRecording::HeaderCameraAscii,
keyframeLine);
SessionRecording::saveHeaderAscii(
times,
SessionRecording::HeaderCameraAscii,
keyframeLine
);
ckf.write(keyframeLine);
}
else if (frameType == SessionRecording::HeaderTimeBinary) {
sessRec->readTimeKeyframeBinary(times, tkf, _iFile, lineNum);
sessRec->saveHeaderAscii(times, SessionRecording::HeaderTimeAscii,
keyframeLine);
SessionRecording::saveHeaderAscii(
times,
SessionRecording::HeaderTimeAscii,
keyframeLine
);
tkf.write(keyframeLine);
}
else if (frameType == SessionRecording::HeaderScriptBinary) {
sessRec->readScriptKeyframeBinary(times, skf, _iFile, lineNum);
sessRec->saveHeaderAscii(times, SessionRecording::HeaderScriptAscii,
keyframeLine);
SessionRecording::saveHeaderAscii(
times,
SessionRecording::HeaderScriptAscii,
keyframeLine
);
skf.write(keyframeLine);
}
else {
@@ -237,19 +254,18 @@ void ConvertRecFormatTask::convertToAscii() {
SessionRecording::saveKeyframeToFile(keyframeLine.str(), _oFile);
lineNum++;
}
_oFile.close();
}
void ConvertRecFormatTask::convertToBinary() {
SessionRecording::Timestamps times;
datamessagestructures::CameraKeyframe ckf;
datamessagestructures::TimeKeyframe tkf;
datamessagestructures::ScriptMessage skf;
datamessagestructures::TimeKeyframe tkf;
datamessagestructures::ScriptMessage skf;
int lineNum = 1;
std::string lineContents;
unsigned char keyframeBuffer[SessionRecording::_saveBufferMaxSize_bytes];
std::array<unsigned char, SessionRecording::_saveBufferMaxSize_bytes> keyframeBuffer;
_oFile.open(_outFilePath, std::ifstream::app | std::ios::binary);
char tmpType = SessionRecording::DataFormatBinaryTag;
const char tmpType = SessionRecording::DataFormatBinaryTag;
_oFile.write(&tmpType, 1);
_oFile.write("\n", 1);
@@ -267,17 +283,17 @@ void ConvertRecFormatTask::convertToBinary() {
if (entryType == SessionRecording::HeaderCameraAscii) {
sessRec->readCameraKeyframeAscii(times, ckf, lineContents, lineNum);
sessRec->saveCameraKeyframeBinary(times, ckf, keyframeBuffer,
sessRec->saveCameraKeyframeBinary(times, ckf, keyframeBuffer.data(),
_oFile);
}
else if (entryType == SessionRecording::HeaderTimeAscii) {
sessRec->readTimeKeyframeAscii(times, tkf, lineContents, lineNum);
sessRec->saveTimeKeyframeBinary(times, tkf, keyframeBuffer,
sessRec->saveTimeKeyframeBinary(times, tkf, keyframeBuffer.data(),
_oFile);
}
else if (entryType == SessionRecording::HeaderScriptAscii) {
sessRec->readScriptKeyframeAscii(times, skf, lineContents, lineNum);
sessRec->saveScriptKeyframeBinary(times, skf, keyframeBuffer,
sessRec->saveScriptKeyframeBinary(times, skf, keyframeBuffer.data(),
_oFile);
}
else if (entryType.substr(0, 1) == SessionRecording::HeaderCommentAscii) {
@@ -297,19 +313,6 @@ void ConvertRecFormatTask::convertToBinary() {
));
}
std::string ConvertRecFormatTask::addFileSuffix(const std::string& filePath,
const std::string& suffix)
{
size_t lastdot = filePath.find_last_of(".");
std::string extension = filePath.substr(0, lastdot);
if (lastdot == std::string::npos) {
return filePath + suffix;
}
else {
return filePath.substr(0, lastdot) + suffix + extension;
}
}
documentation::Documentation ConvertRecFormatTask::documentation() {
using namespace documentation;
return {
+2 -2
View File
@@ -50,13 +50,13 @@ void WebsocketCameraStates::updateStateFromInput(
if (!websocketInputStates.empty()) {
for (int i = 0; i < WebsocketInputState::MaxAxes; i++) {
AxisInformation t = _axisMapping[i];
const AxisInformation t = _axisMapping[i];
if (t.type == AxisType::None) {
continue;
}
float value = websocketInputStates.axis(i);
bool hasValue = std::fabs(value) > t.deadzone;
const bool hasValue = std::fabs(value) > t.deadzone;
if (!hasValue) {
value = 0.f;
+2 -2
View File
@@ -36,7 +36,7 @@ namespace openspace::interaction {
float WebsocketInputStates::axis(int axis) const {
ghoul_precondition(axis >= 0, "axis must be 0 or positive");
float res = std::accumulate(
const float res = std::accumulate(
begin(),
end(),
0.f,
@@ -58,7 +58,7 @@ float WebsocketInputStates::axis(int axis) const {
bool WebsocketInputStates::button(int button, WebsocketAction action) const {
ghoul_precondition(button >= 0, "button must be 0 or positive");
bool res = std::any_of(
const bool res = std::any_of(
begin(),
end(),
[button, action](const std::pair<const size_t, const WebsocketInputState *> state)
+8 -8
View File
@@ -114,10 +114,10 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) {
// user may specify an overall time range. In that case expand this timerange
if (p.timeRange.has_value()) {
std::string start = p.timeRange->start;
std::string end = p.timeRange->end.value_or(start);
const std::string start = p.timeRange->start;
const std::string end = p.timeRange->end.value_or(start);
TimeRange overallTimeRange = TimeRange(
const TimeRange overallTimeRange = TimeRange(
SpiceManager::ref().ephemerisTimeFromDate(start),
SpiceManager::ref().ephemerisTimeFromDate(end)
);
@@ -139,8 +139,8 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) {
}
else {
if (p.timeRange.has_value()) {
std::string start = p.timeRange->start;
std::string end = p.timeRange->end.value_or(start);
const std::string start = p.timeRange->start;
const std::string end = p.timeRange->end.value_or(start);
_timeRange = TimeRange(
SpiceManager::ref().ephemerisTimeFromDate(start),
@@ -165,8 +165,8 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) {
std::string name = milestone.name;
Time newTime = Time(milestone.date);
Milestone newDate = {
.name = name,
.date = newTime
.name = std::move(name),
.date = std::move(newTime)
};
if (milestone.description.has_value()) {
newDate.description = milestone.description.value();
@@ -235,7 +235,7 @@ void MissionPhase::phaseTrace(double time, Trace& trace, int maxDepth) const {
for (const MissionPhase& phase : _subphases) {
if (phase.timeRange().includes(time)) {
trace.push_back(phase);
trace.emplace_back(phase);
phase.phaseTrace(time, trace, maxDepth - 1);
return;
}
+2 -2
View File
@@ -60,8 +60,8 @@ bool MissionManager::hasCurrentMission() const {
std::string MissionManager::loadMission(Mission mission) {
// Changing the values might invalidate the _currentMission iterator
std::string currentMission = hasCurrentMission() ? _currentMission->first : "";
std::string missionName = mission.name();
const std::string currentMission = hasCurrentMission() ? _currentMission->first : "";
const std::string missionName = mission.name();
_missionMap.insert({ missionName, std::move(mission) });
if (_missionMap.size() == 1) {
setCurrentMission(missionName);
+9 -28
View File
@@ -35,24 +35,18 @@
#include <glm/gtx/quaternion.hpp>
#ifdef INTERPOLATION_DEBUG_PRINT
namespace {
constexpr std::string_view _loggerCat = "KeyframeNavigator";
} // namespace
#endif
namespace openspace::interaction {
KeyframeNavigator::CameraPose::CameraPose(datamessagestructures::CameraKeyframe&& kf)
: position(std::move(kf._position))
, rotation(std::move(kf._rotation))
, focusNode(std::move(kf._focusNode))
, scale(std::move(kf._scale))
, followFocusNodeRotation(std::move(kf._followNodeRotation))
, scale(kf._scale)
, followFocusNodeRotation(kf._followNodeRotation)
{}
bool KeyframeNavigator::updateCamera(Camera& camera, bool ignoreFutureKeyframes) {
double now = currentTime();
const double now = currentTime();
bool foundPrevKeyframe = false;
if (_cameraPoseTimeline.nKeyframes() == 0) {
@@ -100,8 +94,8 @@ bool KeyframeNavigator::updateCamera(Camera& camera, bool ignoreFutureKeyframes)
return updateCamera(&camera, prevPose, nextPose, t, ignoreFutureKeyframes);
}
bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose,
const CameraPose nextPose, double t,
bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose& prevPose,
const CameraPose& nextPose, double t,
bool ignoreFutureKeyframes)
{
Scene* scene = camera->parent()->scene();
@@ -142,16 +136,16 @@ bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose,
// Linear interpolation
t = std::max(0.0, std::min(1.0, t));
glm::dvec3 nowCameraPosition = prevKeyframeCameraPosition * (1.0 - t) +
nextKeyframeCameraPosition * t;
const glm::dvec3 nowCameraPosition =
prevKeyframeCameraPosition * (1.0 - t) + nextKeyframeCameraPosition * t;
glm::dquat nowCameraRotation = glm::slerp(
prevKeyframeCameraRotation,
nextKeyframeCameraRotation,
t
);
camera->setPositionVec3(nowCameraPosition);
camera->setRotation(nowCameraRotation);
camera->setPositionVec3(std::move(nowCameraPosition));
camera->setRotation(std::move(nowCameraRotation));
// We want to affect view scaling, such that we achieve
// logarithmic interpolation of distance to an imagined focus node.
@@ -165,19 +159,6 @@ bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose,
camera->setScaling(1.f / glm::exp(interpolatedInvScaleExp));
}
#ifdef INTERPOLATION_DEBUG_PRINT
LINFO(fmt::format(
"Cam pos = {} {} {} rot = {} {} {} {}",
nowCameraPosition.x,
nowCameraPosition.y,
nowCameraPosition.z,
nowCameraRotation.x,
nowCameraRotation.y,
nowCameraRotation.z,
nowCameraRotation.w
));
#endif
return true;
}
+16 -16
View File
@@ -187,8 +187,8 @@ void NavigationHandler::updateCamera(double deltaTime) {
return;
}
OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
bool playbackMode = (mode == OpenSpaceEngine::Mode::SessionRecordingPlayback);
const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
const bool playbackMode = (mode == OpenSpaceEngine::Mode::SessionRecordingPlayback);
// If we're in session recording payback mode, the session recording is responsible
// for navigation. So don't do anything more here
@@ -225,14 +225,14 @@ void NavigationHandler::applyPendingState() {
std::variant<NodeCameraStateSpec, NavigationState> pending = *_pendingState;
if (std::holds_alternative<NavigationState>(pending)) {
NavigationState ns = std::get<NavigationState>(pending);
const NavigationState ns = std::get<NavigationState>(pending);
_orbitalNavigator.setAnchorNode(ns.anchor);
_orbitalNavigator.setAimNode(ns.aim);
_camera->setPose(ns.cameraPose());
}
else if (std::holds_alternative<NodeCameraStateSpec>(pending)) {
NodeCameraStateSpec spec = std::get<NodeCameraStateSpec>(pending);
Waypoint wp = computeWaypointFromNodeInfo(spec);
const NodeCameraStateSpec spec = std::get<NodeCameraStateSpec>(pending);
const Waypoint wp = computeWaypointFromNodeInfo(spec);
_orbitalNavigator.setAnchorNode(wp.nodeIdentifier());
_orbitalNavigator.setAimNode("");
@@ -271,13 +271,13 @@ void NavigationHandler::updateCameraTransitions() {
// Updated checks compared to last time, so we can check if we are still in the
// approach or anchor sphere
bool isInApproachSphere = currDistance < d * af;
bool isInReachSphere = currDistance < d * rf;
const bool isInApproachSphere = currDistance < d * af;
const bool isInReachSphere = currDistance < d * rf;
// Compare these to the values from last frame, to trigger the correct transition
// events
bool wasInApproachSphere = _inAnchorApproachSphere;
bool wasInReachSphere = _inAnchorReachSphere;
const bool wasInApproachSphere = _inAnchorApproachSphere;
const bool wasInReachSphere = _inAnchorReachSphere;
_inAnchorApproachSphere = isInApproachSphere;
_inAnchorReachSphere = isInReachSphere;
@@ -377,7 +377,7 @@ void NavigationHandler::updateCameraTransitions() {
);
};
bool anchorWasChanged = anchorNode() != _lastAnchor;
const bool anchorWasChanged = anchorNode() != _lastAnchor;
if (anchorWasChanged) {
// The anchor was changed between frames, so the transitions we have to check
// are a bit different. Just directly trigger the relevant events for the
@@ -509,8 +509,8 @@ NavigationState NavigationHandler::navigationState(
glm::normalize(_camera->lookUpVectorWorldSpace())
));
glm::dquat localRotation = invNeutralRotation * _camera->rotationQuaternion();
glm::dvec3 eulerAngles = glm::eulerAngles(localRotation);
const glm::dquat localRotation = invNeutralRotation * _camera->rotationQuaternion();
const glm::dvec3 eulerAngles = glm::eulerAngles(localRotation);
const double pitch = eulerAngles.x;
const double yaw = -eulerAngles.y;
@@ -536,7 +536,7 @@ NavigationState NavigationHandler::navigationState(
}
void NavigationHandler::saveNavigationState(const std::filesystem::path& filepath,
const std::string& referenceFrameIdentifier)
const std::string& referenceFrameIdentifier) const
{
ghoul_precondition(!filepath.empty(), "File path must not be empty");
@@ -582,14 +582,14 @@ void NavigationHandler::loadNavigationState(const std::string& filepath) {
throw ghoul::FileNotFoundError(absolutePath.string(), "NavigationState");
}
std::ifstream f(filepath);
std::ifstream f = std::ifstream(filepath);
std::string contents = std::string(
std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>()
);
nlohmann::json json = nlohmann::json::parse(contents);
const nlohmann::json json = nlohmann::json::parse(contents);
NavigationState state = NavigationState(json);
const NavigationState state = NavigationState(json);
setNavigationStateNextFrame(state);
}
+7 -9
View File
@@ -170,22 +170,20 @@ CameraPose NavigationState::cameraPose() const {
resultingPose.position = anchorNode->worldPosition() +
referenceFrameTransform * glm::dvec3(position);
glm::dvec3 upVector = up.has_value() ?
const glm::dvec3 upVector = up.has_value() ?
glm::normalize(referenceFrameTransform * *up) :
glm::dvec3(0.0, 1.0, 0.0);
// Construct vectors of a "neutral" view, i.e. when the anchor is centered in view
glm::dvec3 neutralView =
const glm::dvec3 neutralView =
glm::normalize(anchorNode->worldPosition() - resultingPose.position);
glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast(glm::lookAt(
glm::dvec3(0.0),
neutralView,
upVector
)));
const glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast(
glm::lookAt(glm::dvec3(0.0), neutralView, upVector)
));
glm::dquat pitchRotation = glm::angleAxis(pitch, glm::dvec3(1.0, 0.0, 0.0));
glm::dquat yawRotation = glm::angleAxis(yaw, glm::dvec3(0.0, -1.0, 0.0));
const glm::dquat pitchRotation = glm::angleAxis(pitch, glm::dvec3(1.0, 0.0, 0.0));
const glm::dquat yawRotation = glm::angleAxis(yaw, glm::dvec3(0.0, -1.0, 0.0));
resultingPose.rotation = neutralCameraRotation * yawRotation * pitchRotation;
+121 -106
View File
@@ -411,6 +411,28 @@ namespace {
"choice for globes, and the Y-axis is a good choice for models",
openspace::properties::Property::Visibility::AdvancedUser
};
/**
* Calculates a SurfacePositionHandle given a camera position in world space.
*/
openspace::SurfacePositionHandle calculateSurfacePositionHandle(
const openspace::SceneGraphNode& node,
const glm::dvec3& cameraPositionWorldSpace)
{
ghoul_assert(
glm::length(cameraPositionWorldSpace) > 0.0,
"Cannot have degenerate vector"
);
const glm::dmat4 inverseModelTransform = glm::inverse(node.modelTransform());
const glm::dvec3 cameraPositionModelSpace =
glm::dvec3(inverseModelTransform * glm::dvec4(cameraPositionWorldSpace, 1.0));
const openspace::SurfacePositionHandle posHandle =
node.calculateSurfacePositionHandle(cameraPositionModelSpace);
return posHandle;
}
} // namespace
namespace openspace::interaction {
@@ -468,7 +490,7 @@ OrbitalNavigator::IdleBehavior::IdleBehavior()
OrbitalNavigator::LimitZoom::LimitZoom()
: properties::PropertyOwner(LimitZoomInfo)
, enableZoomInLimit(EnabledMinimumAllowedDistanceInfo, true)
, minimumAllowedDistance(MinimumDistanceInfo, 10.0f, 0.0f, 10000.f)
, minimumAllowedDistance(MinimumDistanceInfo, 10.f, 0.f, 10000.f)
, enableZoomOutLimit(EnabledMaximumDistanceInfo, false)
, maximumAllowedDistance(
MaximumDistanceInfo,
@@ -498,8 +520,8 @@ OrbitalNavigator::OrbitalNavigator()
, _disableZoom(DisableZoomInfo, false)
, _disableRoll(DisableRollInfo, false)
, _mouseSensitivity(MouseSensitivityInfo, 15.f, 1.f, 50.f)
, _joystickSensitivity(JoystickSensitivityInfo, 10.f, 1.0f, 50.f)
, _websocketSensitivity(WebsocketSensitivityInfo, 5.f, 1.0f, 50.f)
, _joystickSensitivity(JoystickSensitivityInfo, 10.f, 1.f, 50.f)
, _websocketSensitivity(WebsocketSensitivityInfo, 5.f, 1.f, 50.f)
, _useAdaptiveStereoscopicDepth(UseAdaptiveStereoscopicDepthInfo, true)
, _stereoscopicDepthOfFocusSurface(
StereoscopicDepthOfFocusSurfaceInfo,
@@ -734,7 +756,7 @@ glm::dvec3 OrbitalNavigator::anchorNodeToCameraVector() const {
}
glm::quat OrbitalNavigator::anchorNodeToCameraRotation() const {
glm::dmat4 invWorldRotation = glm::dmat4(
const glm::dmat4 invWorldRotation = glm::dmat4(
glm::inverse(anchorNode()->worldRotationMatrix())
);
return glm::quat(invWorldRotation) * glm::quat(_camera->rotationQuaternion());
@@ -777,7 +799,8 @@ void OrbitalNavigator::updateStatesFromInput(const MouseInputState& mouseInputSt
_websocketStates.updateStateFromInput(*global::websocketInputStates, deltaTime);
_scriptStates.updateStateFromInput(deltaTime);
bool interactionHappened = _mouseStates.hasNonZeroVelocities() ||
const bool interactionHappened =
_mouseStates.hasNonZeroVelocities() ||
_joystickStates.hasNonZeroVelocities() ||
_websocketStates.hasNonZeroVelocities() ||
_scriptStates.hasNonZeroVelocities();
@@ -789,7 +812,8 @@ void OrbitalNavigator::updateStatesFromInput(const MouseInputState& mouseInputSt
tickIdleBehaviorTimer(deltaTime);
}
bool cameraLocationChanged = _mouseStates.hasNonZeroVelocities(true) ||
const bool cameraLocationChanged =
_mouseStates.hasNonZeroVelocities(true) ||
_joystickStates.hasNonZeroVelocities(true) ||
_websocketStates.hasNonZeroVelocities(true) ||
_scriptStates.hasNonZeroVelocities(true);
@@ -869,7 +893,7 @@ void OrbitalNavigator::updateCameraStateFromStates(double deltaTime) {
// Rotate with the object by finding a differential rotation from the previous
// to the current rotation
glm::dquat anchorRotation = glm::quat_cast(_anchorNode->worldRotationMatrix());
const glm::dquat anchorRotation = glm::quat_cast(_anchorNode->worldRotationMatrix());
glm::dquat anchorNodeRotationDiff = _previousAnchorNodeRotation.has_value() ?
*_previousAnchorNodeRotation * glm::inverse(anchorRotation) :
@@ -893,7 +917,7 @@ void OrbitalNavigator::updateCameraStateFromStates(double deltaTime) {
camRot.localRotation = interpolateLocalRotation(deltaTime, camRot.localRotation);
camRot.localRotation = rotateLocally(deltaTime, camRot.localRotation);
double horizontalTranslationSpeedScale =
const double horizontalTranslationSpeedScale =
rotationSpeedScaleFromCameraHeight(pose.position, posHandle);
// Rotation around target object's up vector based on user input
@@ -986,8 +1010,10 @@ void OrbitalNavigator::updateCameraScalingFromAnchor(double deltaTime) {
return;
}
SurfacePositionHandle posHandle =
calculateSurfacePositionHandle(*_anchorNode, cameraPos);
const SurfacePositionHandle posHandle = calculateSurfacePositionHandle(
*_anchorNode,
cameraPos
);
double targetCameraToSurfaceDistance = glm::length(
cameraToSurfaceVector(cameraPos, anchorPos, posHandle)
@@ -1046,7 +1072,7 @@ void OrbitalNavigator::tickIdleBehaviorTimer(double deltaTime) {
}
glm::dquat OrbitalNavigator::composeCameraRotation(
const CameraRotationDecomposition& decomposition)
const CameraRotationDecomposition& decomposition) const
{
return decomposition.globalRotation * decomposition.localRotation;
}
@@ -1063,13 +1089,13 @@ glm::dvec3 OrbitalNavigator::cameraToSurfaceVector(const glm::dvec3& cameraPos,
const glm::dvec3& centerPos,
const SurfacePositionHandle& posHandle)
{
glm::dmat4 modelTransform = _anchorNode->modelTransform();
glm::dvec3 posDiff = cameraPos - centerPos;
glm::dvec3 centerToActualSurfaceModelSpace =
const glm::dmat4 modelTransform = _anchorNode->modelTransform();
const glm::dvec3 posDiff = cameraPos - centerPos;
const glm::dvec3 centerToActualSurfaceModelSpace =
posHandle.centerToReferenceSurface +
posHandle.referenceSurfaceOutDirection * posHandle.heightToSurface;
glm::dvec3 centerToActualSurface =
const glm::dvec3 centerToActualSurface =
glm::dmat3(modelTransform) * centerToActualSurfaceModelSpace;
return centerToActualSurface - posDiff;
@@ -1256,7 +1282,7 @@ bool OrbitalNavigator::shouldFollowAnchorRotation(const glm::dvec3& cameraPositi
const double distanceToCamera =
glm::distance(cameraPosition, _anchorNode->worldPosition());
bool shouldFollow = distanceToCamera < maximumDistanceForRotation;
const bool shouldFollow = distanceToCamera < maximumDistanceForRotation;
return shouldFollow;
}
@@ -1296,7 +1322,7 @@ double OrbitalNavigator::maxAllowedDistance() const {
}
OrbitalNavigator::CameraRotationDecomposition
OrbitalNavigator::decomposeCameraRotationSurface(CameraPose cameraPose,
OrbitalNavigator::decomposeCameraRotationSurface(const CameraPose& cameraPose,
const SceneGraphNode& reference)
{
const glm::dvec3 cameraUp = cameraPose.rotation * Camera::UpDirectionCameraSpace;
@@ -1330,8 +1356,8 @@ OrbitalNavigator::CameraRotationDecomposition
}
OrbitalNavigator::CameraRotationDecomposition
OrbitalNavigator::decomposeCameraRotation(CameraPose cameraPose,
glm::dvec3 reference)
OrbitalNavigator::decomposeCameraRotation(const CameraPose& cameraPose,
const glm::dvec3& reference)
{
const glm::dvec3 cameraUp = cameraPose.rotation * glm::dvec3(0.0, 1.0, 0.0);
const glm::dvec3 cameraViewDirection = ghoul::viewDirection(cameraPose.rotation);
@@ -1349,8 +1375,8 @@ OrbitalNavigator::CameraRotationDecomposition
return { localCameraRotation, globalCameraRotation };
}
CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAnchor,
Displacement anchorToAim)
CameraPose OrbitalNavigator::followAim(CameraPose pose, const glm::dvec3& cameraToAnchor,
const Displacement& anchorToAim)
{
CameraRotationDecomposition anchorDecomp =
decomposeCameraRotation(pose, pose.position + cameraToAnchor);
@@ -1368,7 +1394,7 @@ CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAncho
// 2. Adjustment of the camera to account for radial displacement of the aim
// Step 1 (Rotation around anchor based on aim's projection)
glm::dvec3 newAnchorToProjectedAim =
const glm::dvec3 newAnchorToProjectedAim =
glm::length(anchorToAim.first) * glm::normalize(anchorToAim.second);
const double spinRotationAngle = glm::angle(
glm::normalize(anchorToAim.first), glm::normalize(newAnchorToProjectedAim)
@@ -1432,11 +1458,11 @@ CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAncho
const double newCameraAimAngle =
glm::pi<double>() - anchorAimAngle - newCameraAnchorAngle;
double distanceRotationAngle = correctionFactor *
const double distanceRotationAngle = correctionFactor *
(newCameraAimAngle - prevCameraAimAngle);
if (glm::abs(distanceRotationAngle) > AngleEpsilon) {
glm::dvec3 distanceRotationAxis = glm::normalize(
const glm::dvec3 distanceRotationAxis = glm::normalize(
glm::cross(intermediateCameraToAnchor, newAnchorToProjectedAim)
);
const glm::dquat orbitRotation =
@@ -1540,62 +1566,67 @@ glm::dquat OrbitalNavigator::interpolateLocalRotation(double deltaTime,
OrbitalNavigator::Displacement
OrbitalNavigator::interpolateRetargetAim(double deltaTime, CameraPose pose,
glm::dvec3 prevCameraToAnchor,
const glm::dvec3& prevCameraToAnchor,
Displacement anchorToAim)
{
if (_retargetAimInterpolator.isInterpolating()) {
double t = _retargetAimInterpolator.value();
_retargetAimInterpolator.setDeltaTime(static_cast<float>(deltaTime));
_retargetAimInterpolator.step();
if (!_retargetAimInterpolator.isInterpolating()) {
return anchorToAim;
}
const glm::dvec3 prevCameraToAim = prevCameraToAnchor + anchorToAim.first;
const double aimDistance = glm::length(prevCameraToAim);
const glm::dquat prevRotation = pose.rotation;
const double t = _retargetAimInterpolator.value();
_retargetAimInterpolator.setDeltaTime(static_cast<float>(deltaTime));
_retargetAimInterpolator.step();
// Introduce a virtual aim - a position straight ahead of the camera,
// that should be rotated around the camera, until it reaches the aim node.
const glm::dvec3 prevCameraToAim = prevCameraToAnchor + anchorToAim.first;
const double aimDistance = glm::length(prevCameraToAim);
const glm::dquat prevRotation = pose.rotation;
const glm::dvec3 prevCameraToVirtualAim =
aimDistance * (prevRotation * Camera::ViewDirectionCameraSpace);
// Introduce a virtual aim - a position straight ahead of the camera,
// that should be rotated around the camera, until it reaches the aim node.
// Max angle: the maximum possible angle between anchor and aim, given that
// the camera orbits the anchor on a fixed distance.
const double maxAngle =
glm::atan(glm::length(anchorToAim.first), glm::length(prevCameraToAnchor));
const glm::dvec3 prevCameraToVirtualAim =
aimDistance * (prevRotation * Camera::ViewDirectionCameraSpace);
// Requested angle: The angle between the vector straight ahead from the
// camera and the vector from camera to anchor should remain constant, in
// order for the anchor not to move in screen space.
const double requestedAngle = glm::angle(
glm::normalize(prevCameraToVirtualAim),
glm::normalize(prevCameraToAnchor)
// Max angle: the maximum possible angle between anchor and aim, given that
// the camera orbits the anchor on a fixed distance.
const double maxAngle =
glm::atan(glm::length(anchorToAim.first), glm::length(prevCameraToAnchor));
// Requested angle: The angle between the vector straight ahead from the
// camera and the vector from camera to anchor should remain constant, in
// order for the anchor not to move in screen space.
const double requestedAngle = glm::angle(
glm::normalize(prevCameraToVirtualAim),
glm::normalize(prevCameraToAnchor)
);
if (requestedAngle <= maxAngle) {
const glm::dvec3 aimPos = pose.position + prevCameraToAnchor + anchorToAim.second;
const CameraRotationDecomposition aimDecomp = decomposeCameraRotation(
std::move(pose),
aimPos
);
if (requestedAngle <= maxAngle) {
glm::dvec3 aimPos = pose.position + prevCameraToAnchor + anchorToAim.second;
CameraRotationDecomposition aimDecomp = decomposeCameraRotation(pose, aimPos);
const glm::dquat interpolatedRotation = glm::slerp(
prevRotation,
aimDecomp.globalRotation,
glm::min(t * _retargetAimInterpolator.deltaTimeScaled(), 1.0)
);
const glm::dquat interpolatedRotation = glm::slerp(
prevRotation,
aimDecomp.globalRotation,
glm::min(t * _retargetAimInterpolator.deltaTimeScaled(), 1.0)
);
const glm::dvec3 recomputedCameraToVirtualAim =
aimDistance * (interpolatedRotation * Camera::ViewDirectionCameraSpace);
const glm::dvec3 recomputedCameraToVirtualAim =
aimDistance * (interpolatedRotation * Camera::ViewDirectionCameraSpace);
return {
prevCameraToVirtualAim - prevCameraToAnchor,
recomputedCameraToVirtualAim - prevCameraToAnchor
};
}
else {
// Bail out.
// Cannot put aim node in center without moving anchor in screen space.
// Future work: Rotate as much as possible,
// or possibly use some other DOF to find solution, like moving the camera.
_retargetAimInterpolator.end();
}
return {
prevCameraToVirtualAim - prevCameraToAnchor,
recomputedCameraToVirtualAim - prevCameraToAnchor
};
}
else {
// Bail out.
// Cannot put aim node in center without moving anchor in screen space.
// Future work: Rotate as much as possible,
// or possibly use some other DOF to find solution, like moving the camera.
_retargetAimInterpolator.end();
}
return anchorToAim;
}
@@ -1609,18 +1640,18 @@ double OrbitalNavigator::interpolateCameraToSurfaceDistance(double deltaTime,
return targetDistance;
}
double t = _cameraToSurfaceDistanceInterpolator.value();
const double t = _cameraToSurfaceDistanceInterpolator.value();
_cameraToSurfaceDistanceInterpolator.setDeltaTime(static_cast<float>(deltaTime));
_cameraToSurfaceDistanceInterpolator.step();
// Interpolate distance logarithmically
double result = glm::exp(glm::mix(
const double result = glm::exp(glm::mix(
glm::log(currentDistance),
glm::log(targetDistance),
glm::min(t * _cameraToSurfaceDistanceInterpolator.deltaTimeScaled(), 1.0))
);
double ratio = currentDistance / targetDistance;
const double ratio = currentDistance / targetDistance;
if (glm::abs(ratio - 1.0) < 0.000001) {
_cameraToSurfaceDistanceInterpolator.end();
}
@@ -1641,12 +1672,12 @@ void OrbitalNavigator::rotateAroundAnchorUp(double deltaTime, double speedScale,
}
}(UpDirectionChoice(_upToUseForRotation.value()));
double combinedXInput = _mouseStates.globalRotationVelocity().x +
const double combinedXInput = _mouseStates.globalRotationVelocity().x +
_joystickStates.globalRotationVelocity().x +
_websocketStates.globalRotationVelocity().x +
_scriptStates.globalRotationVelocity().x;
double angle = combinedXInput * deltaTime * speedScale;
const double angle = combinedXInput * deltaTime * speedScale;
orbitAroundAxis(axis, angle, cameraPosition, globalCameraRotation);
}
@@ -1658,9 +1689,9 @@ glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, double spee
{
// If we are orbiting around an up vector, we only want to allow verical
// movement and not use the x velocity
bool useX = !_shouldRotateAroundUp;
const bool useX = !_shouldRotateAroundUp;
double angleScale = deltaTime * speedScale;
const double angleScale = deltaTime * speedScale;
// Get rotation in camera space
const glm::dquat mouseRotationDiffCamSpace = glm::dquat(glm::dvec3(
@@ -1792,10 +1823,10 @@ glm::dvec3 OrbitalNavigator::pushToSurface(const glm::dvec3& cameraPosition,
const glm::dvec3& objectPosition,
const SurfacePositionHandle& positionHandle) const
{
double minHeight = _limitZoom.enableZoomInLimit ?
const double minHeight = _limitZoom.enableZoomInLimit ?
static_cast<double>(_limitZoom.minimumAllowedDistance) : 0.0;
double maxHeight = _limitZoom.enableZoomOutLimit ?
const double maxHeight = _limitZoom.enableZoomOutLimit ?
static_cast<double>(_limitZoom.maximumAllowedDistance) : -1.0;
if (maxHeight > 0.0 && minHeight > maxHeight) {
@@ -1854,24 +1885,6 @@ glm::dquat OrbitalNavigator::interpolateRotationDifferential(double deltaTime,
);
}
SurfacePositionHandle OrbitalNavigator::calculateSurfacePositionHandle(
const SceneGraphNode& node,
const glm::dvec3& cameraPositionWorldSpace) const
{
ghoul_assert(
glm::length(cameraPositionWorldSpace) > 0.0,
"Cannot have degenerate vector"
);
const glm::dmat4 inverseModelTransform = glm::inverse(node.modelTransform());
const glm::dvec3 cameraPositionModelSpace =
glm::dvec3(inverseModelTransform * glm::dvec4(cameraPositionWorldSpace, 1.0));
const SurfacePositionHandle posHandle =
node.calculateSurfacePositionHandle(cameraPositionModelSpace);
return posHandle;
}
JoystickCameraStates& OrbitalNavigator::joystickStates() {
return _joystickStates;
}
@@ -1897,7 +1910,7 @@ const ScriptCameraStates& OrbitalNavigator::scriptStates() const {
}
void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) {
OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode();
if (mode != OpenSpaceEngine::Mode::UserControl) {
LERROR(
"Could not start idle behavior. The camera is being controlled "
@@ -1910,7 +1923,7 @@ void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) {
_idleBehavior.chosenBehavior = std::nullopt;
}
else {
IdleBehavior::Behavior behavior;
IdleBehavior::Behavior behavior = IdleBehavior::Behavior::Orbit;
if (choice == IdleKeyOrbit) {
behavior = IdleBehavior::Behavior::Orbit;
}
@@ -1921,9 +1934,9 @@ void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) {
behavior = IdleBehavior::Behavior::OrbitAroundUp;
}
else {
throw ghoul::RuntimeError(
fmt::format("No existing IdleBehavior with identifier '{}'", choice)
);
throw ghoul::RuntimeError(fmt::format(
"No existing IdleBehavior with identifier '{}'", choice
));
}
_idleBehavior.chosenBehavior = behavior;
}
@@ -1950,8 +1963,10 @@ void OrbitalNavigator::applyIdleBehavior(double deltaTime, glm::dvec3& position,
return;
}
SurfacePositionHandle posHandle =
calculateSurfacePositionHandle(*_anchorNode, position);
const SurfacePositionHandle posHandle = calculateSurfacePositionHandle(
*_anchorNode,
position
);
// Same speed scale as horizontal translation
double speedScale = rotationSpeedScaleFromCameraHeight(position, posHandle);
@@ -1964,10 +1979,10 @@ void OrbitalNavigator::applyIdleBehavior(double deltaTime, glm::dvec3& position,
}
// Interpolate so that the start and end are smooth
double s = _idleBehaviorDampenInterpolator.value();
const double s = _idleBehaviorDampenInterpolator.value();
speedScale *= _invertIdleBehaviorInterpolation ? (1.0 - s) : s;
double angle = deltaTime * speedScale;
const double angle = deltaTime * speedScale;
// Apply the chosen behavior
const IdleBehavior::Behavior choice = _idleBehavior.chosenBehavior.value_or(
@@ -2021,7 +2036,7 @@ void OrbitalNavigator::orbitAnchor(double angle, glm::dvec3& position,
position += rotationDiffVec3;
}
void OrbitalNavigator::orbitAroundAxis(const glm::dvec3 axis, double angle,
void OrbitalNavigator::orbitAroundAxis(const glm::dvec3& axis, double angle,
glm::dvec3& position, glm::dquat& globalRotation)
{
ghoul_assert(_anchorNode != nullptr, "Node to orbit must be set");
+20 -20
View File
@@ -118,8 +118,8 @@ documentation::Documentation Path::Documentation() {
}
Path::Path(Waypoint start, Waypoint end, Type type, std::optional<float> duration)
: _start(start)
, _end(end)
: _start(std::move(start))
, _end(std::move(end))
, _type(type)
{
switch (_type) {
@@ -196,7 +196,7 @@ CameraPose Path::traversePath(double dt, float speedScale) {
double speed = speedAlongPath(_traveledDistance);
speed *= static_cast<double>(speedScale);
double displacement = dt * speed;
const double displacement = dt * speed;
const double prevDistance = _traveledDistance;
@@ -231,7 +231,7 @@ void Path::quitPath() {
}
std::string Path::currentAnchor() const {
bool pastHalfway = (_traveledDistance / pathLength()) > 0.5;
const bool pastHalfway = (_traveledDistance / pathLength()) > 0.5;
return (pastHalfway) ? _end.nodeIdentifier() : _start.nodeIdentifier();
}
@@ -243,10 +243,10 @@ bool Path::hasReachedEnd() const {
// @TODO (emmbr, 2022-11-07) Handle linear paths separately, as they might
// abort prematurely due to the "isPositionFinished" condition
bool isPositionFinished = (_traveledDistance / pathLength()) >= 1.0;
const bool isPositionFinished = (_traveledDistance / pathLength()) >= 1.0;
constexpr double RotationEpsilon = 0.0001;
bool isRotationFinished = ghoul::isSameOrientation(
const bool isRotationFinished = ghoul::isSameOrientation(
_prevPose.rotation,
_end.rotation(),
RotationEpsilon
@@ -280,8 +280,8 @@ CameraPose Path::linearInterpolatedPose(double distance, double displacement) {
const glm::dvec3 lineDir = glm::normalize(prevPosToEnd);
pose.position = _prevPose.position - displacement * lineDir;
double newRemainingDistance = glm::length(pose.position - _end.position());
double diff = remainingDistance - newRemainingDistance;
const double newRemainingDistance = glm::length(pose.position - _end.position());
const double diff = remainingDistance - newRemainingDistance;
// Avoid remaining distances close to zero, or even negative
if (relativeDistance > 0.5 && diff < LengthEpsilon) {
// The positions are too large, so we are not making progress because of
@@ -342,7 +342,7 @@ glm::dquat Path::linearPathRotation(double) const {
double factor = 5.0 / glm::half_pi<double>();
factor *= global::navigationHandler->pathNavigator().linearRotationSpeedFactor();
double turnDuration = std::max(angle * factor, 1.0); // Always at least 1 second
const double turnDuration = std::max(angle * factor, 1.0); // Always at least 1 second
const double time = glm::clamp(_progressedTime / turnDuration, 0.0, 1.0);
return easedSlerpRotation(time);
@@ -433,10 +433,10 @@ glm::dquat Path::lookAtTargetsRotation(double t) const {
// camera, but just the "hint" up vector for the lookAt. This leads to fast rolling
// when the up vector gets close to the camera's forward vector. Should be improved
// so any rolling is spread out over the entire motion instead
double tUp = ghoul::sineEaseInOut(t);
glm::dvec3 startUp = _start.rotation() * glm::dvec3(0.0, 1.0, 0.0);
glm::dvec3 endUp = _end.rotation() * glm::dvec3(0.0, 1.0, 0.0);
glm::dvec3 up = ghoul::interpolateLinear(tUp, startUp, endUp);
const double tUp = ghoul::sineEaseInOut(t);
const glm::dvec3 startUp = _start.rotation() * glm::dvec3(0.0, 1.0, 0.0);
const glm::dvec3 endUp = _end.rotation() * glm::dvec3(0.0, 1.0, 0.0);
const glm::dvec3 up = ghoul::interpolateLinear(tUp, startUp, endUp);
return ghoul::lookAtQuaternion(_curve->positionAt(t), lookAtPos, up);
}
@@ -448,7 +448,7 @@ double Path::speedAlongPath(double traveledDistance) const {
// Set speed based on distance to closest node
const double distanceToEndNode = glm::distance(_prevPose.position, endNodePos);
const double distanceToStartNode = glm::distance(_prevPose.position, startNodePos);
bool isCloserToEnd = distanceToEndNode < distanceToStartNode;
const bool isCloserToEnd = (distanceToEndNode < distanceToStartNode);
const glm::dvec3 closestPos = isCloserToEnd ? endNodePos : startNodePos;
const double distanceToClosestNode = glm::distance(closestPos, _prevPose.position);
@@ -541,7 +541,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary,
const std::optional<float> duration = p.duration;
Path::Type type;
Path::Type type = Path::Type::Linear;
if (forceType.has_value()) {
type = *forceType;
}
@@ -552,7 +552,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary,
type = global::navigationHandler->pathNavigator().defaultPathType();
}
bool hasStart = p.startState.has_value();
const bool hasStart = p.startState.has_value();
const Waypoint startPoint = hasStart ?
Waypoint(NavigationState(p.startState.value())) :
interaction::waypointFromCamera();
@@ -592,14 +592,14 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary,
));
}
interaction::NodeCameraStateSpec info {
const interaction::NodeCameraStateSpec info {
nodeIdentifier,
p.position,
p.height,
p.useTargetUpDirection.value_or(false)
};
double startToTargetCenterDistance = glm::distance(
const double startToTargetCenterDistance = glm::distance(
startPoint.position(),
targetNode->worldPosition()
);
@@ -607,7 +607,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary,
// Use a linear path if camera start is within the bounding sphere
const PathNavigator& navigator = global::navigationHandler->pathNavigator();
const double bs = navigator.findValidBoundingSphere(targetNode);
bool withinTargetBoundingSphere = startToTargetCenterDistance < bs;
const bool withinTargetBoundingSphere = (startToTargetCenterDistance < bs);
if (withinTargetBoundingSphere) {
LINFO(
"Camera is within the bounding sphere of the target node. "
@@ -616,7 +616,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary,
type = Path::Type::Linear;
}
bool isLinear = type == Path::Type::Linear;
const bool isLinear = type == Path::Type::Linear;
waypoints = { computeWaypointFromNodeInfo(info, startPoint, isLinear) };
break;
}
+22 -18
View File
@@ -83,9 +83,9 @@ void PathCurve::initializeParameterData() {
_lengthSums.reserve(_nSegments + 1);
_lengthSums.push_back(0.0);
for (unsigned int i = 1; i <= _nSegments; i++) {
double u = _curveParameterSteps[i];
double uPrev = _curveParameterSteps[i - 1];
double length = arcLength(uPrev, u);
const double u = _curveParameterSteps[i];
const double uPrev = _curveParameterSteps[i - 1];
const double length = arcLength(uPrev, u);
_lengthSums.push_back(_lengthSums[i - 1] + length);
}
_totalLength = _lengthSums.back();
@@ -100,13 +100,13 @@ void PathCurve::initializeParameterData() {
_parameterSamples.reserve(Steps * _nSegments + 1);
for (unsigned int i = 0; i < _nSegments; i++) {
double uStart = _curveParameterSteps[i];
double sStart = _lengthSums[i];
const double uStart = _curveParameterSteps[i];
const double sStart = _lengthSums[i];
_parameterSamples.push_back({ uStart, sStart });
// Intermediate sampels
for (int j = 1; j < Steps; j++) {
double u = uStart + j * uStep;
double s = sStart + arcLength(uStart, u);
const double u = uStart + j * uStep;
const double s = sStart + arcLength(uStart, u);
// Identify samples that are indistinguishable due to precision limitations
if (std::abs(s - _parameterSamples.back().s) < LengthEpsilon) {
throw InsufficientPrecisionError(
@@ -133,8 +133,12 @@ void PathCurve::initializeParameterData() {
// Input s is a length value, in the range [0, _totalLength]
// Returns curve parameter in range [0, _nSegments]
double PathCurve::curveParameter(double s) const {
if (s <= 0.0) return 0.0;
if (s >= (_totalLength - LengthEpsilon)) return _curveParameterSteps.back();
if (s <= 0.0) {
return 0.0;
}
if (s >= (_totalLength - LengthEpsilon)) {
return _curveParameterSteps.back();
}
unsigned int segmentIndex = 1;
while (s > _lengthSums[segmentIndex]) {
@@ -158,8 +162,8 @@ double PathCurve::curveParameter(double s) const {
return std::distance(samples.begin(), it);
};
size_t startIndex = findIndexOfFirstEqualOrLarger_u(uMin);
size_t endIndex = findIndexOfFirstEqualOrLarger_u(uMax);
const size_t startIndex = findIndexOfFirstEqualOrLarger_u(uMin);
const size_t endIndex = findIndexOfFirstEqualOrLarger_u(uMax);
// Use samples to find an initial guess for Newton's method
// Find first sample with s larger than input s
@@ -186,7 +190,7 @@ double PathCurve::curveParameter(double s) const {
double upper = uMax;
for (int i = 0; i < maxIterations; i++) {
double F = arcLength(uMin, u) - segmentS;
const double F = arcLength(uMin, u) - segmentS;
// The error we tolerate, in meters. Note that distances are very large
constexpr double tolerance = 0.5;
@@ -195,8 +199,8 @@ double PathCurve::curveParameter(double s) const {
}
// Generate a candidate for Newton's method
double dfdu = approximatedDerivative(u); // > 0
double uCandidate = u - F / dfdu;
const double dfdu = approximatedDerivative(u); // > 0
const double uCandidate = u - F / dfdu;
// Update root-bounding interval and test candidate
if (F > 0) { // => candidate < u <= upper
@@ -248,15 +252,15 @@ glm::dvec3 PathCurve::interpolate(double u) const {
return *(_points.end() - 2);
}
std::vector<double>::const_iterator segmentEndIt =
const std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(_curveParameterSteps.begin(), _curveParameterSteps.end(), u);
const int index =
static_cast<int>((segmentEndIt - 1) - _curveParameterSteps.begin());
double segmentStart = _curveParameterSteps[index];
double segmentDuration = (_curveParameterSteps[index + 1] - segmentStart);
double uSegment = (u - segmentStart) / segmentDuration;
const double segmentStart = _curveParameterSteps[index];
const double segmentDuration = (_curveParameterSteps[index + 1] - segmentStart);
const double uSegment = (u - segmentStart) / segmentDuration;
return ghoul::interpolateCatmullRom(
uSegment,
@@ -51,9 +51,9 @@ namespace {
namespace openspace::interaction {
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) {
_relevantNodes = global::navigationHandler->pathNavigator().relevantNodes();
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end)
: _relevantNodes(global::navigationHandler->pathNavigator().relevantNodes())
{
if (!start.node() || !end.node()) { // guard, but should never happen
LERROR("Something went wrong. The start or end node does not exist");
return;
@@ -70,7 +70,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint&
_points.push_back(start.position());
// Add an extra point to first go backwards if starting close to planet
glm::dvec3 nodeToStart = start.position() - startNodeCenter;
const glm::dvec3 nodeToStart = start.position() - startNodeCenter;
const double distanceToStartNode = glm::length(nodeToStart);
// Note that the factor 2.0 is arbitrarily chosen to look ok.
@@ -83,8 +83,8 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint&
if (distanceToStartNode < closeToNodeThresholdFactor * startNodeRadius) {
const double distance = startNodeRadius;
glm::dvec3 newPos = start.position() + distance * glm::normalize(nodeToStart);
_points.push_back(newPos);
glm::dvec3 newP = start.position() + distance * glm::normalize(nodeToStart);
_points.push_back(std::move(newP));
}
const glm::dvec3 startToEnd = end.position() - start.position();
@@ -92,12 +92,12 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint&
// Add point for moving out if the end state is far away and in opposite direction.
// This helps with avoiding fast rotation in the center of the path
const double maxRadius = std::max(startNodeRadius, endNodeRadius);
bool nodesAreDifferent = start.nodeIdentifier() != end.nodeIdentifier();
const bool nodesAreDifferent = (start.nodeIdentifier() != end.nodeIdentifier());
if (glm::length(startToEnd) > 0.5 * maxRadius && nodesAreDifferent) {
double cosAngleToTarget = glm::dot(
const double cosAngleToTarget = glm::dot(
normalize(-startViewDir), normalize(startToEnd)
);
bool targetInOppositeDirection = cosAngleToTarget > 0.7;
const bool targetInOppositeDirection = (cosAngleToTarget > 0.7);
if (targetInOppositeDirection) {
const glm::dquat midleRot = glm::slerp(start.rotation(), end.rotation(), 0.5);
@@ -106,8 +106,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint&
glm::dvec3 newPos = start.position() + 0.2 * startToEnd -
stepOutDistance * glm::normalize(middleViewDir);
_points.push_back(newPos);
_points.push_back(std::move(newPos));
}
}
@@ -118,7 +117,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint&
if (distanceToEndNode < closeToNodeThresholdFactor * endNodeRadius) {
const double distance = endNodeRadius;
glm::dvec3 newPos = end.position() + distance * glm::normalize(nodeToEnd);
_points.push_back(newPos);
_points.push_back(std::move(newPos));
}
_points.push_back(end.position());
@@ -148,32 +147,36 @@ void AvoidCollisionCurve::removeCollisions(int step) {
}
for (SceneGraphNode* node : _relevantNodes) {
using namespace collision;
// Do collision check in relative coordinates, to avoid huge numbers
const glm::dmat4 modelTransform = node->modelTransform();
glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
const glm::dvec3 p1 =
glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
const glm::dvec3 p2 =
glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
// Sphere to check for collision. Make sure it does not have radius zero.
const double minValidBoundingSphere =
global::navigationHandler->pathNavigator().minValidBoundingSphere();
double radius = std::max(node->boundingSphere(), minValidBoundingSphere);
glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0);
constexpr glm::dvec3 Center = glm::dvec3(0.0, 0.0, 0.0);
// Add a buffer to avoid passing too close to the node.
// Dont't add it if any point is inside the buffer
double buffer = CollisionBufferSizeRadiusMultiplier * radius;
bool p1IsInside = collision::isPointInsideSphere(p1, center, radius + buffer);
bool p2IsInside = collision::isPointInsideSphere(p2, center, radius + buffer);
const double buffer = CollisionBufferSizeRadiusMultiplier * radius;
const bool p1IsInside = isPointInsideSphere(p1, Center, radius + buffer);
const bool p2IsInside = isPointInsideSphere(p2, Center, radius + buffer);
if (!p1IsInside && !p2IsInside) {
radius += buffer;
}
glm::dvec3 intersectionPointModelCoords;
bool collision = collision::lineSphereIntersection(
const bool collision = lineSphereIntersection(
p1,
p2,
center,
Center,
radius,
intersectionPointModelCoords
);
@@ -182,12 +185,12 @@ void AvoidCollisionCurve::removeCollisions(int step) {
continue;
}
glm::dvec3 collisionPoint = modelTransform *
const glm::dvec3 collisionPoint = modelTransform *
glm::dvec4(intersectionPointModelCoords, 1.0);
// before collision response, make sure none of the points are inside the node
bool isStartInsideNode = collision::isPointInsideSphere(p1, center, radius);
bool isEndInsideNode = collision::isPointInsideSphere(p2, center, radius);
const bool isStartInsideNode = isPointInsideSphere(p1, Center, radius);
const bool isEndInsideNode = isPointInsideSphere(p2, Center, radius);
if (isStartInsideNode || isEndInsideNode) {
LWARNING(fmt::format(
"Something went wrong! "
@@ -209,7 +212,7 @@ void AvoidCollisionCurve::removeCollisions(int step) {
const double avoidCollisionDistance =
AvoidCollisionDistanceRadiusMultiplier * radius;
glm::dvec3 extraKnot = collisionPoint -
const glm::dvec3 extraKnot = collisionPoint -
avoidCollisionDistance * glm::normalize(orthogonal);
// Don't add invalid positions (indicating precision issues)
@@ -71,8 +71,8 @@ ZoomOutOverviewCurve::ZoomOutOverviewCurve(const Waypoint& start, const Waypoint
if (start.nodeIdentifier() != end.nodeIdentifier() &&
glm::length(startPosToEndPos) > Epsilon)
{
const glm::dvec3 n1 = startTangentDir;
const glm::dvec3 n2 = endTangentDir;
const glm::dvec3& n1 = startTangentDir;
const glm::dvec3& n2 = endTangentDir;
const glm::dvec3 halfWayPos = start.position() + 0.5 * startPosToEndPos;
// Decide the step direction for the "overview point" based on the directions
+12 -11
View File
@@ -32,7 +32,6 @@
#include <openspace/events/eventengine.h>
#include <openspace/navigation/navigationhandler.h>
#include <openspace/navigation/navigationstate.h>
#include <openspace/navigation/pathnavigator.h>
#include <openspace/query/query.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
@@ -267,7 +266,7 @@ void PathNavigator::updateCamera(double deltaTime) {
// Set anchor node in orbitalNavigator, to render visible nodes and add activate
// navigation when we reach the end.
std::string currentAnchor = anchor()->identifier();
const std::string currentAnchor = anchor()->identifier();
if (currentAnchor != newAnchor) {
global::navigationHandler->orbitalNavigator().setFocusNode(newAnchor, false);
}
@@ -294,7 +293,7 @@ void PathNavigator::updateCamera(double deltaTime) {
}
void PathNavigator::createPath(const ghoul::Dictionary& dictionary) {
OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
if (m == OpenSpaceEngine::Mode::SessionRecordingPlayback) {
// Silently ignore any paths that are being created during a session recording
// playback. The camera path should already have been recorded
@@ -334,7 +333,9 @@ void PathNavigator::startPath() {
return;
}
bool success = global::openSpaceEngine->setMode(OpenSpaceEngine::Mode::CameraPath);
const bool success = global::openSpaceEngine->setMode(
OpenSpaceEngine::Mode::CameraPath
);
if (!success) {
LERROR("Could not start camera path");
return; // couldn't switch to camera path mode
@@ -427,8 +428,8 @@ double PathNavigator::findValidBoundingSphere(const SceneGraphNode* node) const
// Use the biggest of the bounding sphere and interaction sphere,
// so we don't accidentally choose a bounding sphere that is much smaller
// than the interaction sphere of the node
double bs = n->boundingSphere();
double is = n->interactionSphere();
const double bs = n->boundingSphere();
const double is = n->interactionSphere();
return std::max(is, bs);
};
@@ -497,7 +498,7 @@ void PathNavigator::findRelevantNodes() {
}
auto isRelevant = [&relevantTags](const SceneGraphNode* node) {
const std::vector<std::string> tags = node->tags();
const std::vector<std::string>& tags = node->tags();
auto result = std::find_first_of(
relevantTags.begin(),
relevantTags.end(),
@@ -547,7 +548,7 @@ SceneGraphNode* PathNavigator::findNodeNearTarget(const SceneGraphNode* node) {
const glm::dvec3 posInModelCoords =
glm::inverse(n->modelTransform()) * glm::dvec4(node->worldPosition(), 1.0);
bool isClose = collision::isPointInsideSphere(
const bool isClose = collision::isPointInsideSphere(
posInModelCoords,
glm::dvec3(0.0, 0.0, 0.0),
proximityRadius
@@ -561,7 +562,7 @@ SceneGraphNode* PathNavigator::findNodeNearTarget(const SceneGraphNode* node) {
return nullptr;
}
void PathNavigator::removeRollRotation(CameraPose& pose) {
void PathNavigator::removeRollRotation(CameraPose& pose) const {
// The actual position for the camera does not really matter. Use the origin,
// to avoid precision problems when we have large values for the position
const glm::dvec3 cameraPos = glm::dvec3(0.0);
@@ -573,9 +574,9 @@ void PathNavigator::removeRollRotation(CameraPose& pose) {
// enough away from the camera
constexpr double NotTooCloseDistance = 10000.0;
glm::dvec3 lookAtPos = cameraPos + NotTooCloseDistance * cameraDir;
const glm::dvec3 lookAtPos = cameraPos + NotTooCloseDistance * cameraDir;
glm::dquat rollFreeRotation = ghoul::lookAtQuaternion(
const glm::dquat rollFreeRotation = ghoul::lookAtQuaternion(
cameraPos,
lookAtPos,
camera()->lookUpVectorWorldSpace()
+15 -15
View File
@@ -43,8 +43,8 @@ namespace {
namespace openspace::interaction {
Waypoint::Waypoint(const glm::dvec3& pos, const glm::dquat& rot, const std::string& ref)
: _nodeIdentifier(ref)
Waypoint::Waypoint(const glm::dvec3& pos, const glm::dquat& rot, std::string ref)
: _nodeIdentifier(std::move(ref))
{
_pose = { .position = pos, .rotation = rot };
@@ -172,7 +172,7 @@ glm::dvec3 computeGoodStepDirection(const SceneGraphNode* targetNode,
}
Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec,
std::optional<Waypoint> startPoint,
const std::optional<Waypoint>& startPoint,
bool useLinear)
{
const SceneGraphNode* targetNode = sceneGraphNode(spec.identifier);
@@ -182,14 +182,14 @@ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec,
}
// Use current camera position if no previous point was specified
Waypoint prevPoint = startPoint.value_or(waypointFromCamera());
const Waypoint prevPoint = startPoint.value_or(waypointFromCamera());
glm::dvec3 stepDir;
glm::dvec3 targetPos;
glm::dvec3 cameraPos;
if (spec.position.has_value()) {
// The position in instruction is given in the targetNode's local coordinates.
// Convert to world coordinates
targetPos = glm::dvec3(
cameraPos = glm::dvec3(
targetNode->modelTransform() * glm::dvec4(*spec.position, 1.0)
);
}
@@ -203,14 +203,14 @@ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec,
if (useLinear) {
// If linear path, compute position along line form start to end point
glm::dvec3 endNodePos = targetNode->worldPosition();
const glm::dvec3 endNodePos = targetNode->worldPosition();
stepDir = glm::normalize(prevPoint.position() - endNodePos);
}
else {
stepDir = computeGoodStepDirection(targetNode, prevPoint);
}
targetPos = targetNode->worldPosition() + stepDir * distanceFromNodeCenter;
cameraPos = targetNode->worldPosition() + stepDir * distanceFromNodeCenter;
}
glm::dvec3 up = global::navigationHandler->camera()->lookUpVectorWorldSpace();
@@ -224,20 +224,20 @@ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec,
// Compute rotation so the camera is looking at the targetted node
glm::dvec3 lookAtPos = targetNode->worldPosition();
// Check if we can distinguish between targetpos and lookAt pos. Otherwise, move it
// Check if we can distinguish between cameraPos and lookAt pos. Otherwise, move it
// further away
const glm::dvec3 diff = targetPos - lookAtPos;
double distSquared = glm::dot(diff, diff);
const glm::dvec3 diff = cameraPos - lookAtPos;
const double distSquared = glm::dot(diff, diff);
if (std::isnan(distSquared) || distSquared < LengthEpsilon) {
double startToEndDist = glm::length(
const double startToEndDist = glm::length(
prevPoint.position() - targetNode->worldPosition()
);
lookAtPos = targetPos - stepDir * 0.1 * startToEndDist;
lookAtPos = cameraPos - stepDir * 0.1 * startToEndDist;
}
const glm::dquat targetRot = ghoul::lookAtQuaternion(targetPos, lookAtPos, up);
const glm::dquat targetRot = ghoul::lookAtQuaternion(cameraPos, lookAtPos, up);
return Waypoint(targetPos, targetRot, spec.identifier);
return Waypoint(cameraPos, targetRot, spec.identifier);
}
} // namespace openspace::interaction
+1 -1
View File
@@ -158,7 +158,7 @@ ParallelConnection::Message ParallelConnection::receiveMessage() {
}
// Make sure that header matches this version of OpenSpace
if (!(headerBuffer[0] == 'O' && headerBuffer[1] == 'S')) {
if (headerBuffer[0] != 'O' || headerBuffer[1] != 'S') {
LERROR("Expected to read message header 'OS' from socket");
throw ConnectionLostError();
}
+31 -29
View File
@@ -247,7 +247,7 @@ void ParallelPeer::sendAuthentication() {
}
void ParallelPeer::queueInMessage(const ParallelConnection::Message& message) {
std::lock_guard unqlock(_receiveBufferMutex);
const std::lock_guard unqlock(_receiveBufferMutex);
_receiveBuffer.push_back(message);
}
@@ -269,7 +269,7 @@ void ParallelPeer::handleMessage(const ParallelConnection::Message& message) {
}
void ParallelPeer::analyzeTimeDifference(double messageTimestamp) {
std::lock_guard latencyLock(_latencyMutex);
const std::lock_guard latencyLock(_latencyMutex);
const double timeDiff = global::windowDelegate->applicationTime() - messageTimestamp;
if (_latencyDiffs.empty()) {
@@ -283,7 +283,7 @@ void ParallelPeer::analyzeTimeDifference(double messageTimestamp) {
}
double ParallelPeer::convertTimestamp(double messageTimestamp) {
std::lock_guard latencyLock(_latencyMutex);
const std::lock_guard latencyLock(_latencyMutex);
return messageTimestamp + _initialTimeDiff + _bufferTime;
}
@@ -291,7 +291,7 @@ double ParallelPeer::convertTimestamp(double messageTimestamp) {
double ParallelPeer::latencyStandardDeviation() const {
double accumulatedLatencyDiffSquared = 0;
double accumulatedLatencyDiff = 0;
for (double diff : _latencyDiffs) {
for (const double diff : _latencyDiffs) {
accumulatedLatencyDiff += diff;
accumulatedLatencyDiffSquared += diff*diff;
}
@@ -319,11 +319,10 @@ void ParallelPeer::dataMessageReceived(const std::vector<char>& message) {
analyzeTimeDifference(timestamp);
std::vector<char> buffer(message.begin() + offset, message.end());
const std::vector<char> buffer(message.begin() + offset, message.end());
switch (static_cast<datamessagestructures::Type>(type)) {
case datamessagestructures::Type::CameraData: {
datamessagestructures::CameraKeyframe kf(buffer);
const datamessagestructures::CameraKeyframe kf(buffer);
const double convertedTimestamp = convertTimestamp(kf._timestamp);
global::navigationHandler->keyframeNavigator().removeKeyframesAfter(
@@ -345,7 +344,7 @@ void ParallelPeer::dataMessageReceived(const std::vector<char>& message) {
}
case datamessagestructures::Type::TimelineData: {
const double now = global::windowDelegate->applicationTime();
datamessagestructures::TimeTimeline timelineMessage(buffer);
const datamessagestructures::TimeTimeline timelineMessage(buffer);
if (timelineMessage._clear) {
global::timeManager->removeKeyframesAfter(
@@ -435,7 +434,6 @@ void ParallelPeer::connectionStatusMessageReceived(const std::vector<char>& mess
if (hostNameSize > 0) {
hostName = std::string(&message[pointer], hostNameSize);
}
pointer += hostNameSize;
if (status > ParallelConnection::Status::Host) {
LERROR("Invalid status");
@@ -463,16 +461,17 @@ void ParallelPeer::nConnectionsMessageReceived(const std::vector<char>& message)
LERROR("Malformed host info message");
return;
}
const uint32_t nConnections = *(reinterpret_cast<const uint32_t*>(&message[0]));
const uint32_t nConnections = *(reinterpret_cast<const uint32_t*>(message.data()));
setNConnections(nConnections);
}
void ParallelPeer::handleCommunication() {
while (!_shouldDisconnect && _connection.isConnectedOrConnecting()) {
try {
ParallelConnection::Message m = _connection.receiveMessage();
const ParallelConnection::Message m = _connection.receiveMessage();
queueInMessage(m);
} catch (const ParallelConnection::ConnectionLostError& e) {
}
catch (const ParallelConnection::ConnectionLostError& e) {
if (e.shouldLogError) {
LERROR("Parallel connection lost");
}
@@ -504,18 +503,21 @@ void ParallelPeer::requestHostship() {
);
buffer.insert(buffer.end(), hostPw.begin(), hostPw.end());
_connection.sendMessage(ParallelConnection::Message(
ParallelConnection::MessageType::HostshipRequest,
buffer
));
_connection.sendMessage(
ParallelConnection::Message(
ParallelConnection::MessageType::HostshipRequest,
buffer
)
);
}
void ParallelPeer::resignHostship() {
std::vector<char> buffer;
_connection.sendMessage(ParallelConnection::Message(
ParallelConnection::MessageType::HostshipResignation,
buffer
));
_connection.sendMessage(
ParallelConnection::Message(
ParallelConnection::MessageType::HostshipResignation,
std::vector<char>()
)
);
}
void ParallelPeer::setPassword(std::string password) {
@@ -537,8 +539,8 @@ void ParallelPeer::sendScript(std::string script) {
std::vector<char> buffer;
sm.serialize(buffer);
double timestamp = global::windowDelegate->applicationTime();
ParallelConnection::DataMessage message(
const double timestamp = global::windowDelegate->applicationTime();
const ParallelConnection::DataMessage message = ParallelConnection::DataMessage(
datamessagestructures::Type::ScriptData,
timestamp,
buffer
@@ -549,22 +551,22 @@ void ParallelPeer::sendScript(std::string script) {
void ParallelPeer::resetTimeOffset() {
global::navigationHandler->keyframeNavigator().clearKeyframes();
global::timeManager->clearKeyframes();
std::lock_guard latencyLock(_latencyMutex);
const std::lock_guard latencyLock(_latencyMutex);
_latencyDiffs.clear();
}
void ParallelPeer::preSynchronization() {
ZoneScoped;
std::unique_lock<std::mutex> unlock(_receiveBufferMutex);
const std::unique_lock unlock(_receiveBufferMutex);
while (!_receiveBuffer.empty()) {
ParallelConnection::Message& message = _receiveBuffer.front();
const ParallelConnection::Message& message = _receiveBuffer.front();
handleMessage(message);
_receiveBuffer.pop_front();
}
if (isHost()) {
double now = global::windowDelegate->applicationTime();
const double now = global::windowDelegate->applicationTime();
if (_lastCameraKeyframeTimestamp + _cameraKeyframeInterval < now) {
sendCameraKeyframe();
@@ -586,7 +588,7 @@ void ParallelPeer::preSynchronization() {
void ParallelPeer::setStatus(ParallelConnection::Status status) {
if (_status != status) {
ParallelConnection::Status prevStatus = _status;
const ParallelConnection::Status prevStatus = _status;
_status = status;
_timeJumped = true;
_connectionEvent->publish("statusChanged");
@@ -768,7 +770,7 @@ void ParallelPeer::sendTimeTimeline() {
// Fill the timeline buffer
timelineMessage.serialize(buffer);
double timestamp = global::windowDelegate->applicationTime();
const double timestamp = global::windowDelegate->applicationTime();
// Send message
_connection.sendDataMessage(ParallelConnection::DataMessage(
datamessagestructures::Type::TimelineData,
+1 -1
View File
@@ -46,7 +46,7 @@ int DoubleListProperty::typeLua() const {
}
std::string DoubleListProperty::toStringConversion() const {
nlohmann::json json(_value);
const nlohmann::json json(_value);
return json.dump();
}
+1 -1
View File
@@ -45,7 +45,7 @@ int IntListProperty::typeLua() const {
}
std::string IntListProperty::toStringConversion() const {
nlohmann::json json(_value);
const nlohmann::json json = _value;
return json.dump();
}
+1 -1
View File
@@ -46,7 +46,7 @@ int StringListProperty::typeLua() const {
}
std::string StringListProperty::toStringConversion() const {
nlohmann::json json(_value);
const nlohmann::json json = nlohmann::json(_value);
return json.dump();
}
+9 -11
View File
@@ -59,7 +59,7 @@ const std::vector<OptionProperty::Option>& OptionProperty::options() const {
}
void OptionProperty::addOption(int value, std::string desc) {
Option option = { .value = std::move(value), .description = std::move(desc) };
Option option = { .value = value, .description = std::move(desc) };
for (const Option& o : _options) {
if (o.value == option.value) {
@@ -79,7 +79,7 @@ void OptionProperty::addOption(int value, std::string desc) {
void OptionProperty::addOptions(std::vector<std::pair<int, std::string>> options) {
for (std::pair<int, std::string>& p : options) {
addOption(std::move(p.first), std::move(p.second));
addOption(p.first, std::move(p.second));
}
}
@@ -96,9 +96,8 @@ void OptionProperty::clearOptions() {
void OptionProperty::setValue(int value) {
// Check if the passed value belongs to any option
for (size_t i = 0; i < _options.size(); i++) {
const Option& o = _options[i];
if (o.value == value) {
for (const Option& option : _options) {
if (option.value == value) {
// If it does, set it by calling the superclasses setValue method
// @TODO(abock): This should be setValue(value) instead or otherwise the
// stored indices and option values start to drift if the
@@ -154,14 +153,13 @@ std::string OptionProperty::getDescriptionByValue(int value) {
std::string OptionProperty::generateAdditionalJsonDescription() const {
// @REFACTOR from selectionproperty.cpp, possible refactoring? ---abock
std::string result =
"{ \"" + OptionsKey + "\": [";
std::string result = "{ \"" + OptionsKey + "\": [";
for (size_t i = 0; i < _options.size(); i++) {
const Option& o = _options[i];
std::string v = std::to_string(o.value);
std::string vSan = escapedJson(v);
std::string d = o.description;
std::string dSan = escapedJson(d);
const std::string v = std::to_string(o.value);
const std::string vSan = escapedJson(v);
const std::string d = o.description;
const std::string dSan = escapedJson(d);
result += '{';
result += fmt::format(R"("{}": "{}")", vSan, dSan);
+19 -17
View File
@@ -80,9 +80,9 @@ std::string Property::fullyQualifiedIdentifier() const {
std::string identifier = _identifier;
PropertyOwner* currentOwner = owner();
while (currentOwner) {
std::string ownerId = currentOwner->identifier();
const std::string& ownerId = currentOwner->identifier();
if (!ownerId.empty()) {
identifier = ownerId + "." + identifier;
identifier = fmt::format("{}.{}", ownerId, identifier);
}
currentOwner = currentOwner->owner();
}
@@ -157,7 +157,7 @@ void Property::setNeedsConfirmation(bool state) {
void Property::setViewOption(std::string option, bool value) {
ghoul::Dictionary d;
d.setValue(option, value);
d.setValue(std::move(option), value);
_metaData.setValue(std::string(MetaDataKeyViewOptions), d);
}
@@ -165,7 +165,8 @@ bool Property::viewOption(const std::string& option, bool defaultValue) const {
if (!_metaData.hasValue<ghoul::Dictionary>(MetaDataKeyViewOptions)) {
return defaultValue;
}
ghoul::Dictionary d = _metaData.value<ghoul::Dictionary>(MetaDataKeyViewOptions);
const ghoul::Dictionary d =
_metaData.value<ghoul::Dictionary>(MetaDataKeyViewOptions);
if (d.hasKey(option)) {
return d.value<bool>(option);
}
@@ -185,7 +186,7 @@ std::string Property::jsonValue() const {
Property::OnChangeHandle Property::onChange(std::function<void()> callback) {
ghoul_assert(callback, "The callback must not be empty");
OnChangeHandle handle = _currentHandleValue++;
const OnChangeHandle handle = _currentHandleValue++;
_onChangeCallbacks.emplace_back(handle, std::move(callback));
return handle;
}
@@ -193,7 +194,7 @@ Property::OnChangeHandle Property::onChange(std::function<void()> callback) {
Property::OnChangeHandle Property::onDelete(std::function<void()> callback) {
ghoul_assert(callback, "The callback must not be empty");
OnDeleteHandle handle = _currentHandleValue++;
const OnDeleteHandle handle = _currentHandleValue++;
_onDeleteCallbacks.emplace_back(handle, std::move(callback));
return handle;
}
@@ -266,13 +267,13 @@ void Property::resetToUnchanged() {
}
std::string Property::generateJsonDescription() const {
std::string cName = escapedJson(std::string(className()));
std::string identifier = fullyQualifiedIdentifier();
std::string identifierSan = escapedJson(identifier);
std::string gName = guiName();
std::string gNameSan = escapedJson(gName);
std::string metaData = generateMetaDataJsonDescription();
std::string description = generateAdditionalJsonDescription();
const std::string cName = escapedJson(std::string(className()));
const std::string identifier = fullyQualifiedIdentifier();
const std::string identifierSan = escapedJson(identifier);
const std::string gName = guiName();
const std::string gNameSan = escapedJson(gName);
const std::string metaData = generateMetaDataJsonDescription();
const std::string description = generateAdditionalJsonDescription();
return fmt::format(
R"({{"{}":"{}","{}":"{}","{}":"{}","{}":{},"{}":{}}})",
@@ -290,8 +291,9 @@ std::string Property::generateMetaDataJsonDescription() const {
{ Visibility::Developer, "Developer" },
{ Visibility::Hidden, "Hidden" }
};
Visibility visibility = static_cast<Visibility>(
_metaData.value<std::underlying_type_t<Visibility>>(MetaDataKeyVisibility));
const Visibility visibility = static_cast<Visibility>(
_metaData.value<std::underlying_type_t<Visibility>>(MetaDataKeyVisibility)
);
const std::string& vis = VisibilityConverter.at(visibility);
bool isReadOnly = false;
@@ -306,8 +308,8 @@ std::string Property::generateMetaDataJsonDescription() const {
}
std::string needsConfirmationString = (needsConfirmation ? "true" : "false");
std::string groupId = groupIdentifier();
std::string sanitizedGroupId = escapedJson(groupId);
const std::string groupId = groupIdentifier();
const std::string sanitizedGroupId = escapedJson(groupId);
std::string viewOptions = "{}";
if (_metaData.hasValue<ghoul::Dictionary>(MetaDataKeyViewOptions)) {
+9 -14
View File
@@ -58,7 +58,7 @@ namespace {
for (properties::Property* p : properties) {
nlohmann::json propertyJson;
std::string name = !p->guiName().empty() ? p->guiName() : p->identifier();
propertyJson["name"] = name;
propertyJson["name"] = std::move(name);
propertyJson["type"] = p->className();
propertyJson["uri"] = p->fullyQualifiedIdentifier();
propertyJson["identifier"] = p->identifier();
@@ -70,7 +70,6 @@ namespace {
auto propertyOwners = owner->propertySubOwners();
for (properties::PropertyOwner* o : propertyOwners) {
nlohmann::json propertyOwner;
json["propertyOwners"].push_back(createJson(o));
}
sortJson(json["propertyOwners"], "name");
@@ -157,10 +156,7 @@ bool PropertyOwner::hasProperty(const std::string& uri) const {
bool PropertyOwner::hasProperty(const Property* prop) const {
ghoul_precondition(prop != nullptr, "prop must not be nullptr");
std::vector<Property*>::const_iterator it = std::find(
_properties.begin(), _properties.end(), prop
);
auto it = std::find(_properties.begin(), _properties.end(), prop);
return it != _properties.end();
}
@@ -169,7 +165,7 @@ const std::vector<PropertyOwner*>& PropertyOwner::propertySubOwners() const {
}
PropertyOwner* PropertyOwner::propertySubOwner(const std::string& identifier) const {
std::vector<PropertyOwner*>::const_iterator it = std::find_if(
auto it = std::find_if(
_subOwners.begin(),
_subOwners.end(),
[&identifier](PropertyOwner* owner) { return owner->identifier() == identifier; }
@@ -209,7 +205,7 @@ void PropertyOwner::addProperty(Property* prop) {
return;
}
// See if we can find the identifier of the property to add in the properties list
std::vector<Property*>::const_iterator it = std::find_if(
auto it = std::find_if(
_properties.begin(),
_properties.end(),
[id = prop->identifier()](Property* p) { return p->identifier() == id; }
@@ -253,7 +249,7 @@ void PropertyOwner::addPropertySubOwner(openspace::properties::PropertyOwner* ow
);
// See if we can find the name of the propertyowner to add using the lower bound
std::vector<PropertyOwner*>::const_iterator it = std::find_if(
auto it = std::find_if(
_subOwners.begin(),
_subOwners.end(),
[identifier = owner->identifier()](PropertyOwner* o) {
@@ -294,7 +290,7 @@ void PropertyOwner::removeProperty(Property* prop) {
ghoul_precondition(prop != nullptr, "prop must not be nullptr");
// See if we can find the identifier of the property to add in the properties list
std::vector<Property*>::const_iterator it = std::find_if(
auto it = std::find_if(
_properties.begin(),
_properties.end(),
[id = prop->identifier()](Property* p) { return p->identifier() == id; }
@@ -320,7 +316,7 @@ void PropertyOwner::removePropertySubOwner(openspace::properties::PropertyOwner*
ghoul_precondition(owner != nullptr, "owner must not be nullptr");
// See if we can find the name of the propertyowner to add
std::vector<PropertyOwner*>::const_iterator it = std::find_if(
auto it = std::find_if(
_subOwners.begin(),
_subOwners.end(),
[identifier = owner->identifier()](PropertyOwner* o) {
@@ -390,12 +386,11 @@ nlohmann::json PropertyOwner::generateJson() const {
ZoneScoped;
nlohmann::json json;
std::vector<PropertyOwner*> subOwners = propertySubOwners();
const std::vector<PropertyOwner*>& subOwners = propertySubOwners();
for (PropertyOwner* owner : subOwners) {
if (owner->identifier() != "Scene") {
nlohmann::json jsonOwner = createJson(owner);
json.push_back(jsonOwner);
json.push_back(std::move(jsonOwner));
}
}
sortJson(json, "name");
+9 -9
View File
@@ -99,7 +99,7 @@ void SelectionProperty::setOptions(const std::vector<std::string>& keys) {
sortOptions();
// In case we have a selection, remove non-existing options
bool changed = removeInvalidKeys(_value);
const bool changed = removeInvalidKeys(_value);
if (changed) {
_isValueDirty = true;
}
@@ -135,12 +135,12 @@ std::set<std::string> SelectionProperty::fromLuaConversion(lua_State* state) con
}
void SelectionProperty::toLuaConversion(lua_State* state) const {
std::vector<std::string> value(_value.begin(), _value.end());
const std::vector<std::string> value(_value.begin(), _value.end());
ghoul::lua::push(state, value);
}
std::string SelectionProperty::toStringConversion() const {
nlohmann::json json(_value);
const nlohmann::json json(_value);
return json.dump();
}
@@ -148,9 +148,9 @@ void SelectionProperty::sortOptions() {
std::sort(_options.begin(), _options.end());
}
bool SelectionProperty::removeInvalidKeys(std::set<std::string>& keys) {
bool SelectionProperty::removeInvalidKeys(std::set<std::string>& keys) const {
bool changed = false;
std::set<std::string>::iterator it = keys.begin();
auto it = keys.begin();
while (it != keys.end()) {
if (!hasOption(*it)) {
LWARNING(fmt::format(
@@ -167,10 +167,10 @@ bool SelectionProperty::removeInvalidKeys(std::set<std::string>& keys) {
}
std::string SelectionProperty::generateAdditionalJsonDescription() const {
nlohmann::json optionsJson(_options);
std::string result = "{ ";
result += fmt::format("\"{}\": {}", OptionsKey, optionsJson.dump());
result += " }";
const nlohmann::json optionsJson(_options);
std::string result = fmt::format(
R"({{ "{}": {} }})", OptionsKey, optionsJson.dump()
);
return result;
}
+13 -13
View File
@@ -240,7 +240,7 @@ ColorMappingComponent::ColorMappingComponent()
addProperty(setRangeFromData);
colorMapFile.onChange([this]() {
bool fileExists = std::filesystem::exists(colorMapFile.value());
const bool fileExists = std::filesystem::exists(colorMapFile.value());
if (!fileExists) {
LERROR(fmt::format("Could not find cmap file: {}", colorMapFile.value()));
}
@@ -354,9 +354,9 @@ void ColorMappingComponent::initializeTexture() {
return;
}
unsigned int width = static_cast<unsigned int>(_colorMap.entries.size());
unsigned int height = 1;
unsigned int size = width * height;
const unsigned int width = static_cast<unsigned int>(_colorMap.entries.size());
const unsigned int height = 1;
const unsigned int size = width * height;
std::vector<GLubyte> img;
img.reserve(size * 4);
@@ -399,14 +399,14 @@ void ColorMappingComponent::update(const dataloader::Dataset& dataset) {
}
glm::vec4 ColorMappingComponent::colorFromColorMap(float valueToColorFrom) const {
glm::vec2 currentColorRange = valueRange;
float cmax = currentColorRange.y;
float cmin = currentColorRange.x;
const glm::vec2 currentColorRange = valueRange;
const float cmax = currentColorRange.y;
const float cmin = currentColorRange.x;
float nColors = static_cast<float>(_colorMap.entries.size());
const float nColors = static_cast<float>(_colorMap.entries.size());
bool isOutsideMin = valueToColorFrom < cmin;
bool isOutsideMax = valueToColorFrom > cmax;
const bool isOutsideMin = valueToColorFrom < cmin;
const bool isOutsideMax = valueToColorFrom > cmax;
if (hideOutsideRange && (isOutsideMin || isOutsideMax)) {
return glm::vec4(0.f);
@@ -417,7 +417,7 @@ glm::vec4 ColorMappingComponent::colorFromColorMap(float valueToColorFrom) const
}
// Find color value using Nearest neighbor (same as texture)
float normalization = (cmax != cmin) ? (nColors) / (cmax - cmin) : 0;
const float normalization = (cmax != cmin) ? (nColors) / (cmax - cmin) : 0;
int colorIndex = static_cast<int>((valueToColorFrom - cmin) * normalization);
// Clamp color index to valid range
@@ -434,8 +434,8 @@ void ColorMappingComponent::initializeParameterData(const dataloader::Dataset& d
// Initialize empty ranges based on values in the dataset
for (const properties::OptionProperty::Option& option : dataColumn.options()) {
int optionIndex = option.value;
int colorParameterIndex = dataset.index(option.description);
const int optionIndex = option.value;
const int colorParameterIndex = dataset.index(option.description);
glm::vec2& range = _colorRangeData[optionIndex];
if (glm::length(range) < glm::epsilon<float>()) {
+2 -2
View File
@@ -61,7 +61,7 @@ documentation::Documentation DashboardItem::Documentation() {
}
std::unique_ptr<DashboardItem> DashboardItem::createFromDictionary(
ghoul::Dictionary dictionary)
const ghoul::Dictionary& dictionary)
{
ghoul::TemplateFactory<DashboardItem>* factory =
FactoryManager::ref().factory<DashboardItem>();
@@ -69,7 +69,7 @@ std::unique_ptr<DashboardItem> DashboardItem::createFromDictionary(
const std::string& dashboardType = dictionary.value<std::string>(KeyType);
DashboardItem* item = factory->create(dashboardType, std::move(dictionary));
DashboardItem* item = factory->create(dashboardType, dictionary);
item->_type = dashboardType;
return std::unique_ptr<DashboardItem>(item);
+42 -43
View File
@@ -77,7 +77,7 @@ namespace {
constexpr std::string_view RenderFragmentShaderPath =
"${SHADERS}/framebuffer/renderframebuffer.frag";
const GLenum ColorAttachmentArray[4] = {
constexpr std::array<GLenum, 4> ColorAttachmentArray = {
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2,
@@ -92,7 +92,7 @@ namespace openspace {
//============================//
GLuint FramebufferRenderer::additionalColorTexture1() const {
// Gives access to the currently NOT used pingPongTexture
int unusedPingPongIndex = _pingPongIndex == 0 ? 1 : 0;
const int unusedPingPongIndex = _pingPongIndex == 0 ? 1 : 0;
return _pingPongBuffers.colorTexture[unusedPingPongIndex];
}
@@ -140,7 +140,7 @@ void FramebufferRenderer::initialize() {
LDEBUG("Initializing FramebufferRenderer");
const GLfloat vertexData[] = {
constexpr std::array<GLfloat, 12> VertexData = {
// x y
-1.f, -1.f,
1.f, 1.f,
@@ -156,7 +156,7 @@ void FramebufferRenderer::initialize() {
glGenBuffers(1, &_vertexPositionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr);
glEnableVertexAttribArray(0);
@@ -492,8 +492,8 @@ void FramebufferRenderer::applyFXAA(const glm::ivec4& viewport) {
renderedTextureUnit
);
glm::vec2 inverseScreenSize = glm::vec2(1.f / _resolution.x, 1.f / _resolution.y);
_fxaaProgram->setUniform(_fxaaUniformCache.inverseScreenSize, inverseScreenSize);
const glm::vec2 invScreenSize = glm::vec2(1.f / _resolution.x, 1.f / _resolution.y);
_fxaaProgram->setUniform(_fxaaUniformCache.inverseScreenSize, invScreenSize);
_fxaaProgram->setUniform(_fxaaUniformCache.Viewport, glm::vec4(viewport));
_fxaaProgram->setUniform(_fxaaUniformCache.Resolution, glm::vec2(_resolution));
@@ -510,8 +510,8 @@ void FramebufferRenderer::applyFXAA(const glm::ivec4& viewport) {
_fxaaProgram->deactivate();
}
void FramebufferRenderer::updateDownscaleTextures() {
float cdf = _downscaleVolumeRendering.currentDownscaleFactor;
void FramebufferRenderer::updateDownscaleTextures() const {
const float cdf = _downscaleVolumeRendering.currentDownscaleFactor;
glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture);
glTexImage2D(
@@ -833,7 +833,7 @@ void FramebufferRenderer::updateResolution() {
glObjectLabel(GL_TEXTURE, _fxaaBuffers.fxaaTexture, -1, "FXAA");
}
float cdf = _downscaleVolumeRendering.currentDownscaleFactor;
const float cdf = _downscaleVolumeRendering.currentDownscaleFactor;
// Downscale Volume Rendering
glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture);
@@ -853,8 +853,8 @@ void FramebufferRenderer::updateResolution() {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
float volumeBorderColor[] = { 0.f, 0.f, 0.f, 1.f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, volumeBorderColor);
constexpr std::array<float, 4> VolumeBorderColor = { 0.f, 0.f, 0.f, 1.f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, VolumeBorderColor.data());
if (glbinding::Binding::ObjectLabel.isResolved()) {
glObjectLabel(
GL_TEXTURE,
@@ -1019,14 +1019,14 @@ void FramebufferRenderer::updateDeferredcastData() {
for (Deferredcaster* caster : deferredcasters) {
DeferredcastData data = { .id = nextId++, .namespaceName = "HELPER" };
std::filesystem::path vsPath = caster->deferredcastVSPath();
std::filesystem::path fsPath = caster->deferredcastFSPath();
const std::filesystem::path vsPath = caster->deferredcastVSPath();
const std::filesystem::path fsPath = caster->deferredcastFSPath();
ghoul::Dictionary dict;
dict.setValue("rendererData", _rendererData);
//dict.setValue("fragmentPath", fsPath);
dict.setValue("id", data.id);
std::filesystem::path helperPath = caster->helperPath();
const std::filesystem::path helperPath = caster->helperPath();
ghoul::Dictionary helpersDict;
if (!helperPath.empty()) {
helpersDict.setValue("0", helperPath.string());
@@ -1090,10 +1090,10 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO);
global::renderEngine->openglStateCache().setDefaultFramebuffer(_defaultFBO);
GLint vp[4] = { 0 };
glGetIntegerv(GL_VIEWPORT, vp);
global::renderEngine->openglStateCache().setViewportState(vp);
glm::ivec4 viewport = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);
std::array<GLint, 4> vp = {};
glGetIntegerv(GL_VIEWPORT, vp.data());
global::renderEngine->openglStateCache().setViewportState(vp.data());
const glm::ivec4 viewport = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);
// Reset Render Pipeline State
global::renderEngine->openglStateCache().resetCachedStates();
@@ -1110,36 +1110,35 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
TracyGpuZone("Deferred G-Buffer");
glBindFramebuffer(GL_FRAMEBUFFER, _gBuffers.framebuffer);
glDrawBuffers(3, ColorAttachmentArray);
glDrawBuffers(3, ColorAttachmentArray.data());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearBufferfv(GL_COLOR, 1, glm::value_ptr(PosBufferClearVal));
}
Time time = global::timeManager->time();
RenderData data = {
.camera = *camera,
.time = std::move(time),
.time = global::timeManager->time(),
.renderBinMask = 0
};
RendererTasks tasks;
{
TracyGpuZone("Background")
ghoul::GLDebugGroup group("Background");
const ghoul::GLDebugGroup group("Background");
data.renderBinMask = static_cast<int>(Renderable::RenderBin::Background);
scene->render(data, tasks);
}
{
TracyGpuZone("Opaque")
ghoul::GLDebugGroup group("Opaque");
const ghoul::GLDebugGroup group("Opaque");
data.renderBinMask = static_cast<int>(Renderable::RenderBin::Opaque);
scene->render(data, tasks);
}
{
TracyGpuZone("PreDeferredTransparent")
ghoul::GLDebugGroup group("PreDeferredTransparent");
const ghoul::GLDebugGroup group("PreDeferredTransparent");
data.renderBinMask = static_cast<int>(
Renderable::RenderBin::PreDeferredTransparent
);
@@ -1149,13 +1148,13 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
// Run Volume Tasks
{
TracyGpuZone("Raycaster Tasks")
ghoul::GLDebugGroup group("Raycaster Tasks");
const ghoul::GLDebugGroup group("Raycaster Tasks");
performRaycasterTasks(tasks.raycasterTasks, viewport);
}
if (!tasks.deferredcasterTasks.empty()) {
TracyGpuZone("Deferred Caster Tasks")
ghoul::GLDebugGroup group("Deferred Caster Tasks");
const ghoul::GLDebugGroup group("Deferred Caster Tasks");
// We use ping pong rendering in order to be able to render multiple deferred
// tasks at same time (e.g. more than 1 ATM being seen at once) to the same final
@@ -1171,14 +1170,14 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
{
TracyGpuZone("Overlay")
ghoul::GLDebugGroup group("Overlay");
const ghoul::GLDebugGroup group("Overlay");
data.renderBinMask = static_cast<int>(Renderable::RenderBin::Overlay);
scene->render(data, tasks);
}
{
TracyGpuZone("PostDeferredTransparent")
ghoul::GLDebugGroup group("PostDeferredTransparent");
const ghoul::GLDebugGroup group("PostDeferredTransparent");
data.renderBinMask = static_cast<int>(
Renderable::RenderBin::PostDeferredTransparent
);
@@ -1187,7 +1186,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
{
TracyGpuZone("Sticker")
ghoul::GLDebugGroup group("Sticker");
const ghoul::GLDebugGroup group("Sticker");
data.renderBinMask = static_cast<int>(
Renderable::RenderBin::Sticker
);
@@ -1201,7 +1200,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
if (_enableFXAA) {
glBindFramebuffer(GL_FRAMEBUFFER, _fxaaBuffers.fxaaFramebuffer);
glDrawBuffers(1, ColorAttachmentArray);
glDrawBuffers(1, ColorAttachmentArray.data());
glDisable(GL_BLEND);
}
@@ -1214,14 +1213,14 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac
{
// Apply the selected TMO on the results and resolve the result to the default FBO
TracyGpuZone("Apply TMO");
ghoul::GLDebugGroup group("Apply TMO");
const ghoul::GLDebugGroup group("Apply TMO");
applyTMO(blackoutFactor, viewport);
}
if (_enableFXAA) {
TracyGpuZone("Apply FXAA")
ghoul::GLDebugGroup group("Apply FXAA");
const ghoul::GLDebugGroup group("Apply FXAA");
glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO);
applyFXAA(viewport);
}
@@ -1251,13 +1250,13 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector<RaycasterTask>
if (raycaster->downscaleRender() < 1.f) {
glBindFramebuffer(GL_FRAMEBUFFER, _downscaleVolumeRendering.framebuffer);
const float s = raycaster->downscaleRender();
GLint newVP[4] = {
const std::array<GLint, 4> newVP = {
static_cast<GLint>(viewport[0] * s),
static_cast<GLint>(viewport[1] * s),
static_cast<GLint>(viewport[2] * s),
static_cast<GLint>(viewport[3] * s)
};
global::renderEngine->openglStateCache().setViewportState(newVP);
global::renderEngine->openglStateCache().setViewportState(newVP.data());
if (_downscaleVolumeRendering.currentDownscaleFactor != s) {
_downscaleVolumeRendering.currentDownscaleFactor = s;
@@ -1270,7 +1269,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector<RaycasterTask>
}
glm::vec3 cameraPosition = glm::vec3(0.f);
bool isCameraInside = raycaster->isCameraInside(
const bool isCameraInside = raycaster->isCameraInside(
raycasterTask.renderData,
cameraPosition
);
@@ -1320,7 +1319,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector<RaycasterTask>
raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit);
if (raycaster->downscaleRender() < 1.f) {
float scaleDown = raycaster->downscaleRender();
const float scaleDown = raycaster->downscaleRender();
raycastProgram->setUniform(
"windowSize",
glm::vec2(_resolution.x * scaleDown, _resolution.y * scaleDown)
@@ -1379,7 +1378,7 @@ void FramebufferRenderer::performDeferredTasks(
if (deferredcastProgram) {
_pingPongIndex = _pingPongIndex == 0 ? 1 : 0;
int fromIndex = _pingPongIndex == 0 ? 1 : 0;
const int fromIndex = _pingPongIndex == 0 ? 1 : 0;
glDrawBuffers(1, &ColorAttachmentArray[_pingPongIndex]);
glDisablei(GL_BLEND, 0);
glDisablei(GL_BLEND, 1);
@@ -1462,25 +1461,25 @@ void FramebufferRenderer::setResolution(glm::ivec2 res) {
}
void FramebufferRenderer::setDisableHDR(bool disable) {
_disableHDR = std::move(disable);
_disableHDR = disable;
}
void FramebufferRenderer::setHDRExposure(float hdrExposure) {
ghoul_assert(hdrExposure > 0.f, "HDR exposure must be greater than zero");
_hdrExposure = std::move(hdrExposure);
_hdrExposure = hdrExposure;
updateRendererData();
}
void FramebufferRenderer::setGamma(float gamma) {
ghoul_assert(gamma > 0.f, "Gamma value must be greater than zero");
_gamma = std::move(gamma);
_gamma = gamma;
}
void FramebufferRenderer::setHueValueSaturation(float hue, float value, float saturation)
{
_hue = std::move(hue);
_value = std::move(value);
_saturation = std::move(saturation);
_hue = hue;
_value = value;
_saturation = saturation;
}
void FramebufferRenderer::enableFXAA(bool enable) {
+37 -21
View File
@@ -221,11 +221,11 @@ void initialize() {
glBindBuffer(GL_ARRAY_BUFFER, vertexObjects.square.vbo);
struct VertexXYUVRGBA {
GLfloat xy[2];
GLfloat uv[2];
GLfloat rgba[4];
std::array<GLfloat, 2> xy;
std::array<GLfloat, 2> uv;
std::array<GLfloat, 4> rgba;
};
VertexXYUVRGBA data[] = {
constexpr std::array<VertexXYUVRGBA, 6> Vtx = {
// X Y U V R G B A
-1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f,
-1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f,
@@ -235,16 +235,28 @@ void initialize() {
1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f,
1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f
};
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(VertexXYUVRGBA), data, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(VertexXYUVRGBA), Vtx.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA), nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA),
reinterpret_cast<GLvoid*>(offsetof(VertexXYUVRGBA, uv)));
glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
sizeof(VertexXYUVRGBA),
reinterpret_cast<GLvoid*>(offsetof(VertexXYUVRGBA, uv))
);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA),
reinterpret_cast<GLvoid*>(offsetof(VertexXYUVRGBA, rgba)));
glVertexAttribPointer(
2,
4,
GL_FLOAT,
GL_FALSE,
sizeof(VertexXYUVRGBA),
reinterpret_cast<GLvoid*>(offsetof(VertexXYUVRGBA, rgba))
);
glBindVertexArray(0);
@@ -502,7 +514,7 @@ std::vector<VertexXYZ> convert(std::vector<Vertex> v) {
}
Vertex computeCircleVertex(int i, int nSegments, float radius,
glm::vec4 color = glm::vec4(1.f))
const glm::vec4& color = glm::vec4(1.f))
{
const float fsegments = static_cast<float>(nSegments);
@@ -520,7 +532,7 @@ Vertex computeCircleVertex(int i, int nSegments, float radius,
return { x, y, z, u, v, color.r, color.g, color.b, color.a };
}
std::vector<Vertex> createRing(int nSegments, float radius, glm::vec4 colors) {
std::vector<Vertex> createRing(int nSegments, float radius, const glm::vec4& colors) {
const int nVertices = nSegments + 1;
std::vector<Vertex> vertices(nVertices);
@@ -535,14 +547,14 @@ std::vector<VertexXYZ> createRingXYZ(int nSegments, float radius) {
std::vector<VertexXYZ> vertices(nVertices);
for (int i = 0; i <= nSegments; i++) {
Vertex fullVertex = computeCircleVertex(i, nSegments, radius);
const Vertex fullVertex = computeCircleVertex(i, nSegments, radius);
vertices[i] = { fullVertex.xyz[0], fullVertex.xyz[1], fullVertex.xyz[2] };
}
return vertices;
}
VertexIndexListCombo<Vertex> createSphere(int nSegments, glm::vec3 radii,
glm::vec4 colors)
const glm::vec4& colors)
{
std::vector<Vertex> vertices;
vertices.reserve(nSegments * nSegments);
@@ -558,9 +570,10 @@ VertexIndexListCombo<Vertex> createSphere(int nSegments, glm::vec3 radii,
// 0 -> 2*PI
const float phi = fj * glm::pi<float>() * 2.f / nSegments;
const float x = radii[0] * sin(theta) * cos(phi);
const float y = radii[1] * sin(theta) * sin(phi);
const float z = radii[2] * cos(theta); // Z points towards pole (theta = 0)
const float x = radii[0] * std::sin(theta) * std::cos(phi);
const float y = radii[1] * std::sin(theta) * std::sin(phi);
// Z points towards pole (theta = 0)
const float z = radii[2] * std::cos(theta);
Vertex v;
v.xyz[0] = x;
@@ -640,7 +653,7 @@ VertexIndexListCombo<VertexXYZNormal> createConicalCylinder(unsigned int nSegmen
);
}
else {
glm::vec3 p = glm::closestPointOnLine(
const glm::vec3 p = glm::closestPointOnLine(
glm::vec3(0.f),
glm::vec3(vBot.xyz[0], vBot.xyz[1], vBot.xyz[2]),
glm::vec3(vTop.xyz[0], vTop.xyz[1], vTop.xyz[2])
@@ -693,12 +706,15 @@ VertexIndexListCombo<VertexXYZNormal> createConicalCylinder(unsigned int nSegmen
return static_cast<GLushort>(1 + ringIndex * (nSegments + 1) + i);
};
GLushort botCenterIndex = 0;
GLushort topCenterIndex = static_cast<GLushort>(vertices.size()) - 1;
const GLushort botCenterIndex = 0;
const GLushort topCenterIndex = static_cast<GLushort>(vertices.size()) - 1;
for (unsigned int i = 0; i < nSegments; i++) {
bool isLast = (i == nSegments - 1);
GLushort v0, v1, v2, v3;
const bool isLast = (i == nSegments - 1);
GLushort v0 = 0;
GLushort v1 = 0;
GLushort v2 = 0;
GLushort v3 = 0;
// Bottom triangle
v0 = ringVerticeIndex(0, i);
+8 -6
View File
@@ -289,9 +289,10 @@ void LabelsComponent::render(const RenderData& data,
if (!_enabled) {
return;
}
float scale = static_cast<float>(toMeter(_unit));
const float scale = static_cast<float>(toMeter(_unit));
int renderOption = _faceCamera ? RenderOptionFaceCamera : RenderOptionPositionNormal;
const int renderOption =
_faceCamera ? RenderOptionFaceCamera : RenderOptionPositionNormal;
ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo;
labelInfo.orthoRight = orthoRight;
@@ -306,7 +307,7 @@ void LabelsComponent::render(const RenderData& data,
labelInfo.enableDepth = true;
labelInfo.enableFalseDepth = false;
glm::vec4 textColor = glm::vec4(glm::vec3(_color), opacity() * fadeInVariable);
const glm::vec4 textColor = glm::vec4(glm::vec3(_color), opacity() * fadeInVariable);
for (const dataloader::Labelset::Entry& e : _labelset.entries) {
if (!e.isEnabled) {
@@ -314,9 +315,10 @@ void LabelsComponent::render(const RenderData& data,
}
// Transform and scale the labels
glm::vec3 transformedPos(_transformationMatrix * glm::dvec4(e.position, 1.0));
glm::vec3 scaledPos(transformedPos);
scaledPos *= scale;
const glm::vec3 transformedPos = glm::vec3(
_transformationMatrix * glm::dvec4(e.position, 1.0)
);
const glm::vec3 scaledPos = glm::vec3(transformedPos * scale);
ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render(
*_font,
+16 -20
View File
@@ -84,15 +84,11 @@ namespace {
rhsLl -= glm::vec2(ItemStandoffDistance / 2.f);
rhsUr += glm::vec2(ItemStandoffDistance / 2.f);
return !(
lhsUr.x < rhsLl.x ||
lhsLl.x > rhsUr.x ||
lhsUr.y < rhsLl.y ||
lhsLl.y > rhsUr.y
);
return lhsUr.x >= rhsLl.x && lhsLl.x <= rhsUr.x &&
lhsUr.y >= rhsLl.y && lhsLl.y <= rhsUr.y;
}
glm::vec2 ndcToScreen(glm::vec2 ndc, glm::ivec2 res) {
glm::vec2 ndcToScreen(glm::vec2 ndc, const glm::ivec2& res) {
ndc.x = (ndc.x + 1.f) / 2.f * res.x;
ndc.y = (ndc.y + 1.f) / 2.f * res.y;
return ndc;
@@ -261,7 +257,7 @@ void LoadingScreen::exec(AssetManager& manager, Scene& scene) {
return;
}
bool finishedLoading = std::all_of(
const bool finishedLoading = std::all_of(
allAssets.begin(),
allAssets.end(),
[](const Asset* asset) { return asset->isInitialized() || asset->isFailed(); }
@@ -298,9 +294,9 @@ void LoadingScreen::render() {
const glm::ivec2 res =
glm::vec2(global::windowDelegate->firstWindowResolution()) * dpiScaling;
float screenAspectRatio = static_cast<float>(res.x) / static_cast<float>(res.y);
const float screenAspectRatio = static_cast<float>(res.x) / static_cast<float>(res.y);
float textureAspectRatio = static_cast<float>(_logoTexture->dimensions().x) /
const float textureAspectRatio = static_cast<float>(_logoTexture->dimensions().x) /
static_cast<float>(_logoTexture->dimensions().y);
ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize(res);
@@ -359,7 +355,7 @@ void LoadingScreen::render() {
glm::vec2 messageLl = glm::vec2(0.f);
glm::vec2 messageUr = glm::vec2(0.f);
if (_showMessage) {
std::lock_guard guard(_messageMutex);
const std::lock_guard guard(_messageMutex);
const glm::vec2 bboxMessage = _messageFont->boundingBox(_message);
@@ -373,8 +369,8 @@ void LoadingScreen::render() {
renderer.render(*_messageFont, messageLl, _message);
}
glm::vec2 logLl = glm::vec2(0.f, 0.f);
glm::vec2 logUr = glm::vec2(res.x, res.y * (LogBackgroundPosition + 0.015));
const glm::vec2 logLl = glm::vec2(0.f, 0.f);
const glm::vec2 logUr = glm::vec2(res.x, res.y * (LogBackgroundPosition + 0.015));
// Font rendering enables depth testing so we disable again to render the log box
glDisable(GL_DEPTH_TEST);
@@ -389,9 +385,9 @@ void LoadingScreen::render() {
}
if (_showNodeNames) {
std::lock_guard guard(_itemsMutex);
const std::lock_guard guard(_itemsMutex);
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
const auto now = std::chrono::system_clock::now();
const glm::vec2 logoLl = glm::vec2(LogoCenter.x - size.x, LogoCenter.y - size.y);
const glm::vec2 logoUr = glm::vec2(LogoCenter.x + size.x, LogoCenter.y + size.y);
@@ -585,7 +581,7 @@ void LoadingScreen::renderLogMessages() const {
const std::vector<ScreenLog::LogEntry>& entries = _log->entries();
size_t nRows = 0;
size_t j = std::min(MaxNumberMessages, entries.size());
const size_t j = std::min(MaxNumberMessages, entries.size());
for (size_t i = 1; i <= j; i++) {
ZoneScopedN("Entry");
@@ -630,13 +626,13 @@ void LoadingScreen::renderLogMessages() const {
// Render # of warnings and error messages
std::map<ghoul::logging::LogLevel, size_t> numberOfErrorsPerLevel;
for (auto& entry : _log->entries()) {
for (const auto& entry : _log->entries()) {
numberOfErrorsPerLevel[entry.level]++;
}
size_t row = 0;
for (auto& [level, amount] : numberOfErrorsPerLevel) {
const std::string text = fmt::format("{}: {}", ghoul::to_string(level), amount);
glm::vec2 bbox = _logFont->boundingBox(text);
const glm::vec2 bbox = _logFont->boundingBox(text);
renderer.render(
*_logFont,
glm::vec2(
@@ -651,7 +647,7 @@ void LoadingScreen::renderLogMessages() const {
}
void LoadingScreen::postMessage(std::string message) {
std::lock_guard guard(_messageMutex);
const std::lock_guard guard(_messageMutex);
_message = std::move(message);
}
@@ -688,7 +684,7 @@ void LoadingScreen::updateItem(const std::string& itemIdentifier,
// also would create any of the text information
return;
}
std::lock_guard guard(_itemsMutex);
const std::lock_guard guard(_itemsMutex);
auto it = std::find_if(
_items.begin(),
+17 -18
View File
@@ -56,8 +56,8 @@ namespace {
constexpr uint64_t CurrentVersion = 0xFEEE'FEEE'0000'0001;
constexpr std::string_view FontName = "Console";
constexpr float EntryFontSize = 14.0f;
constexpr float HistoryFontSize = 11.0f;
constexpr float EntryFontSize = 14.f;
constexpr float HistoryFontSize = 11.f;
// Additional space between the entry text and the history (in pixels)
constexpr float SeparatorSpace = 30.f;
@@ -183,8 +183,6 @@ LuaConsole::LuaConsole()
addProperty(_historyTextColor);
}
LuaConsole::~LuaConsole() {}
void LuaConsole::initialize() {
ZoneScoped;
@@ -197,7 +195,7 @@ void LuaConsole::initialize() {
if (file.good()) {
// Read the number of commands from the history
uint64_t version;
uint64_t version = 0;
file.read(reinterpret_cast<char*>(&version), sizeof(uint64_t));
if (version != CurrentVersion) {
@@ -207,16 +205,16 @@ void LuaConsole::initialize() {
);
}
else {
int64_t nCommands;
int64_t nCommands = 0;
file.read(reinterpret_cast<char*>(&nCommands), sizeof(int64_t));
for (int64_t i = 0; i < nCommands; i++) {
int64_t length;
int64_t length = 0;
file.read(reinterpret_cast<char*>(&length), sizeof(int64_t));
std::vector<char> tmp(length);
file.read(tmp.data(), length);
_commandsHistory.emplace_back(std::string(tmp.begin(), tmp.end()));
_commandsHistory.emplace_back(tmp.begin(), tmp.end());
}
}
}
@@ -244,7 +242,7 @@ void LuaConsole::initialize() {
"luaConsole",
"statusChanged",
[this]() {
ParallelConnection::Status status = global::parallelPeer->status();
const ParallelConnection::Status status = global::parallelPeer->status();
parallelConnectionChanged(status);
}
);
@@ -451,7 +449,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio
}
if (key == Key::Enter || key == Key::KeypadEnter) {
std::string cmd = _commands.at(_activeCommand);
const std::string cmd = _commands.at(_activeCommand);
if (!cmd.empty()) {
global::scriptEngine->queueScript(
cmd,
@@ -489,7 +487,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio
std::vector<std::string> allCommands = global::scriptEngine->allLuaFunctions();
std::sort(allCommands.begin(), allCommands.end());
std::string currentCommand = _commands.at(_activeCommand);
const std::string currentCommand = _commands.at(_activeCommand);
// Check if it is the first time the tab has been pressed. If so, we need to
// store the already entered command so that we can later start the search
@@ -510,10 +508,11 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio
const size_t fullLength = _autoCompleteInfo.initialValue.length();
const bool correctLength = command.length() >= fullLength;
std::string commandLowerCase = ghoul::toLowerCase(command);
const std::string commandLowerCase = ghoul::toLowerCase(command);
std::string initialValueLowerCase =
ghoul::toLowerCase(_autoCompleteInfo.initialValue);
const std::string initialValueLowerCase = ghoul::toLowerCase(
_autoCompleteInfo.initialValue
);
const bool correctCommand =
commandLowerCase.substr(0, fullLength) == initialValueLowerCase;
@@ -661,7 +660,7 @@ void LuaConsole::render() {
using namespace ghoul::fontrendering;
ghoul::GLDebugGroup group("LuaConsole");
const ghoul::GLDebugGroup group("LuaConsole");
// Don't render the console if it's collapsed.
if (_currentHeight < 1.f) {
@@ -831,7 +830,7 @@ void LuaConsole::render() {
else if (_shouldSendToRemote) {
const glm::vec4 Red(1.f, 0.f, 0.f, 1.f);
ParallelConnection::Status status = global::parallelPeer->status();
const ParallelConnection::Status status = global::parallelPeer->status();
const int nClients =
status != ParallelConnection::Status::Disconnected ?
global::parallelPeer->nConnections() - 1 :
@@ -863,9 +862,9 @@ void LuaConsole::setCommandInputButton(Key key) {
_commandInputButton = key;
}
void LuaConsole::addToCommand(std::string c) {
void LuaConsole::addToCommand(const std::string& c) {
const size_t length = c.length();
_commands.at(_activeCommand).insert(_inputPosition, std::move(c));
_commands.at(_activeCommand).insert(_inputPosition, c);
_inputPosition += length;
}
+15 -16
View File
@@ -116,7 +116,7 @@ documentation::Documentation Renderable::Documentation() {
}
ghoul::mm_unique_ptr<Renderable> Renderable::createFromDictionary(
ghoul::Dictionary dictionary)
const ghoul::Dictionary& dictionary)
{
if (!dictionary.hasKey(KeyType)) {
throw ghoul::RuntimeError("Tried to create Renderable but no 'Type' was found");
@@ -125,7 +125,7 @@ ghoul::mm_unique_ptr<Renderable> Renderable::createFromDictionary(
// This should be done in the constructor instead with noexhaustive
documentation::testSpecificationAndThrow(Documentation(), dictionary, "Renderable");
std::string renderableType = dictionary.value<std::string>(KeyType);
const std::string renderableType = dictionary.value<std::string>(KeyType);
ghoul::TemplateFactory<Renderable>* factory =
FactoryManager::ref().factory<Renderable>();
ghoul_assert(factory, "Renderable factory did not exist");
@@ -142,7 +142,6 @@ ghoul::mm_unique_ptr<Renderable> Renderable::createFromDictionary(
Renderable::Renderable(const ghoul::Dictionary& dictionary, RenderableSettings settings)
: properties::PropertyOwner({ "Renderable" })
, Fadeable()
, _enabled(EnabledInfo, true)
, _renderableType(RenderableTypeInfo, "Renderable")
, _dimInAtmosphere(DimInAtmosphereInfo, false)
@@ -340,29 +339,29 @@ bool Renderable::hasOverrideRenderBin() const noexcept {
glm::dmat4 Renderable::calcModelTransform(const RenderData& data,
const AlternativeTransform& altTransform) const
{
glm::dvec3 translation =
const glm::dvec3 translation =
altTransform.translation.value_or(data.modelTransform.translation);
glm::dmat3 rotation = altTransform.rotation.value_or(data.modelTransform.rotation);
glm::dvec3 scale = altTransform.scale.value_or(data.modelTransform.scale);
const glm::dmat3 rot = altTransform.rotation.value_or(data.modelTransform.rotation);
const glm::dvec3 scale = altTransform.scale.value_or(data.modelTransform.scale);
return glm::translate(glm::dmat4(1.0), translation) *
glm::dmat4(rotation) *
glm::dmat4(rot) *
glm::scale(glm::dmat4(1.0), scale);
}
glm::dmat4 Renderable::calcModelViewTransform(const RenderData& data,
std::optional<glm::dmat4> modelTransform) const
const std::optional<glm::dmat4>& modelTransform) const
{
glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data));
const glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data));
return data.camera.combinedViewMatrix() * modelMatrix;
}
glm::dmat4 Renderable::calcModelViewProjectionTransform(const RenderData& data,
std::optional<glm::dmat4> modelTransform) const
const std::optional<glm::dmat4>& modelTransform) const
{
glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data));
glm::dmat4 viewMatrix = data.camera.combinedViewMatrix();
glm::dmat4 projectionMatrix = data.camera.projectionMatrix();
const glm::dmat4& modelMatrix = modelTransform.value_or(calcModelTransform(data));
const glm::dmat4 viewMatrix = data.camera.combinedViewMatrix();
const glm::dmat4 projectionMatrix = data.camera.projectionMatrix();
return glm::dmat4(projectionMatrix * viewMatrix * modelMatrix);
}
@@ -370,9 +369,9 @@ std::tuple<glm::dmat4, glm::dmat4, glm::dmat4> Renderable::calcAllTransforms(
const RenderData& data,
const AlternativeTransform& altModelTransform) const
{
glm::dmat4 modelTransform = calcModelTransform(data, altModelTransform);
glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform);
glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform(
const glm::dmat4 modelTransform = calcModelTransform(data, altModelTransform);
const glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform);
const glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform(
data,
modelTransform
);
+42 -41
View File
@@ -330,7 +330,7 @@ RenderEngine::RenderEngine()
, _hdrExposure(HDRExposureInfo, 3.7f, 0.01f, 10.f)
, _gamma(GammaInfo, 0.95f, 0.01f, 5.f)
, _hue(HueInfo, 0.f, 0.f, 360.f)
, _saturation(SaturationInfo, 1.f, 0.0f, 2.f)
, _saturation(SaturationInfo, 1.f, 0.f, 2.f)
, _value(ValueInfo, 1.f, 0.f, 2.f)
, _framerateLimit(FramerateLimitInfo, 0, 0, 500)
, _horizFieldOfView(HorizFieldOfViewInfo, 80.f, 1.f, 179.f)
@@ -407,13 +407,13 @@ RenderEngine::RenderEngine()
// Going from 'false' -> 'true'
// We might need to create the folder first
std::time_t now = std::time(nullptr);
const std::time_t now = std::time(nullptr);
std::tm* nowTime = std::localtime(&now);
char date[128];
strftime(date, sizeof(date), "%Y-%m-%d-%H-%M", nowTime);
std::array<char, 128> date;
strftime(date.data(), sizeof(date), "%Y-%m-%d-%H-%M", nowTime);
std::filesystem::path newFolder = absPath(
"${STARTUP_SCREENSHOT}/" + std::string(date)
const std::filesystem::path newFolder = absPath(
"${STARTUP_SCREENSHOT}/" + std::string(date.data())
);
FileSys.registerPathToken(
@@ -494,7 +494,7 @@ void RenderEngine::initialize() {
if (global::versionChecker->hasLatestVersionInfo()) {
VersionChecker::SemanticVersion latest = global::versionChecker->latestVersion();
VersionChecker::SemanticVersion current {
const VersionChecker::SemanticVersion current {
OPENSPACE_VERSION_MAJOR,
OPENSPACE_VERSION_MINOR,
OPENSPACE_VERSION_PATCH
@@ -525,7 +525,7 @@ void RenderEngine::initializeGL() {
// initialized window
_horizFieldOfView = static_cast<float>(global::windowDelegate->getHorizFieldOfView());
Configuration::FontSizes fontSize = global::configuration->fontSize;
const Configuration::FontSizes fontSize = global::configuration->fontSize;
{
ZoneScopedN("Fonts");
TracyGpuZone("Fonts");
@@ -632,21 +632,21 @@ glm::ivec2 RenderEngine::fontResolution() const {
}
glm::mat4 RenderEngine::globalRotation() const {
glm::vec3 rot = _globalRotation;
const glm::vec3 rot = _globalRotation;
glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
return glm::mat4_cast(glm::normalize(pitch * yaw * roll));
}
glm::mat4 RenderEngine::screenSpaceRotation() const {
glm::vec3 rot = _screenSpaceRotation;
const glm::vec3 rot = _screenSpaceRotation;
glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
return glm::mat4_cast(glm::normalize(pitch * yaw * roll));
}
@@ -655,11 +655,11 @@ glm::mat4 RenderEngine::nodeRotation() const {
if (!global::windowDelegate->isMaster()) {
return glm::mat4(1.f);
}
glm::vec3 rot = _masterRotation;
const glm::vec3 rot = _masterRotation;
glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f));
const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f));
const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f));
return glm::mat4_cast(glm::normalize(pitch * yaw * roll));
}
@@ -679,7 +679,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat
const glm::mat4 globalRot = globalRotation();
const glm::mat4 nodeRot = nodeRotation();
glm::mat4 combinedGlobalRot = nodeRot * globalRot;
const glm::mat4 combinedGlobalRot = nodeRot * globalRot;
if (_camera) {
_camera->sgctInternal.setViewMatrix(viewMatrix * combinedGlobalRot * sceneMatrix);
@@ -719,7 +719,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat
);
std::string fn = std::to_string(_frameNumber);
WindowDelegate::Frustum frustum = global::windowDelegate->frustumMode();
const WindowDelegate::Frustum frustum = global::windowDelegate->frustumMode();
std::string fr = [](WindowDelegate::Frustum f) -> std::string {
switch (f) {
case WindowDelegate::Frustum::Mono: return "";
@@ -733,7 +733,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat
std::string dt = std::to_string(global::windowDelegate->deltaTime());
std::string avgDt = std::to_string(global::windowDelegate->averageDeltaTime());
std::string res = fmt::format(
const std::string res = fmt::format(
"Frame: {} {}\nSwap group frame: {}\nDt: {}\nAvg Dt: {}",
fn, fr, sgFn, dt, avgDt
);
@@ -782,12 +782,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons
if (intersects(mousePosition, _cameraButtonLocations.rotation)) {
constexpr const char ToggleRotationFrictionScript[] = R"(
constexpr std::string_view ToggleRotationFrictionScript = R"(
local f = 'NavigationHandler.OrbitalNavigator.Friction.RotationalFriction';
openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)";
global::scriptEngine->queueScript(
ToggleRotationFrictionScript,
std::string(ToggleRotationFrictionScript),
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
scripting::ScriptEngine::ShouldSendToRemote::Yes
);
@@ -795,12 +795,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons
}
if (intersects(mousePosition, _cameraButtonLocations.zoom)) {
constexpr const char ToggleZoomFrictionScript[] = R"(
constexpr std::string_view ToggleZoomFrictionScript = R"(
local f = 'NavigationHandler.OrbitalNavigator.Friction.ZoomFriction';
openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)";
global::scriptEngine->queueScript(
ToggleZoomFrictionScript,
std::string(ToggleZoomFrictionScript),
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
scripting::ScriptEngine::ShouldSendToRemote::Yes
);
@@ -808,12 +808,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons
}
if (intersects(mousePosition, _cameraButtonLocations.roll)) {
constexpr const char ToggleRollFrictionScript[] = R"(
constexpr std::string_view ToggleRollFrictionScript = R"(
local f = 'NavigationHandler.OrbitalNavigator.Friction.RollFriction';
openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)";
global::scriptEngine->queueScript(
ToggleRollFrictionScript,
std::string(ToggleRollFrictionScript),
scripting::ScriptEngine::ShouldBeSynchronized::Yes,
scripting::ScriptEngine::ShouldSendToRemote::Yes
);
@@ -871,7 +871,7 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) {
glEnable(GL_BLEND);
// t = 1.f -> start of shutdown counter t = 0.f -> timer has reached shutdown
float t = 1.f - (timer / fullTime);
const float t = 1.f - (timer / fullTime);
rendering::helper::renderBox(
glm::vec2(0.f),
@@ -905,10 +905,10 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) {
RenderFont(*_fontShutdown, penPosition, "Press ESC again to abort");
}
void RenderEngine::renderDashboard() {
void RenderEngine::renderDashboard() const {
ZoneScoped;
glm::vec2 dashboardStart = global::dashboard->getStartPositionOffset();
const glm::vec2 dashboardStart = global::dashboard->getStartPositionOffset();
glm::vec2 penPosition = glm::vec2(
dashboardStart.x,
dashboardStart.y + fontResolution().y - global::luaConsole->currentHeight()
@@ -965,7 +965,7 @@ bool RenderEngine::isHdrDisabled() const {
std::unique_ptr<ghoul::opengl::ProgramObject> RenderEngine::buildRenderProgram(
const std::string& name,
const std::filesystem::path& vsPath,
std::filesystem::path fsPath,
const std::filesystem::path& fsPath,
ghoul::Dictionary data)
{
ghoul::Dictionary dict = std::move(data);
@@ -997,7 +997,7 @@ std::unique_ptr<ghoul::opengl::ProgramObject> RenderEngine::buildRenderProgram(
std::unique_ptr<ghoul::opengl::ProgramObject> RenderEngine::buildRenderProgram(
const std::string& name,
const std::filesystem::path& vsPath,
std::filesystem::path fsPath,
const std::filesystem::path& fsPath,
const std::filesystem::path& csPath,
ghoul::Dictionary data)
{
@@ -1275,8 +1275,8 @@ void RenderEngine::renderVersionInformation() {
);
}
[[maybe_unused]] float debugOffset = 0.f;
#ifdef _DEBUG
[[maybe_unused]] float debugOffset = 0.f;
{
const glm::vec2 debugBox = _fontVersionInfo->boundingBox("Debug build");
debugOffset = debugBox.y;
@@ -1291,6 +1291,8 @@ void RenderEngine::renderVersionInformation() {
glm::vec4(0.2f, 0.75f, 0.15f, 1.f)
);
}
#else // !_DEBUG
[[maybe_unused]] const float debugOffset = 0.f;
#endif // _DEBUG
#ifdef TRACY_ENABLE
@@ -1348,14 +1350,15 @@ void RenderEngine::renderScreenLog() {
const double d = (diff - ttf).count();
const float t = static_cast<float>(d) / static_cast<float>(FadeTime.count());
const float p = 0.8f - t;
alpha = (p <= 0.f) ? 0.f : pow(p, 0.4f);
alpha = (p <= 0.f) ? 0.f : std::pow(p, 0.4f);
}
// Since all log entries are ordered, once one exceeds alpha, all have
if (alpha <= 0.f) {
break;
}
std::string_view message = std::string_view(it.message).substr(0, MessageLength);
const std::string_view message =
std::string_view(it.message).substr(0, MessageLength);
nRows += std::count(message.begin(), message.end(), '\n');
const glm::vec4 white = glm::vec4(0.9f, 0.9f, 0.9f, alpha);
@@ -1370,7 +1373,6 @@ void RenderEngine::renderScreenLog() {
std::string_view(it.category).substr(0, CategoryLength),
it.category.length() > CategoryLength ? "..." : ""
);
std::string_view text = std::string_view(buf.data(), end - buf.data());
RenderFont(
*_fontLog,
@@ -1378,7 +1380,7 @@ void RenderEngine::renderScreenLog() {
10.f,
_fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset
),
text,
std::string_view(buf.data(), end - buf.data()),
white
);
}
@@ -1390,14 +1392,13 @@ void RenderEngine::renderScreenLog() {
const std::string_view lvl = ghoul::to_string(it.level);
std::fill(buf.begin(), buf.end(), char(0));
char* end = fmt::format_to(buf.data(), "({})", lvl);
std::string_view levelText = std::string_view(buf.data(), end - buf.data());
RenderFont(
*_fontLog,
glm::vec2(
10 + (30 + 3) * _fontLog->pointSize(),
_fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset
),
levelText,
std::string_view(buf.data(), end - buf.data()),
color
);
}
+31 -30
View File
@@ -283,7 +283,7 @@ std::string ScreenSpaceRenderable::makeUniqueIdentifier(std::string name) {
return taken;
};
std::string baseName = name;
const std::string baseName = name;
int i = 1;
while (nameTaken(name)) {
name = baseName + std::to_string(i);
@@ -424,7 +424,7 @@ ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary
// when this triggerProperty was pressed in the gui, therefor it has already been
// synced and sent to the connected nodes and peers
global::scriptEngine->queueScript(
script,
std::move(script),
scripting::ScriptEngine::ShouldBeSynchronized::No,
scripting::ScriptEngine::ShouldSendToRemote::No
);
@@ -459,7 +459,7 @@ bool ScreenSpaceRenderable::deinitializeGL() {
void ScreenSpaceRenderable::render(float blackoutFactor) {
ZoneScoped;
glm::mat4 mat =
const glm::mat4 mat =
globalRotationMatrix() *
translationMatrix() *
localRotationMatrix() *
@@ -533,7 +533,7 @@ void ScreenSpaceRenderable::createShaders() {
glm::mat4 ScreenSpaceRenderable::scaleMatrix() {
// to scale the plane
float textureRatio =
const float textureRatio =
static_cast<float>(_objectSize.y) / static_cast<float>(_objectSize.x);
glm::mat4 scale = glm::scale(
@@ -549,7 +549,8 @@ glm::vec2 ScreenSpaceRenderable::screenSpacePosition() {
}
glm::vec2 ScreenSpaceRenderable::screenSpaceDimensions() {
float ratio = static_cast<float>(_objectSize.x) / static_cast<float>(_objectSize.y);
const float ratio =
static_cast<float>(_objectSize.x) / static_cast<float>(_objectSize.y);
return glm::vec2(2.f * _scale * ratio, 2.f * _scale);
}
@@ -561,22 +562,22 @@ glm::vec2 ScreenSpaceRenderable::lowerLeftCornerScreenSpace() {
return screenSpacePosition() - (screenSpaceDimensions() / 2.0f);
}
bool ScreenSpaceRenderable::isIntersecting(glm::vec2 coord) {
bool isUnderTopBorder = coord.x < upperRightCornerScreenSpace().x;
bool isLeftToRightBorder = coord.y < upperRightCornerScreenSpace().y;
bool isRightToLeftBorder = coord.x > lowerLeftCornerScreenSpace().x;
bool isOverBottomBorder = coord.y > lowerLeftCornerScreenSpace().y;
bool ScreenSpaceRenderable::isIntersecting(const glm::vec2& coord) {
const bool isUnderTopBorder = coord.x < upperRightCornerScreenSpace().x;
const bool isLeftToRightBorder = coord.y < upperRightCornerScreenSpace().y;
const bool isRightToLeftBorder = coord.x > lowerLeftCornerScreenSpace().x;
const bool isOverBottomBorder = coord.y > lowerLeftCornerScreenSpace().y;
return isUnderTopBorder && isLeftToRightBorder &&
isRightToLeftBorder && isOverBottomBorder;
}
void ScreenSpaceRenderable::translate(glm::vec2 translation, glm::vec2 position) {
glm::mat4 translationMatrix = glm::translate(
const glm::mat4 translationMatrix = glm::translate(
glm::mat4(1.f),
glm::vec3(translation, 0.0f)
glm::vec3(translation, 0.f)
);
glm::vec4 origin = glm::vec4(position, _cartesianPosition.value().z, 1.0f);
const glm::vec4 origin = glm::vec4(position, _cartesianPosition.value().z, 1.f);
_cartesianPosition = translationMatrix * origin;
}
@@ -597,7 +598,7 @@ glm::mat4 ScreenSpaceRenderable::globalRotationMatrix() {
// 1) The global rotation of the view applied in the render engine
// 2) sgct's scene matrix (also called model matrix by sgct)
glm::mat4 inverseRotation = glm::inverse(
const glm::mat4 inverseRotation = glm::inverse(
global::renderEngine->globalRotation() *
global::windowDelegate->modelMatrix()
);
@@ -609,7 +610,7 @@ glm::mat4 ScreenSpaceRenderable::globalRotationMatrix() {
glm::mat4 ScreenSpaceRenderable::localRotationMatrix() {
glm::mat4 rotation = glm::mat4(1.f);
if (_faceCamera) {
glm::vec3 translation = _useRadiusAzimuthElevation ?
const glm::vec3 translation = _useRadiusAzimuthElevation ?
sphericalToCartesian(raeToSpherical(_raePosition)) :
_cartesianPosition;
@@ -620,9 +621,9 @@ glm::mat4 ScreenSpaceRenderable::localRotationMatrix() {
));
}
float roll = _localRotation.value().x;
float pitch = _localRotation.value().y;
float yaw = _localRotation.value().z;
const float roll = _localRotation.value().x;
const float pitch = _localRotation.value().y;
const float yaw = _localRotation.value().z;
return rotation * glm::mat4(glm::quat(glm::vec3(pitch, yaw, roll)));
}
@@ -635,19 +636,19 @@ glm::vec3 ScreenSpaceRenderable::cartesianToRae(const glm::vec3& cartesian) cons
}
glm::mat4 ScreenSpaceRenderable::translationMatrix() {
glm::vec3 translation = _useRadiusAzimuthElevation ?
const glm::vec3 translation = _useRadiusAzimuthElevation ?
sphericalToCartesian(raeToSpherical(_raePosition)) :
_cartesianPosition;
return glm::translate(glm::mat4(1.f), translation);
}
void ScreenSpaceRenderable::draw(glm::mat4 modelTransform, float blackoutFactor) {
void ScreenSpaceRenderable::draw(const glm::mat4& modelTransform, float blackoutFactor) {
glDisable(GL_CULL_FACE);
_shader->activate();
// Calculate the border from pixels to UV coordinates
glm::vec2 borderUV = glm::vec2(
const glm::vec2 borderUV = glm::vec2(
_borderWidth / static_cast<float>(_objectSize.x),
_borderWidth / static_cast<float>(_objectSize.y)
);
@@ -715,18 +716,18 @@ glm::vec3 ScreenSpaceRenderable::sphericalToCartesian(glm::vec3 spherical) const
glm::vec3 ScreenSpaceRenderable::cartesianToSpherical(const glm::vec3& cartesian) const {
// Rotate cartesian coordinates.
glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y);
const glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y);
const float r = sqrt(
pow(rotated.x, 2.f) + pow(rotated.y, 2.f) + pow(rotated.z, 2.f)
const float r = std::sqrt(
std::pow(rotated.x, 2.f) + std::pow(rotated.y, 2.f) + std::pow(rotated.z, 2.f)
);
const float theta = acos(rotated.z / r);
const float phi = atan2(rotated.y, rotated.x);
const float theta = std::acos(rotated.z / r);
const float phi = std::atan2(rotated.y, rotated.x);
return sanitizeSphericalCoordinates(glm::vec3(r, theta, phi));
}
// Radius, azimiuth, elevation to spherical coordinates.
glm::vec3 ScreenSpaceRenderable::raeToSpherical(glm::vec3 rae) const {
glm::vec3 ScreenSpaceRenderable::raeToSpherical(const glm::vec3& rae) const {
//return rae;
const float r = rae.x;
@@ -741,15 +742,15 @@ glm::vec3 ScreenSpaceRenderable::raeToSpherical(glm::vec3 rae) const {
}
// Spherical coordinates to radius, azimuth and elevation.
glm::vec3 ScreenSpaceRenderable::sphericalToRae(glm::vec3 spherical) const {
glm::vec3 ScreenSpaceRenderable::sphericalToRae(const glm::vec3& spherical) const {
//return spherical;
const float r = spherical.x;
// Azimuth on screen is angle from negative y, as opposed to from x.
float azimuth = spherical.z + glm::half_pi<float>();
const float azimuth = spherical.z + glm::half_pi<float>();
// Elevation is polar angle - pi/2
float elevation = wrap(
const float elevation = wrap(
spherical.y - glm::half_pi<float>(),
-glm::pi<float>(),
glm::pi<float>()
+10 -7
View File
@@ -26,7 +26,6 @@
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/opengl/texture.h>
@@ -56,7 +55,7 @@ void TransferFunction::setPath(const std::string& filepath) {
if (_file) {
_file = nullptr;
}
std::filesystem::path f = absPath(filepath);
const std::filesystem::path f = absPath(filepath);
if (!std::filesystem::is_regular_file(f)) {
LERROR("Could not find transfer function file");
_file = nullptr;
@@ -71,7 +70,7 @@ void TransferFunction::setPath(const std::string& filepath) {
ghoul::opengl::Texture& TransferFunction::texture() {
ghoul_assert(_texture != nullptr, "Transfer function is null");
update();
return *_texture.get();
return *_texture;
}
void TransferFunction::update() {
@@ -127,8 +126,8 @@ void TransferFunction::setTextureFromTxt() {
upper = glm::clamp(upper, lower, 1.f);
}
else if (key == "mappingkey") {
float intensity;
glm::vec4 rgba = glm::vec4(0.f);
float intensity = 0.f;
glm::vec4 rgba;
iss >> intensity;
for(int i = 0; i < 4; i++) {
iss >> rgba[i];
@@ -156,8 +155,12 @@ void TransferFunction::setTextureFromTxt() {
transferFunction[i] = 0.f;
}
size_t lowerIndex = static_cast<size_t>(floorf(lower * static_cast<float>(width-1)));
size_t upperIndex = static_cast<size_t>(floorf(upper * static_cast<float>(width-1)));
const size_t lowerIndex = static_cast<size_t>(
std::floor(lower * static_cast<float>(width - 1))
);
const size_t upperIndex = static_cast<size_t>(
std::floor(upper * static_cast<float>(width - 1))
);
auto prevKey = mappingKeys.begin();
auto currentKey = prevKey + 1;
+37 -32
View File
@@ -194,7 +194,7 @@ void AssetManager::update() {
for (const std::string& asset : _assetAddQueue) {
ZoneScopedN("Adding queued assets");
std::filesystem::path path = generateAssetPath(_assetRootDirectory, asset);
const std::filesystem::path path = generateAssetPath(_assetRootDirectory, asset);
Asset* a = nullptr;
try {
a = retrieveAsset(path, "");
@@ -384,18 +384,18 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) {
lua_getglobal(*_luaState, AssetGlobalVariableName);
ghoul_assert(lua_istable(*_luaState, -1), "Expected 'asset' table");
lua_getfield(*_luaState, -1, "meta");
ghoul::Dictionary metaDict = ghoul::lua::luaDictionaryFromState(*_luaState);
const ghoul::Dictionary metaDict = ghoul::lua::luaDictionaryFromState(*_luaState);
if (!metaDict.isEmpty()) {
Parameters p = codegen::bake<Parameters>(metaDict);
const Parameters p = codegen::bake<Parameters>(metaDict);
Asset::MetaInformation meta;
meta.name = p.name.value_or("");
meta.version = p.version.value_or("");
meta.description = p.description.value_or("");
meta.author = p.author.value_or("");
meta.url = p.url.value_or("");
meta.license = p.license.value_or("");
meta.identifiers = p.identifiers.value_or(std::vector<std::string>());
meta.name = p.name.value_or(meta.name);
meta.version = p.version.value_or(meta.version);
meta.description = p.description.value_or(meta.description);
meta.author = p.author.value_or(meta.author);
meta.url = p.url.value_or(meta.url);
meta.license = p.license.value_or(meta.license);
meta.identifiers = p.identifiers.value_or(meta.identifiers);
// We need to do this as the asset might have 'export'ed identifiers before
// defining the meta table. Therefore the meta information already contains some
@@ -415,12 +415,12 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) {
void AssetManager::unloadAsset(Asset* asset) {
ghoul_precondition(asset, "Asset must not be nullptr");
for (int ref : _onInitializeFunctionRefs[asset]) {
for (const int ref : _onInitializeFunctionRefs[asset]) {
luaL_unref(*_luaState, LUA_REGISTRYINDEX, ref);
}
_onInitializeFunctionRefs[asset].clear();
for (int ref : _onDeinitializeFunctionRefs[asset]) {
for (const int ref : _onDeinitializeFunctionRefs[asset]) {
luaL_unref(*_luaState, LUA_REGISTRYINDEX, ref);
}
_onDeinitializeFunctionRefs[asset].clear();
@@ -435,7 +435,7 @@ void AssetManager::unloadAsset(Asset* asset) {
ghoul::lua::push(*_luaState, ghoul::lua::nil_t());
// Clear entry from global asset table (pushed to the Lua stack earlier)
std::string path = asset->path().string();
const std::string path = asset->path().string();
lua_setfield(*_luaState, globalTableIndex, path.c_str());
lua_settop(*_luaState, top);
@@ -509,11 +509,12 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource");
if (ghoul::lua::hasValue<ghoul::Dictionary>(L)) {
ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(L);
const ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(L);
std::unique_ptr<ResourceSynchronization> s =
ResourceSynchronization::createFromDictionary(d);
std::string uid = d.value<std::string>("Type") + "/" + s->generateUid();
const std::string uid =
d.value<std::string>("Type") + "/" + s->generateUid();
SyncItem* syncItem = nullptr;
auto it = manager->_synchronizations.find(uid);
if (it == manager->_synchronizations.end()) {
@@ -539,7 +540,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
}
else if (ghoul::lua::hasValue<std::optional<std::string>>(L)) {
auto [name] = ghoul::lua::values<std::optional<std::string>>(L);
std::filesystem::path path =
const std::filesystem::path path =
name.has_value() ?
thisAsset->path().parent_path() / *name :
thisAsset->path().parent_path();
@@ -569,7 +570,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource");
auto [name] = ghoul::lua::values<std::optional<std::string>>(L);
std::filesystem::path path =
const std::filesystem::path path =
name.has_value() ?
thisAsset->path().parent_path() / *name :
thisAsset->path().parent_path();
@@ -595,11 +596,11 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
Asset* thisAsset = ghoul::lua::userData<Asset>(L, 2);
ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource");
ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(L);
const ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(L);
std::unique_ptr<ResourceSynchronization> s =
ResourceSynchronization::createFromDictionary(d);
std::string uid = d.value<std::string>("Type") + "/" + s->generateUid();
const std::string uid = d.value<std::string>("Type") + "/" + s->generateUid();
SyncItem* syncItem = nullptr;
auto it = manager->_synchronizations.find(uid);
if (it == manager->_synchronizations.end()) {
@@ -645,7 +646,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
auto [assetName, explicitEnable] =
ghoul::lua::values<std::string, std::optional<bool>>(L);
std::filesystem::path path = manager->generateAssetPath(
const std::filesystem::path path = manager->generateAssetPath(
parent->path().parent_path(),
assetName
);
@@ -683,7 +684,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
// Get the exports table
lua_rawgeti(L, LUA_REGISTRYINDEX, manager->_assetsTableRef);
std::string p = dependency->path().string();
const std::string p = dependency->path().string();
lua_getfield(L, -1, p.c_str());
lua_getfield(L, -1, ExportsTableName);
return 1;
@@ -705,7 +706,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::exists");
const std::string name = ghoul::lua::value<std::string>(L);
std::filesystem::path path = manager->generateAssetPath(
const std::filesystem::path path = manager->generateAssetPath(
thisAsset->path().parent_path(),
name
);
@@ -728,12 +729,16 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
AssetManager* manager = ghoul::lua::userData<AssetManager>(L, 1);
Asset* thisAsset = ghoul::lua::userData<Asset>(L, 2);
int n = ghoul::lua::checkArgumentsAndThrow(L, { 1 , 2 }, "lua::exportAsset");
const int n = ghoul::lua::checkArgumentsAndThrow(
L,
{ 1 , 2 },
"lua::exportAsset"
);
std::string exportName;
std::string identifier;
int targetLocation;
int targetLocation = 0;
if (n == 1) {
ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(
const ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(
L,
1,
ghoul::lua::PopValue::No
@@ -762,7 +767,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
// the identifier if it actually is a table *and* if that table
// contains the 'Identifier' key
ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(
const ghoul::Dictionary d = ghoul::lua::value<ghoul::Dictionary>(
L,
2,
ghoul::lua::PopValue::No
@@ -779,7 +784,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
lua_rawgeti(L, LUA_REGISTRYINDEX, manager->_assetsTableRef);
std::string path = thisAsset->path().string();
const std::string path = thisAsset->path().string();
lua_getfield(L, -1, path.c_str());
lua_getfield(L, -1, ExportsTableName);
const int exportsTableIndex = lua_gettop(L);
@@ -864,7 +869,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) {
// Extend global asset info table (pushed to the Lua stack earlier)
// with this AssetInfo table
std::string path = asset->path().string();
const std::string path = asset->path().string();
lua_setfield(*_luaState, globalTableIndex, path.c_str());
lua_settop(*_luaState, top);
}
@@ -935,7 +940,7 @@ void AssetManager::callOnInitialize(Asset* asset) const {
return;
}
for (int init : it->second) {
for (const int init : it->second) {
lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, init);
if (lua_pcall(*_luaState, 0, 0, 0) != LUA_OK) {
throw ghoul::lua::LuaRuntimeException(fmt::format(
@@ -958,7 +963,7 @@ void AssetManager::callOnDeinitialize(Asset* asset) const {
return;
}
for (int deinit : it->second) {
for (const int deinit : it->second) {
lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, deinit);
if (lua_pcall(*_luaState, 0, 0, 0) != LUA_OK) {
throw ghoul::lua::LuaRuntimeException(fmt::format(
@@ -983,7 +988,7 @@ void AssetManager::setCurrentAsset(Asset* asset) {
else {
// Set `asset` lua global to point to the current asset table
lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, _assetsTableRef);
std::string path = asset->path().string();
const std::string path = asset->path().string();
lua_getfield(*_luaState, -1, path.c_str());
lua_getfield(*_luaState, -1, AssetTableName);
lua_setglobal(*_luaState, AssetGlobalVariableName);
@@ -1000,7 +1005,7 @@ std::filesystem::path AssetManager::generateAssetPath(
// 3) Absolute paths (*:/* or /*)
// 2) Relative to the global asset root (*)
PathType pathType = classifyPath(assetPath);
const PathType pathType = classifyPath(assetPath);
std::string prefix;
if (pathType == PathType::RelativeToAsset) {
prefix = baseDirectory.string() + '/';
+11 -11
View File
@@ -83,7 +83,7 @@ namespace {
}
}
else {
const nlohmann::json value = j[key];
const nlohmann::json& value = j[key];
if (!(value.*checkFunc)()) {
std::string type = [](auto c) {
if (c == &nlohmann::json::is_string) { return "a string"; }
@@ -229,7 +229,7 @@ void to_json(nlohmann::json& j, const Profile::Property::SetType& v) {
}
void from_json(const nlohmann::json& j, Profile::Property::SetType& v) {
std::string value = j.get<std::string>();
const std::string value = j.get<std::string>();
if (value == "setPropertyValue") {
v = Profile::Property::SetType::SetPropertyValue;
}
@@ -315,7 +315,7 @@ void to_json(nlohmann::json& j, const Profile::Time::Type& v) {
}
void from_json(const nlohmann::json& j, Profile::Time::Type& v) {
std::string value = j.get<std::string>();
const std::string value = j.get<std::string>();
if (value == "absolute") {
v = Profile::Time::Type::Absolute;
}
@@ -381,14 +381,14 @@ void to_json(nlohmann::json& j, const Profile::CameraNavState& v) {
j["aim"] = *v.aim;
}
j["frame"] = v.referenceFrame;
nlohmann::json p {
const nlohmann::json p {
{ "x", v.position.x },
{ "y", v.position.y },
{ "z", v.position.z }
};
j["position"] = p;
if (v.up.has_value()) {
nlohmann::json u {
const nlohmann::json u {
{ "x", v.up->x },
{ "y", v.up->y },
{ "z", v.up->z }
@@ -577,14 +577,14 @@ void convertVersion10to11(nlohmann::json& profile) {
profile.at("keybindings").get<std::vector<version10::Keybinding>>();
for (size_t i = 0; i < kbs.size(); i++) {
version10::Keybinding& kb = kbs[i];
std::string identifier = fmt::format("profile.keybind.{}", i);
const std::string identifier = fmt::format("profile.keybind.{}", i);
Profile::Action action;
action.identifier = identifier;
action.documentation = std::move(kb.documentation);
action.name = std::move(kb.name);
action.guiPath = std::move(kb.guiPath);
action.isLocal = std::move(kb.isLocal);
action.isLocal = kb.isLocal;
action.script = std::move(kb.script);
actions.push_back(std::move(action));
@@ -635,7 +635,7 @@ void Profile::saveCurrentSettingsToProfile(const properties::PropertyOwner& root
version = Profile::CurrentVersion;
// Update properties
std::vector<properties::Property*> ps = changedProperties(rootOwner);
const std::vector<properties::Property*> ps = changedProperties(rootOwner);
for (properties::Property* prop : ps) {
Property p;
@@ -754,8 +754,8 @@ Profile::Profile(const std::filesystem::path& path) {
));
}
std::string content(
(std::istreambuf_iterator<char>(inFile)),
const std::string content = std::string(
std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>()
);
@@ -830,7 +830,7 @@ Profile::Profile(const std::filesystem::path& path) {
}
catch (const nlohmann::json::exception& e) {
std::string err = e.what();
throw ParsingError(ParsingError::Severity::Error, err);
throw ParsingError(ParsingError::Severity::Error, std::move(err));
}
}
+36 -31
View File
@@ -90,6 +90,16 @@ namespace {
}
#endif // TRACY_ENABLE
std::chrono::steady_clock::time_point currentTimeForInterpolation() {
using namespace openspace::global;
if (sessionRecording->isSavingFramesDuringPlayback()) {
return sessionRecording->currentPlaybackInterpolationTime();
}
else {
return std::chrono::steady_clock::now();
}
}
template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
} // namespace
@@ -146,7 +156,7 @@ Camera* Scene::camera() const {
}
void Scene::registerNode(SceneGraphNode* node) {
if (_nodesByIdentifier.count(node->identifier())) {
if (_nodesByIdentifier.contains(node->identifier())) {
throw Scene::InvalidSceneError(fmt::format(
"Node with identifier '{}' already exists", node->identifier()
));
@@ -276,8 +286,8 @@ bool Scene::isInitializing() const {
void Scene::update(const UpdateData& data) {
ZoneScoped;
std::vector<SceneGraphNode*> initializedNodes = _initializer->takeInitializedNodes();
for (SceneGraphNode* node : initializedNodes) {
const std::vector<SceneGraphNode*> initialized = _initializer->takeInitializedNodes();
for (SceneGraphNode* node : initialized) {
try {
node->initializeGL();
}
@@ -394,12 +404,12 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) {
// TODO: Throw exception
LERROR("Dependencies did not have the corrent type");
}
ghoul::Dictionary nodeDependencies =
const ghoul::Dictionary nodeDependencies =
nodeDictionary.value<ghoul::Dictionary>(SceneGraphNode::KeyDependencies);
for (std::string_view key : nodeDependencies.keys()) {
for (const std::string_view key : nodeDependencies.keys()) {
std::string value = nodeDependencies.value<std::string>(key);
dependencyNames.push_back(value);
dependencyNames.push_back(std::move(value));
}
}
@@ -437,15 +447,6 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) {
return rawNodePointer;
}
std::chrono::steady_clock::time_point Scene::currentTimeForInterpolation() {
if (global::sessionRecording->isSavingFramesDuringPlayback()) {
return global::sessionRecording->currentPlaybackInterpolationTime();
}
else {
return std::chrono::steady_clock::now();
}
}
void Scene::addPropertyInterpolation(properties::Property* prop, float durationSeconds,
std::string postScript,
ghoul::EasingFunction easingFunction)
@@ -469,7 +470,7 @@ void Scene::addPropertyInterpolation(properties::Property* prop, float durationS
ghoul::easingFunction<float>(easingFunction);
// First check if the current property already has an interpolation information
std::chrono::steady_clock::time_point now = currentTimeForInterpolation();
const std::chrono::steady_clock::time_point now = currentTimeForInterpolation();
for (PropertyInterpolationInfo& info : _propertyInterpolationInfos) {
if (info.prop == prop) {
info.beginTime = now;
@@ -520,10 +521,10 @@ void Scene::updateInterpolations() {
using namespace std::chrono;
steady_clock::time_point now = currentTimeForInterpolation();
const steady_clock::time_point now = currentTimeForInterpolation();
// First, let's update the properties
for (PropertyInterpolationInfo& i : _propertyInterpolationInfos) {
long long us =
const long long us =
duration_cast<std::chrono::microseconds>(now - i.beginTime).count();
const float t = glm::clamp(
@@ -636,7 +637,7 @@ ProfilePropertyLua Scene::propertyProcessValue(ghoul::lua::LuaState& L,
const std::string& value)
{
ProfilePropertyLua result;
PropertyValueType pType = propertyValueType(value);
const PropertyValueType pType = propertyValueType(value);
switch (pType) {
case PropertyValueType::Boolean:
@@ -648,27 +649,31 @@ ProfilePropertyLua Scene::propertyProcessValue(ghoul::lua::LuaState& L,
case PropertyValueType::Nil:
result = ghoul::lua::nil_t();
break;
case PropertyValueType::Table:
ghoul::trimSurroundingCharacters(const_cast<std::string&>(value), '{');
ghoul::trimSurroundingCharacters(const_cast<std::string&>(value), '}');
handlePropertyLuaTableEntry(L, value);
case PropertyValueType::Table: {
std::string val = value;
ghoul::trimSurroundingCharacters(val, '{');
ghoul::trimSurroundingCharacters(val, '}');
handlePropertyLuaTableEntry(L, val);
_valueIsTable = true;
break;
}
case PropertyValueType::String:
default:
ghoul::trimSurroundingCharacters(const_cast<std::string&>(value), '\"');
ghoul::trimSurroundingCharacters(const_cast<std::string&>(value), '[');
ghoul::trimSurroundingCharacters(const_cast<std::string&>(value), ']');
result = value;
default: {
std::string val = value;
ghoul::trimSurroundingCharacters(val, '\"');
ghoul::trimSurroundingCharacters(val, '[');
ghoul::trimSurroundingCharacters(val, ']');
result = val;
break;
}
}
return result;
}
void Scene::handlePropertyLuaTableEntry(ghoul::lua::LuaState& L, const std::string& value)
{
PropertyValueType enclosedType;
size_t commaPos = value.find(',', 0);
PropertyValueType enclosedType = PropertyValueType::Nil;
const size_t commaPos = value.find(',', 0);
if (commaPos != std::string::npos) {
enclosedType = propertyValueType(value.substr(0, commaPos));
}
@@ -767,7 +772,7 @@ PropertyValueType Scene::propertyValueType(const std::string& value) {
}
std::vector<properties::Property*> Scene::propertiesMatchingRegex(
std::string propertyString)
const std::string& propertyString)
{
return findMatchesInAllProperties(propertyString, allProperties(), "");
}
-1
View File
@@ -578,7 +578,6 @@ namespace {
else if (!nodeName.empty()) {
size_t nodePos = id.find(nodeName);
if (nodePos != std::string::npos) {
// Check tag
if (!groupName.empty()) {
properties::PropertyOwner* matchingTaggedOwner =
+17 -13
View File
@@ -689,8 +689,7 @@ void SceneGraphNode::update(const UpdateData& data) {
ZoneScoped;
ZoneName(identifier().c_str(), identifier().size());
State s = _state;
if (s != State::Initialized && _state != State::GLInitialized) {
if (_state != State::Initialized && _state != State::GLInitialized) {
return;
}
if (!isTimeFrameActive(data.time)) {
@@ -719,12 +718,13 @@ void SceneGraphNode::update(const UpdateData& data) {
newUpdateData.modelTransform.rotation = _worldRotationCached;
newUpdateData.modelTransform.scale = _worldScaleCached;
glm::dmat4 translation = glm::translate(
const glm::dmat4 translation = glm::translate(
glm::dmat4(1.0),
newUpdateData.modelTransform.translation
);
glm::dmat4 rotation = glm::dmat4(newUpdateData.modelTransform.rotation);
glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), newUpdateData.modelTransform.scale);
const glm::dmat4 rotation = glm::dmat4(newUpdateData.modelTransform.rotation);
const glm::dmat4 scaling =
glm::scale(glm::dmat4(1.0), newUpdateData.modelTransform.scale);
_modelTransformCached = translation * rotation * scaling;
@@ -780,7 +780,7 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) {
}
}
bool isInStickerBin =
const bool isInStickerBin =
data.renderBinMask & static_cast<int>(Renderable::RenderBin::Sticker);
if (_showDebugSphere && isInStickerBin) {
@@ -794,15 +794,17 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) {
}
}
void SceneGraphNode::renderDebugSphere(const Camera& camera, double size, glm::vec4 color)
void SceneGraphNode::renderDebugSphere(const Camera& camera, double size,
const glm::vec4& color)
{
glm::dvec3 scaleVec = _worldScaleCached * size;
glm::dmat4 modelTransform =
const glm::dvec3 scaleVec = _worldScaleCached * size;
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), _worldPositionCached) *
glm::dmat4(_worldRotationCached) *
glm::scale(glm::dmat4(1.0), scaleVec);
glm::mat4 modelViewProjection = camera.projectionMatrix() *
const glm::mat4 modelViewProjection = camera.projectionMatrix() *
glm::mat4(camera.combinedViewMatrix() * modelTransform);
_debugSphereProgram->activate();
@@ -982,13 +984,14 @@ void SceneGraphNode::computeScreenSpaceData(RenderData& newData) {
return;
}
glm::ivec2 res = global::windowDelegate->currentSubwindowSize();
const glm::ivec2 res = global::windowDelegate->currentSubwindowSize();
// Get the radius of node
double nodeRadius = boundingSphere();
const double nodeRadius = boundingSphere();
// Distance from the camera to the node
double distFromCamToNode = glm::distance(cam.positionVec3(), worldPos) - nodeRadius;
const double distFromCamToNode =
glm::distance(cam.positionVec3(), worldPos) - nodeRadius;
// Fix to limit the update of properties
if (distFromCamToNode >= _visibilityDistance) {
@@ -1182,6 +1185,7 @@ void SceneGraphNode::setScene(Scene* scene) {
std::vector<SceneGraphNode*> SceneGraphNode::children() const {
std::vector<SceneGraphNode*> nodes;
nodes.reserve(_children.size());
for (const ghoul::mm_unique_ptr<SceneGraphNode>& child : _children) {
nodes.push_back(child.get());
}
+4 -4
View File
@@ -71,7 +71,7 @@ void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) {
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
}
std::lock_guard g(_mutex);
const std::lock_guard g(_mutex);
_initializedNodes.push_back(node);
_initializingNodes.erase(node);
@@ -98,7 +98,7 @@ void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) {
);
}
std::lock_guard g(_mutex);
const std::lock_guard g(_mutex);
_initializingNodes.insert(node);
_threadPool.enqueue(initFunction);
}
@@ -111,13 +111,13 @@ std::vector<SceneGraphNode*> MultiThreadedSceneInitializer::takeInitializedNodes
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::lock_guard g(_mutex);
const std::lock_guard g(_mutex);
std::vector<SceneGraphNode*> nodes = std::move(_initializedNodes);
return nodes;
}
bool MultiThreadedSceneInitializer::isInitializing() const {
std::lock_guard g(_mutex);
const std::lock_guard g(_mutex);
return !_initializingNodes.empty();
}
+34 -27
View File
@@ -60,11 +60,16 @@ namespace {
std::vector<std::string> result;
std::string total = prefix;
std::string total = std::move(prefix);
if (!library.name.empty()) {
total += library.name + ".";
}
result.reserve(
library.functions.size() +
library.subLibraries.size() +
library.documentations.size()
);
for (const LuaLibrary::Function& function : library.functions) {
result.push_back(total + function.name);
}
@@ -193,7 +198,7 @@ bool ScriptEngine::hasLibrary(const std::string& name) {
return (it != _registeredLibraries.end());
}
bool ScriptEngine::runScript(const std::string& script, ScriptCallback callback) {
bool ScriptEngine::runScript(const std::string& script, const ScriptCallback& callback) {
ZoneScoped;
ghoul_assert(!script.empty(), "Script must not be empty");
@@ -207,7 +212,7 @@ bool ScriptEngine::runScript(const std::string& script, ScriptCallback callback)
if (callback) {
ghoul::Dictionary returnValue =
ghoul::lua::loadArrayDictionaryFromString(script, _state);
callback(returnValue);
callback(std::move(returnValue));
}
else {
ghoul::lua::runScript(_state, script);
@@ -370,7 +375,7 @@ void ScriptEngine::addLibraryFunctions(lua_State* state, LuaLibrary& library,
lua_pushnil(state);
while (lua_next(state, -2)) {
ghoul::Dictionary d = ghoul::lua::luaDictionaryFromState(state);
const ghoul::Dictionary d = ghoul::lua::luaDictionaryFromState(state);
try {
const Parameters p = codegen::bake<Parameters>(d);
@@ -454,25 +459,24 @@ nlohmann::json ScriptEngine::generateJson() const {
nlohmann::json json;
for (const LuaLibrary& l : _registeredLibraries) {
using namespace openspace;
using namespace openspace::scripting;
nlohmann::json library;
std::string libraryName = l.name;
const std::string libraryName = l.name;
// Keep the library key for backwards compatability
library["library"] = libraryName;
library["name"] = libraryName;
std::string os = "openspace";
library["fullName"] = libraryName.empty() ? os : os + "." + libraryName;
library["fullName"] =
libraryName.empty() ?
"openspace" :
"openspace." + libraryName;
for (const LuaLibrary::Function& f : l.functions) {
bool hasSourceLocation = true;
library["functions"].push_back(toJson(f, hasSourceLocation));
constexpr bool HasSourceLocation = true;
library["functions"].push_back(toJson(f, HasSourceLocation));
}
for (const LuaLibrary::Function& f : l.documentations) {
bool hasSourceLocation = false;
library["functions"].push_back(toJson(f, hasSourceLocation));
constexpr bool HasSourceLocation = false;
library["functions"].push_back(toJson(f, HasSourceLocation));
}
sortJson(library["functions"], "name");
json.push_back(library);
@@ -495,7 +499,10 @@ void ScriptEngine::writeLog(const std::string& script) {
LDEBUG(fmt::format("Using script log file '{}'", _logFilename));
// Test file and clear previous input
std::ofstream file(_logFilename, std::ofstream::out | std::ofstream::trunc);
const std::ofstream file = std::ofstream(
_logFilename,
std::ofstream::out | std::ofstream::trunc
);
if (!file.good()) {
LERROR(fmt::format(
@@ -524,10 +531,10 @@ void ScriptEngine::writeLog(const std::string& script) {
void ScriptEngine::preSync(bool isMaster) {
ZoneScoped;
std::lock_guard guard(_clientScriptsMutex);
const std::lock_guard guard(_clientScriptsMutex);
if (isMaster) {
while (!_incomingScripts.empty()) {
QueueItem item = std::move(_incomingScripts.front());
const QueueItem item = std::move(_incomingScripts.front());
_incomingScripts.pop();
// Not really a received script but the master also needs to run the script...
@@ -552,9 +559,9 @@ void ScriptEngine::preSync(bool isMaster) {
}
else {
while (!_incomingScripts.empty()) {
QueueItem item = std::move(_incomingScripts.front());
_incomingScripts.pop();
const QueueItem& item = std::move(_incomingScripts.front());
_clientScriptQueue.push(item.script);
_incomingScripts.pop();
}
}
}
@@ -562,7 +569,7 @@ void ScriptEngine::preSync(bool isMaster) {
void ScriptEngine::encode(SyncBuffer* syncBuffer) {
ZoneScoped;
size_t nScripts = _scriptsToSync.size();
const size_t nScripts = _scriptsToSync.size();
syncBuffer->encode(nScripts);
for (const std::string& s : _scriptsToSync) {
syncBuffer->encode(s);
@@ -573,8 +580,8 @@ void ScriptEngine::encode(SyncBuffer* syncBuffer) {
void ScriptEngine::decode(SyncBuffer* syncBuffer) {
ZoneScoped;
std::lock_guard guard(_clientScriptsMutex);
size_t nScripts;
const std::lock_guard guard(_clientScriptsMutex);
size_t nScripts = 0;
syncBuffer->decode(nScripts);
for (size_t i = 0; i < nScripts; i++) {
@@ -589,11 +596,11 @@ void ScriptEngine::postSync(bool isMaster) {
if (isMaster) {
while (!_masterScriptQueue.empty()) {
std::string script = std::move(_masterScriptQueue.front().script);
ScriptCallback callback = std::move(_masterScriptQueue.front().callback);
const std::string script = std::move(_masterScriptQueue.front().script);
const ScriptCallback cb = std::move(_masterScriptQueue.front().callback);
_masterScriptQueue.pop();
try {
runScript(script, callback);
runScript(script, cb);
}
catch (const ghoul::RuntimeError& e) {
LERRORC(e.component, e.message);
@@ -602,7 +609,7 @@ void ScriptEngine::postSync(bool isMaster) {
}
}
else {
std::lock_guard guard(_clientScriptsMutex);
const std::lock_guard guard(_clientScriptsMutex);
while (!_clientScriptQueue.empty()) {
try {
runScript(_clientScriptQueue.front());
@@ -712,7 +719,7 @@ void ScriptEngine::addBaseLibrary() {
codegen::lua::UnzipFile
}
};
addLibrary(lib);
addLibrary(std::move(lib));
}
} // namespace openspace::scripting
+5 -5
View File
@@ -120,7 +120,7 @@ void ScriptScheduler::loadScripts(std::vector<ScheduledScript> scheduledScripts)
);
for (ScheduledScript& script : scheduledScripts) {
_scripts.push_back(script);
_scripts.push_back(std::move(script));
}
// Re-sort so it is always in sorted order in regards to time
@@ -176,7 +176,7 @@ std::vector<std::string> ScriptScheduler::progressTo(double newTime) {
if (newTime > _currentTime) {
// Moving forward in time; we need to find the highest entry in the timings
// vector that is still smaller than the newTime
size_t prevIndex = _currentIndex;
const size_t prevIndex = _currentIndex;
const auto it = std::upper_bound(
_scripts.begin() + prevIndex, // We only need to start at the previous time
_scripts.end(),
@@ -201,7 +201,7 @@ std::vector<std::string> ScriptScheduler::progressTo(double newTime) {
std::string script = iter->universalScript.empty() ?
iter->forwardScript :
iter->universalScript + "; " + iter->forwardScript;
result.push_back(script);
result.push_back(std::move(script));
}
return result;
@@ -234,7 +234,7 @@ std::vector<std::string> ScriptScheduler::progressTo(double newTime) {
std::string script = iter->universalScript.empty() ?
iter->backwardScript :
iter->universalScript + "; " + iter->backwardScript;
result.push_back(script);
result.push_back(std::move(script));
if (iter == _scripts.begin()) {
break;
@@ -255,7 +255,7 @@ double ScriptScheduler::currentTime() const {
void ScriptScheduler::setCurrentTime(double time) {
// Ensure _currentIndex and _currentTime is accurate after time jump
std::vector<std::string> scheduledScripts = progressTo(time);
const std::vector<std::string> scheduledScripts = progressTo(time);
if (_shouldRunAllTimeJump) {
// Queue all scripts for the time jump
+17 -16
View File
@@ -37,8 +37,8 @@ namespace openspace {
BlockPlaneIntersectionGeometry::BlockPlaneIntersectionGeometry(glm::vec3 blockSize,
glm::vec3 planeNormal,
float planeDistance)
: _size(blockSize)
, _normal(planeNormal)
: _size(std::move(blockSize))
, _normal(std::move(planeNormal))
, _planeDistance(planeDistance)
{}
@@ -52,7 +52,7 @@ void BlockPlaneIntersectionGeometry::setBlockSize(glm::vec3 size) {
updateVertices();
}
void BlockPlaneIntersectionGeometry::setPlane(glm::vec3 normal, float distance) {
void BlockPlaneIntersectionGeometry::setPlane(const glm::vec3& normal, float distance) {
_normal = glm::normalize(normal);
_planeDistance = distance;
updateVertices();
@@ -61,7 +61,7 @@ void BlockPlaneIntersectionGeometry::setPlane(glm::vec3 normal, float distance)
void BlockPlaneIntersectionGeometry::updateVertices() {
_vertices.clear();
const int cornersInLines[24] = {
constexpr std::array<int, 24> CornersInLines = {
0, 1,
1, 5,
5, 4,
@@ -84,23 +84,24 @@ void BlockPlaneIntersectionGeometry::updateVertices() {
int nIntersections = 0;
for (int i = 0; i < 12; i++) {
int iCorner0 = cornersInLines[i * 2];
int iCorner1 = cornersInLines[i * 2 + 1];
const int iCorner0 = CornersInLines[i * 2];
const int iCorner1 = CornersInLines[i * 2 + 1];
glm::vec3 corner0 = glm::vec3(
const glm::vec3 corner0 = glm::vec3(
iCorner0 % 2,
(iCorner0 / 2) % 2,
iCorner0 / 4
) - halfSize;
glm::vec3 corner1 = glm::vec3(
const glm::vec3 corner1 = glm::vec3(
iCorner1 % 2,
(iCorner1 / 2) % 2,
iCorner1 / 4
) - halfSize;
glm::vec3 line = corner1 - corner0;
const glm::vec3 line = corner1 - corner0;
float t = (_planeDistance - glm::dot(corner0, _normal)) / glm::dot(line, _normal);
const float t =
(_planeDistance - glm::dot(corner0, _normal)) / glm::dot(line, _normal);
if (t >= 0.0 && t <= 1.0) {
intersections[nIntersections++] = corner0 + t * line;
}
@@ -115,13 +116,13 @@ void BlockPlaneIntersectionGeometry::updateVertices() {
std::vector<std::pair<int, float>> angles(nIntersections - 1);
glm::vec3 vector1 = glm::normalize(intersections[1] - intersections[0]);
angles[0] = std::pair<int, float>(1, 0.0f);
const glm::vec3 vec1 = glm::normalize(intersections[1] - intersections[0]);
angles[0] = std::pair<int, float>(1, 0.f);
for (int i = 2; i < nIntersections; i++) {
glm::vec3 vectorI = glm::normalize(intersections[i] - intersections[0]);
float sinA = glm::dot(glm::cross(vector1, vectorI), _normal);
float cosA = glm::dot(vector1, vectorI);
const glm::vec3 vectorI = glm::normalize(intersections[i] - intersections[0]);
const float sinA = glm::dot(glm::cross(vec1, vectorI), _normal);
const float cosA = glm::dot(vec1, vectorI);
angles[i - 1] = { i, glm::sign(sinA) * (1.f - cosA) };
}
@@ -137,7 +138,7 @@ void BlockPlaneIntersectionGeometry::updateVertices() {
_vertices.push_back(intersections[0].z);
//_vertices.push_back(_w);
for (int i = 0; i < nIntersections - 1; i++) {
int j = angles[i].first;
const int j = angles[i].first;
_vertices.push_back(intersections[j].x);
_vertices.push_back(intersections[j].y);
_vertices.push_back(intersections[j].z);
+21 -27
View File
@@ -47,27 +47,27 @@ bool BoxGeometry::initialize() {
const float y = _size.y * 0.5f;
const float z = _size.z * 0.5f;
const GLfloat vertices[] = {
const std::array<GLfloat, 108> vertices = {
-x, -y, z, // blue corner
x, y, z, // white corner
x, y, z, // white corner
-x, y, z, // cyan corner
-x, -y, z, // blue corner
x, -y, z, // magenta corner
x, y, z, // white corner
x, -y, z, // magenta corner
x, y, z, // white corner
-x, -y, -z, // black corner
-x, y, -z, // green
x, y, -z, // yellow corner
x, y, -z, // yellow corner
-x, -y, -z, // black
x, y, -z, // yellow
x, -y, -z, // red
x, y, -z, // yellow
x, -y, -z, // red
x, -y, -z, // red
x, y, z, // yellow
x, -y, z, // magenta
x, -y, -z, // red
x, y, -z, // yellow
x, y, z, // white
x, -y, -z, // red
x, y, z, // yellow
x, -y, z, // magenta
x, -y, -z, // red
x, y, -z, // yellow
x, y, z, // white
-x, -y, -z, // black
-x, -y, z, // blue
@@ -76,19 +76,19 @@ bool BoxGeometry::initialize() {
-x, y, z, // cyan
-x, y, -z, // green
x, y, z, // white
x, y, z, // white
-x, y, -z, // green
-x, y, z, // cyan
-x, y, -z, // green
x, y, z, // white
x, y, -z, // yellow
x, y, z, // white
x, y, -z, // yellow
-x, -y, -z, // black
x, -y, z, // magenta
x, -y, z, // magenta
-x, -y, z, // blue
-x, -y, -z, // black
x, -y, -z, // red
x, -y, z // magenta
x, -y, -z, // red
x, -y, z // magenta
};
if (_vaoId == 0) {
@@ -97,18 +97,12 @@ bool BoxGeometry::initialize() {
if (_vBufferId == 0) {
glGenBuffers(1, &_vBufferId);
if (_vBufferId == 0) {
LERROR("Could not create vertex buffer");
return false;
}
}
// First VAO setup
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 3, nullptr);
@@ -117,7 +111,7 @@ bool BoxGeometry::initialize() {
return true;
}
void BoxGeometry::render() {
void BoxGeometry::render() const {
glBindVertexArray(_vaoId); // select first VAO
glDrawArrays(GL_TRIANGLES, 0, 6*6);
glBindVertexArray(0);
+7 -7
View File
@@ -29,21 +29,21 @@
namespace openspace::collision {
// Source: http://paulbourke.net/geometry/circlesphere/raysphere.c
bool lineSphereIntersection(glm::dvec3 p1, glm::dvec3 p2, glm::dvec3 center,
double r, glm::dvec3& intersectionPoint)
bool lineSphereIntersection(const glm::dvec3& p1, const glm::dvec3& p2,
const glm::dvec3& center, double r,
glm::dvec3& intersectionPoint)
{
double a, b, c;
const glm::dvec3 diffp = p2 - p1;
a = diffp.x * diffp.x + diffp.y * diffp.y + diffp.z * diffp.z;
b = 2.0 * (diffp.x * (p1.x - center.x) + diffp.y * (p1.y - center.y) +
const double a = diffp.x * diffp.x + diffp.y * diffp.y + diffp.z * diffp.z;
const double b = 2.0 * (diffp.x * (p1.x - center.x) + diffp.y * (p1.y - center.y) +
diffp.z * (p1.z - center.z));
c = center.x * center.x + center.y * center.y + center.z * center.z;
double c = center.x * center.x + center.y * center.y + center.z * center.z;
c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z;
c -= 2.0 * (center.x * p1.x + center.y * p1.y + center.z * p1.z);
c -= r * r;
double intersectionTest = b * b - 4.0 * a * c;
const double intersectionTest = b * b - 4.0 * a * c;
// No intersection
if (std::abs(a) < 0 || intersectionTest < 0.0) {
+48 -46
View File
@@ -42,10 +42,10 @@ namespace {
double& seconds)
{
// Find hms or dms indicies
size_t hOrDIndex =
const size_t hOrDIndex =
(str.find('h') != std::string::npos) ? str.find('h') : str.find('d');
size_t mIndex = str.find('m');
size_t sIndex = str.find('s');
const size_t mIndex = str.find('m');
const size_t sIndex = str.find('s');
if (hOrDIndex == std::string::npos || mIndex == std::string::npos ||
sIndex == std::string::npos)
{
@@ -56,9 +56,9 @@ namespace {
}
// Construct the number strings
std::string sHoursOrDegrees = str.substr(0, hOrDIndex);
std::string sMinutes = str.substr(hOrDIndex + 1, mIndex - hOrDIndex - 1);
std::string sSeconds = str.substr(mIndex + 1, sIndex - mIndex - 1);
const std::string sHoursOrDegrees = str.substr(0, hOrDIndex);
const std::string sMinutes = str.substr(hOrDIndex + 1, mIndex - hOrDIndex - 1);
const std::string sSeconds = str.substr(mIndex + 1, sIndex - mIndex - 1);
// Convert the strings to numbers
try {
@@ -176,21 +176,23 @@ namespace openspace {
// https://www.atnf.csiro.au/people/Tobias.Westmeier/tools_coords.php
glm::dvec3 icrsToGalacticCartesian(double ra, double dec, double distance) {
// (Ra, Dec) -> (a, d)
double a = glm::radians(ra);
double d = glm::radians(dec);
const double a = glm::radians(ra);
const double d = glm::radians(dec);
// Convert to galactic reference frame
double l = L0 - atan2(
cos(d) * sin(a - A0),
sin(d) * cos(D0) - cos(d) * sin(D0) * cos(a - A0)
const double l = L0 - std::atan2(
std::cos(d) * std::sin(a - A0),
std::sin(d) * std::cos(D0) - std::cos(d) * std::sin(D0) * std::cos(a - A0)
);
const double b = std::asin(
std::sin(d) * std::sin(D0) + std::cos(d) * std::cos(D0) * std::cos(a - A0)
);
double b = asin(sin(d) * sin(D0) + cos(d) * cos(D0) * cos(a - A0));
// Convert to cartesian
glm::dvec3 rGalactic = glm::dvec3(
cos(b) * cos(l),
cos(b) * sin(l),
sin(b)
const glm::dvec3 rGalactic = glm::dvec3(
std::cos(b) * std::cos(l),
std::cos(b) * std::sin(l),
std::sin(b)
);
return distance * rGalactic;
@@ -211,13 +213,15 @@ glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) {
}
// Parse right ascension
int raHours, raMinutes;
double raSeconds;
int raHours = 0;
int raMinutes = 0;
double raSeconds = 0.0;
parseRa(ra, raHours, raMinutes, raSeconds);
// Parse declination
int decDegrees, decMinutes;
double decSeconds;
int decDegrees = 0;
int decMinutes = 0;
double decSeconds = 0.0;
parseDec(dec, decDegrees, decMinutes, decSeconds);
const bool isValid = isRaDecValid(raHours,
@@ -236,12 +240,12 @@ glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) {
}
// Convert from hours/degrees, minutes, seconds to decimal degrees
double sign = std::signbit(static_cast<float>(decDegrees)) ? -1.0 : 1.0;
double raDeg = (raHours * 15.0) +
const double sign = std::signbit(static_cast<float>(decDegrees)) ? -1.0 : 1.0;
const double raDeg = (raHours * 15.0) +
(raMinutes * 15.0 / 60.0) +
(raSeconds * 15.0 / 3600.0);
double decDeg = (abs(decDegrees) +
const double decDeg = (std::abs(decDegrees) +
(decMinutes / 60.0) +
(decSeconds / 3600.0)) * sign;
@@ -255,22 +259,24 @@ glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) {
// https://en.wikipedia.org/wiki/Celestial_coordinate_system
glm::dvec3 galacticCartesianToIcrs(double x, double y, double z) {
// Normalize
double distance = sqrt(x*x + y*y + z*z);
double nX = x / distance;
double nY = y / distance;
double nZ = z / distance;
const double distance = std::sqrt(x*x + y*y + z*z);
double const nX = x / distance;
const double nY = y / distance;
const double nZ = z / distance;
// Convert from cartesian
// (x, y, z) -> (l, b)
double l = atan2(nY, nX);
double b = asin(nZ);
const double l = std::atan2(nY, nX);
const double b = std::asin(nZ);
// Convert to equatorial reference frame
double a = atan2(
cos(b) * sin(L0 - l),
sin(b) * cos(D0) - cos(b) * sin(D0) * cos(L0 - l)
const double a = std::atan2(
std::cos(b) * std::sin(L0 - l),
std::sin(b) * std::cos(D0) - std::cos(b) * std::sin(D0) * std::cos(L0 - l)
) + A0;
double d = asin(sin(b) * sin(D0) + cos(b) * cos(D0) * cos(L0 - l));
const double d = std::asin(
std::sin(b) * std::sin(D0) + std::cos(b) * std::cos(D0) * std::cos(L0 - l)
);
return glm::dvec3(glm::degrees(a), glm::degrees(d), distance);
}
@@ -281,12 +287,8 @@ glm::dvec3 galacticCartesianToIcrs(double x, double y, double z) {
// https://math.stackexchange.com/questions/15323/how-do-i-calculate-the-cartesian-
// coordinates-of-stars
std::pair<std::string, std::string> decimalDegreesToIcrs(double ra, double dec) {
// Radians to degrees
double raDeg = ra;
double decDeg = dec;
// Check input
if (raDeg < 0 || raDeg > 360 || decDeg < -90 || decDeg > 90) {
if (ra < 0.0 || ra > 360.0 || dec < -90.0 || dec > 90.0) {
LWARNING(fmt::format(
"Ra '{}' or Dec '{}' is outside the allowed range, result may be incorrect",
ra, dec
@@ -294,16 +296,16 @@ std::pair<std::string, std::string> decimalDegreesToIcrs(double ra, double dec)
}
// Calculate Ra
int raHours = static_cast<int>(std::trunc(raDeg) / 15.0);
double raMinutesFull = (raDeg - raHours * 15.0) * 60.0 / 15.0;
int raMinutes = static_cast<int>(std::trunc(raMinutesFull));
double raSeconds = (raMinutesFull - raMinutes) * 60.0;
const int raHours = static_cast<int>(std::trunc(ra) / 15.0);
const double raMinutesFull = (ra - raHours * 15.0) * 60.0 / 15.0;
const int raMinutes = static_cast<int>(std::trunc(raMinutesFull));
const double raSeconds = (raMinutesFull - raMinutes) * 60.0;
// Calculate Dec
int decDegrees = static_cast<int>(std::trunc(decDeg));
double decMinutesFull = (std::abs(decDeg) - std::abs(decDegrees)) * 60.0;
int decMinutes = static_cast<int>(std::trunc(decMinutesFull));
double decSeconds = (decMinutesFull - decMinutes) * 60.0;
const int decDegrees = static_cast<int>(std::trunc(dec));
const double decMinutesFull = (std::abs(dec) - std::abs(decDegrees)) * 60.0;
const int decMinutes = static_cast<int>(std::trunc(decMinutesFull));
const double decSeconds = (decMinutesFull - decMinutes) * 60.0;
// Construct strings
std::pair<std::string, std::string> result;
+5 -5
View File
@@ -99,11 +99,11 @@ std::pair<double, std::string_view> simplifyDistance(double meters,
}
float convertMasPerYearToMeterPerSecond(float masPerYear, float parallax) {
double degreeFromMas = 1.0 / 3600000.0;
double radiusInMeter = (distanceconstants::Parsec * 1000.0) / parallax;
double perYearToPerSecond = 1.0 / SecondsPerYear;
double meterPerSecond = masPerYear * degreeFromMas * radiusInMeter *
perYearToPerSecond;
const double degreeFromMas = 1.0 / 3600000.0;
const double radiusInMeter = (distanceconstants::Parsec * 1000.0) / parallax;
const double perYearToPerSecond = 1.0 / SecondsPerYear;
const double meterPerSecond =
masPerYear * degreeFromMas * radiusInMeter * perYearToPerSecond;
return static_cast<float>(meterPerSecond);
}
+4 -4
View File
@@ -81,8 +81,8 @@ nlohmann::json generateJsonDocumentation(const Documentation& d) {
}
}
else if (tv) {
Documentation doc = { .entries = tv->documentations };
nlohmann::json restrictions = generateJsonDocumentation(doc);
const Documentation doc = { .entries = tv->documentations };
const nlohmann::json restrictions = generateJsonDocumentation(doc);
// We have a TableVerifier, so we need to recurse
entry["restrictions"] = restrictions;
}
@@ -160,7 +160,7 @@ nlohmann::json FactoryManager::generateJson() const {
return d.name == factoryInfo.name;
});
if (factoryDoc != docs.end()) {
nlohmann::json documentation = generateJsonDocumentation(*factoryDoc);
const nlohmann::json documentation = generateJsonDocumentation(*factoryDoc);
factory["classes"].push_back(documentation);
// Remove documentation from list check at the end if all docs got put in
docs.erase(factoryDoc);
@@ -182,7 +182,7 @@ nlohmann::json FactoryManager::generateJson() const {
return d.name == c;
});
if (found != docs.end()) {
nlohmann::json documentation = generateJsonDocumentation(*found);
const nlohmann::json documentation = generateJsonDocumentation(*found);
factory["classes"].push_back(documentation);
docs.erase(found);
}
+23 -23
View File
@@ -76,7 +76,7 @@ bool Histogram::add(float value, float repeat) {
const float normalizedValue = (value - _minValue) / (_maxValue - _minValue);
const int binIndex = static_cast<int>(std::min(
static_cast<float>(floor(normalizedValue * _numBins)),
static_cast<float>(std::floor(normalizedValue * _numBins)),
_numBins - 1.f
)); // [0, _numBins - 1]
@@ -92,16 +92,16 @@ void Histogram::changeRange(float minValue, float maxValue){
}
float* oldData = _data;
float oldMin = _minValue;
float oldMax = _maxValue;
const float oldMin = _minValue;
const float oldMax = _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 = static_cast<int>(std::min(
static_cast<float>(floor(normalizedValue * _numBins)),
const float unNormalizedValue = i * (oldMax - oldMin) + oldMin;
const float normalizedValue = (unNormalizedValue - _minValue) /
(_maxValue - _minValue); // [0.0, 1.0]
const int binIndex = static_cast<int>(std::min(
static_cast<float>(std::floor(normalizedValue * _numBins)),
_numBins - 1.f
)); // [0, _numBins - 1]
@@ -153,8 +153,8 @@ bool Histogram::addRectangle(float lowBin, float highBin, float value) {
const float lowBinIndex = normalizedLowBin * _numBins;
const float highBinIndex = normalizedHighBin * _numBins;
const int fillLow = static_cast<int>(floor(lowBinIndex));
const int fillHigh = static_cast<int>(ceil(highBinIndex));
const int fillLow = static_cast<int>(std::floor(lowBinIndex));
const int fillHigh = static_cast<int>(std::ceil(highBinIndex));
for (int i = fillLow; i < fillHigh; i++) {
_data[i] += value;
@@ -176,9 +176,9 @@ float Histogram::interpolate(float bin) const {
const float normalizedBin = (bin - _minValue) / (_maxValue - _minValue);
const float binIndex = normalizedBin * _numBins - 0.5f; // Center
const float interpolator = binIndex - floor(binIndex);
int binLow = static_cast<int>(floor(binIndex));
int binHigh = static_cast<int>(ceil(binIndex));
const float interpolator = binIndex - std::floor(binIndex);
int binLow = static_cast<int>(std::floor(binIndex));
int binHigh = static_cast<int>(std::ceil(binIndex));
// Clamp bins
if (binLow < 0) {
@@ -222,11 +222,11 @@ void Histogram::normalize() {
* value will be the value at the index.
*/
void Histogram::generateEqualizer() {
float previousCdf = 0.0f;
_equalizer = std::vector<float>(_numBins, 0.0f);
float previousCdf = 0.f;
_equalizer = std::vector<float>(_numBins, 0.f);
for (int i = 0; i < _numBins; i++) {
const float probability = _data[i] / static_cast<float>(_numValues);
const float cdf = std::min(1.0f, previousCdf + probability);
const float cdf = std::min(1.f, previousCdf + probability);
_equalizer[i] = cdf * (_numBins-1);
previousCdf = cdf;
}
@@ -257,8 +257,8 @@ float Histogram::equalize(float value) const {
// " val: " + std::to_string(value)
// );
// }
float normalizedValue = (value-_minValue)/(_maxValue-_minValue);
int bin = static_cast<int>(floor(normalizedValue * _numBins));
const float normalizedValue = (value - _minValue) / (_maxValue - _minValue);
int bin = static_cast<int>(std::floor(normalizedValue * _numBins));
// If value == _maxValues then bin == _numBins, which is a invalid index.
bin = std::min(_numBins-1, bin);
bin = std::max(0, bin);
@@ -271,7 +271,7 @@ float Histogram::entropy() {
for (int i = 0; i < _numBins; i++) {
if (_data[i] != 0) {
entropy -= (_data[i] / static_cast<float>(_numValues)) *
(log2(_data[i]) / static_cast<float>(_numValues));
(std::log2(_data[i]) / static_cast<float>(_numValues));
}
}
return entropy;
@@ -326,9 +326,9 @@ float Histogram::highestBinValue(bool equalized, int overBins){
if (!equalized) {
float low = _minValue + static_cast<float>(highestBin) /
_numBins * (_maxValue - _minValue);
float high = low + (_maxValue - _minValue) / static_cast<float>(_numBins);
const float low = _minValue + static_cast<float>(highestBin) /
_numBins * (_maxValue - _minValue);
const float high = low + (_maxValue - _minValue) / static_cast<float>(_numBins);
return (high+low) / 2.f;
}
else {
@@ -337,7 +337,7 @@ float Histogram::highestBinValue(bool equalized, int overBins){
}
}
float Histogram::binWidth() {
float Histogram::binWidth() const {
return (_maxValue - _minValue) / _numBins;
}
+14 -11
View File
@@ -72,7 +72,8 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) {
CURLOPT_HEADERFUNCTION,
+[](char* ptr, size_t size, size_t nmemb, void* userData) {
HttpRequest* r = reinterpret_cast<HttpRequest*>(userData);
bool shouldContinue = r->_onHeader ? r->_onHeader(ptr, size * nmemb) : true;
const bool shouldContinue =
r->_onHeader ? r->_onHeader(ptr, size * nmemb) : true;
return shouldContinue ? size * nmemb : 0;
}
);
@@ -83,7 +84,7 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) {
CURLOPT_WRITEFUNCTION,
+[](char* ptr, size_t size, size_t nmemb, void* userData) {
HttpRequest* r = reinterpret_cast<HttpRequest*>(userData);
bool shouldContinue = r->_onData ? r->_onData(ptr, size * nmemb) : true;
const bool shouldContinue = r->_onData ? r->_onData(ptr, size * nmemb) : true;
return shouldContinue ? size * nmemb : 0;
}
);
@@ -103,7 +104,8 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) {
totalBytes = nTotalDownloadBytes;
}
bool shouldContinue = r->_onProgress ?
const bool shouldContinue =
r->_onProgress ?
r->_onProgress(nDownloadedBytes, totalBytes) :
true;
return shouldContinue ? 0 : 1;
@@ -112,10 +114,10 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, static_cast<long>(timeout.count()));
CURLcode res = curl_easy_perform(curl);
const CURLcode res = curl_easy_perform(curl);
bool success = false;
if (res == CURLE_OK) {
long responseCode;
long responseCode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
if (responseCode >= 400) {
@@ -156,8 +158,8 @@ HttpDownload::HttpDownload(std::string url)
});
_httpRequest.onProgress(
[this](int64_t downloadedBytes, std::optional<int64_t> totalBytes) {
bool cont = _onProgress ? _onProgress(downloadedBytes, totalBytes) : true;
[this](int64_t nDownloaded, std::optional<int64_t> nTotal) {
const bool cont =_onProgress ? _onProgress(nDownloaded, nTotal) : true;
return cont && !_shouldCancel;
}
);
@@ -262,8 +264,8 @@ HttpFileDownload::HttpFileDownload(std::string url, std::filesystem::path destin
bool HttpFileDownload::setup() {
{
std::lock_guard g(_directoryCreationMutex);
std::filesystem::path d = _destination.parent_path();
const std::lock_guard g(_directoryCreationMutex);
const std::filesystem::path d = _destination.parent_path();
if (!std::filesystem::is_directory(d)) {
std::filesystem::create_directories(d);
}
@@ -310,12 +312,13 @@ bool HttpFileDownload::setup() {
#else // ^^^ WIN32 / !WIN32 vvv
if (errno) {
#ifdef __unix__
char buffer[256];
std::array<char, 256> buffer;
LERRORC(
"HttpFileDownload",
fmt::format(
"Cannot open file '{}': {}",
_destination, std::string(strerror_r(errno, buffer, sizeof(buffer)))
_destination,
std::string(strerror_r(errno, buffer.data(), sizeof(buffer)))
)
);
return false;
+7 -7
View File
@@ -91,8 +91,8 @@ void sortJson(nlohmann::json& json, const std::string& key) {
json.begin(),
json.end(),
[&key](const nlohmann::json& lhs, const nlohmann::json& rhs) {
std::string lhsString = ghoul::toLowerCase(lhs[key]);
std::string rhsString = ghoul::toLowerCase(rhs[key]);
const std::string lhsString = ghoul::toLowerCase(lhs[key]);
const std::string rhsString = ghoul::toLowerCase(rhs[key]);
return rhsString > lhsString;
}
@@ -116,7 +116,7 @@ ghoul::Dictionary jsonToDictionary(const nlohmann::json& json) {
break;
case nlohmann::json::value_t::object: {
ghoul::Dictionary subDict = jsonToDictionary(j);
dict.setValue(key, std::move(subDict));
dict.setValue(std::move(key), std::move(subDict));
break;
}
case nlohmann::json::value_t::array: {
@@ -128,19 +128,19 @@ ghoul::Dictionary jsonToDictionary(const nlohmann::json& json) {
// We add 1 to the key to make Lua happy :-/
addToDict(subDict, fmt::format("{}", i + 1), value);
}
dict.setValue(key, std::move(subDict));
dict.setValue(std::move(key), std::move(subDict));
break;
}
case nlohmann::json::value_t::string:
dict.setValue(key, j.get<std::string>());
dict.setValue(std::move(key), j.get<std::string>());
break;
case nlohmann::json::value_t::boolean:
dict.setValue(key, j.get<bool>());
dict.setValue(std::move(key), j.get<bool>());
break;
case nlohmann::json::value_t::number_integer:
case nlohmann::json::value_t::number_unsigned:
case nlohmann::json::value_t::number_float:
dict.setValue(key, j.get<double>());
dict.setValue(std::move(key), j.get<double>());
break;
case nlohmann::json::value_t::binary:
throw ghoul::RuntimeError(
+12 -12
View File
@@ -34,7 +34,7 @@
namespace openspace {
KeyWithModifier stringToKey(std::string str) {
KeyWithModifier stringToKey(const std::string& str) {
std::vector<std::string> tokens = ghoul::tokenizeString(str, '+');
// "Keypad +" will tokenize into "Keypad " + ""
if (tokens.size() == 2 && tokens[0] == "Keypad " && tokens[1].empty()) {
@@ -49,7 +49,7 @@ KeyWithModifier stringToKey(std::string str) {
// default is unknown
Key key = Key::Unknown;
std::string keyName = tokens.back();
std::string keyNameOriginal = originalTokens.back();
const std::string keyNameOriginal = originalTokens.back();
for (const KeyInfo& ki : KeyInfos) {
if (ki.identifier == keyName || ki.name == keyName ||
ki.identifier == keyNameOriginal || ki.name == keyNameOriginal)
@@ -120,9 +120,9 @@ std::string keyToString(KeyWithModifier keyWithModifier) {
namespace ghoul {
template <>
std::string to_string(const openspace::Key& key) {
std::string to_string(const openspace::Key& value) {
for (const openspace::KeyInfo& ki : openspace::KeyInfos) {
if (ki.key == key) {
if (ki.key == value) {
return std::string(ki.name);
}
}
@@ -131,20 +131,20 @@ std::string to_string(const openspace::Key& key) {
}
template <>
std::string to_string(const openspace::KeyModifier& mod) {
std::string to_string(const openspace::KeyModifier& value) {
using namespace openspace;
if (mod == KeyModifier::None) {
if (value == KeyModifier::None) {
return "";
}
std::string result;
for (const openspace::KeyModifierInfo& kmi : openspace::KeyModifierInfos) {
for (const KeyModifierInfo& kmi : KeyModifierInfos) {
// No need for an extra check for the empty modifier since that is mapped to 0,
// meaning that the `hasKeyModifier` will always fail for it since it checks
// internally against != 0
if (hasKeyModifier(mod, kmi.modifier)) {
if (hasKeyModifier(value, kmi.modifier)) {
result += fmt::format("{}+", kmi.name);
}
@@ -156,12 +156,12 @@ std::string to_string(const openspace::KeyModifier& mod) {
}
template <>
std::string to_string(const openspace::KeyWithModifier& key) {
if (key.modifier == openspace::KeyModifier::None) {
return to_string(key.key);
std::string to_string(const openspace::KeyWithModifier& value) {
if (value.modifier == openspace::KeyModifier::None) {
return to_string(value.key);
}
else {
return fmt::format("{}+{}", to_string(key.modifier), to_string(key.key));
return fmt::format("{}+{}", to_string(value.modifier), to_string(value.key));
}
}
+4 -4
View File
@@ -50,14 +50,14 @@ void OpenSpaceModule::initialize(const ghoul::Dictionary& configuration) {
ZoneScoped;
ZoneName(identifier().c_str(), identifier().size());
std::string upperIdentifier = ghoul::toUpperCase(identifier());
const std::string upperIdentifier = ghoul::toUpperCase(identifier());
std::string moduleToken = "${" + std::string(ModuleBaseToken) + upperIdentifier + "}";
std::filesystem::path path = modulePath();
if (!path.empty()) {
LDEBUG(fmt::format("Registering module path '{}' -> {}", moduleToken, path));
FileSys.registerPathToken(moduleToken, std::move(path));
FileSys.registerPathToken(std::move(moduleToken), std::move(path));
}
internalInitialize(configuration);
@@ -105,10 +105,10 @@ std::vector<std::string> OpenSpaceModule::requiredOpenGLExtensions() const {
}
std::filesystem::path OpenSpaceModule::modulePath() const {
std::string moduleIdentifier = ghoul::toLowerCase(identifier());
const std::string moduleIdentifier = ghoul::toLowerCase(identifier());
// First try the internal module directory
std::filesystem::path path = absPath("${MODULES}/" + moduleIdentifier);
const std::filesystem::path path = absPath("${MODULES}/" + moduleIdentifier);
return std::filesystem::is_directory(path) ? path : "";
}
+9 -9
View File
@@ -53,7 +53,7 @@ void PlaneGeometry::deinitialize() {
_vBufferId = 0;
}
void PlaneGeometry::render() {
void PlaneGeometry::render() const {
glBindVertexArray(_vaoId);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
@@ -77,18 +77,18 @@ void PlaneGeometry::updateGeometry() {
GLfloat t;
};
VertexData vertices[] = {
{ -size.x, -size.y, 0.f, 0.f },
{ size.x, size.y, 1.f, 1.f },
{ -size.x, size.y, 0.f, 1.f },
{ -size.x, -size.y, 0.f, 0.f },
{ size.x, -size.y, 1.f, 0.f },
{ size.x, size.y, 1.f, 1.f }
const std::array<VertexData, 6> vertices = {
VertexData{ -size.x, -size.y, 0.f, 0.f },
VertexData{ size.x, size.y, 1.f, 1.f },
VertexData{ -size.x, size.y, 0.f, 1.f },
VertexData{ -size.x, -size.y, 0.f, 0.f },
VertexData{ size.x, -size.y, 1.f, 0.f },
VertexData{ size.x, size.y, 1.f, 1.f }
};
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr);
glEnableVertexAttribArray(1);
+1 -1
View File
@@ -42,7 +42,7 @@ ProgressBar::~ProgressBar() {
void ProgressBar::print(int current) {
const float progress = static_cast<float>(current) / static_cast<float>(_end);
const int iprogress = static_cast<int>(progress * 100.0f);
const int iprogress = static_cast<int>(progress * 100.f);
if (iprogress != _previous) {
const int pos = static_cast<int>(static_cast<float>(_width)* progress);
const int eqWidth = pos + 1;
+3 -3
View File
@@ -29,14 +29,14 @@
namespace openspace {
ScreenLog::ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel)
: _timeToLive(std::move(timeToLive))
: _timeToLive(timeToLive)
, _logLevel(logLevel)
{
_entries.reserve(64);
}
void ScreenLog::removeExpiredEntries() {
std::lock_guard guard(_mutex);
const std::lock_guard guard(_mutex);
const auto t = std::chrono::steady_clock::now();
const auto rit = std::remove_if(
@@ -49,7 +49,7 @@ void ScreenLog::removeExpiredEntries() {
}
void ScreenLog::log(LogLevel level, std::string_view category, std::string_view message) {
std::lock_guard guard(_mutex);
const std::lock_guard guard(_mutex);
if (level >= _logLevel) {
_entries.push_back({
level,
+7 -6
View File
@@ -61,9 +61,10 @@ Sphere::Sphere(glm::vec3 radius, int segments)
// Spherical coordinates based on ISO standard.
// https://en.wikipedia.org/wiki/Spherical_coordinate_system
const float x = radius[0] * sin(theta) * cos(phi);
const float y = radius[1] * sin(theta) * sin(phi);
const float z = radius[2] * cos(theta); // Z points towards pole (theta = 0)
// Z points towards pole (theta = 0)
const float x = radius[0] * std::sin(theta) * std::cos(phi);
const float y = radius[1] * std::sin(theta) * std::sin(phi);
const float z = radius[2] * std::cos(theta);
_varray[nr].location[0] = x;
_varray[nr].location[1] = y;
@@ -71,7 +72,7 @@ Sphere::Sphere(glm::vec3 radius, int segments)
_varray[nr].location[3] = 0.0;
glm::vec3 normal = glm::vec3(x, y, z);
if (!(x == 0.f && y == 0.f && z == 0.f)) {
if (x != 0.f || y != 0.f || z != 0.f) {
normal = glm::vec3(glm::normalize(glm::dvec3(normal)));
}
@@ -197,8 +198,8 @@ bool Sphere::initialize() {
return true;
}
void Sphere::render() {
glBindVertexArray(_vaoID); // select first VAO
void Sphere::render() const {
glBindVertexArray(_vaoID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID);
glDrawElements(GL_TRIANGLES, _isize, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
+75 -60
View File
@@ -150,10 +150,19 @@ SpiceManager::TerminatorType SpiceManager::terminatorTypeFromString(
}
SpiceManager::SpiceManager() {
// The third parameter for the erract_c function is a SpiceChar*, not ConstSpiceChar*
// so we have to do this weird memory copying trick
std::array<char, 7> buffer;
// Set the SPICE library to not exit the program if an error occurs
erract_c("SET", 0, const_cast<char*>("REPORT"));
std::memset(buffer.data(), 0, buffer.size());
std::strcpy(buffer.data(), "REPORT");
erract_c("SET", 0, buffer.data());
// But we do not want SPICE to print the errors, we will fetch them ourselves
errprt_c("SET", 0, const_cast<char*>("NONE"));
std::memset(buffer.data(), 0, buffer.size());
std::strcpy(buffer.data(), "NONE");
errprt_c("SET", 0, buffer.data());
loadLeapSecondsSpiceKernel();
}
@@ -193,8 +202,9 @@ SpiceManager& SpiceManager::ref() {
// If an error occurred, true is returned, otherwise, false
void throwSpiceError(const std::string& errorMessage) {
if (openspace::SpiceManager::ref().exceptionHandling()) {
char buffer[SpiceErrorBufferSize];
getmsg_c("LONG", SpiceErrorBufferSize, buffer);
std::string buffer;
buffer.resize(SpiceErrorBufferSize);
getmsg_c("LONG", SpiceErrorBufferSize, buffer.data());
reset_c();
throw openspace::SpiceManager::SpiceException(errorMessage + ": " + buffer);
}
@@ -217,7 +227,7 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) {
)
);
std::filesystem::path path = absPath(std::move(filePath));
const std::filesystem::path path = absPath(std::move(filePath));
const auto it = std::find_if(
_loadedKernels.begin(),
_loadedKernels.end(),
@@ -232,9 +242,9 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) {
// We need to set the current directory as meta-kernels are usually defined relative
// to the directory they reside in. The directory change is not necessary for regular
// kernels
std::filesystem::path currentDirectory = std::filesystem::current_path();
const std::filesystem::path currentDirectory = std::filesystem::current_path();
std::filesystem::path p = path.parent_path();
const std::filesystem::path p = path.parent_path();
std::filesystem::current_path(p);
LINFO(fmt::format("Loading SPICE kernel '{}'", path));
@@ -248,7 +258,7 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) {
throwSpiceError("Kernel loading");
}
std::filesystem::path fileExtension = path.extension();
const std::filesystem::path fileExtension = path.extension();
if (fileExtension == ".bc" || fileExtension == ".BC") {
findCkCoverage(path.string()); // binary ck kernel
}
@@ -256,7 +266,7 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) {
findSpkCoverage(path.string()); // binary spk kernel
}
KernelHandle kernelId = ++_lastAssignedKernel;
const KernelHandle kernelId = ++_lastAssignedKernel;
ghoul_assert(kernelId != 0, "Kernel Handle wrapped around to 0");
_loadedKernels.push_back({ path.string(), kernelId, 1 });
return kernelId;
@@ -291,7 +301,7 @@ void SpiceManager::unloadKernel(KernelHandle kernelId) {
void SpiceManager::unloadKernel(std::string filePath) {
ghoul_assert(!filePath.empty(), "Empty filename");
std::filesystem::path path = absPath(std::move(filePath));
const std::filesystem::path path = absPath(std::move(filePath));
const auto it = std::find_if(
_loadedKernels.begin(),
@@ -415,8 +425,7 @@ std::vector<std::pair<int, std::string>> SpiceManager::spiceBodies(
{
std::vector<std::pair<int, std::string>> bodies;
constexpr int Frnmln = 33;
static SpiceInt idsetBuffer[SPICE_CELL_CTRLSZ + 8192];
static std::array<SpiceInt, SPICE_CELL_CTRLSZ + 8192> idsetBuffer;
static SpiceCell idset = {
SPICE_INT,
0,
@@ -425,11 +434,12 @@ std::vector<std::pair<int, std::string>> SpiceManager::spiceBodies(
SPICETRUE,
SPICEFALSE,
SPICEFALSE,
&idsetBuffer,
&(idsetBuffer[SPICE_CELL_CTRLSZ])
idsetBuffer.data(),
idsetBuffer.data() + SPICE_CELL_CTRLSZ
};
SpiceChar frname[Frnmln];
constexpr int Frnmln = 33;
std::array<SpiceChar, Frnmln> frname;
for (SpiceInt i = 1; i <= 6; i++) {
if (i < 6) {
@@ -453,13 +463,11 @@ std::vector<std::pair<int, std::string>> SpiceManager::spiceBodies(
frmnam_c(
(reinterpret_cast<SpiceInt*>(idset.data))[j],
Frnmln,
frname
frname.data()
);
bodies.push_back(
std::make_pair(
static_cast<long>(reinterpret_cast<SpiceInt*>(idset.data)[j]),
frname
)
bodies.emplace_back(
static_cast<long>(reinterpret_cast<SpiceInt*>(idset.data)[j]),
frname.data()
);
}
}
@@ -474,15 +482,15 @@ bool SpiceManager::hasValue(const std::string& body, const std::string& item) co
ghoul_assert(!body.empty(), "Empty body");
ghoul_assert(!item.empty(), "Empty item");
int id = naifId(body);
const int id = naifId(body);
return hasValue(id, item);
}
int SpiceManager::naifId(const std::string& body) const {
ghoul_assert(!body.empty(), "Empty body");
SpiceBoolean success;
SpiceInt id;
SpiceBoolean success = SPICEFALSE;
SpiceInt id = 0;
bods2c_c(body.c_str(), &id, &success);
if (!success && _useExceptions) {
throw SpiceException(fmt::format("Could not find NAIF ID of body '{}'", body));
@@ -493,8 +501,8 @@ int SpiceManager::naifId(const std::string& body) const {
bool SpiceManager::hasNaifId(const std::string& body) const {
ghoul_assert(!body.empty(), "Empty body");
SpiceBoolean success;
SpiceInt id;
SpiceBoolean success = SPICEFALSE;
SpiceInt id = 0;
bods2c_c(body.c_str(), &id, &success);
reset_c();
return success;
@@ -503,7 +511,7 @@ bool SpiceManager::hasNaifId(const std::string& body) const {
int SpiceManager::frameId(const std::string& frame) const {
ghoul_assert(!frame.empty(), "Empty frame");
SpiceInt id;
SpiceInt id = 0;
namfrm_c(frame.c_str(), &id);
if (id == 0 && _useExceptions) {
throw SpiceException(fmt::format("Could not find NAIF ID of frame '{}'", frame));
@@ -514,7 +522,7 @@ int SpiceManager::frameId(const std::string& frame) const {
bool SpiceManager::hasFrameId(const std::string& frame) const {
ghoul_assert(!frame.empty(), "Empty frame");
SpiceInt id;
SpiceInt id = 0;
namfrm_c(frame.c_str(), &id);
return id != 0;
}
@@ -526,7 +534,7 @@ void getValueInternal(const std::string& body, const std::string& value, int siz
ghoul_assert(!value.empty(), "Empty value");
ghoul_assert(v != nullptr, "Empty value pointer");
SpiceInt n;
SpiceInt n = 0;
bodvrd_c(body.c_str(), value.c_str(), size, &n, v);
if (failed_c()) {
@@ -568,11 +576,13 @@ void SpiceManager::getValue(const std::string& body, const std::string& value,
getValueInternal(body, value, static_cast<int>(v.size()), v.data());
}
double SpiceManager::spacecraftClockToET(const std::string& craft, double craftTicks) {
double SpiceManager::spacecraftClockToET(const std::string& craft,
double craftTicks) const
{
ghoul_assert(!craft.empty(), "Empty craft");
int craftId = naifId(craft);
double et;
const int craftId = naifId(craft);
double et = 0.0;
sct2e_c(craftId, craftTicks, &et);
if (failed_c()) {
throwSpiceError(fmt::format(
@@ -589,7 +599,7 @@ double SpiceManager::ephemerisTimeFromDate(const std::string& timeString) const
}
double SpiceManager::ephemerisTimeFromDate(const char* timeString) const {
double et;
double et = 0.0;
str2et_c(timeString, &et);
if (failed_c()) {
throwSpiceError(fmt::format("Error converting date '{}'", timeString));
@@ -600,10 +610,10 @@ double SpiceManager::ephemerisTimeFromDate(const char* timeString) const {
std::string SpiceManager::dateFromEphemerisTime(double ephemerisTime, const char* format)
{
constexpr int BufferSize = 128;
char Buffer[BufferSize];
std::memset(Buffer, char(0), BufferSize);
std::array<char, BufferSize> Buffer;
std::memset(Buffer.data(), char(0), BufferSize);
timout_c(ephemerisTime, format, BufferSize, Buffer);
timout_c(ephemerisTime, format, BufferSize, Buffer.data());
if (failed_c()) {
throwSpiceError(fmt::format(
"Error converting ephemeris time '{}' to date with format '{}'",
@@ -613,11 +623,11 @@ std::string SpiceManager::dateFromEphemerisTime(double ephemerisTime, const char
if (Buffer[0] == '*') {
// The conversion failed and we need to use et2utc
constexpr int SecondsPrecision = 3;
et2utc_c(ephemerisTime, "C", SecondsPrecision, BufferSize, Buffer);
et2utc_c(ephemerisTime, "C", SecondsPrecision, BufferSize, Buffer.data());
}
return std::string(Buffer);
return std::string(Buffer.data());
}
glm::dvec3 SpiceManager::targetPosition(const std::string& target,
@@ -630,8 +640,8 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target,
ghoul_assert(!observer.empty(), "Observer is not empty");
ghoul_assert(!referenceFrame.empty(), "Reference frame is not empty");
bool targetHasCoverage = hasSpkCoverage(target, ephemerisTime);
bool observerHasCoverage = hasSpkCoverage(observer, ephemerisTime);
const bool targetHasCoverage = hasSpkCoverage(target, ephemerisTime);
const bool observerHasCoverage = hasSpkCoverage(observer, ephemerisTime);
if (!targetHasCoverage && !observerHasCoverage) {
if (_useExceptions) {
throw SpiceException(
@@ -665,10 +675,12 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target,
return position;
}
else if (targetHasCoverage) {
// observer has no coverage
// observer has no coverage, so we try getting position from the reverse
const std::string& invObserver = target;
const std::string& invTarget = observer;
return getEstimatedPosition(
observer,
target,
invTarget,
invObserver,
referenceFrame,
aberrationCorrection,
ephemerisTime,
@@ -754,7 +766,7 @@ SpiceManager::SurfaceInterceptResult SpiceManager::surfaceIntercept(
SurfaceInterceptResult result;
SpiceBoolean found;
SpiceBoolean found = SPICEFALSE;
sincpt_c(ComputationMethod.c_str(),
target.c_str(),
ephemerisTime,
@@ -795,8 +807,9 @@ bool SpiceManager::isTargetInFieldOfView(const std::string& target,
ghoul_assert(!referenceFrame.empty(), "Reference frame must not be empty");
ghoul_assert(!instrument.empty(), "Instrument must not be empty");
int visible;
fovtrg_c(instrument.c_str(),
int visible = 0;
fovtrg_c(
instrument.c_str(),
target.c_str(),
toString(method),
referenceFrame.c_str(),
@@ -897,7 +910,7 @@ glm::dmat3 SpiceManager::positionTransformMatrix(const std::string& sourceFrame,
if (failed_c()) {
throwSpiceError("");
}
SpiceBoolean success = !(failed_c());
const SpiceBoolean success = !(failed_c());
reset_c();
if (!success) {
result = getEstimatedTransformMatrix(
@@ -950,7 +963,7 @@ SpiceManager::FieldOfViewResult SpiceManager::fieldOfView(int instrument) const
FieldOfViewResult res;
SpiceInt nrReturned;
SpiceInt nrReturned = 0;
double boundsArr[MaxBoundsSize][3];
char fovShapeBuffer[BufferSize];
char frameNameBuffer[BufferSize];
@@ -977,7 +990,7 @@ SpiceManager::FieldOfViewResult SpiceManager::fieldOfView(int instrument) const
res.bounds.emplace_back(boundsArr[i][0], boundsArr[i][1], boundsArr[i][2]);
}
std::string shape = std::string(fovShapeBuffer);
const std::string shape = std::string(fovShapeBuffer);
static const std::map<std::string, FieldOfViewResult::Shape> Map = {
{ "POLYGON", FieldOfViewResult::Shape::Polygon },
{ "RECTANGLE" , FieldOfViewResult::Shape::Rectangle },
@@ -1080,7 +1093,8 @@ void SpiceManager::findCkCoverage(const std::string& path) {
for (SpiceInt j = 0; j < numberOfIntervals; j++) {
// Get the endpoints of the jth interval.
SpiceDouble b, e;
SpiceDouble b = 0.0;
SpiceDouble e = 0.0;
wnfetd_c(&cover, j, &b, &e);
if (failed_c()) {
throwSpiceError("Error finding Ck Coverage");
@@ -1139,7 +1153,8 @@ void SpiceManager::findSpkCoverage(const std::string& path) {
for (SpiceInt j = 0; j < numberOfIntervals; j++) {
//Get the endpoints of the jth interval.
SpiceDouble b, e;
SpiceDouble b = 0.0;
SpiceDouble e = 0.0;
wnfetd_c(&cover, j, &b, &e);
if (failed_c()) {
throwSpiceError("Error finding Spk coverage");
@@ -1167,7 +1182,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target,
ghoul_assert(!referenceFrame.empty(), "Reference frame must not be empty");
ghoul_assert(target != observer, "Target and observer must be different");
int targetId = naifId(target);
const int targetId = naifId(target);
if (targetId == 0) {
// SOLAR SYSTEM BARYCENTER special case, no definition in kernels
@@ -1227,8 +1242,8 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target,
else {
// coverage both earlier and later, interpolate these positions
glm::dvec3 posEarlier = glm::dvec3(0.0);
double ltEarlier;
double timeEarlier = *std::prev((coveredTimes.lower_bound(ephemerisTime)));
double ltEarlier = 0.0;
const double timeEarlier = *std::prev((coveredTimes.lower_bound(ephemerisTime)));
spkpos_c(
target.c_str(),
timeEarlier,
@@ -1240,8 +1255,8 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target,
);
glm::dvec3 posLater = glm::dvec3(0.0);
double ltLater;
double timeLater = *(coveredTimes.upper_bound(ephemerisTime));
double ltLater = 0.0;
const double timeLater = *(coveredTimes.upper_bound(ephemerisTime));
spkpos_c(
target.c_str(),
timeLater,
@@ -1322,8 +1337,8 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram
}
else {
// coverage both earlier and later, interpolate these transformations
double earlier = *std::prev((coveredTimes.lower_bound(time)));
double later = *(coveredTimes.upper_bound(time));
const double earlier = *std::prev((coveredTimes.lower_bound(time)));
const double later = *(coveredTimes.upper_bound(time));
glm::dmat3 earlierTransform = glm::dmat3(1.0);
pxform_c(
@@ -1515,8 +1530,8 @@ DELTET/DELTA_AT = ( 10, @1972-JAN-1
)";
std::filesystem::path path = std::filesystem::temp_directory_path();
std::filesystem::path file = path / "naif0012.tls";
const std::filesystem::path path = std::filesystem::temp_directory_path();
const std::filesystem::path file = path / "naif0012.tls";
{
std::ofstream f(file);
f << Naif00012tlsSource;
+3 -5
View File
@@ -34,12 +34,10 @@ SyncBuffer::SyncBuffer(size_t n)
_dataStream.resize(_n);
}
SyncBuffer::~SyncBuffer() {}
void SyncBuffer::encode(const std::string& s) {
ZoneScoped;
int32_t anticpatedBufferSize = static_cast<int32_t>(
const int32_t anticpatedBufferSize = static_cast<int32_t>(
_encodeOffset + (sizeof(char) * s.size()) + sizeof(int32_t)
);
if (anticpatedBufferSize >= static_cast<int32_t>(_n)) {
@@ -60,8 +58,8 @@ void SyncBuffer::encode(const std::string& s) {
std::string SyncBuffer::decode() {
ZoneScoped;
int32_t length;
memcpy(
int32_t length = 0;
std::memcpy(
reinterpret_cast<char*>(&length),
_dataStream.data() + _decodeOffset,
sizeof(int32_t)
+6 -6
View File
@@ -42,19 +42,19 @@ namespace {
namespace openspace {
std::vector<std::unique_ptr<Task>> TaskLoader::tasksFromDictionary(
const ghoul::Dictionary& tasksDictionary)
const ghoul::Dictionary& dictionary)
{
std::vector<std::unique_ptr<Task>> tasks;
for (std::string_view key : tasksDictionary.keys()) {
if (tasksDictionary.hasValue<std::string>(key)) {
std::string taskName = tasksDictionary.value<std::string>(key);
for (const std::string_view key : dictionary.keys()) {
if (dictionary.hasValue<std::string>(key)) {
const std::string taskName = dictionary.value<std::string>(key);
const std::string path = taskName + ".task";
std::vector<std::unique_ptr<Task>> subTasks = tasksFromFile(path);
std::move(subTasks.begin(), subTasks.end(), std::back_inserter(tasks));
}
else if (tasksDictionary.hasValue<ghoul::Dictionary>(key)) {
ghoul::Dictionary subTask = tasksDictionary.value<ghoul::Dictionary>(key);
else if (dictionary.hasValue<ghoul::Dictionary>(key)) {
const ghoul::Dictionary subTask = dictionary.value<ghoul::Dictionary>(key);
const std::string& taskType = subTask.value<std::string>("Type");
std::unique_ptr<Task> task = Task::createFromDictionary(subTask);
if (!task) {
+9 -13
View File
@@ -31,9 +31,8 @@ Worker::Worker(ThreadPool& p) : pool(p) {}
void Worker::operator()() {
std::function<void()> task;
while (true) {
// acquire lock
{
std::unique_lock<std::mutex> lock(pool.queue_mutex);
std::unique_lock lock(pool.queue_mutex);
// look for a work item
while (!pool.stop && pool.tasks.empty()) {
@@ -48,8 +47,7 @@ void Worker::operator()() {
// get the task from the queue
task = pool.tasks.front();
pool.tasks.pop_front();
} // release lock
}
// execute the task
task();
@@ -58,7 +56,7 @@ void Worker::operator()() {
ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; i++) {
workers.emplace_back(std::thread(Worker(*this)));
workers.emplace_back(Worker(*this));
}
}
@@ -68,7 +66,7 @@ ThreadPool::ThreadPool(const ThreadPool& toCopy) : ThreadPool(toCopy.workers.siz
ThreadPool::~ThreadPool() {
// stop all threads
{
std::unique_lock<std::mutex> lock(queue_mutex);
const std::unique_lock lock(queue_mutex);
stop = true;
}
condition.notify_all();
@@ -81,22 +79,20 @@ ThreadPool::~ThreadPool() {
// add new work item to the pool
void ThreadPool::enqueue(std::function<void()> f) {
{ // acquire lock
std::unique_lock<std::mutex> lock(queue_mutex);
{
const std::unique_lock lock(queue_mutex);
// add the task
tasks.push_back(std::move(f));
} // release lock
}
// wake up one thread
condition.notify_one();
}
void ThreadPool::clearTasks() {
{ // acquire lock
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.clear();
} // release lock
const std::unique_lock lock(queue_mutex);
tasks.clear();
}
bool ThreadPool::hasOutstandingTasks() const {
+11 -13
View File
@@ -61,10 +61,9 @@ double Time::convertTime(const char* time) {
}
std::string Time::currentWallTime() {
std::time_t t = std::time(nullptr);
const std::time_t t = std::time(nullptr);
std::tm* utcTime = std::gmtime(&t);
std::string time = fmt::format(
const std::string time = fmt::format(
"{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}",
utcTime->tm_year + 1900, utcTime->tm_mon + 1, utcTime->tm_mday,
utcTime->tm_hour, utcTime->tm_min, utcTime->tm_sec
@@ -79,20 +78,19 @@ Time::Time(const std::string& time) :
{}
Time Time::now() {
Time now;
time_t secondsSince1970;
secondsSince1970 = time(nullptr);
const time_t secondsSince1970 = time(nullptr);
const time_t secondsInAYear = static_cast<time_t>(365.25 * 24 * 60 * 60);
const double secondsSince2000 = static_cast<double>(
secondsSince1970 - 30 * secondsInAYear
);
Time now;
now.setTime(secondsSince2000);
return now;
}
void Time::setTime(double value) {
_time = value;
void Time::setTime(double j2000Seconds) {
_time = j2000Seconds;
}
double Time::j2000Seconds() const {
@@ -144,8 +142,8 @@ void Time::ISO8601(char* buffer) const {
SpiceManager::ref().dateFromEphemerisTime(_time, buffer, S, Format);
}
std::string Time::advancedTime(std::string base, std::string change) {
double j2000Seconds = Time::convertTime(base);
std::string Time::advancedTime(const std::string& base, std::string change) {
const double j2000Seconds = Time::convertTime(base);
double dt = 0.0;
if (change.empty()) {
@@ -168,8 +166,8 @@ std::string Time::advancedTime(std::string base, std::string change) {
);
try {
double value = std::stod(std::string(change.begin(), it));
std::string uName = std::string(it, change.end());
const double value = std::stod(std::string(change.begin(), it));
const std::string_view uName = std::string_view(it, change.end());
TimeUnit unit = TimeUnit::Second;
if (uName == "s") { unit = TimeUnit::Second; }
@@ -193,7 +191,7 @@ std::string Time::advancedTime(std::string base, std::string change) {
));
}
std::string_view ret = Time(j2000Seconds + dt).ISO8601();
const std::string_view ret = Time(j2000Seconds + dt).ISO8601();
return std::string(ret);
}
+8 -9
View File
@@ -78,9 +78,8 @@ namespace {
namespace openspace {
std::pair<double, std::string_view> simplifyTime(double seconds, bool forceSingularForm) {
std::pair<double, TimeUnit> p = extractUnit(seconds);
bool pluralForm = (p.first != 1.0 && !forceSingularForm);
const std::pair<double, TimeUnit> p = extractUnit(seconds);
const bool pluralForm = (p.first != 1.0 && !forceSingularForm);
return { p.first, nameForTimeUnit(p.second, pluralForm) };
}
@@ -92,21 +91,21 @@ std::vector<std::pair<double, std::string_view>> splitTime(double seconds,
double secondsVal = std::abs(seconds);
do {
std::pair<double, TimeUnit> p = extractUnit(secondsVal);
const std::pair<double, TimeUnit> p = extractUnit(secondsVal);
if (p.second == TimeUnit::Nanosecond) {
// We have reached the lowest supported time unit
bool pluralForm = (p.first != 1.0 && !forceSingularForm);
res.push_back({ p.first, nameForTimeUnit(p.second, pluralForm) });
const bool pluralForm = (p.first != 1.0 && !forceSingularForm);
res.emplace_back(p.first, nameForTimeUnit(p.second, pluralForm));
break;
}
double pt = std::floor(p.first);
const double pt = std::floor(p.first);
// Add the unit the list
bool pluralForm = (p.first != 1.0 && !forceSingularForm);
res.push_back({ pt, nameForTimeUnit(p.second, pluralForm) });
const bool pluralForm = (p.first != 1.0 && !forceSingularForm);
res.emplace_back(pt, nameForTimeUnit(p.second, pluralForm));
// Adjust the remaining time
secondsVal -= convertTime(pt, p.second, TimeUnit::Second);
+5
View File
@@ -26,6 +26,11 @@
namespace openspace {
KeyframeBase::KeyframeBase(size_t id_, double timestamp_)
: id(id_)
, timestamp(timestamp_)
{}
bool compareKeyframeTimes(const KeyframeBase& a, const KeyframeBase& b) {
return a.timestamp < b.timestamp;
}
+43 -40
View File
@@ -81,8 +81,6 @@ namespace {
namespace openspace {
using datamessagestructures::TimeKeyframe;
TimeManager::TimeManager()
: properties::PropertyOwner({ "TimeManager", "Time Manager" })
, _defaultTimeInterpolationDuration(DefaultTimeInterpolationDurationInfo,
@@ -118,7 +116,7 @@ TimeManager::TimeManager()
void TimeManager::interpolateTime(double targetTime, double durationSeconds) {
ghoul_precondition(durationSeconds > 0.f, "durationSeconds must be positive");
OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
if (m == OpenSpaceEngine::Mode::CameraPath) {
LERROR("Cannot change simulation time during camera path");
return;
@@ -240,7 +238,7 @@ TimeKeyframeData TimeManager::interpolate(double applicationTime) {
else if (hasPastKeyframes) {
// Extrapolate based on last past keyframe
const double deltaApplicationTime = applicationTime - lastPastKeyframe->timestamp;
Time predictedTime(
const Time predictedTime = Time(
lastPastKeyframe->data.time.j2000Seconds() +
deltaApplicationTime *
(lastPastKeyframe->data.pause ? 0.0 : lastPastKeyframe->data.delta)
@@ -259,7 +257,7 @@ TimeKeyframeData TimeManager::interpolate(double applicationTime) {
void TimeManager::progressTime(double dt) {
ZoneScoped;
OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
if (m == OpenSpaceEngine::Mode::CameraPath) {
// We don't want to progress time when a camera path is playing, so return
return;
@@ -298,7 +296,7 @@ void TimeManager::progressTime(double dt) {
const double now = currentApplicationTimeForInterpolation();
const std::deque<Keyframe<TimeKeyframeData>>& keyframes = _timeline.keyframes();
std::function<bool(const KeyframeBase&, double)> comparisonFunc =
const std::function<bool(const KeyframeBase&, double)> comparisonFunc =
(isPlayingBackSessionRecording()) ?
&compareKeyframeTimeWithTime_playbackWithFrames : &compareKeyframeTimeWithTime;
@@ -323,7 +321,7 @@ void TimeManager::progressTime(double dt) {
if (hasFutureKeyframes && hasPastKeyframes && !firstFutureKeyframe->data.jump) {
// If keyframes exist before and after this frame,
// interpolate between those.
TimeKeyframeData interpolated = interpolate(
const TimeKeyframeData interpolated = interpolate(
*lastPastKeyframe,
*firstFutureKeyframe,
now
@@ -409,7 +407,7 @@ void TimeManager::addKeyframe(double timestamp, TimeKeyframeData time) {
}
void TimeManager::removeKeyframesAfter(double timestamp, bool inclusive) {
size_t nKeyframes = _timeline.nKeyframes();
const size_t nKeyframes = _timeline.nKeyframes();
_timeline.removeKeyframesAfter(timestamp, inclusive);
if (nKeyframes != _timeline.nKeyframes()) {
_timelineChanged = true;
@@ -417,7 +415,7 @@ void TimeManager::removeKeyframesAfter(double timestamp, bool inclusive) {
}
void TimeManager::removeKeyframesBefore(double timestamp, bool inclusive) {
size_t nKeyframes = _timeline.nKeyframes();
const size_t nKeyframes = _timeline.nKeyframes();
_timeline.removeKeyframesBefore(timestamp, inclusive);
if (nKeyframes != _timeline.nKeyframes()) {
_timelineChanged = true;
@@ -425,7 +423,7 @@ void TimeManager::removeKeyframesBefore(double timestamp, bool inclusive) {
}
void TimeManager::clearKeyframes() {
size_t nKeyframes = _timeline.nKeyframes();
const size_t nKeyframes = _timeline.nKeyframes();
_timeline.clearKeyframes();
if (nKeyframes != _timeline.nKeyframes()) {
_timelineChanged = true;
@@ -433,7 +431,7 @@ void TimeManager::clearKeyframes() {
}
void TimeManager::setTimeNextFrame(Time t) {
OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode();
if (m == OpenSpaceEngine::Mode::CameraPath) {
LERROR("Cannot change simulation time during camera path");
return;
@@ -455,7 +453,7 @@ void TimeManager::setDeltaTimeSteps(std::vector<double> deltaTimes) {
deltaTimes.begin(),
deltaTimes.end(),
std::back_inserter(negatives),
std::negate<double>()
std::negate<>()
);
deltaTimes.reserve(2 * deltaTimes.size());
@@ -535,7 +533,7 @@ void TimeManager::addDeltaTimesKeybindings() {
modifier = KeyModifier::Control;
}
KeyModifier negativeModifier = modifier | KeyModifier::Alt;
const KeyModifier negativeModifier = modifier | KeyModifier::Alt;
addDeltaTimeKeybind(key, modifier, deltaTimeStep);
addDeltaTimeKeybind(key, negativeModifier, -deltaTimeStep);
@@ -556,7 +554,7 @@ void TimeManager::addDeltaTimesKeybindings() {
void TimeManager::clearDeltaTimesKeybindings() {
// Iterate over all of the registered actions with the common prefix that we created
// in the addDeltaTimesKeybindings function
std::vector<interaction::Action> actions = global::actionManager->actions();
const std::vector<interaction::Action> actions = global::actionManager->actions();
for (const interaction::Action& action : actions) {
if (action.identifier.starts_with(DeltaTimeActionPrefix)) {
global::actionManager->removeAction(action.identifier);
@@ -603,14 +601,14 @@ std::vector<Syncable*> TimeManager::syncables() {
}
TimeManager::CallbackHandle TimeManager::addTimeChangeCallback(TimeChangeCallback cb) {
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_timeChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_deltaTimeChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
@@ -618,21 +616,21 @@ TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCa
TimeManager::CallbackHandle
TimeManager::addDeltaTimeStepsChangeCallback(TimeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_deltaTimeStepsChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
TimeManager::CallbackHandle TimeManager::addTimeJumpCallback(TimeChangeCallback cb) {
CallbackHandle handle = _nextCallbackHandle++;
const CallbackHandle handle = _nextCallbackHandle++;
_timeJumpCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
TimeManager::CallbackHandle TimeManager::addTimelineChangeCallback(TimeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
_timelineChangeCallbacks.push_back({ handle, std::move(cb) });
const CallbackHandle handle = _nextCallbackHandle++;
_timelineChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
@@ -766,17 +764,17 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation
return;
}
Time newTime(
const Time newTime = Time(
time().j2000Seconds() + (_deltaTime + newDeltaTime) * 0.5 * interpolationDuration
);
TimeKeyframeData currentKeyframe = {
const TimeKeyframeData currentKeyframe = {
.time = time(),
.delta = _deltaTime,
.pause = false,
.jump = false
};
TimeKeyframeData futureKeyframe = {
const TimeKeyframeData futureKeyframe = {
.time = newTime,
.delta = newDeltaTime,
.pause = false,
@@ -785,7 +783,7 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation
_targetDeltaTime = newDeltaTime;
double now = isPlayingBackSessionRecording() ?
const double now = isPlayingBackSessionRecording() ?
previousApplicationTimeForInterpolation() :
currentApplicationTimeForInterpolation();
@@ -797,7 +795,8 @@ std::optional<double> TimeManager::nextDeltaTimeStep() {
if (!hasNextDeltaTimeStep()) {
return std::nullopt;
}
std::vector<double>::iterator nextStepIterator = std::upper_bound(
const std::vector<double>::iterator nextStepIterator = std::upper_bound(
_deltaTimeSteps.begin(),
_deltaTimeSteps.end(),
_targetDeltaTime
@@ -814,7 +813,7 @@ std::optional<double> TimeManager::previousDeltaTimeStep() {
if (!hasPreviousDeltaTimeStep()) {
return std::nullopt;
}
std::vector<double>::iterator lowerBoundIterator = std::lower_bound(
const std::vector<double>::iterator lowerBoundIterator = std::lower_bound(
_deltaTimeSteps.begin(),
_deltaTimeSteps.end(),
_targetDeltaTime
@@ -824,20 +823,22 @@ std::optional<double> TimeManager::previousDeltaTimeStep() {
return std::nullopt; // should not get here
}
std::vector<double>::iterator prevStepIterator = lowerBoundIterator - 1;
const std::vector<double>::iterator prevStepIterator = lowerBoundIterator - 1;
return *prevStepIterator;
}
bool TimeManager::hasNextDeltaTimeStep() const {
if (_deltaTimeSteps.empty())
if (_deltaTimeSteps.empty()) {
return false;
}
return _targetDeltaTime < _deltaTimeSteps.back();
}
bool TimeManager::hasPreviousDeltaTimeStep() const {
if (_deltaTimeSteps.empty())
if (_deltaTimeSteps.empty()) {
return false;
}
return _targetDeltaTime > _deltaTimeSteps.front();
}
@@ -851,18 +852,20 @@ void TimeManager::setPreviousDeltaTimeStep() {
}
void TimeManager::interpolateNextDeltaTimeStep(double durationSeconds) {
if (!hasNextDeltaTimeStep())
if (!hasNextDeltaTimeStep()) {
return;
}
double nextDeltaTime = nextDeltaTimeStep().value();
const double nextDeltaTime = nextDeltaTimeStep().value();
interpolateDeltaTime(nextDeltaTime, durationSeconds);
}
void TimeManager::interpolatePreviousDeltaTimeStep(double durationSeconds) {
if (!hasPreviousDeltaTimeStep())
if (!hasPreviousDeltaTimeStep()) {
return;
}
double previousDeltaTime = previousDeltaTimeStep().value();
const double previousDeltaTime = previousDeltaTimeStep().value();
interpolateDeltaTime(previousDeltaTime, durationSeconds);
}
@@ -875,24 +878,24 @@ void TimeManager::interpolatePause(bool pause, double interpolationDuration) {
return;
}
OpenSpaceEngine::Mode engineMode = global::openSpaceEngine->currentMode();
const OpenSpaceEngine::Mode engineMode = global::openSpaceEngine->currentMode();
if (!pause && engineMode == OpenSpaceEngine::Mode::CameraPath) {
LERROR("Cannot unpause simulation time during camera path");
return;
}
double targetDelta = pause ? 0.0 : _targetDeltaTime;
Time newTime(
const double targetDelta = pause ? 0.0 : _targetDeltaTime;
const Time newTime = Time(
time().j2000Seconds() + (_deltaTime + targetDelta) * 0.5 * interpolationDuration
);
TimeKeyframeData currentKeyframe = {
const TimeKeyframeData currentKeyframe = {
.time = time(),
.delta = _deltaTime,
.pause = false,
.jump = false
};
TimeKeyframeData futureKeyframe = {
const TimeKeyframeData futureKeyframe = {
.time = newTime,
.delta = _targetDeltaTime,
.pause = pause,
@@ -900,7 +903,7 @@ void TimeManager::interpolatePause(bool pause, double interpolationDuration) {
};
_timePaused = pause;
double now = isPlayingBackSessionRecording() ?
const double now = isPlayingBackSessionRecording() ?
previousApplicationTimeForInterpolation() :
currentApplicationTimeForInterpolation();
@@ -942,7 +945,7 @@ void TimeManager::setTimeFromProfile(const Profile& p) {
switch (p.time->type) {
case Profile::Time::Type::Relative:
{
std::string t = Time::currentWallTime();
const std::string t = Time::currentWallTime();
std::variant<std::string, double> t2 =
Time::advancedTime(t, p.time->value);
ghoul_assert(std::holds_alternative<std::string>(t2), "Wrong type");
+2 -2
View File
@@ -39,12 +39,12 @@ TouchInput::TouchInput(size_t touchDeviceId_, size_t fingerId_, float x_, float
, timestamp(timestamp_)
{}
glm::vec2 TouchInput::screenCoordinates(glm::vec2 resolution) const {
glm::vec2 TouchInput::screenCoordinates(const glm::vec2& resolution) const {
return { std::floor(x * resolution.x + 0.5f), std::floor(y * resolution.y + 0.5f) };
}
glm::vec2 TouchInput::currentWindowCoordinates() const {
glm::vec2 res = global::windowDelegate->currentSubwindowSize();
const glm::vec2 res = global::windowDelegate->currentSubwindowSize();
return { std::floor(x * res.x + 0.5f), std::floor(y * res.y + 0.5f) };
}
+1 -1
View File
@@ -42,7 +42,7 @@ tstring temporaryString(std::string_view str) {
}
tstring temporaryString(const char str[]) {
size_t size = strlen(str);
const size_t size = strlen(str);
void* ptr = global::memoryManager->TemporaryMemory.do_allocate(size, 8);
std::strcpy(reinterpret_cast<char*>(ptr), str);
return tstring(reinterpret_cast<char*>(ptr), size);
+1 -1
View File
@@ -32,7 +32,7 @@ double shiftAndScale(double t, double start, double end) {
"Values must be 0.0 < start < end < 1.0"
);
double tScaled = t / (end - start) - start;
const double tScaled = t / (end - start) - start;
return std::max(0.0, std::min(tScaled, 1.0));
}
+8 -7
View File
@@ -79,16 +79,16 @@ void VersionChecker::cancel() {
if (_request->hasSucceeded()) {
_request->wait();
std::vector<char> data = _request->downloadedData();
std::string versionString(data.begin(), data.end());
const std::string versionString(data.begin(), data.end());
std::istringstream versionData(versionString);
std::string token;
std::getline(versionData, token, '.');
int major = std::atoi(token.c_str());
const int major = std::atoi(token.c_str());
std::getline(versionData, token, '.');
int minor = std::atoi(token.c_str());
const int minor = std::atoi(token.c_str());
std::getline(versionData, token, '.');
int patch = std::atoi(token.c_str());
const int patch = std::atoi(token.c_str());
_latestVersion = { major, minor, patch };
_request = nullptr;
@@ -125,10 +125,11 @@ void VersionChecker::cancel() {
_request->cancel();
_request->wait();
std::vector<char> data = _request->downloadedData();
std::string response(data.begin(), data.end());
const std::string response = std::string(data.begin(), data.end());
LWARNING(fmt::format(
"Failed to get latest OpenSpace version information from {}",
_request->url()
"Failed to get OpenSpace version information from {}. Response: {}",
_request->url(),
response
));
_request = nullptr;
return false;