最近试着用 imgui-rust 绘制界面,发现窗口最小化后CPU占用会增大。
查询的资料如下:
原因: 最小化后渲染后端不受控制的运行,imgui 进行许多无用的渲染,EventsLoop不断的拉取无用事件。
解决办法: 检测到最小化后,让当前渲染线程的休眠,不要过快的执行。
impl System {
pub fn main_loop(self, mut run_ui: F) {
let System {
mut events_loop,
mut imgui,
mut platform,
mut render_sys,
..
} = self;
let mut encoder: gfx::Encoder<_ _> = render_sys.factory.create_command_buffer().into();
let mut last_frame = Instant::now();
let mut run = true;
let mut minimized = true;
while run {
events_loop.poll_events(|event| {
platform.handle_event(imgui.io_mut(), render_sys.window(), &event);
if let Event::WindowEvent { event, .. } = event {
match event {
WindowEvent::Resized(size) => {
if size.height as usize == 0 && size.width as usize == 0 {
//最小化
minimized = true;
println!("minimized");
} else {
if minimized {
//从最小化恢复
println!("resume from minimized");
}
minimized = false;
}
render_sys.update_views(size);
},
WindowEvent::CloseRequested => run = false,
_ => (),
}
}
});
if minimized {
//检测到最小化,不要让渲染线程跑太快,如果需要在渲染线程处理其他高频率的事件,应该使用新的线程。
std::thread::sleep(std::time::Duration::from_millis(100));
//continue;
}
let io = imgui.io_mut();
platform
.prepare_frame(io, render_sys.window())
.expect("Failed to start frame");
last_frame = io.update_delta_time(last_frame);
let mut ui = imgui.frame();
run_ui(&mut run, &mut ui);
if let Some(main_color) = render_sys.main_color.as_mut() {
encoder.clear(main_color, [1.0, 1.0, 1.0, 1.0]);
}
platform.prepare_render(&ui, render_sys.window());
let draw_data = ui.render();
if let Some(main_color) = render_sys.main_color.as_mut() {
render_sys
.renderer
.render(&mut render_sys.factory, &mut encoder, main_color, draw_data)
.expect("Rendering failed");
}
encoder.flush(&mut render_sys.device);
render_sys.swap_buffers();
render_sys.device.cleanup();
}
}
}