WindowResolution

Struct WindowResolution 

Source
pub struct WindowResolution { /* private fields */ }
Expand description

Controls the size of a Window

§Physical, logical and requested sizes

There are three sizes associated with a window:

  • the physical size, which represents the actual height and width in physical pixels the window occupies on the monitor,
  • the logical size, which represents the size that should be used to scale elements inside the window, measured in logical pixels,
  • the requested size, measured in logical pixels, which is the value submitted to the API when creating the window, or requesting that it be resized.

§Scale factor

The reason logical size and physical size are separated and can be different is to account for the cases where:

  • several monitors have different pixel densities,
  • the user has set up a pixel density preference in its operating system,
  • the Bevy App has specified a specific scale factor between both.

The factor between physical size and logical size can be retrieved with WindowResolution::scale_factor.

For the first two cases, a scale factor is set automatically by the operating system through the window backend. You can get it with WindowResolution::base_scale_factor.

For the third case, you can override this automatic scale factor with WindowResolution::set_scale_factor_override.

§Requested and obtained sizes

The logical size should be equal to the requested size after creating/resizing, when possible. The reason the requested size and logical size might be different is because the corresponding physical size might exceed limits (either the size limits of the monitor, or limits defined in WindowResizeConstraints).

Note: The requested size is not kept in memory, for example requesting a size too big for the screen, making the logical size different from the requested size, and then setting a scale factor that makes the previous requested size within the limits of the screen will not get back that previous requested size.

Implementations§

Source§

impl WindowResolution

Source

pub fn new(physical_width: u32, physical_height: u32) -> WindowResolution

Creates a new WindowResolution.

Examples found in repository?
examples/window/scale_factor_override.rs (line 13)
9fn main() {
10    App::new()
11        .add_plugins(DefaultPlugins.set(WindowPlugin {
12            primary_window: Some(Window {
13                resolution: WindowResolution::new(500, 300).with_scale_factor_override(1.0),
14                ..default()
15            }),
16            ..default()
17        }))
18        .add_systems(Startup, setup)
19        .add_systems(
20            Update,
21            (display_override, toggle_override, change_scale_factor),
22        )
23        .run();
24}
More examples
Hide additional examples
examples/stress_tests/many_cameras_lights.rs (line 18)
13fn main() {
14    App::new()
15        .add_plugins(DefaultPlugins.set(WindowPlugin {
16            primary_window: Some(Window {
17                present_mode: PresentMode::AutoNoVsync,
18                resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
19                ..default()
20            }),
21            ..default()
22        }))
23        .insert_resource(WinitSettings::continuous())
24        .add_systems(Startup, setup)
25        .add_systems(Update, rotate_cameras)
26        .run();
27}
examples/stress_tests/text_pipeline.rs (line 20)
14fn main() {
15    App::new()
16        .add_plugins((
17            DefaultPlugins.set(WindowPlugin {
18                primary_window: Some(Window {
19                    present_mode: PresentMode::AutoNoVsync,
20                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
21                    ..default()
22                }),
23                ..default()
24            }),
25            FrameTimeDiagnosticsPlugin::default(),
26            LogDiagnosticsPlugin::default(),
27        ))
28        .insert_resource(WinitSettings::continuous())
29        .add_systems(Startup, spawn)
30        .add_systems(Update, update_text_bounds)
31        .run();
32}
tests/window/resizing.rs (line 25)
20fn main() {
21    App::new()
22        .add_plugins(
23            DefaultPlugins.set(WindowPlugin {
24                primary_window: Some(Window {
25                    resolution: WindowResolution::new(MAX_WIDTH as u32, MAX_HEIGHT as u32)
26                        .with_scale_factor_override(1.0),
27                    title: "Resizing".into(),
28                    ..default()
29                }),
30                ..default()
31            }),
32        )
33        .insert_resource(Dimensions {
34            width: MAX_WIDTH,
35            height: MAX_HEIGHT,
36        })
37        .insert_resource(ContractingY)
38        .add_systems(Startup, (setup_3d, setup_2d))
39        .add_systems(Update, (change_window_size, sync_dimensions))
40        .run();
41}
examples/stress_tests/many_lights.rs (line 24)
19fn main() {
20    App::new()
21        .add_plugins((
22            DefaultPlugins.set(WindowPlugin {
23                primary_window: Some(Window {
24                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
25                    title: "many_lights".into(),
26                    present_mode: PresentMode::AutoNoVsync,
27                    ..default()
28                }),
29                ..default()
30            }),
31            FrameTimeDiagnosticsPlugin::default(),
32            LogDiagnosticsPlugin::default(),
33            LogVisibleLights,
34        ))
35        .insert_resource(WinitSettings::continuous())
36        .add_systems(Startup, setup)
37        .add_systems(Update, (move_camera, print_light_count))
38        .run();
39}
examples/stress_tests/many_gizmos.rs (line 21)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins((
17        DefaultPlugins.set(WindowPlugin {
18            primary_window: Some(Window {
19                title: "Many Debug Lines".to_string(),
20                present_mode: PresentMode::AutoNoVsync,
21                resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
22                ..default()
23            }),
24            ..default()
25        }),
26        FrameTimeDiagnosticsPlugin::default(),
27        LogDiagnosticsPlugin::default(),
28    ))
29    .insert_resource(WinitSettings::continuous())
30    .insert_resource(Config {
31        line_count: 50_000,
32        fancy: false,
33    })
34    .add_systems(Startup, setup)
35    .add_systems(Update, (input, ui_system));
36
37    for _ in 0..SYSTEM_COUNT {
38        app.add_systems(Update, system);
39    }
40
41    app.run();
42}
Source

pub fn with_scale_factor_override( self, scale_factor_override: f32, ) -> WindowResolution

Builder method for adding a scale factor override to the resolution.

Examples found in repository?
examples/window/scale_factor_override.rs (line 13)
9fn main() {
10    App::new()
11        .add_plugins(DefaultPlugins.set(WindowPlugin {
12            primary_window: Some(Window {
13                resolution: WindowResolution::new(500, 300).with_scale_factor_override(1.0),
14                ..default()
15            }),
16            ..default()
17        }))
18        .add_systems(Startup, setup)
19        .add_systems(
20            Update,
21            (display_override, toggle_override, change_scale_factor),
22        )
23        .run();
24}
More examples
Hide additional examples
examples/stress_tests/many_cameras_lights.rs (line 18)
13fn main() {
14    App::new()
15        .add_plugins(DefaultPlugins.set(WindowPlugin {
16            primary_window: Some(Window {
17                present_mode: PresentMode::AutoNoVsync,
18                resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
19                ..default()
20            }),
21            ..default()
22        }))
23        .insert_resource(WinitSettings::continuous())
24        .add_systems(Startup, setup)
25        .add_systems(Update, rotate_cameras)
26        .run();
27}
examples/stress_tests/text_pipeline.rs (line 20)
14fn main() {
15    App::new()
16        .add_plugins((
17            DefaultPlugins.set(WindowPlugin {
18                primary_window: Some(Window {
19                    present_mode: PresentMode::AutoNoVsync,
20                    resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
21                    ..default()
22                }),
23                ..default()
24            }),
25            FrameTimeDiagnosticsPlugin::default(),
26            LogDiagnosticsPlugin::default(),
27        ))
28        .insert_resource(WinitSettings::continuous())
29        .add_systems(Startup, spawn)
30        .add_systems(Update, update_text_bounds)
31        .run();
32}
examples/window/multi_window_text.rs (line 18)
10fn main() {
11    App::new()
12        // By default, a primary window is spawned by `WindowPlugin`, contained in `DefaultPlugins`.
13        // The primary window is given the `PrimaryWindow` marker component.
14        .add_plugins(DefaultPlugins.set(WindowPlugin {
15            primary_window: Some(Window {
16                title: "Primary window".to_owned(),
17                // Override the primary window's scale factor and use `1.` (no scaling).
18                resolution: WindowResolution::default().with_scale_factor_override(1.),
19                ..default()
20            }),
21            ..Default::default()
22        }))
23        .add_systems(Startup, setup_scene)
24        .run();
25}
26
27fn setup_scene(mut commands: Commands) {
28    // The first camera; no render target is specified, its render target will be set to the primary window automatically.
29    // This camera has no `RenderLayers` component, so it only renders entities belonging to render layer `0`.
30    commands.spawn(Camera2d);
31
32    // Spawn a second window
33    let secondary_window = commands
34        .spawn(Window {
35            title: "Secondary Window".to_owned(),
36            // Override the secondary window's scale factor and set it to double that of the primary window.
37            // This means the second window's text will use glyphs drawn at twice the resolution of the primary window's text,
38            // and they will be twice as big on screen.
39            resolution: WindowResolution::default().with_scale_factor_override(2.),
40            ..default()
41        })
42        .id();
43
44    // Spawn a second camera
45    let secondary_window_camera = commands
46        .spawn((
47            Camera2d,
48            // This camera will only render entities belonging to render layer `1`.
49            RenderLayers::layer(1),
50            Camera {
51                // Without an explicit render target, this camera would also target the primary window.
52                target: RenderTarget::Window(WindowRef::Entity(secondary_window)),
53                ..default()
54            },
55        ))
56        .id();
57
58    let node = Node {
59        position_type: PositionType::Absolute,
60        top: Val::Px(12.0),
61        left: Val::Px(12.0),
62        ..default()
63    };
64
65    let text_font = TextFont::from_font_size(30.);
66
67    // UI nodes can only be rendered by one camera at a time and ignore `RenderLayers`.
68    // This root UI node has no `UiTargetCamera` so `bevy_ui` will try to find a
69    // camera with the `IsDefaultUiCamera` marker component. When that fails (neither
70    // camera spawned here has an `IsDefaultUiCamera`), it queries for the
71    // first camera targeting the primary window and uses that.
72    commands.spawn(node.clone()).with_child((
73        Text::new("UI Text Primary Window"),
74        text_font.clone(),
75        TextShadow::default(),
76    ));
77
78    commands
79        .spawn((node, UiTargetCamera(secondary_window_camera)))
80        .with_child((
81            Text::new("UI Text Secondary Window"),
82            text_font.clone(),
83            TextShadow::default(),
84        ));
85
86    // `Text2d` belonging to render layer `0`.
87    commands.spawn((
88        Text2d::new("Text2d Primary Window"),
89        TextColor(YELLOW.into()),
90        text_font.clone(),
91        Text2dShadow::default(),
92    ));
93
94    // `Text2d` belonging to render layer `1`.
95    commands.spawn((
96        Text2d::new("Text2d Secondary Window"),
97        TextColor(YELLOW.into()),
98        text_font.clone(),
99        Text2dShadow::default(),
100        RenderLayers::layer(1),
101    ));
102
103    // This `Text2d` entity belongs to both render layers `0` and `1`, so it will be rendered by both
104    // cameras. A single text layout is generated per `Text2d` entity, targeting a specific scale
105    // factor. Since the two camera's render targets have different scale factors, the text layout
106    // will be generated using the higher scale factor (the secondary window's), and then downscaled when it is
107    // drawn by the camera targeting the primary window.
108    commands.spawn((
109        Text2d::new("Text2d Both Windows"),
110        TextColor(LIGHT_CYAN.into()),
111        text_font,
112        Text2dShadow::default(),
113        RenderLayers::from_layers(&[0, 1]),
114        Transform::from_xyz(0., -50., 0.),
115    ));
116}
tests/window/resizing.rs (line 26)
20fn main() {
21    App::new()
22        .add_plugins(
23            DefaultPlugins.set(WindowPlugin {
24                primary_window: Some(Window {
25                    resolution: WindowResolution::new(MAX_WIDTH as u32, MAX_HEIGHT as u32)
26                        .with_scale_factor_override(1.0),
27                    title: "Resizing".into(),
28                    ..default()
29                }),
30                ..default()
31            }),
32        )
33        .insert_resource(Dimensions {
34            width: MAX_WIDTH,
35            height: MAX_HEIGHT,
36        })
37        .insert_resource(ContractingY)
38        .add_systems(Startup, (setup_3d, setup_2d))
39        .add_systems(Update, (change_window_size, sync_dimensions))
40        .run();
41}
examples/ui/text_wrap_debug.rs (line 27)
18fn main() {
19    // `from_env` panics on the web
20    #[cfg(not(target_arch = "wasm32"))]
21    let args: Args = argh::from_env();
22    #[cfg(target_arch = "wasm32")]
23    let args = Args::from_args(&[], &[]).unwrap();
24
25    let window = if let Some(scale_factor) = args.scale_factor {
26        Window {
27            resolution: WindowResolution::default().with_scale_factor_override(scale_factor),
28            ..Default::default()
29        }
30    } else {
31        Window::default()
32    };
33
34    App::new()
35        .add_plugins(DefaultPlugins.set(WindowPlugin {
36            primary_window: Some(window),
37            ..Default::default()
38        }))
39        .insert_resource(UiScale(args.ui_scale))
40        .add_systems(Startup, spawn)
41        .run();
42}
Source

pub fn width(&self) -> f32

The window’s client area width in logical pixels.

Examples found in repository?
examples/stress_tests/many_cameras_lights.rs (line 70)
34fn setup(
35    mut commands: Commands,
36    mut meshes: ResMut<Assets<Mesh>>,
37    mut materials: ResMut<Assets<StandardMaterial>>,
38    window: Query<&Window>,
39) -> Result {
40    // circular base
41    commands.spawn((
42        Mesh3d(meshes.add(Circle::new(4.0))),
43        MeshMaterial3d(materials.add(Color::WHITE)),
44        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
45    ));
46
47    // cube
48    commands.spawn((
49        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
50        MeshMaterial3d(materials.add(Color::WHITE)),
51        Transform::from_xyz(0.0, 0.5, 0.0),
52    ));
53
54    // lights
55    for i in 0..NUM_LIGHTS {
56        let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
57        commands.spawn((
58            PointLight {
59                color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
60                intensity: 2_000_000.0 / NUM_LIGHTS as f32,
61                shadows_enabled: true,
62                ..default()
63            },
64            Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
65        ));
66    }
67
68    // cameras
69    let window = window.single()?;
70    let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
71    let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
72    let mut i = 0;
73    for y in 0..CAMERA_COLS {
74        for x in 0..CAMERA_ROWS {
75            let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
76            commands.spawn((
77                Camera3d::default(),
78                Camera {
79                    viewport: Some(Viewport {
80                        physical_position: UVec2::new(
81                            (x as f32 * width) as u32,
82                            (y as f32 * height) as u32,
83                        ),
84                        physical_size: UVec2::new(width as u32, height as u32),
85                        ..default()
86                    }),
87                    order: i,
88                    ..default()
89                },
90                Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
91                    .looking_at(Vec3::ZERO, Vec3::Y),
92            ));
93            i += 1;
94        }
95    }
96    Ok(())
97}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (line 396)
386fn spawn_birds(
387    commands: &mut Commands,
388    args: &Args,
389    primary_window_resolution: &WindowResolution,
390    counter: &mut BevyCounter,
391    spawn_count: usize,
392    bird_resources: &mut BirdResources,
393    waves_to_simulate: Option<usize>,
394    wave: usize,
395) {
396    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
397    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
398
399    let half_extents = 0.5 * primary_window_resolution.size();
400
401    let color = counter.color;
402    let current_count = counter.count;
403
404    match args.mode {
405        Mode::Sprite => {
406            let batch = (0..spawn_count)
407                .map(|count| {
408                    let bird_z = if args.ordered_z {
409                        (current_count + count) as f32 * 0.00001
410                    } else {
411                        bird_resources.transform_rng.random::<f32>()
412                    };
413
414                    let (transform, velocity) = bird_velocity_transform(
415                        half_extents,
416                        Vec3::new(bird_x, bird_y, bird_z),
417                        &mut bird_resources.velocity_rng,
418                        waves_to_simulate,
419                        FIXED_DELTA_TIME,
420                    );
421
422                    let color = if args.vary_per_instance {
423                        Color::linear_rgb(
424                            bird_resources.color_rng.random(),
425                            bird_resources.color_rng.random(),
426                            bird_resources.color_rng.random(),
427                        )
428                    } else {
429                        color
430                    };
431                    (
432                        Sprite {
433                            image: bird_resources
434                                .textures
435                                .choose(&mut bird_resources.material_rng)
436                                .unwrap()
437                                .clone(),
438                            color,
439                            ..default()
440                        },
441                        transform,
442                        Bird { velocity },
443                    )
444                })
445                .collect::<Vec<_>>();
446            commands.spawn_batch(batch);
447        }
448        Mode::Mesh2d => {
449            let batch = (0..spawn_count)
450                .map(|count| {
451                    let bird_z = if args.ordered_z {
452                        (current_count + count) as f32 * 0.00001
453                    } else {
454                        bird_resources.transform_rng.random::<f32>()
455                    };
456
457                    let (transform, velocity) = bird_velocity_transform(
458                        half_extents,
459                        Vec3::new(bird_x, bird_y, bird_z),
460                        &mut bird_resources.velocity_rng,
461                        waves_to_simulate,
462                        FIXED_DELTA_TIME,
463                    );
464
465                    let material =
466                        if args.vary_per_instance || args.material_texture_count > args.waves {
467                            bird_resources
468                                .materials
469                                .choose(&mut bird_resources.material_rng)
470                                .unwrap()
471                                .clone()
472                        } else {
473                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
474                        };
475                    (
476                        Mesh2d(bird_resources.quad.clone()),
477                        MeshMaterial2d(material),
478                        transform,
479                        Bird { velocity },
480                    )
481                })
482                .collect::<Vec<_>>();
483            commands.spawn_batch(batch);
484        }
485    }
486
487    counter.count += spawn_count;
488    counter.color = Color::linear_rgb(
489        bird_resources.color_rng.random(),
490        bird_resources.color_rng.random(),
491        bird_resources.color_rng.random(),
492    );
493}
Source

pub fn height(&self) -> f32

The window’s client area height in logical pixels.

Examples found in repository?
examples/stress_tests/many_cameras_lights.rs (line 71)
34fn setup(
35    mut commands: Commands,
36    mut meshes: ResMut<Assets<Mesh>>,
37    mut materials: ResMut<Assets<StandardMaterial>>,
38    window: Query<&Window>,
39) -> Result {
40    // circular base
41    commands.spawn((
42        Mesh3d(meshes.add(Circle::new(4.0))),
43        MeshMaterial3d(materials.add(Color::WHITE)),
44        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
45    ));
46
47    // cube
48    commands.spawn((
49        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
50        MeshMaterial3d(materials.add(Color::WHITE)),
51        Transform::from_xyz(0.0, 0.5, 0.0),
52    ));
53
54    // lights
55    for i in 0..NUM_LIGHTS {
56        let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
57        commands.spawn((
58            PointLight {
59                color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
60                intensity: 2_000_000.0 / NUM_LIGHTS as f32,
61                shadows_enabled: true,
62                ..default()
63            },
64            Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
65        ));
66    }
67
68    // cameras
69    let window = window.single()?;
70    let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
71    let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
72    let mut i = 0;
73    for y in 0..CAMERA_COLS {
74        for x in 0..CAMERA_ROWS {
75            let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
76            commands.spawn((
77                Camera3d::default(),
78                Camera {
79                    viewport: Some(Viewport {
80                        physical_position: UVec2::new(
81                            (x as f32 * width) as u32,
82                            (y as f32 * height) as u32,
83                        ),
84                        physical_size: UVec2::new(width as u32, height as u32),
85                        ..default()
86                    }),
87                    order: i,
88                    ..default()
89                },
90                Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
91                    .looking_at(Vec3::ZERO, Vec3::Y),
92            ));
93            i += 1;
94        }
95    }
96    Ok(())
97}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (line 397)
386fn spawn_birds(
387    commands: &mut Commands,
388    args: &Args,
389    primary_window_resolution: &WindowResolution,
390    counter: &mut BevyCounter,
391    spawn_count: usize,
392    bird_resources: &mut BirdResources,
393    waves_to_simulate: Option<usize>,
394    wave: usize,
395) {
396    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
397    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
398
399    let half_extents = 0.5 * primary_window_resolution.size();
400
401    let color = counter.color;
402    let current_count = counter.count;
403
404    match args.mode {
405        Mode::Sprite => {
406            let batch = (0..spawn_count)
407                .map(|count| {
408                    let bird_z = if args.ordered_z {
409                        (current_count + count) as f32 * 0.00001
410                    } else {
411                        bird_resources.transform_rng.random::<f32>()
412                    };
413
414                    let (transform, velocity) = bird_velocity_transform(
415                        half_extents,
416                        Vec3::new(bird_x, bird_y, bird_z),
417                        &mut bird_resources.velocity_rng,
418                        waves_to_simulate,
419                        FIXED_DELTA_TIME,
420                    );
421
422                    let color = if args.vary_per_instance {
423                        Color::linear_rgb(
424                            bird_resources.color_rng.random(),
425                            bird_resources.color_rng.random(),
426                            bird_resources.color_rng.random(),
427                        )
428                    } else {
429                        color
430                    };
431                    (
432                        Sprite {
433                            image: bird_resources
434                                .textures
435                                .choose(&mut bird_resources.material_rng)
436                                .unwrap()
437                                .clone(),
438                            color,
439                            ..default()
440                        },
441                        transform,
442                        Bird { velocity },
443                    )
444                })
445                .collect::<Vec<_>>();
446            commands.spawn_batch(batch);
447        }
448        Mode::Mesh2d => {
449            let batch = (0..spawn_count)
450                .map(|count| {
451                    let bird_z = if args.ordered_z {
452                        (current_count + count) as f32 * 0.00001
453                    } else {
454                        bird_resources.transform_rng.random::<f32>()
455                    };
456
457                    let (transform, velocity) = bird_velocity_transform(
458                        half_extents,
459                        Vec3::new(bird_x, bird_y, bird_z),
460                        &mut bird_resources.velocity_rng,
461                        waves_to_simulate,
462                        FIXED_DELTA_TIME,
463                    );
464
465                    let material =
466                        if args.vary_per_instance || args.material_texture_count > args.waves {
467                            bird_resources
468                                .materials
469                                .choose(&mut bird_resources.material_rng)
470                                .unwrap()
471                                .clone()
472                        } else {
473                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
474                        };
475                    (
476                        Mesh2d(bird_resources.quad.clone()),
477                        MeshMaterial2d(material),
478                        transform,
479                        Bird { velocity },
480                    )
481                })
482                .collect::<Vec<_>>();
483            commands.spawn_batch(batch);
484        }
485    }
486
487    counter.count += spawn_count;
488    counter.color = Color::linear_rgb(
489        bird_resources.color_rng.random(),
490        bird_resources.color_rng.random(),
491        bird_resources.color_rng.random(),
492    );
493}
Source

pub fn size(&self) -> Vec2

The window’s client size in logical pixels

Examples found in repository?
examples/stress_tests/bevymark.rs (line 399)
386fn spawn_birds(
387    commands: &mut Commands,
388    args: &Args,
389    primary_window_resolution: &WindowResolution,
390    counter: &mut BevyCounter,
391    spawn_count: usize,
392    bird_resources: &mut BirdResources,
393    waves_to_simulate: Option<usize>,
394    wave: usize,
395) {
396    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
397    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
398
399    let half_extents = 0.5 * primary_window_resolution.size();
400
401    let color = counter.color;
402    let current_count = counter.count;
403
404    match args.mode {
405        Mode::Sprite => {
406            let batch = (0..spawn_count)
407                .map(|count| {
408                    let bird_z = if args.ordered_z {
409                        (current_count + count) as f32 * 0.00001
410                    } else {
411                        bird_resources.transform_rng.random::<f32>()
412                    };
413
414                    let (transform, velocity) = bird_velocity_transform(
415                        half_extents,
416                        Vec3::new(bird_x, bird_y, bird_z),
417                        &mut bird_resources.velocity_rng,
418                        waves_to_simulate,
419                        FIXED_DELTA_TIME,
420                    );
421
422                    let color = if args.vary_per_instance {
423                        Color::linear_rgb(
424                            bird_resources.color_rng.random(),
425                            bird_resources.color_rng.random(),
426                            bird_resources.color_rng.random(),
427                        )
428                    } else {
429                        color
430                    };
431                    (
432                        Sprite {
433                            image: bird_resources
434                                .textures
435                                .choose(&mut bird_resources.material_rng)
436                                .unwrap()
437                                .clone(),
438                            color,
439                            ..default()
440                        },
441                        transform,
442                        Bird { velocity },
443                    )
444                })
445                .collect::<Vec<_>>();
446            commands.spawn_batch(batch);
447        }
448        Mode::Mesh2d => {
449            let batch = (0..spawn_count)
450                .map(|count| {
451                    let bird_z = if args.ordered_z {
452                        (current_count + count) as f32 * 0.00001
453                    } else {
454                        bird_resources.transform_rng.random::<f32>()
455                    };
456
457                    let (transform, velocity) = bird_velocity_transform(
458                        half_extents,
459                        Vec3::new(bird_x, bird_y, bird_z),
460                        &mut bird_resources.velocity_rng,
461                        waves_to_simulate,
462                        FIXED_DELTA_TIME,
463                    );
464
465                    let material =
466                        if args.vary_per_instance || args.material_texture_count > args.waves {
467                            bird_resources
468                                .materials
469                                .choose(&mut bird_resources.material_rng)
470                                .unwrap()
471                                .clone()
472                        } else {
473                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
474                        };
475                    (
476                        Mesh2d(bird_resources.quad.clone()),
477                        MeshMaterial2d(material),
478                        transform,
479                        Bird { velocity },
480                    )
481                })
482                .collect::<Vec<_>>();
483            commands.spawn_batch(batch);
484        }
485    }
486
487    counter.count += spawn_count;
488    counter.color = Color::linear_rgb(
489        bird_resources.color_rng.random(),
490        bird_resources.color_rng.random(),
491        bird_resources.color_rng.random(),
492    );
493}
Source

pub fn physical_width(&self) -> u32

The window’s client area width in physical pixels.

Source

pub fn physical_height(&self) -> u32

The window’s client area height in physical pixels.

Source

pub fn physical_size(&self) -> UVec2

The window’s client size in physical pixels

Examples found in repository?
examples/2d/2d_viewport_to_world.rs (line 52)
42fn controls(
43    camera_query: Single<(&mut Camera, &mut Transform, &mut Projection)>,
44    window: Single<&Window>,
45    input: Res<ButtonInput<KeyCode>>,
46    time: Res<Time<Fixed>>,
47) {
48    let (mut camera, mut transform, mut projection) = camera_query.into_inner();
49
50    let fspeed = 600.0 * time.delta_secs();
51    let uspeed = fspeed as u32;
52    let window_size = window.resolution.physical_size();
53
54    // Camera movement controls
55    if input.pressed(KeyCode::ArrowUp) {
56        transform.translation.y += fspeed;
57    }
58    if input.pressed(KeyCode::ArrowDown) {
59        transform.translation.y -= fspeed;
60    }
61    if input.pressed(KeyCode::ArrowLeft) {
62        transform.translation.x -= fspeed;
63    }
64    if input.pressed(KeyCode::ArrowRight) {
65        transform.translation.x += fspeed;
66    }
67
68    // Camera zoom controls
69    if let Projection::Orthographic(projection2d) = &mut *projection {
70        if input.pressed(KeyCode::Comma) {
71            projection2d.scale *= powf(4.0f32, time.delta_secs());
72        }
73
74        if input.pressed(KeyCode::Period) {
75            projection2d.scale *= powf(0.25f32, time.delta_secs());
76        }
77    }
78
79    if let Some(viewport) = camera.viewport.as_mut() {
80        // Viewport movement controls
81        if input.pressed(KeyCode::KeyW) {
82            viewport.physical_position.y = viewport.physical_position.y.saturating_sub(uspeed);
83        }
84        if input.pressed(KeyCode::KeyS) {
85            viewport.physical_position.y += uspeed;
86        }
87        if input.pressed(KeyCode::KeyA) {
88            viewport.physical_position.x = viewport.physical_position.x.saturating_sub(uspeed);
89        }
90        if input.pressed(KeyCode::KeyD) {
91            viewport.physical_position.x += uspeed;
92        }
93
94        // Bound viewport position so it doesn't go off-screen
95        viewport.physical_position = viewport
96            .physical_position
97            .min(window_size - viewport.physical_size);
98
99        // Viewport size controls
100        if input.pressed(KeyCode::KeyI) {
101            viewport.physical_size.y = viewport.physical_size.y.saturating_sub(uspeed);
102        }
103        if input.pressed(KeyCode::KeyK) {
104            viewport.physical_size.y += uspeed;
105        }
106        if input.pressed(KeyCode::KeyJ) {
107            viewport.physical_size.x = viewport.physical_size.x.saturating_sub(uspeed);
108        }
109        if input.pressed(KeyCode::KeyL) {
110            viewport.physical_size.x += uspeed;
111        }
112
113        // Bound viewport size so it doesn't go off-screen
114        viewport.physical_size = viewport
115            .physical_size
116            .min(window_size - viewport.physical_position)
117            .max(UVec2::new(20, 20));
118    }
119}
120
121fn setup(
122    mut commands: Commands,
123    mut meshes: ResMut<Assets<Mesh>>,
124    mut materials: ResMut<Assets<ColorMaterial>>,
125    window: Single<&Window>,
126) {
127    let window_size = window.resolution.physical_size().as_vec2();
128
129    // Initialize centered, non-window-filling viewport
130    commands.spawn((
131        Camera2d,
132        Camera {
133            viewport: Some(Viewport {
134                physical_position: (window_size * 0.125).as_uvec2(),
135                physical_size: (window_size * 0.75).as_uvec2(),
136                ..default()
137            }),
138            ..default()
139        },
140    ));
141
142    // Create a minimal UI explaining how to interact with the example
143    commands.spawn((
144        Text::new(
145            "Move the mouse to see the circle follow your cursor.\n\
146                    Use the arrow keys to move the camera.\n\
147                    Use the comma and period keys to zoom in and out.\n\
148                    Use the WASD keys to move the viewport.\n\
149                    Use the IJKL keys to resize the viewport.",
150        ),
151        Node {
152            position_type: PositionType::Absolute,
153            top: px(12),
154            left: px(12),
155            ..default()
156        },
157    ));
158
159    // Add mesh to make camera movement visible
160    commands.spawn((
161        Mesh2d(meshes.add(Rectangle::new(40.0, 20.0))),
162        MeshMaterial2d(materials.add(Color::from(GREEN))),
163    ));
164
165    // Add background to visualize viewport bounds
166    commands.spawn((
167        Mesh2d(meshes.add(Rectangle::new(50000.0, 50000.0))),
168        MeshMaterial2d(materials.add(Color::linear_rgb(0.01, 0.01, 0.01))),
169        Transform::from_translation(Vec3::new(0.0, 0.0, -200.0)),
170    ));
171}
Source

pub fn scale_factor(&self) -> f32

The ratio of physical pixels to logical pixels.

physical_pixels = logical_pixels * scale_factor

Examples found in repository?
examples/stress_tests/many_cameras_lights.rs (line 70)
34fn setup(
35    mut commands: Commands,
36    mut meshes: ResMut<Assets<Mesh>>,
37    mut materials: ResMut<Assets<StandardMaterial>>,
38    window: Query<&Window>,
39) -> Result {
40    // circular base
41    commands.spawn((
42        Mesh3d(meshes.add(Circle::new(4.0))),
43        MeshMaterial3d(materials.add(Color::WHITE)),
44        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
45    ));
46
47    // cube
48    commands.spawn((
49        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
50        MeshMaterial3d(materials.add(Color::WHITE)),
51        Transform::from_xyz(0.0, 0.5, 0.0),
52    ));
53
54    // lights
55    for i in 0..NUM_LIGHTS {
56        let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
57        commands.spawn((
58            PointLight {
59                color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
60                intensity: 2_000_000.0 / NUM_LIGHTS as f32,
61                shadows_enabled: true,
62                ..default()
63            },
64            Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
65        ));
66    }
67
68    // cameras
69    let window = window.single()?;
70    let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
71    let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
72    let mut i = 0;
73    for y in 0..CAMERA_COLS {
74        for x in 0..CAMERA_ROWS {
75            let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
76            commands.spawn((
77                Camera3d::default(),
78                Camera {
79                    viewport: Some(Viewport {
80                        physical_position: UVec2::new(
81                            (x as f32 * width) as u32,
82                            (y as f32 * height) as u32,
83                        ),
84                        physical_size: UVec2::new(width as u32, height as u32),
85                        ..default()
86                    }),
87                    order: i,
88                    ..default()
89                },
90                Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
91                    .looking_at(Vec3::ZERO, Vec3::Y),
92            ));
93            i += 1;
94        }
95    }
96    Ok(())
97}
Source

pub fn base_scale_factor(&self) -> f32

The window scale factor as reported by the window backend.

This value is unaffected by WindowResolution::scale_factor_override.

Source

pub fn scale_factor_override(&self) -> Option<f32>

The scale factor set with WindowResolution::set_scale_factor_override.

This value may be different from the scale factor reported by the window backend.

Examples found in repository?
examples/window/scale_factor_override.rs (line 69)
62fn display_override(
63    mut window: Single<&mut Window>,
64    mut custom_text: Single<&mut Text, With<CustomText>>,
65) {
66    let text = format!(
67        "Scale factor: {:.1} {}",
68        window.scale_factor(),
69        if window.resolution.scale_factor_override().is_some() {
70            "(overridden)"
71        } else {
72            "(default)"
73        }
74    );
75
76    window.title.clone_from(&text);
77    custom_text.0 = text;
78}
79
80/// This system toggles scale factor overrides when enter is pressed
81fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {
82    if input.just_pressed(KeyCode::Enter) {
83        let scale_factor_override = window.resolution.scale_factor_override();
84        window
85            .resolution
86            .set_scale_factor_override(scale_factor_override.xor(Some(1.0)));
87    }
88}
89
90/// This system changes the scale factor override when up or down is pressed
91fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {
92    let scale_factor_override = window.resolution.scale_factor_override();
93    if input.just_pressed(KeyCode::ArrowUp) {
94        window
95            .resolution
96            .set_scale_factor_override(scale_factor_override.map(|n| n + 1.0));
97    } else if input.just_pressed(KeyCode::ArrowDown) {
98        window
99            .resolution
100            .set_scale_factor_override(scale_factor_override.map(|n| (n - 1.0).max(1.0)));
101    }
102}
Source

pub fn set(&mut self, width: f32, height: f32)

Set the window’s logical resolution.

Examples found in repository?
tests/window/resizing.rs (line 101)
99fn sync_dimensions(dim: Res<Dimensions>, mut window: Single<&mut Window>) {
100    if dim.is_changed() {
101        window.resolution.set(dim.width as f32, dim.height as f32);
102    }
103}
More examples
Hide additional examples
examples/window/window_resizing.rs (line 61)
54fn toggle_resolution(
55    keys: Res<ButtonInput<KeyCode>>,
56    mut window: Single<&mut Window>,
57    resolution: Res<ResolutionSettings>,
58) {
59    if keys.just_pressed(KeyCode::Digit1) {
60        let res = resolution.small;
61        window.resolution.set(res.x, res.y);
62    }
63    if keys.just_pressed(KeyCode::Digit2) {
64        let res = resolution.medium;
65        window.resolution.set(res.x, res.y);
66    }
67    if keys.just_pressed(KeyCode::Digit3) {
68        let res = resolution.large;
69        window.resolution.set(res.x, res.y);
70    }
71}
Source

pub fn set_physical_resolution(&mut self, width: u32, height: u32)

Set the window’s physical resolution.

This will ignore the scale factor setting, so most of the time you should prefer to use WindowResolution::set.

Source

pub fn set_scale_factor(&mut self, scale_factor: f32)

Set the window’s scale factor, this may get overridden by the backend.

Source

pub fn set_scale_factor_override(&mut self, scale_factor_override: Option<f32>)

Set the window’s scale factor, this will be used over what the backend decides.

This can change the logical and physical sizes if the resulting physical size is not within the limits.

Examples found in repository?
examples/window/scale_factor_override.rs (line 86)
81fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {
82    if input.just_pressed(KeyCode::Enter) {
83        let scale_factor_override = window.resolution.scale_factor_override();
84        window
85            .resolution
86            .set_scale_factor_override(scale_factor_override.xor(Some(1.0)));
87    }
88}
89
90/// This system changes the scale factor override when up or down is pressed
91fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {
92    let scale_factor_override = window.resolution.scale_factor_override();
93    if input.just_pressed(KeyCode::ArrowUp) {
94        window
95            .resolution
96            .set_scale_factor_override(scale_factor_override.map(|n| n + 1.0));
97    } else if input.just_pressed(KeyCode::ArrowDown) {
98        window
99            .resolution
100            .set_scale_factor_override(scale_factor_override.map(|n| (n - 1.0).max(1.0)));
101    }
102}

Trait Implementations§

Source§

impl Clone for WindowResolution

Source§

fn clone(&self) -> WindowResolution

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for WindowResolution

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for WindowResolution

Source§

fn default() -> WindowResolution

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for WindowResolution

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<WindowResolution, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<[u32; 2]> for WindowResolution

Source§

fn from(_: [u32; 2]) -> WindowResolution

Converts to this type from the input type.
Source§

impl From<(u32, u32)> for WindowResolution

Source§

fn from(_: (u32, u32)) -> WindowResolution

Converts to this type from the input type.
Source§

impl From<UVec2> for WindowResolution

Source§

fn from(res: UVec2) -> WindowResolution

Converts to this type from the input type.
Source§

impl FromArg for WindowResolution

Source§

type This<'from_arg> = WindowResolution

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<WindowResolution as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for WindowResolution

Source§

fn from_reflect( reflect: &(dyn PartialReflect + 'static), ) -> Option<WindowResolution>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl GetOwnership for WindowResolution

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for WindowResolution

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl IntoReturn for WindowResolution

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where WindowResolution: 'into_return,

Converts Self into a Return value.
Source§

impl PartialEq for WindowResolution

Source§

fn eq(&self, other: &WindowResolution) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialReflect for WindowResolution

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<WindowResolution>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<WindowResolution>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<WindowResolution>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Debug formatter for the value. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails. Read more
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for WindowResolution

Source§

fn into_any(self: Box<WindowResolution>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>. Read more
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<WindowResolution>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl Serialize for WindowResolution

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Struct for WindowResolution

Source§

fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field named name as a &dyn PartialReflect.
Source§

fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field named name as a &mut dyn PartialReflect.
Source§

fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn PartialReflect.
Source§

fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn PartialReflect.
Source§

fn name_at(&self, index: usize) -> Option<&str>

Returns the name of the field with index index.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
Source§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
Source§

fn to_dynamic_struct(&self) -> DynamicStruct

Creates a new DynamicStruct from this struct.
Source§

fn get_represented_struct_info(&self) -> Option<&'static StructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for WindowResolution

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for WindowResolution

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl StructuralPartialEq for WindowResolution

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<S> GetField for S
where S: Struct,

Source§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field named name, downcast to T.
Source§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field named name, downcast to T.
Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of this value.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Reflectable for T

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,