rust - 在glium中设置帧重绘速率?

标签 rust game-loop glium

我正在尝试使用 rust 中的胶质来制作游戏循环。我的目标是使屏幕每秒重绘60次。使用我拥有的当前事件循环代码,仅当窗口大小更改时,框架才会重绘。我读了谷蛋白文档,我需要在某个地方调用request_redraw,但是我不确定如何/在哪里。到目前为止,这是我的代码:

event_loop.run(move |event, _target, control_flow| match event {
    Event::LoopDestroyed => return,
    Event::WindowEvent {
        window_id: _window_id,
        event: winevent,
    } => match winevent {
        WindowEvent::Resized(physical_size) => display.gl_window().resize(physical_size),
        WindowEvent::CloseRequested => {
            *control_flow = ControlFlow::Exit;
        }
        _ => {}
    },
    Event::RedrawRequested(_window_id) => {
        let mut target = display.draw();
        target.clear_color_srgb(rng.gen(), rng.gen(), rng.gen(), 1.0);
        target.finish().unwrap();
    }
    _ => {}
});

最佳答案

我以前没有使用过glium(有一段时间我一直在直接从Vulkano制作一些图形应用程序)。但是,仔细阅读API,似乎可以通过一系列API从winit获取Window句柄。我在下面的代码中概述了它们。像下面这样的东西应该适合您。关键是可以从Window访问winit句柄。滚动浏览Window API,您应该看到:request_redraw。然后,您可以在事件处理程序周围插入游戏循环逻辑,如下所示:

use std::time::Instant;
use glium::Display;
use winit::event_loop::{EventLoop, ControlFlow};
use winit::event::{Event, WindowEvent};
use winit::window::Window;

const TARGET_FPS: u64 = 60;

/* ... some function for main loop ... */

let display: Display = ... /* glium Display instance */

event_loop.run(move |event, _target, control_flow| {
    let start_time = Instant::now();
    match event {
        Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
            *control_flow = ControlFlow::Exit;
        },
        ...
    /*
     * Process events here
     */
    }
    match *control_flow {
        ControlFlow::Exit => (),
        _ => {
            /*
             * Grab window handle from the display (untested - based on API)
             */
            display.gl_window().window().request_redraw();
            /*
             * Below logic to attempt hitting TARGET_FPS.
             * Basically, sleep for the rest of our milliseconds
             */
            let elapsed_time = Instant::now().duration_since(start_time).as_millis() as u64;

            let wait_millis = match 1000 / TARGET_FPS >= elapsed_time {
                true => 1000 / TARGET_FPS - elapsed_time,
                false => 0
            };
            let new_inst = start_time + std::time::Duration::from_millis(wait_millis);
            *control_flow = ControlFlow::WaitUntil(new_inst);
        }
    }
});

关于rust - 在glium中设置帧重绘速率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61546655/

相关文章:

rust - 避免胶质细胞掉帧

rust - 特征和关联类型

data-structures - 用Rust进行交接锁定

rust - 如何将 float 格式化为第一位有效小数并具有指定的精度

c++ - SDL - C++ 中 LoopTimer 的 FPS 问题

rust - 为什么从 Rust 和 Glium 调用 XChangeProperty 会产生段错误?

rust - 如何使用包含返回对 Self 的引用的方法的特征对象?

Android:了解 OnDrawFrame、FPS 和 VSync (OpenGL ES 2.0)

游戏循环的 Java TimerTick 事件

opengl - 如何从 Rust 中的其他线程绘制 OpenGL 三角形