Merge pull request #1282 from OpenSpace/issue/1174

Issue/1174 - step between delta time steps using GUI or keybindings
This commit is contained in:
Alexander Bock
2020-08-24 14:17:30 +02:00
committed by GitHub
14 changed files with 663 additions and 10 deletions
+33 -1
View File
@@ -109,7 +109,39 @@ openspace.setPropertyValueSingle("RenderEngine.ShowCamera", not isEnabled)]],
Documentation = "Toggles the rendering on master",
GuiPath = "/Rendering",
Local = true
}
},
{
Key = "Right",
Name = "Next Delta Time Step (Interpolate)",
Command = "openspace.time.interpolateNextDeltaTimeStep()",
Documentation = "Smoothly interpolates the simulation speed to the next delta time step, if one exists.",
GuiPath = "/Simulation Speed",
Local = true
},
{
Key = "Shift+Right",
Name = "Next Delta Time Step (Immediate)",
Command = "openspace.time.setNextDeltaTimeStep()",
Documentation = "Immediately set the simulation speed to the next delta time step, if one exists.",
GuiPath = "/Simulation Speed",
Local = true
},
{
Key = "Left",
Name = "Previous Delta Time Step (Interpolate)",
Command = "openspace.time.interpolatePreviousDeltaTimeStep()",
Documentation = "Smoothly interpolates the simulation speed to the previous delta time step, if one exists.",
GuiPath = "/Simulation Speed",
Local = true
},
{
Key = "Shift+Left",
Name = "Previous Delta Time Step (Immediate)",
Command = "openspace.time.setPreviousDeltaTimeStep()",
Documentation = "Immediately set the simulation speed to the previous delta time step, if one exists.",
GuiPath = "/Simulation Speed",
Local = true
},
}
local DeltaTimeKeys
+1
View File
@@ -151,6 +151,7 @@ private:
std::vector<Property> properties;
std::vector<Keybinding> keybindings;
std::optional<Time> time;
std::vector<double> deltaTimes;
std::optional<CameraType> camera;
std::vector<std::string> markNodes;
std::vector<std::string> additionalScripts;
+19
View File
@@ -29,6 +29,7 @@
#include <openspace/util/time.h>
#include <openspace/util/timeline.h>
#include <functional>
#include <optional>
#include <utility>
#include <vector>
@@ -68,6 +69,7 @@ public:
void setTimeNextFrame(Time t);
void setDeltaTime(double deltaTime);
void setPause(bool pause);
void setDeltaTimeSteps(const std::vector<double> deltaTimes);
/**
* Returns the delta time, unaffected by pause
@@ -80,6 +82,8 @@ public:
double deltaTime() const;
bool isPaused() const;
std::vector<double> deltaTimeSteps() const;
float defaultTimeInterpolationDuration() const;
float defaultDeltaTimeInterpolationDuration() const;
float defaultPauseInterpolationDuration() const;
@@ -90,6 +94,15 @@ public:
void interpolateDeltaTime(double targetDeltaTime, double durationSeconds);
void interpolatePause(bool pause, double durationSeconds);
std::optional<double> nextDeltaTimeStep();
std::optional<double> previousDeltaTimeStep();
bool hasNextDeltaTimeStep() const;
bool hasPreviousDeltaTimeStep() const;
void setNextDeltaTimeStep();
void setPreviousDeltaTimeStep();
void interpolateNextDeltaTimeStep(double durationSeconds);
void interpolatePreviousDeltaTimeStep(double durationSeconds);
void addKeyframe(double timestamp, TimeKeyframeData kf);
void removeKeyframesBefore(double timestamp, bool inclusive = false);
void removeKeyframesAfter(double timestamp, bool inclusive = false);
@@ -99,11 +112,13 @@ public:
CallbackHandle addTimeChangeCallback(TimeChangeCallback cb);
CallbackHandle addDeltaTimeChangeCallback(TimeChangeCallback cb);
CallbackHandle addDeltaTimeStepsChangeCallback(TimeChangeCallback cb);
CallbackHandle addTimeJumpCallback(TimeChangeCallback cb);
CallbackHandle addTimelineChangeCallback(TimeChangeCallback cb);
void removeTimeChangeCallback(CallbackHandle handle);
void removeDeltaTimeChangeCallback(CallbackHandle handle);
void removeDeltaTimeStepsChangeCallback(CallbackHandle handle);
void triggerPlaybackStart();
void removeTimeJumpCallback(CallbackHandle handle);
void removeTimelineChangeCallback(CallbackHandle handle);
@@ -126,6 +141,9 @@ private:
double _lastDeltaTime = 0.0;
double _lastTargetDeltaTime = 0.0;
std::vector<double> _deltaTimeSteps;
bool _deltaTimeStepsChanged = false;
properties::FloatProperty _defaultTimeInterpolationDuration;
properties::FloatProperty _defaultDeltaTimeInterpolationDuration;
properties::FloatProperty _defaultPauseInterpolationDuration;
@@ -142,6 +160,7 @@ private:
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _timeChangeCallbacks;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _deltaTimeChangeCallbacks;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _deltaTimeStepsChangeCallbacks;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _timeJumpCallbacks;
std::vector<std::pair<CallbackHandle, TimeChangeCallback>> _timelineChangeCallbacks;
+2
View File
@@ -33,6 +33,7 @@ set(HEADER_FILES
include/serverinterface.h
include/topics/authorizationtopic.h
include/topics/bouncetopic.h
include/topics/deltatimestepstopic.h
include/topics/documentationtopic.h
include/topics/flightcontrollertopic.h
include/topics/getpropertytopic.h
@@ -56,6 +57,7 @@ set(SOURCE_FILES
src/serverinterface.cpp
src/topics/authorizationtopic.cpp
src/topics/bouncetopic.cpp
src/topics/deltatimestepstopic.cpp
src/topics/documentationtopic.cpp
src/topics/flightcontrollertopic.cpp
src/topics/getpropertytopic.cpp
@@ -0,0 +1,57 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_SERVER___DELTA_TIME_STEPS_TOPIC___H__
#define __OPENSPACE_MODULE_SERVER___DELTA_TIME_STEPS_TOPIC___H__
#include <modules/server/include/topics/topic.h>
#include <optional>
namespace openspace {
class DeltaTimeStepsTopic : public Topic {
public:
DeltaTimeStepsTopic();
virtual ~DeltaTimeStepsTopic();
void handleJson(const nlohmann::json& json) override;
bool isDone() const override;
private:
const int UnsetOnChangeHandle = -1;
bool dataHasChanged();
void sendDeltaTimesData();
int _deltaTimeCallbackHandle = UnsetOnChangeHandle;
int _deltaTimesListCallbackHandle = UnsetOnChangeHandle;
bool _isDone = false;
std::optional<double> _lastNextDeltaTime = std::nullopt;
std::optional<double> _lastPrevDeltaTime = std::nullopt;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_SERVER___DELTA_TIME_STEPS_TOPIC___H__
+3
View File
@@ -26,6 +26,7 @@
#include <modules/server/include/topics/authorizationtopic.h>
#include <modules/server/include/topics/bouncetopic.h>
#include <modules/server/include/topics/deltatimestepstopic.h>
#include <modules/server/include/topics/documentationtopic.h>
#include <modules/server/include/topics/flightcontrollertopic.h>
#include <modules/server/include/topics/getpropertytopic.h>
@@ -56,6 +57,7 @@ namespace {
constexpr const char* VersionTopicKey = "version";
constexpr const char* AuthenticationTopicKey = "authorize";
constexpr const char* DeltaTimeStepsTopicKey = "deltatimesteps";
constexpr const char* DocumentationTopicKey = "documentation";
constexpr const char* GetPropertyTopicKey = "get";
constexpr const char* LuaScriptTopicKey = "luascript";
@@ -95,6 +97,7 @@ Connection::Connection(std::unique_ptr<ghoul::io::Socket> s,
);
_topicFactory.registerClass<DocumentationTopic>(DocumentationTopicKey);
_topicFactory.registerClass<DeltaTimeStepsTopic>(DeltaTimeStepsTopicKey);
_topicFactory.registerClass<GetPropertyTopic>(GetPropertyTopicKey);
_topicFactory.registerClass<LuaScriptTopic>(LuaScriptTopicKey);
_topicFactory.registerClass<SessionRecordingTopic>(SessionRecordingTopicKey);
@@ -0,0 +1,127 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include "modules/server/include/topics/deltatimestepstopic.h"
#include <modules/server/include/connection.h>
#include <openspace/engine/globals.h>
#include <openspace/properties/property.h>
#include <openspace/query/query.h>
#include <openspace/util/timemanager.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr const char* EventKey = "event";
constexpr const char* SubscribeEvent = "start_subscription";
constexpr const char* UnsubscribeEvent = "stop_subscription";
} // namespace
using nlohmann::json;
namespace openspace {
DeltaTimeStepsTopic::DeltaTimeStepsTopic() {}
DeltaTimeStepsTopic::~DeltaTimeStepsTopic() {
if (_deltaTimeCallbackHandle != UnsetOnChangeHandle) {
global::timeManager.removeDeltaTimeChangeCallback(
_deltaTimeCallbackHandle
);
}
if (_deltaTimesListCallbackHandle != UnsetOnChangeHandle) {
global::timeManager.removeDeltaTimeStepsChangeCallback(
_deltaTimesListCallbackHandle
);
}
}
bool DeltaTimeStepsTopic::isDone() const {
return _isDone;
}
bool DeltaTimeStepsTopic::dataHasChanged() {
std::optional<double> nextStep = global::timeManager.nextDeltaTimeStep();
std::optional<double> prevStep = global::timeManager.previousDeltaTimeStep();
return (nextStep != _lastNextDeltaTime || prevStep != _lastPrevDeltaTime);
}
void DeltaTimeStepsTopic::handleJson(const nlohmann::json& json) {
std::string event = json.at(EventKey).get<std::string>();
if (event == UnsubscribeEvent) {
_isDone = true;
return;
}
sendDeltaTimesData();
if (event != SubscribeEvent) {
_isDone = true;
return;
}
_deltaTimeCallbackHandle = global::timeManager.addDeltaTimeChangeCallback(
[this]() {
if (dataHasChanged()) {
sendDeltaTimesData();
}
}
);
_deltaTimesListCallbackHandle = global::timeManager.addDeltaTimeStepsChangeCallback(
[this]() {
if (dataHasChanged()) {
sendDeltaTimesData();
}
}
);
}
void DeltaTimeStepsTopic::sendDeltaTimesData() {
std::optional<double> nextStep = global::timeManager.nextDeltaTimeStep();
std::optional<double> prevStep = global::timeManager.previousDeltaTimeStep();
bool hasNext = nextStep.has_value();
bool hasPrev = prevStep.has_value();
json deltaTimesListJson = {
{ "hasNextStep", hasNext },
{ "hasPrevStep", hasPrev }
};
if (hasNext) {
deltaTimesListJson["nextStep"] = nextStep.value();
}
if (hasPrev) {
deltaTimesListJson["prevStep"] = prevStep.value();
}
_connection->sendJson(wrappedPayload(deltaTimesListJson));
_lastNextDeltaTime = nextStep;
_lastPrevDeltaTime = prevStep;
}
} // namespace openspace
+41
View File
@@ -45,6 +45,7 @@ namespace {
constexpr const char* headerProperty = "#Property";
constexpr const char* headerKeybinding = "#Keybinding";
constexpr const char* headerTime = "#Time";
constexpr const char* headerDeltaTimes = "#DeltaTimes";
constexpr const char* headerCamera = "#Camera";
constexpr const char* headerMarkNodes = "#MarkNodes";
constexpr const char* headerAdditionalScripts = "#AdditionalScripts";
@@ -91,6 +92,7 @@ namespace {
Property,
Keybinding,
Time,
DeltaTimes,
Camera,
MarkNodes,
AdditionalScripts
@@ -104,6 +106,7 @@ namespace {
if (line == headerProperty) { return Section::Property; }
if (line == headerKeybinding) { return Section::Keybinding; }
if (line == headerTime) { return Section::Time; }
if (line == headerDeltaTimes) { return Section::DeltaTimes; }
if (line == headerCamera) { return Section::Camera; }
if (line == headerMarkNodes) { return Section::MarkNodes; }
if (line == headerAdditionalScripts) { return Section::AdditionalScripts; }
@@ -318,6 +321,18 @@ namespace {
return time;
}
[[ nodiscard ]] double parseDeltaTime(const std::string& line, int lineNumber) {
try {
return std::stod(line);
}
catch (const std::invalid_argument&) {
throw ProfileParsingError(
lineNumber,
fmt::format("Expected a number for delta time entry, got '{}'", line)
);
}
}
[[ nodiscard ]] Profile::CameraType parseCamera(const std::string& line, int lineNumber) {
std::vector<std::string> fields = ghoul::tokenizeString(line, '\t');
Profile::CameraType camera = [&](const std::string& type) ->
@@ -480,6 +495,10 @@ void Profile::saveCurrentSettingsToProfile(const properties::PropertyOwner& root
t.type = Time::Type::Absolute;
time = std::move(t);
// Delta times
std::vector<double> dts = global::timeManager.deltaTimeSteps();
deltaTimes = std::move(dts);
// Camera
CameraNavState c;
@@ -648,6 +667,13 @@ std::string Profile::serialize() const {
}
}
if (!deltaTimes.empty()) {
output += fmt::format("\n{}\n", headerDeltaTimes);
for (const double d : deltaTimes) {
output += fmt::format("{}\n", d);
}
}
if (camera.has_value()) {
output += fmt::format("\n{}\n", headerCamera);
output += std::visit(
@@ -870,6 +896,12 @@ Profile::Profile(const std::vector<std::string>& content) {
time = parseTime(line, lineNum);
foundTime = true;
break;
case Section::DeltaTimes:
{
const double d = parseDeltaTime(line, lineNum);
deltaTimes.push_back(d);
break;
}
case Section::Camera:
if (foundCamera) {
throw ProfileParsingError(
@@ -981,6 +1013,15 @@ std::string Profile::convertToScene() const {
throw ghoul::MissingCaseException();
}
// Delta Times
{
std::string times;
for (const double d : deltaTimes) {
times += fmt::format("{} ,", d);
}
output += fmt::format("openspace.time.setDeltaTimeSteps({{ {} }});\n", times);
}
// Mark Nodes
{
std::string nodes;
+62 -9
View File
@@ -126,6 +126,16 @@ scripting::LuaLibrary Time::luaLibrary() {
"Sets the amount of simulation time that happens "
"in one second of real time"
},
{
"setDeltaTimeSteps",
&luascriptfunctions::time_setDeltaTimeSteps,
{},
"List of numbers",
"Sets the list of discrete delta time steps for the simulation speed "
"that can be quickly jumped between. The list will be sorted to be in "
"increasing order. A negative verison of each specified time step will "
"be added per default as well."
},
{
"deltaTime",
&luascriptfunctions::time_deltaTime,
@@ -166,31 +176,74 @@ scripting::LuaLibrary Time::luaLibrary() {
&luascriptfunctions::time_interpolateTimeRelative,
{},
"number [, number]",
"Increments the current simulation time "
"by the specified number of seconds."
"Increments the current simulation time by the specified number of "
"seconds. If a second input value is given, the interpolation is done "
"over the specified number of seconds."
},
{
"interpolateDeltaTime",
&luascriptfunctions::time_interpolateDeltaTime,
{},
"number",
"Sets the amount of simulation time that happens "
"in one second of real time"
"number [, number]",
"Sets the amount of simulation time that happens in one second of real "
"time. If a second input value is given, the interpolation is done "
"over the specified number of seconds."
},
{
"setNextDeltaTimeStep",
&luascriptfunctions::time_setNextDeltaTimeStep,
{},
"",
"Immediately set the simulation speed to the first delta time step in "
"the list that is larger than the current choice of simulation speed, "
"if any."
},
{
"setPreviousDeltaTimeStep",
&luascriptfunctions::time_setPreviousDeltaTimeStep,
{},
"",
"Immediately set the simulation speed to the first delta time step in "
"the list that is smaller than the current choice of simulation speed. "
"if any."
},
{
"interpolateNextDeltaTimeStep",
&luascriptfunctions::time_interpolateNextDeltaTimeStep,
{},
"[number]",
"Interpolate the simulation speed to the first delta time step in the "
"list that is larger than the current simulation speed, if any. If an "
"input value is given, the interpolation is done over the specified "
"number of seconds."
},
{
"interpolatePreviousDeltaTimeStep",
&luascriptfunctions::time_interpolatePreviousDeltaTimeStep,
{},
"[number]",
"Interpolate the simulation speed to the first delta time step in the "
"list that is smaller than the current simulation speed, if any. If an "
"input value is given, the interpolation is done over the specified "
"number of seconds."
},
{
"interpolatePause",
&luascriptfunctions::time_interpolatePause,
{},
"bool",
"Pauses the simulation time or restores the delta time"
"bool [, number]",
"Pauses the simulation time or restores the delta time. If a second "
"input value is given, the interpolation is done over the specified "
"number of seconds."
},
{
"interpolateTogglePause",
&luascriptfunctions::time_interpolateTogglePause,
{},
"",
"[number]",
"Toggles the pause function, i.e. temporarily setting the delta time to 0"
" and restoring it afterwards"
" and restoring it afterwards. If an input value is given, the "
"interpolation is done over the specified number of seconds."
},
{
"currentTime",
+150
View File
@@ -69,6 +69,156 @@ int time_setDeltaTime(lua_State* L) {
return 0;
}
/**
* \ingroup LuaScripts
* interpolateNextDeltaTimeStep(list of numbers):
* Sets the list of discrete delta time steps for the simulation speed.
*/
int time_setDeltaTimeSteps(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::time_setDeltaTimeSteps");
ghoul::Dictionary dict;
ghoul::lua::luaDictionaryFromState(L, dict);
const size_t nItems = dict.size();
std::vector<double> inputDeltaTimes;
inputDeltaTimes.reserve(nItems);
for (size_t i = 1; i <= nItems; ++i) {
std::string key = std::to_string(i);
if (dict.hasKeyAndValue<double>(key)) {
const double time = dict.value<double>(key);
inputDeltaTimes.push_back(time);
}
else {
const char* msg = lua_pushfstring(L,
"Error setting delta times. Expected list of numbers.");
return ghoul::lua::luaError(L, fmt::format("bad argument ({})", msg));
}
}
lua_pop(L, 1);
global::timeManager.setDeltaTimeSteps(inputDeltaTimes);
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
/**
* \ingroup LuaScripts
* setNextDeltaTimeStep():
* Immediately set the simulation speed to the first delta time step in the list that is
* larger than the current choice of simulation speed, if any.
*/
int time_setNextDeltaTimeStep(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::time_setNextDeltaTimeStep");
global::timeManager.setNextDeltaTimeStep();
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
/**
* \ingroup LuaScripts
* setPreviousDeltaTimeStep():
* Immediately set the simulation speed to the first delta time step in the list that is
* smaller than the current choice of simulation speed, if any.
*/
int time_setPreviousDeltaTimeStep(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 0, "lua::time_setPreviousDeltaTimeStep");
global::timeManager.setPreviousDeltaTimeStep();
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
/**
* \ingroup LuaScripts
* interpolateNextDeltaTimeStep([interpolationDuration]):
* Interpolate the simulation speed to the next delta time step in the list. If an input
* value is given, the interpolation is done over the specified number of seconds.
* If interpolationDuration is not provided, the interpolation time will be based on the
* `defaultDeltaTimeInterpolationDuration` property of the TimeManager.
*/
int time_interpolateNextDeltaTimeStep(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(
L,
{ 0, 1 },
"lua::time_interpolateNextDeltaTimeStep"
);
double interpolationDuration =
global::timeManager.defaultDeltaTimeInterpolationDuration();
const int nArguments = lua_gettop(L);
if (nArguments == 1) {
const bool durationIsNumber = (lua_isnumber(L, 1) != 0);
if (!durationIsNumber) {
lua_settop(L, 0);
const char* msg = lua_pushfstring(
L,
"%s expected, got %s",
lua_typename(L, LUA_TNUMBER),
luaL_typename(L, -1)
);
return luaL_error(L, "bad argument #%d (%s)", 1, msg);
}
interpolationDuration = lua_tonumber(L, 1);
}
global::timeManager.interpolateNextDeltaTimeStep(interpolationDuration);
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
/**
* \ingroup LuaScripts
* interpolatePreviousDeltaTimeStep([interpolationDuration]):
* Interpolate the simulation speed to the previous delta time step in the list. If an
* input value is given, the interpolation is done over the specified number of seconds.
* If interpolationDuration is not provided, the interpolation time will be based on the
* `defaultDeltaTimeInterpolationDuration` property of the TimeManager.
*/
int time_interpolatePreviousDeltaTimeStep(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(
L,
{ 0, 1 },
"lua::time_interpolatePreviousDeltaTimeStep"
);
double interpolationDuration =
global::timeManager.defaultDeltaTimeInterpolationDuration();
const int nArguments = lua_gettop(L);
if (nArguments == 1) {
const bool durationIsNumber = (lua_isnumber(L, 1) != 0);
if (!durationIsNumber) {
lua_settop(L, 0);
const char* msg = lua_pushfstring(
L,
"%s expected, got %s",
lua_typename(L, LUA_TNUMBER),
luaL_typename(L, -1)
);
return luaL_error(L, "bad argument #%d (%s)", 1, msg);
}
interpolationDuration = lua_tonumber(L, 1);
}
global::timeManager.interpolatePreviousDeltaTimeStep(interpolationDuration);
lua_settop(L, 0);
ghoul_assert(lua_gettop(L) == 0, "Incorrect number of items left on stack");
return 0;
}
/**
* \ingroup LuaScripts
* time_interpolateDeltaTime(number [, number]):
+130
View File
@@ -155,6 +155,13 @@ void TimeManager::preSynchronization(double dt) {
it.second();
}
}
if (_deltaTimeStepsChanged) {
using K = const CallbackHandle;
using V = TimeChangeCallback;
for (const std::pair<K, V>& it : _deltaTimeStepsChangeCallbacks) {
it.second();
}
}
if (_timelineChanged) {
using K = const CallbackHandle;
using V = TimeChangeCallback;
@@ -167,6 +174,7 @@ void TimeManager::preSynchronization(double dt) {
_lastDeltaTime = _deltaTime;
_lastTargetDeltaTime = _targetDeltaTime;
_lastTimePaused = _timePaused;
_deltaTimeStepsChanged = false;
_timelineChanged = false;
}
@@ -380,6 +388,26 @@ void TimeManager::setDeltaTime(double deltaTime) {
interpolateDeltaTime(deltaTime, 0.0);
}
void TimeManager::setDeltaTimeSteps(std::vector<double> deltaTimes) {
std::vector<double> negatives;
negatives.reserve(deltaTimes.size());
std::transform(
deltaTimes.begin(),
deltaTimes.end(),
std::back_inserter(negatives),
[](double d) { return -d; }
);
deltaTimes.reserve(2 * deltaTimes.size());
deltaTimes.insert(deltaTimes.end(), negatives.begin(), negatives.end());
std::sort(deltaTimes.begin(), deltaTimes.end());
deltaTimes.erase(std::unique(deltaTimes.begin(), deltaTimes.end()), deltaTimes.end());
_deltaTimeSteps = std::move(deltaTimes);
_deltaTimeStepsChanged = true;
}
size_t TimeManager::nKeyframes() const {
return _timeline.nKeyframes();
}
@@ -413,6 +441,14 @@ TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCa
return handle;
}
TimeManager::CallbackHandle
TimeManager::addDeltaTimeStepsChangeCallback(TimeChangeCallback cb)
{
CallbackHandle handle = _nextCallbackHandle++;
_deltaTimeStepsChangeCallbacks.emplace_back(handle, std::move(cb));
return handle;
}
TimeManager::CallbackHandle TimeManager::addTimeJumpCallback(TimeChangeCallback cb) {
CallbackHandle handle = _nextCallbackHandle++;
_timeJumpCallbacks.emplace_back(handle, std::move(cb));
@@ -460,6 +496,23 @@ void TimeManager::removeDeltaTimeChangeCallback(CallbackHandle handle) {
_deltaTimeChangeCallbacks.erase(it);
}
void TimeManager::removeDeltaTimeStepsChangeCallback(CallbackHandle handle) {
const auto it = std::find_if(
_deltaTimeStepsChangeCallbacks.begin(),
_deltaTimeStepsChangeCallbacks.end(),
[handle](const std::pair<CallbackHandle, std::function<void()>>& cb) {
return cb.first == handle;
}
);
ghoul_assert(
it != _deltaTimeStepsChangeCallbacks.end(),
"handle must be a valid callback handle"
);
_deltaTimeStepsChangeCallbacks.erase(it);
}
void TimeManager::triggerPlaybackStart() {
_playbackModeEnabled = true;
}
@@ -526,6 +579,10 @@ double TimeManager::targetDeltaTime() const {
return _targetDeltaTime;
}
std::vector<double> TimeManager::deltaTimeSteps() const {
return _deltaTimeSteps;
}
void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolationDuration)
{
if (newDeltaTime == _targetDeltaTime) {
@@ -553,6 +610,79 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation
addKeyframe(now + interpolationDuration, futureKeyframe);
}
std::optional<double> TimeManager::nextDeltaTimeStep() {
if (!hasNextDeltaTimeStep()) {
return std::nullopt;
}
std::vector<double>::iterator nextStepIterator = std::upper_bound(
_deltaTimeSteps.begin(),
_deltaTimeSteps.end(),
_targetDeltaTime
);
if (nextStepIterator == _deltaTimeSteps.end()) {
return std::nullopt; // should not get here
}
return *nextStepIterator;
}
std::optional<double> TimeManager::previousDeltaTimeStep() {
if (!hasPreviousDeltaTimeStep()) {
return std::nullopt;
}
std::vector<double>::iterator lowerBoundIterator = std::lower_bound(
_deltaTimeSteps.begin(),
_deltaTimeSteps.end(),
_targetDeltaTime
);
if (lowerBoundIterator == _deltaTimeSteps.begin()) {
return std::nullopt; // should not get here
}
std::vector<double>::iterator prevStepIterator = lowerBoundIterator - 1;
return *prevStepIterator;
}
bool TimeManager::hasNextDeltaTimeStep() const {
if (_deltaTimeSteps.empty())
return false;
return _targetDeltaTime < _deltaTimeSteps.back();
}
bool TimeManager::hasPreviousDeltaTimeStep() const {
if (_deltaTimeSteps.empty())
return false;
return _targetDeltaTime > _deltaTimeSteps.front();
}
void TimeManager::setNextDeltaTimeStep() {
interpolateNextDeltaTimeStep(0);
}
void TimeManager::setPreviousDeltaTimeStep() {
interpolatePreviousDeltaTimeStep(0);
}
void TimeManager::interpolateNextDeltaTimeStep(double durationSeconds) {
if (!hasNextDeltaTimeStep())
return;
double nextDeltaTime = nextDeltaTimeStep().value();
interpolateDeltaTime(nextDeltaTime, durationSeconds);
}
void TimeManager::interpolatePreviousDeltaTimeStep(double durationSeconds) {
if (!hasPreviousDeltaTimeStep())
return;
double previousDeltaTime = previousDeltaTimeStep().value();
interpolateDeltaTime(previousDeltaTime, durationSeconds);
}
void TimeManager::setPause(bool pause) {
interpolatePause(pause, 0);
}
+9
View File
@@ -0,0 +1,9 @@
#Version
12.13
#DeltaTimes
1.0
30.0
60.0
1000.0
36000.0
@@ -0,0 +1,8 @@
#Version
12.13
#DeltaTimes
1
10
notANumber
200
+21
View File
@@ -168,6 +168,16 @@ TEST_CASE("Basic Time Absolute", "[profile]") {
REQUIRE(serialized == contents);
}
TEST_CASE("Basic Delta Times", "[profile]") {
constexpr const char* TestFile = "${TESTDIR}/profile/basic_deltatimes.profile";
Profile p = loadProfile(TestFile);
std::string serialized = p.serialize();
std::string contents = loadFile(TestFile);
REQUIRE(serialized == contents);
}
TEST_CASE("Basic Camera NavState", "[profile]") {
constexpr const char* TestFile = "${TESTDIR}/profile/basic_camera_navstate.profile";
Profile p = loadProfile(TestFile);
@@ -691,6 +701,17 @@ TEST_CASE("Error time wrong parameter type 'type'", "[profile]") {
);
}
TEST_CASE("Error deltatimes wrong parameter type", "[profile]") {
constexpr const char* TestFile =
"${TESTDIR}/profile/error_deltatimes_wrong_parameter_value_type.profile";
REQUIRE_THROWS_WITH(
loadProfile(TestFile),
Catch::Matchers::Contains(
"Expected a number for delta time entry, got 'notANumber'"
)
);
}
TEST_CASE("Error camera navigation state too few parameters", "[profile]") {
constexpr const char* TestFile =
"${TESTDIR}/profile/error_camera_navstate_too_few_parameters.profile";