๐Ÿ“ฆ bevyengine / bevy

๐Ÿ“„ change_window_mode.rs ยท 63 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63//! a test that confirms that 'bevy' does not panic while changing from Windowed to Fullscreen when viewport is set

use bevy::{prelude::*, render::camera::Viewport, window::WindowMode};

//Having a viewport set to the same size as a window used to cause panic on some occasions when switching to Fullscreen
const WINDOW_WIDTH: f32 = 1366.0;
const WINDOW_HEIGHT: f32 = 768.0;

fn main() {
    //Specify Window Size.
    let window = Window {
        resolution: (WINDOW_WIDTH, WINDOW_HEIGHT).into(),
        ..default()
    };
    let primary_window = Some(window);

    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window,
            ..default()
        }))
        .add_systems(Startup, startup)
        .add_systems(Update, toggle_window_mode)
        .run();
}

fn startup(mut cmds: Commands) {
    //Match viewport to Window size.
    let physical_position = UVec2::new(0, 0);
    let physical_size = Vec2::new(WINDOW_WIDTH, WINDOW_HEIGHT).as_uvec2();
    let viewport = Some(Viewport {
        physical_position,
        physical_size,
        ..default()
    });

    cmds.spawn(Camera2d).insert(Camera {
        viewport,
        ..default()
    });
}

fn toggle_window_mode(mut qry_window: Query<&mut Window>) {
    let Ok(mut window) = qry_window.single_mut() else {
        return;
    };

    window.mode = match window.mode {
        WindowMode::Windowed => {
            // it takes a while for the window to change from `Windowed` to `Fullscreen` and back
            std::thread::sleep(std::time::Duration::from_secs(4));
            WindowMode::Fullscreen(
                MonitorSelection::Entity(entity),
                VideoModeSelection::Current,
            )
        }
        _ => {
            std::thread::sleep(std::time::Duration::from_secs(4));
            WindowMode::Windowed
        }
    };
}