這段程式碼是使用 Rust 語言和 Bevy 框架來創建一個應用程序,它展示如何在低功耗模式下運行窗口,適合桌面應用程序或其他不需要持續運行事件循環的程序。以下是對每一行的詳細解釋:
//! This example illustrates how to run a winit window in a reactive, low power mode.
//!
//! This is useful for making desktop applications, or any other program that doesn't need to be
//! running the event loop non-stop.
這是用於說明的註解,表明這個範例展示了如何在反應式低功耗模式下運行 winit 窗口,適合用於桌面應用程序。
use bevy::{
prelude::*,
utils::Duration,
window::{PresentMode, RequestRedraw, WindowPlugin},
winit::{EventLoopProxyWrapper, WakeUp, WinitSettings},
};
這段代碼導入了 Bevy 框架的核心模塊,包括預設模組、持續時間、窗口設置,以及與 winit 事件循環相關的功能。
fn main() {
App::new()
定義 main 函數,Bevy 應用程序從這裡開始執行。
// Continuous rendering for games - bevy's default.
.insert_resource(WinitSettings::game())
將 WinitSettings::game() 資源插入(默認的連續渲染模式)供應用程序使用。
// Power-saving reactive rendering for applications.
.insert_resource(WinitSettings::desktop_app())
插入 WinitSettings::desktop_app(),這是一個適合桌面應用的反應式渲染設定,可以根據焦點自動調整更新行為。
// You can also customize update behavior with the fields of [`WinitSettings`]
.insert_resource(WinitSettings {
focused_mode: bevy::winit::UpdateMode::Continuous,
unfocused_mode: bevy::winit::UpdateMode::reactive_low_power(Duration::from_millis(10)),
})
用自定義的 WinitSettings 資源設置獲得更新行為。當窗口聚焦時,設置為連續模式;當窗口失去焦點時,則使用低功耗的反應模式,等待 10 毫秒再更新。
.insert_resource(ExampleMode::Game)
插入一個 ExampleMode 資源,默認設置為 Game 模式。
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
添加預設插件,特別是窗口插件。
// Turn off vsync to maximize CPU/GPU usage
present_mode: PresentMode::AutoNoVsync,
設置渲染模式為自動無 VSync,以最大化 CPU/GPU 的使用效率。
..default()
}),
..default()
}))
使用預設選項填充其他窗口屬性。
.add_systems(Startup, test_setup::setup)
在啟動階段添加一個系統,執行場景設置。
.add_systems(
Update,
(
test_setup::cycle_modes,
test_setup::rotate_cube,
test_setup::update_text,
update_winit,
),
)
在每次更新中添加多個系統,包括模式循環、立方體旋轉、文本更新及窗口配置更新。
.run();
}
執行 Bevy 應用。
#[derive(Resource, Debug)]
enum ExampleMode {
Game,
Application,
ApplicationWithRequestRedraw,
ApplicationWithWakeUp,
}
定義一個資源枚舉 ExampleMode,包含四種模式:Game、Application、ApplicationWithRequestRedraw 和 ApplicationWithWakeUp。
/// Update winit based on the current `ExampleMode`
fn update_winit(
mode: Res<ExampleMode>,
mut winit_config: ResMut<WinitSettings>,
event_loop_proxy: Res<EventLoopProxyWrapper<WakeUp>>,
mut redraw_request_events: EventWriter<RequestRedraw>,
) {
定義一個系統函數 update_winit,根據當前模式更新 winit 設定。它接收多個參數,包括當前模式、可變的 WinitSettings 配置、事件循環代理和事件寫入器。
use ExampleMode::*;
將 ExampleMode 枚舉的變體引入,可以簡化後續代碼的用法。
*winit_config = match *mode {
開始匹配當前的模式。
Game => {
// In the default `WinitSettings::game()` mode:
// * When focused: the event loop runs as fast as possible
// * When not focused: the app will update when the window is directly interacted with
// (e.g. the mouse hovers over a visible part of the out of focus window), a
// [`RequestRedraw`] event is received, or one sixtieth of a second has passed
// without the app updating (60 Hz refresh rate max).
WinitSettings::game()
}
如果當前模式為 Game,則使用默認的 WinitSettings::game(),在聚焦時事件循環以最快速度執行,在不聚焦時只有在特定事件觸發時才更新。
Application => {
// While in `WinitSettings::desktop_app()` mode:
// * When focused: the app will update any time a winit event (e.g. the window is
// moved/resized, the mouse moves, a button is pressed, etc.), a [`RequestRedraw`]
// event is received, or after 5 seconds if the app has not updated.
// * When not focused: the app will update when the window is directly interacted with
// (e.g. the mouse hovers over a visible part of the out of focus window), a
// [`RequestRedraw`] event is received, or one minute has passed without the app
// updating.
WinitSettings::desktop_app()
}
如果當前模式為 Application,則使用 WinitSettings::desktop_app(),聚焦時每當接收到 winit 事件、重繪請求事件或超過 5 秒時會更新;不聚焦時,只有在特定事件時才會更新。
ApplicationWithRequestRedraw => {
// Sending a `RequestRedraw` event is useful when you want the app to update the next
// frame regardless of any user input. For example, your application might use
// `WinitSettings::desktop_app()` to reduce power use, but UI animations need to play even
// when there are no inputs, so you send redraw requests while the animation is playing.
// Note that in this example the RequestRedraw winit event will make the app run in the same
// way as continuous
redraw_request_events.send(RequestRedraw);
WinitSettings::desktop_app()
}
如果當前模式為 ApplicationWithRequestRedraw,則發送一個重繪請求事件來強制應用程序更新,特別適用於 UI 動畫需要持續更新時,即使沒有用戶輸入,然後使用 desktop_app() 設定。
ApplicationWithWakeUp => {
// Sending a `WakeUp` event is useful when you want the app to update the next
// frame regardless of any user input. This can be used from outside Bevy, see example
// `window/custom_user_event.rs` for an example usage from outside.
// Note that in this example the Wakeup winit event will make the app run in the same
// way as continuous
let _ = event_loop_proxy.send_event(WakeUp);
WinitSettings::desktop_app()
}
如果當前模式為 ApplicationWithWakeUp,則發送 WakeUp 事件來更新應用,這樣可以從 Bevy 之外的地方觸發更新。
};
}
結束 update_winit 函數。
/// Everything in this module is for setting up and animating the scene, and is not important to the
/// demonstrated features.
pub(crate) mod test_setup {
定義一個公共模組 test_setup,用來設置和管理場景,具體與前面展示的功能無關。
use crate::ExampleMode;
use bevy::{
color::palettes::basic::{LIME, YELLOW},
prelude::*,
window::RequestRedraw,
};
導入 Bevy 模組及顏色調色板。
/// Switch between update modes when the mouse is clicked.
pub(crate) fn cycle_modes(
mut mode: ResMut<ExampleMode>,
button_input: Res<ButtonInput<KeyCode>>,
) {
定義一個函數來在點擊事件發生時切換更新模式。
if button_input.just_pressed(KeyCode::Space) {
檢測當空格鍵被按下的事件。
*mode = match *mode {
ExampleMode::Game => ExampleMode::Application,
ExampleMode::Application => ExampleMode::ApplicationWithRequestRedraw,
ExampleMode::ApplicationWithRequestRedraw => ExampleMode::ApplicationWithWakeUp,
ExampleMode::ApplicationWithWakeUp => ExampleMode::Game,
};
}
}
根據當前模式循環切換四種不同的模式。
#[derive(Component)]
pub(crate) struct Rotator;
定義一個組件 Rotator,用於到後續的查詢和操作。
/// Rotate the cube to make it clear when the app is updating
pub(crate) fn rotate_cube(
time: Res<Time>,
mut cube_transform: Query<&mut Transform, With<Rotator>>,
) {
定義一個函數來旋轉立方體,以明確展示應用何時更新。
for mut transform in &mut cube_transform {
transform.rotate_x(time.delta_secs());
transform.rotate_local_y(time.delta_secs());
}
}
遍歷 Rotator 組件的查詢對象,並根據時間旋轉立方體。
#[derive(Component)]
pub struct ModeText;
定義一個組件 ModeText,用於標記顯示當前模式的文本。
pub(crate) fn update_text(
mut frame: Local<usize>,
mode: Res<ExampleMode>,
text: Single<Entity, With<ModeText>>,
mut writer: TextUiWriter,
) {
定義一個函數來更新正在顯示的文本,顯示當前的模式和幀數。
*frame += 1;
增加幀數計數。
let mode = match *mode {
根據當前的模式設置顯示文本。
ExampleMode::Game => "game(), continuous, default",
ExampleMode::Application => "desktop_app(), reactive",
ExampleMode::ApplicationWithRequestRedraw => {
"desktop_app(), reactive, RequestRedraw sent"
}
ExampleMode::ApplicationWithWakeUp => "desktop_app(), reactive, WakeUp sent",
};
根據當前模式返回不同的顯示文本。
*writer.text(*text, 2) = mode.to_string();
*writer.text(*text, 4) = frame.to_string();
}
更新文本 UI 元素顯示的內容。
/// Set up a scene with a cube and some text
pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut event: EventWriter<RequestRedraw>,
) {
定義一個設置場景的函數,創建一個立方體和文本元素。
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
Rotator,
));
創建一個立方體的 3D 網格,並設置材質和 Rotator 組件,以便後續進行旋轉。
commands.spawn((
DirectionalLight::default(),
Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
));
創建一個方向光源,設置其位置和方向。
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
));
創建一個 3D 相機,並設置其位置和方向,指向場景的中心。
event.send(RequestRedraw);
發送一個重繪請求事件,確保首先繪製內容。
commands
.spawn((
Text::default(),
Node {
align_self: AlignSelf::FlexStart,
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
ModeText,
))
創建一個文本元素並設置其為絕對定位,並指定文本內容位置。
.with_children(|p| {
p.spawn(TextSpan::new("Press space bar to cycle modes\n"));
p.spawn((TextSpan::default(), TextColor(LIME.into())));
p.spawn((TextSpan::new("\nFrame: "), TextColor(YELLOW.into())));
p.spawn((TextSpan::new(""), TextColor(YELLOW.into())));
});
在文本元素中添加子元素,包括說明和幀數信息的表示。
整體而言,此範例展示如何利用 Bevy 框架和 Rust 語言創建一個具有多種模式的低功耗桌面應用程序,並透過合理的設置與更新機制,降低資源使用,提供良好的用戶體驗。