【问题标题】:Gaffer on games timestep: std::chrono implementation游戏时间步长上的灯光师:std::chrono implementation
【发布时间】:2020-04-13 22:31:13
【问题描述】:

如果您不熟悉 Gaffer on Games 文章“修复您的时间步长”,您可以在此处找到它: https://gafferongames.com/post/fix_your_timestep/

我正在构建一个游戏引擎,为了让 std::chrono 更加舒适,我一直在尝试使用 std::chrono 来实现一个固定的时间步长。似乎无法绕过它。这是我正在努力的伪代码:

double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
    double newTime = time();
    double frameTime = newTime - currentTime;
    if ( frameTime > 0.25 )
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    State state = currentState * alpha + 
        previousState * ( 1.0 - alpha );

    render( state );
}

目标:

  • 我不希望渲染受帧率限制。我应该在繁忙的循环中渲染
  • 我想要一个完全固定的时间步长,我用 float 增量时间调用我的更新函数
  • 不睡觉

我目前的尝试(半固定):

#include <algorithm>
#include <chrono>
#include <SDL.h>

namespace {
    using frame_period = std::chrono::duration<long long, std::ratio<1, 60>>;
    const float s_desiredFrameRate = 60.0f;
    const float s_msPerSecond = 1000;
    const float s_desiredFrameTime = s_msPerSecond / s_desiredFrameRate;
    const int s_maxUpdateSteps = 6;
    const float s_maxDeltaTime = 1.0f;
}


auto framePrev = std::chrono::high_resolution_clock::now();
auto frameCurrent = framePrev;

auto frameDiff = frameCurrent - framePrev;
float previousTicks = SDL_GetTicks();
while (m_mainWindow->IsOpen())
{

    float newTicks = SDL_GetTicks();
    float frameTime = newTicks - previousTicks;
    previousTicks = newTicks;

    // 32 ms in a frame would cause this to be .5, 16ms would be 1.0
    float totalDeltaTime = frameTime / s_desiredFrameTime;

    // Don't execute anything below
    while (frameDiff < frame_period{ 1 })
    {
        frameCurrent = std::chrono::high_resolution_clock::now();
        frameDiff = frameCurrent - framePrev;
    }

    using hr_duration = std::chrono::high_resolution_clock::duration;
    framePrev = std::chrono::time_point_cast<hr_duration>(framePrev + frame_period{ 1 });
    frameDiff = frameCurrent - framePrev;

    // Time step
    int i = 0;
    while (totalDeltaTime > 0.0f && i < s_maxUpdateSteps)
    {
        float deltaTime = std::min(totalDeltaTime, s_maxDeltaTime);
        m_gameController->Update(deltaTime);
        totalDeltaTime -= deltaTime;
        i++;
    }

    // ProcessCallbackQueue();
    // ProcessSDLEvents();
    // m_renderEngine->Render();
}

这个实现的问题

  • 渲染、处理输入等与帧速率相关
  • 我正在使用 SDL_GetTicks() 而不是 std::chrono

我的实际问题

  • 如何将SDL_GetTicks() 替换为std::chrono::high_resolution_clock::now()?似乎无论我需要使用什么count(),但我从 Howard Hinnant 本人那里读到了这句话:

如果您使用 count(),并且/或者您的计时码中有转换因子,那么您就太努力了。 所以我想也许有更直观的方法。

  • 如何将所有 floats 替换为实际的 std::chrono_literal 时间值,除了我将浮点 deltaTime 作为模拟修改器传递给更新函数的末尾?

【问题讨论】:

    标签: c++ c++11 game-engine chrono game-loop


    【解决方案1】:

    下面我使用&lt;chrono&gt; 实现了来自Fix your Timestep 的几个不同版本的“最终触摸”。我希望这个例子能转化为你想要的代码。

    主要的挑战是弄清楚每个double 在Fix your Timestep 中代表什么单位。一旦完成,转换为&lt;chrono&gt; 就相当机械了。

    头条

    为了让我们可以轻松更改时钟,以Clock 类型开头,例如:

    using Clock = std::chrono::steady_clock;
    

    稍后我将展示,如果需要,甚至可以将 Clock 实现为 SDL_GetTicks()。

    如果您可以控制integrate 函数的签名,我建议时间参数使用双基秒单位:

    void
    integrate(State& state,
              std::chrono::time_point<Clock, std::chrono::duration<double>>,
              std::chrono::duration<double> dt);
    

    这将允许您传递您想要的任何内容(只要time_point 基于Clock),而不必担心显式转换为正确的单位。再加上物理计算通常以浮点数完成,因此这也适用于这一点。例如,如果State 只包含一个加速度和一个速度:

    struct State
    {
        double acceleration = 1;  // m/s^2
        double velocity = 0;  // m/s
    };
    

    而integrate 应该计算新的速度:

    void
    integrate(State& state,
              std::chrono::time_point<Clock, std::chrono::duration<double>>,
              std::chrono::duration<double> dt)
    {
        using namespace std::literals;
        state.velocity += state.acceleration * dt/1s;
    };
    

    表达式dt/1s 只是将基于double 的chrono seconds 转换为double,因此它可以参与物理计算。

    std::literals 和 1s 是 C++14。如果你卡在 C++11 上,你可以用 seconds{1} 替换它们。

    版本 1

    using namespace std::literals;
    auto constexpr dt = 1.0s/60.;
    using duration = std::chrono::duration<double>;
    using time_point = std::chrono::time_point<Clock, duration>;
    
    time_point t{};
    
    time_point currentTime = Clock::now();
    duration accumulator = 0s;
    
    State previousState;
    State currentState;
    
    while (!quit)
    {
        time_point newTime = Clock::now();
        auto frameTime = newTime - currentTime;
        if (frameTime > 0.25s)
            frameTime = 0.25s;
        currentTime = newTime;
    
        accumulator += frameTime;
    
        while (accumulator >= dt)
        {
            previousState = currentState;
            integrate(currentState, t, dt);
            t += dt;
            accumulator -= dt;
        }
    
        const double alpha = accumulator / dt;
    
        State state = currentState * alpha + previousState * (1 - alpha);
        render(state);
    }
    

    此版本与 Fix your Timestep 保持几乎完全相同,除了一些 doubles 更改为类型 duration&lt;double&gt;(如果它们代表持续时间),而其他更改为 time_point&lt;Clock, duration&lt;double&gt;&gt;(如果它们表示时间点)。

    dt 的单位为duration&lt;double&gt;(双基秒),我假设来自Fix your Timestep 的0.01 是类型o,所需的值为1./60。在 C++11 中,1.0s/60. 可以更改为 seconds{1}/60.。

    duration 和 time_point 的本地类型别名设置为使用基于 Clock 和 double 的秒数。

    从现在开始,代码几乎与Fix your Timestep 相同,除了使用duration 或time_point 代替double 的类型。

    注意alpha不是时间单位,而是一个无量纲的double系数。

    • 如何将 SDL_GetTicks() 替换为 std::chrono::high_resolution_clock::now()?似乎无论我需要使用什么 count()

    如上。没有使用SDL_GetTicks() 和.count()。

    • 我如何用实际的 std::chrono_literal 时间值替换所有浮点数,除了我得到浮点 deltaTime 作为模拟修改器传递到更新函数的末尾?

    如上所述,您不需要将浮点 delaTime 传递给更新函数,除非该函数签名超出您的控制范围。如果是这样的话,那么:

    m_gameController->Update(deltaTime/1s);
    

    第 2 版

    现在让我们更进一步:我们真的需要对 duration 和 time_point 单位使用浮点吗?

    不。以下是使用基于整数的时间单位执行相同操作的方法:

    using namespace std::literals;
    auto constexpr dt = std::chrono::duration<long long, std::ratio<1, 60>>{1};
    using duration = decltype(Clock::duration{} + dt);
    using time_point = std::chrono::time_point<Clock, duration>;
    
    time_point t{};
    
    time_point currentTime = Clock::now();
    duration accumulator = 0s;
    
    State previousState;
    State currentState;
    
    while (!quit)
    {
        time_point newTime = Clock::now();
        auto frameTime = newTime - currentTime;
        if (frameTime > 250ms)
            frameTime = 250ms;
        currentTime = newTime;
    
        accumulator += frameTime;
    
        while (accumulator >= dt)
        {
            previousState = currentState;
            integrate(currentState, t, dt);
            t += dt;
            accumulator -= dt;
        }
    
        const double alpha = std::chrono::duration<double>{accumulator} / dt;
    
        State state = currentState * alpha + previousState * (1 - alpha);
        render(state);
    }
    

    与第 1 版相比,几乎没有什么变化:

    • dt 现在的值为 1,由 long long 表示,单位为 1/60 秒。

    • duration 现在有一个奇怪的类型,我们甚至不必知道它的细节。它与Clock::duration 和dt 的总和类型相同。这将是最粗略的精度,可以准确地表示 Clock::duration 和 1/60 秒。谁在乎它是什么。重要的是,如果Clock::duration 是基于整数的,则基于时间的算术将没有截断误差,甚至没有任何舍入误差。 (谁说在电脑上不能准确表示1/3?!)

    • 0.25s 限制改为转换为 250ms(C++11 中为 milliseconds{250})。

    • alpha 的计算应积极转换为双精度单位,以避免与基于整数的除法相关的截断。

    更多关于Clock

    • 如果您不需要将t 映射到物理中的日历时间,并且/或者您不关心t 是否会慢慢偏离准确的物理时间,请使用steady_clock。没有时钟是完美的,steady_clock 永远不会调整到正确的时间(例如通过 NTP 服务)。

    • 如果您需要将t 映射到日历时间,或者如果您希望t 与UTC 保持同步,请使用system_clock。这将需要在游戏进行时对Clock 进行一些小的(可能是毫秒级或更小)调整。

    • 如果您不在乎得到steady_clock 或system_clock 并希望每次将代码移植到新平台或编译器时都会感到惊讶,请使用high_resolution_clock。 :-)

    • 最后,如果你愿意,你甚至可以坚持使用SDL_GetTicks(),像这样编写自己的Clock:

    例如:

    struct Clock
    {
        using duration = std::chrono::milliseconds;
        using rep = duration::rep;
        using period = duration::period;
        using time_point = std::chrono::time_point<Clock>;
        static constexpr bool is_steady = true;
    
        static
        time_point
        now() noexcept
        {
            return time_point{duration{SDL_GetTicks()}};
        }
    };
    

    切换:

    • using Clock = std::chrono::steady_clock;
    • using Clock = std::chrono::system_clock;
    • using Clock = std::chrono::high_resolution_clock;
    • struct Clock {...}; // SDL_GetTicks based

    需要对事件循环、物理引擎或渲染引擎进行零次更改。重新编译就好了。转换常数会自动更新。因此,您可以轻松地试验哪个 Clock 最适合您的应用程序。

    附录

    我完整的State代码:

    struct State
    {
        double acceleration = 1;  // m/s^2
        double velocity = 0;  // m/s
    };
    
    void
    integrate(State& state,
              std::chrono::time_point<Clock, std::chrono::duration<double>>,
              std::chrono::duration<double> dt)
    {
        using namespace std::literals;
        state.velocity += state.acceleration * dt/1s;
    };
    
    State operator+(State x, State y)
    {
        return {x.acceleration + y.acceleration, x.velocity + y.velocity};
    }
    
    State operator*(State x, double y)
    {
        return {x.acceleration * y, x.velocity * y};
    }
    
    void render(State state)
    {
        using namespace std::chrono;
        static auto t = time_point_cast<seconds>(steady_clock::now());
        static int frame_count = 0;
        static int frame_rate = 0;
        auto pt = t;
        t = time_point_cast<seconds>(steady_clock::now());
        ++frame_count;
        if (t != pt)
        {
            frame_rate = frame_count;
            frame_count = 0;
        }
        std::cout << "Frame rate is " << frame_rate << " frames per second.  Velocity = "
                  << state.velocity << " m/s\n";
    }
    

    【讨论】:

    • 天哪,非常感谢您抽出宝贵时间回复!这真是太棒了!我从来不知道 std::chrono 看起来这么干净!现在所有的 std::chrono 东西都非常有意义,再次感谢您!我确实可以完全控制集成,并且我使用的是最新的 MSVC。我对 State 对象有疑问。您是否认为State state = currentState * alpha + previousState * (1 - alpha) 会扩展到对state.acceleration 和state.velocity 执行该操作?我不确定是否暗示了可以执行该操作的 operator= 重载
    • 很高兴我能帮上忙。在State 上,是的,插值可以在两个字段上进行。我在我的原型中这样做了。我已将我所有的 State 代码添加到我的答案中作为示例。
    • 你知道250ms代表什么吗?
    • 250ms 是写milliseconds{250} 的另一种方式。语法要求 C++14 或更高版本,以及using namespace std::chrono_literals;。
    • @Lukas__:250ms 是为应对spiral of death 设置的帧时间限制。它不必完全是250ms,但它应该足够高以处理(希望是暂时的)负载峰值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2015-09-11
    • 2017-08-31
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多