pub struct Window {Show 40 fields
pub present_mode: PresentMode,
pub mode: WindowMode,
pub position: WindowPosition,
pub resolution: WindowResolution,
pub title: String,
pub name: Option<String>,
pub composite_alpha_mode: CompositeAlphaMode,
pub resize_constraints: WindowResizeConstraints,
pub resizable: bool,
pub enabled_buttons: EnabledButtons,
pub decorations: bool,
pub transparent: bool,
pub focused: bool,
pub window_level: WindowLevel,
pub canvas: Option<String>,
pub fit_canvas_to_parent: bool,
pub prevent_default_event_handling: bool,
pub internal: InternalWindowState,
pub ime_enabled: bool,
pub ime_position: Vec2,
pub window_theme: Option<WindowTheme>,
pub visible: bool,
pub skip_taskbar: bool,
pub clip_children: bool,
pub desired_maximum_frame_latency: Option<NonZero<u32>>,
pub recognize_pinch_gesture: bool,
pub recognize_rotation_gesture: bool,
pub recognize_doubletap_gesture: bool,
pub recognize_pan_gesture: Option<(u8, u8)>,
pub movable_by_window_background: bool,
pub fullsize_content_view: bool,
pub has_shadow: bool,
pub titlebar_shown: bool,
pub titlebar_transparent: bool,
pub titlebar_show_title: bool,
pub titlebar_show_buttons: bool,
pub borderless_game: bool,
pub prefers_home_indicator_hidden: bool,
pub prefers_status_bar_hidden: bool,
pub preferred_screen_edges_deferring_system_gestures: ScreenEdge,
}Expand description
The defining Component for window entities,
storing information about how it should appear and behave.
Each window corresponds to an entity, and is uniquely identified by the value of their Entity.
When the Window component is added to an entity, a new window will be opened.
When it is removed or the entity is despawned, the window will close.
The primary window entity (and the corresponding window) is spawned by default
by WindowPlugin and is marked with the PrimaryWindow component.
This component is synchronized with winit through bevy_winit:
it will reflect the current state of the window and can be modified to change this state.
§Example
Because this component is synchronized with winit, it can be used to perform
OS-integrated windowing operations. For example, here’s a simple system
to change the window mode:
fn change_window_mode(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
// Query returns one window typically.
for mut window in windows.iter_mut() {
window.mode =
WindowMode::Fullscreen(MonitorSelection::Current, VideoModeSelection::Current);
}
}Fields§
§present_mode: PresentModeWhat presentation mode to give the window.
mode: WindowModeWhich fullscreen or windowing mode should be used.
position: WindowPositionWhere the window should be placed.
resolution: WindowResolutionWhat resolution the window should have.
title: StringStores the title of the window.
name: Option<String>Stores the application ID (on Wayland), WM_CLASS (on X11) or window class name (on Windows) of the window.
For details about application ID conventions, see the Desktop Entry Spec.
For details about WM_CLASS, see the X11 Manual Pages.
For details about Windows’s window class names, see About Window Classes.
§Platform-specific
Windows: Can only be set while building the window, setting the window’s window class name.Wayland: Can only be set while building the window, setting the window’s application ID.X11: Can only be set while building the window, setting the window’sWM_CLASS.macOS,iOS,Android, andWeb: not applicable.
Notes: Changing this field during runtime will have no effect for now.
composite_alpha_mode: CompositeAlphaModeHow the alpha channel of textures should be handled while compositing.
resize_constraints: WindowResizeConstraintsThe limits of the window’s logical size
(found in its resolution) when resizing.
resizable: boolShould the window be resizable?
Note: This does not stop the program from fullscreening/setting the size programmatically.
Specifies which window control buttons should be enabled.
§Platform-specific
iOS, Android, and the Web do not have window control buttons.
On some Linux environments these values have no effect.
decorations: boolShould the window have decorations enabled?
(Decorations are the minimize, maximize, and close buttons on desktop apps)
§Platform-specific
iOS, Android, and the Web do not have decorations.
transparent: boolShould the window be transparent?
Defines whether the background of the window should be transparent.
§Platform-specific
- iOS / Android / Web: Unsupported.
- macOS: Not working as expected.
macOS transparent works with winit out of the box, so this issue might be related to: https://github.com/gfx-rs/wgpu/issues/687.
You should also set the window composite_alpha_mode to CompositeAlphaMode::PostMultiplied.
focused: boolGet/set whether the window is focused.
It cannot be set unfocused after creation.
§Platform-specific
- iOS / Android / X11 / Wayland: Spawning unfocused is not supported.
- iOS / Android / Web / Wayland: Setting focused after creation is not supported.
window_level: WindowLevelWhere should the window appear relative to other overlapping window.
§Platform-specific
- iOS / Android / Web / Wayland: Unsupported.
canvas: Option<String>The “html canvas” element selector.
If set, this selector will be used to find a matching html canvas element, rather than creating a new one. Uses the CSS selector format.
This value has no effect on non-web platforms.
fit_canvas_to_parent: boolWhether or not to fit the canvas element’s size to its parent element’s size.
Warning: this will not behave as expected for parents that set their size according to the size of their children. This creates a “feedback loop” that will result in the canvas growing on each resize. When using this feature, ensure the parent’s size is not affected by its children.
This value has no effect on non-web platforms.
prevent_default_event_handling: boolWhether or not to stop events from propagating out of the canvas element
When true, this will prevent common browser hotkeys like F5, F12, Ctrl+R, tab, etc.
from performing their default behavior while the bevy app has focus.
This value has no effect on non-web platforms.
internal: InternalWindowStateStores internal state that isn’t directly accessible.
ime_enabled: boolShould the window use Input Method Editor?
If enabled, the window will receive Ime events instead of
KeyboardInput from bevy_input.
IME should be enabled during text input, but not when you expect to get the exact key pressed.
§Platform-specific
- iOS / Android / Web: Unsupported.
ime_position: Vec2Sets location of IME candidate box in client area coordinates relative to the top left.
§Platform-specific
- iOS / Android / Web: Unsupported.
window_theme: Option<WindowTheme>Sets a specific theme for the window.
If None is provided, the window will use the system theme.
§Platform-specific
- iOS / Android / Web: Unsupported.
visible: boolSets the window’s visibility.
If false, this will hide the window completely, it won’t appear on the screen or in the task bar.
If true, this will show the window.
Note that this doesn’t change its focused or minimized state.
§Platform-specific
- Android / Wayland / Web: Unsupported.
skip_taskbar: boolSets whether the window should be shown in the taskbar.
If true, the window will not appear in the taskbar.
If false, the window will appear in the taskbar.
Note that this will only take effect on window creation.
§Platform-specific
- Only supported on Windows.
clip_children: boolSets whether the window should draw over its child windows.
If true, the window excludes drawing over areas obscured by child windows.
If false, the window can draw over child windows.
§Platform-specific
- Only supported on Windows.
desired_maximum_frame_latency: Option<NonZero<u32>>Optional hint given to the rendering API regarding the maximum number of queued frames admissible on the GPU.
Given values are usually within the 1-3 range. If not provided, this will default to 2.
See wgpu::SurfaceConfiguration::desired_maximum_frame_latency.
recognize_pinch_gesture: boolSets whether this window recognizes PinchGesture
§Platform-specific
- Only used on iOS.
- On macOS, they are recognized by default and can’t be disabled.
recognize_rotation_gesture: boolSets whether this window recognizes RotationGesture
§Platform-specific
- Only used on iOS.
- On macOS, they are recognized by default and can’t be disabled.
recognize_doubletap_gesture: boolSets whether this window recognizes DoubleTapGesture
§Platform-specific
- Only used on iOS.
- On macOS, they are recognized by default and can’t be disabled.
recognize_pan_gesture: Option<(u8, u8)>Sets whether this window recognizes PanGesture,
with a number of fingers between the first value and the last.
§Platform-specific
- Only used on iOS.
movable_by_window_background: boolEnables click-and-drag behavior for the entire window, not just the titlebar.
Corresponds to WindowAttributesExtMacOS::with_movable_by_window_background.
§Platform-specific
- Only used on macOS.
fullsize_content_view: boolMakes the window content appear behind the titlebar.
Corresponds to WindowAttributesExtMacOS::with_fullsize_content_view.
For apps which want to render the window buttons on top of the apps
itself, this should be enabled along with titlebar_transparent.
§Platform-specific
- Only used on macOS.
has_shadow: boolToggles drawing the drop shadow behind the window.
Corresponds to WindowAttributesExtMacOS::with_has_shadow.
§Platform-specific
- Only used on macOS.
titlebar_shown: boolToggles drawing the titlebar.
Corresponds to WindowAttributesExtMacOS::with_titlebar_hidden.
§Platform-specific
- Only used on macOS.
titlebar_transparent: boolMakes the titlebar transparent, allowing the app content to appear behind it.
Corresponds to WindowAttributesExtMacOS::with_titlebar_transparent.
§Platform-specific
- Only used on macOS.
titlebar_show_title: boolToggles showing the window title.
Corresponds to WindowAttributesExtMacOS::with_title_hidden.
§Platform-specific
- Only used on macOS.
Toggles showing the traffic light window buttons.
Corresponds to WindowAttributesExtMacOS::with_titlebar_buttons_hidden.
§Platform-specific
- Only used on macOS.
borderless_game: boolHides the dock and menu bar when a borderless fullscreen window is active.
Corresponds to WindowAttributesExtMacOS::with_borderless_game.
Defaults to true as this is the expected behavior for games.
§Platform-specific
- Only used on macOS.
Sets whether the Window prefers the home indicator hidden.
Corresponds to WindowAttributesExtIOS::with_prefers_home_indicator_hidden.
§Platform-specific
- Only used on iOS.
Sets whether the Window prefers the status bar hidden.
Corresponds to WindowAttributesExtIOS::with_prefers_status_bar_hidden.
§Platform-specific
- Only used on iOS.
preferred_screen_edges_deferring_system_gestures: ScreenEdgeSets screen edges for which you want your gestures to take precedence over the system gestures.
Corresponds to WindowAttributesExtIOS::with_preferred_screen_edges_deferring_system_gestures.
§Platform-specific
- Only used on iOS.
Implementations§
Source§impl Window
impl Window
Sourcepub fn set_maximized(&mut self, maximized: bool)
pub fn set_maximized(&mut self, maximized: bool)
Setting to true will attempt to maximize the window.
Setting to false will attempt to un-maximize the window.
Sourcepub fn set_minimized(&mut self, minimized: bool)
pub fn set_minimized(&mut self, minimized: bool)
Setting to true will attempt to minimize the window.
Setting to false will attempt to un-minimize the window.
Sourcepub fn start_drag_move(&mut self)
pub fn start_drag_move(&mut self)
Calling this will attempt to start a drag-move of the window.
There is no guarantee that this will work unless the left mouse button was pressed immediately before this function was called.
Examples found in repository?
122fn move_or_resize_windows(
123 mut windows: Query<&mut Window>,
124 action: Res<LeftClickAction>,
125 input: Res<ButtonInput<MouseButton>>,
126 dir: Res<ResizeDir>,
127) {
128 // Both `start_drag_move()` and `start_drag_resize()` must be called after a
129 // left mouse button press as done here.
130 //
131 // winit 0.30.5 may panic when initiated without a left mouse button press.
132 if input.just_pressed(MouseButton::Left) {
133 for mut window in windows.iter_mut() {
134 match *action {
135 LeftClickAction::Nothing => (),
136 LeftClickAction::Move => window.start_drag_move(),
137 LeftClickAction::Resize => {
138 let d = DIRECTIONS[dir.0];
139 window.start_drag_resize(d);
140 }
141 }
142 }
143 }
144}Sourcepub fn start_drag_resize(&mut self, direction: CompassOctant)
pub fn start_drag_resize(&mut self, direction: CompassOctant)
Calling this will attempt to start a drag-resize of the window.
There is no guarantee that this will work unless the left mouse button was pressed immediately before this function was called.
Examples found in repository?
122fn move_or_resize_windows(
123 mut windows: Query<&mut Window>,
124 action: Res<LeftClickAction>,
125 input: Res<ButtonInput<MouseButton>>,
126 dir: Res<ResizeDir>,
127) {
128 // Both `start_drag_move()` and `start_drag_resize()` must be called after a
129 // left mouse button press as done here.
130 //
131 // winit 0.30.5 may panic when initiated without a left mouse button press.
132 if input.just_pressed(MouseButton::Left) {
133 for mut window in windows.iter_mut() {
134 match *action {
135 LeftClickAction::Nothing => (),
136 LeftClickAction::Move => window.start_drag_move(),
137 LeftClickAction::Resize => {
138 let d = DIRECTIONS[dir.0];
139 window.start_drag_resize(d);
140 }
141 }
142 }
143 }
144}Sourcepub fn width(&self) -> f32
pub fn width(&self) -> f32
The window’s client area width in logical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
45fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
46 let Ok(window) = window.single() else {
47 return;
48 };
49 let width = window.width();
50 let height = window.height();
51 let left = width / -2.0;
52 let right = width / 2.0;
53 let bottom = height / -2.0;
54 let top = height / 2.0;
55 // The default batch size can also be overridden.
56 // In this case a batch size of 32 is chosen to limit the overhead of
57 // ParallelIterator, since negating a vector is very inexpensive.
58 sprites
59 .par_iter_mut()
60 .batching_strategy(BatchingStrategy::fixed(32))
61 .for_each(|(transform, mut v)| {
62 if !(left < transform.translation.x
63 && transform.translation.x < right
64 && bottom < transform.translation.y
65 && transform.translation.y < top)
66 {
67 // For simplicity, just reverse the velocity; don't use realistic bounces
68 v.0 = -v.0;
69 }
70 });
71}Sourcepub fn height(&self) -> f32
pub fn height(&self) -> f32
The window’s client area height in logical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
45fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
46 let Ok(window) = window.single() else {
47 return;
48 };
49 let width = window.width();
50 let height = window.height();
51 let left = width / -2.0;
52 let right = width / 2.0;
53 let bottom = height / -2.0;
54 let top = height / 2.0;
55 // The default batch size can also be overridden.
56 // In this case a batch size of 32 is chosen to limit the overhead of
57 // ParallelIterator, since negating a vector is very inexpensive.
58 sprites
59 .par_iter_mut()
60 .batching_strategy(BatchingStrategy::fixed(32))
61 .for_each(|(transform, mut v)| {
62 if !(left < transform.translation.x
63 && transform.translation.x < right
64 && bottom < transform.translation.y
65 && transform.translation.y < top)
66 {
67 // For simplicity, just reverse the velocity; don't use realistic bounces
68 v.0 = -v.0;
69 }
70 });
71}Sourcepub fn size(&self) -> Vec2
pub fn size(&self) -> Vec2
The window’s client size in logical pixels
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
More examples
427fn animate_image_scale(
428 mut animated_images_query: Query<&mut Transform, With<AnimatedImage>>,
429 windows_query: Query<&Window, With<PrimaryWindow>>,
430 app_status: Res<AppStatus>,
431 time: Res<Time>,
432) {
433 let window_size = windows_query.iter().next().unwrap().size();
434 let animated_mesh_size = app_status.animated_mesh_size(window_size);
435
436 for mut animated_image_transform in &mut animated_images_query {
437 animated_image_transform.scale =
438 animated_mesh_size.extend(1.0) * triangle_wave(time.elapsed_secs(), ANIMATION_PERIOD);
439 }
440}
441
442/// Evaluates a [triangle wave] with the given wavelength.
443///
444/// This is used as part of [`animate_image_scale`], to derive the scale from
445/// the current elapsed time.
446///
447/// [triangle wave]: https://en.wikipedia.org/wiki/Triangle_wave#Definition
448fn triangle_wave(time: f32, wavelength: f32) -> f32 {
449 2.0 * ops::abs(time / wavelength - ops::floor(time / wavelength + 0.5))
450}
451
452/// Adds the top mipmap level of the image to [`MipGenerationJobs`].
453///
454/// Note that this must run in the render world, not the main world, as
455/// [`MipGenerationJobs`] is a resource that exists in the former. Consequently,
456/// it must use [`Extract`] to access main world resources.
457fn extract_mipmap_source_image(
458 mipmap_source_image: Extract<Res<MipmapSourceImage>>,
459 app_status: Extract<Res<AppStatus>>,
460 mut mip_generation_jobs: ResMut<MipGenerationJobs>,
461) {
462 if app_status.enable_mip_generation == EnableMipGeneration::On {
463 mip_generation_jobs.add(MIP_GENERATION_PHASE_ID, mipmap_source_image.id());
464 }
465}
466
467/// Updates the widgets at the bottom of the screen to reflect the settings that
468/// the user has chosen.
469fn update_radio_buttons(
470 mut widgets: Query<
471 (
472 Entity,
473 Option<&mut BackgroundColor>,
474 Has<Text>,
475 &WidgetClickSender<AppSetting>,
476 ),
477 Or<(With<RadioButton>, With<RadioButtonText>)>,
478 >,
479 app_status: Res<AppStatus>,
480 mut writer: TextUiWriter,
481) {
482 for (entity, image, has_text, sender) in widgets.iter_mut() {
483 let selected = match **sender {
484 AppSetting::RegenerateTopMipLevel => continue,
485 AppSetting::EnableMipGeneration(enable_mip_generation) => {
486 enable_mip_generation == app_status.enable_mip_generation
487 }
488 AppSetting::ImageWidth(image_width) => image_width == app_status.image_width,
489 AppSetting::ImageHeight(image_height) => image_height == app_status.image_height,
490 };
491
492 if let Some(mut bg_color) = image {
493 widgets::update_ui_radio_button(&mut bg_color, selected);
494 }
495 if has_text {
496 widgets::update_ui_radio_button_text(entity, &mut writer, selected);
497 }
498 }
499}
500
501/// Handles a request from the user to change application settings via the UI.
502///
503/// This also handles clicks on the "Regenerate Top Mip Level" button.
504fn handle_app_setting_change(
505 mut events: MessageReader<WidgetClickEvent<AppSetting>>,
506 mut app_status: ResMut<AppStatus>,
507 mut regenerate_image_message_writer: MessageWriter<RegenerateImage>,
508) {
509 for event in events.read() {
510 // If this is a setting, update the setting. Fall through if, in
511 // addition to updating the setting, we need to regenerate the image.
512 match **event {
513 AppSetting::EnableMipGeneration(enable_mip_generation) => {
514 app_status.enable_mip_generation = enable_mip_generation;
515 continue;
516 }
517
518 AppSetting::RegenerateTopMipLevel => {}
519 AppSetting::ImageWidth(image_size) => app_status.image_width = image_size,
520 AppSetting::ImageHeight(image_size) => app_status.image_height = image_size,
521 }
522
523 // Schedule the image to be regenerated.
524 regenerate_image_message_writer.write(RegenerateImage);
525 }
526}
527
528/// Handles resize events for the window.
529///
530/// Resizing the window invalidates the image and repositions all image views.
531/// (Regenerating the image isn't strictly necessary, but it's simplest to have
532/// a single function that both regenerates the image and recreates the image
533/// views.)
534fn handle_window_resize_events(
535 mut events: MessageReader<WindowResized>,
536 mut regenerate_image_message_writer: MessageWriter<RegenerateImage>,
537) {
538 for _ in events.read() {
539 regenerate_image_message_writer.write(RegenerateImage);
540 }
541}
542
543/// Recreates the image, as well as all views that show the image, when a
544/// [`RegenerateImage`] message is received.
545///
546/// The views that show the image consist of the animated mesh on the left side
547/// of the window and the column of mipmap level views on the right side of the
548/// window.
549fn regenerate_image_when_requested(
550 mut commands: Commands,
551 image_views_query: Query<Entity, With<ImageView>>,
552 windows_query: Query<&Window, With<PrimaryWindow>>,
553 app_assets: Res<AppAssets>,
554 mut app_status: ResMut<AppStatus>,
555 mut images: ResMut<Assets<Image>>,
556 mut single_mip_level_materials: ResMut<Assets<SingleMipLevelMaterial>>,
557 mut color_materials: ResMut<Assets<ColorMaterial>>,
558 mut message_reader: MessageReader<RegenerateImage>,
559) {
560 // Only do this at most once per frame, or else the despawn logic below will
561 // get confused.
562 if message_reader.read().count() == 0 {
563 return;
564 }
565
566 // Despawn all entities that show the image.
567 for entity in image_views_query.iter() {
568 commands.entity(entity).despawn();
569 }
570
571 // Regenerate the image.
572 let image_handle = app_status.regenerate_mipmap_source_image(&mut commands, &mut images);
573
574 // Respawn the animated image view on the left side of the window.
575 spawn_animated_mesh(
576 &mut commands,
577 &app_status,
578 &app_assets,
579 &windows_query,
580 &mut color_materials,
581 &image_handle,
582 );
583
584 // Respawn the column of mip level views on the right side of the window.
585 spawn_mip_level_views(
586 &mut commands,
587 &app_status,
588 &app_assets,
589 &windows_query,
590 &mut single_mip_level_materials,
591 &image_handle,
592 );
593}
594
595/// Spawns the image on the left that continually changes scale.
596///
597/// Continually changing scale effectively cycles though each mip level,
598/// demonstrating the difference between mip level images being present and mip
599/// level image being absent.
600fn spawn_animated_mesh(
601 commands: &mut Commands,
602 app_status: &AppStatus,
603 app_assets: &AppAssets,
604 windows_query: &Query<&Window, With<PrimaryWindow>>,
605 color_materials: &mut Assets<ColorMaterial>,
606 image_handle: &Handle<Image>,
607) {
608 let window_size = windows_query.iter().next().unwrap().size();
609 let animated_mesh_area_size = app_status.animated_mesh_area_size(window_size);
610 let animated_mesh_size = app_status.animated_mesh_size(window_size);
611
612 commands.spawn((
613 Mesh2d(app_assets.rectangle.clone()),
614 MeshMaterial2d(color_materials.add(ColorMaterial {
615 texture: Some(image_handle.clone()),
616 ..default()
617 })),
618 Transform::from_translation(
619 (animated_mesh_area_size * 0.5 - window_size * 0.5).extend(0.0),
620 )
621 .with_scale(animated_mesh_size.extend(1.0)),
622 AnimatedImage,
623 ImageView,
624 ));
625}
626
627/// Creates the column on the right side of the window that displays each mip
628/// level by itself.
629fn spawn_mip_level_views(
630 commands: &mut Commands,
631 app_status: &AppStatus,
632 app_assets: &AppAssets,
633 windows_query: &Query<&Window, With<PrimaryWindow>>,
634 single_mip_level_materials: &mut Assets<SingleMipLevelMaterial>,
635 image_handle: &Handle<Image>,
636) {
637 let window_size = windows_query.iter().next().unwrap().size();
638
639 // Calculate the placement of the column of mipmap levels.
640 let max_slice_size = app_status.max_mip_slice_size(window_size);
641 let y_origin = app_status.vertical_mip_slice_origin(window_size);
642 let y_spacing = app_status.vertical_mip_slice_spacing(window_size);
643 let x_origin = app_status.horizontal_mip_slice_origin(window_size);
644
645 for (mip_level, mip_size) in MipmapSizeIterator::new(app_status).enumerate() {
646 let y_center = y_origin - y_spacing * mip_level as f32;
647
648 // Size each image to fit its container, preserving aspect ratio.
649 let mut slice_size = mip_size.as_vec2();
650 let ratios = max_slice_size / slice_size;
651 let slice_scale = ratios.x.min(ratios.y).min(1.0);
652 slice_size *= slice_scale;
653
654 // Spawn the image. Use the `SingleMipLevelMaterial` with its custom
655 // shader so that only the mip level in question is displayed.
656 commands.spawn((
657 Mesh2d(app_assets.rectangle.clone()),
658 MeshMaterial2d(single_mip_level_materials.add(SingleMipLevelMaterial {
659 mip_level: mip_level as u32,
660 texture: image_handle.clone(),
661 })),
662 Transform::from_xyz(x_origin, y_center, 0.0).with_scale(slice_size.extend(1.0)),
663 ImageView,
664 ));
665
666 // Display a label to the side.
667 commands.spawn((
668 Text2d::new(format!(
669 "Level {}\n{}×{}",
670 mip_level, mip_size.x, mip_size.y
671 )),
672 app_assets.text_font.clone(),
673 TextLayout::justify(Justify::Center),
674 Text2dShadow::default(),
675 Transform::from_xyz(x_origin - max_slice_size.x * 0.5 - 64.0, y_center, 0.0),
676 ImageView,
677 ));
678 }
679}255fn collisions(
256 window: Query<&Window>,
257 mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>,
258 mut rng: ResMut<SharedRng>,
259) {
260 let Ok(window) = window.single() else {
261 return;
262 };
263
264 let window_size = window.size();
265
266 let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.);
267
268 // The maximum height the birbs should try to reach is one birb below the top of the window.
269 let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0);
270 let min_bounce_height = max_bounce_height * 0.4;
271
272 for (mut velocity, mut transform) in &mut query {
273 // Clamp the translation to not go out of the bounds
274 if transform.translation.y < collision_area.min.y {
275 transform.translation.y = collision_area.min.y;
276
277 // How high this birb will bounce.
278 let bounce_height = rng.random_range(min_bounce_height..=max_bounce_height);
279
280 // Apply the velocity that would bounce the birb up to bounce_height.
281 velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt();
282 }
283
284 // Birbs might hit the ceiling if the window is resized.
285 // If they do, bounce them.
286 if transform.translation.y > collision_area.max.y {
287 transform.translation.y = collision_area.max.y;
288 velocity.translation.y *= -1.0;
289 }
290
291 // On side walls flip the horizontal velocity
292 if transform.translation.x < collision_area.min.x {
293 transform.translation.x = collision_area.min.x;
294 velocity.translation.x *= -1.0;
295 velocity.rotation *= -1.0;
296 }
297 if transform.translation.x > collision_area.max.x {
298 transform.translation.x = collision_area.max.x;
299 velocity.translation.x *= -1.0;
300 velocity.rotation *= -1.0;
301 }
302 }
303}Sourcepub fn physical_width(&self) -> u32
pub fn physical_width(&self) -> u32
The window’s client area width in physical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
235fn create_mirror_texture_resource(
236 commands: &mut Commands,
237 windows_query: &Query<&Window>,
238 images: &mut Assets<Image>,
239) -> Handle<Image> {
240 let window = windows_query.iter().next().expect("No window found");
241 let window_size = uvec2(window.physical_width(), window.physical_height());
242 let image = create_mirror_texture_image(images, window_size);
243 commands.insert_resource(MirrorImage(image.clone()));
244 image
245}
246
247/// Spawns the camera that renders the mirror world.
248fn spawn_mirror_camera(
249 commands: &mut Commands,
250 camera_transform: &Transform,
251 camera_projection: &PerspectiveProjection,
252 mirror_transform: &Transform,
253 mirror_render_target: Handle<Image>,
254) {
255 let (mirror_camera_transform, mirror_camera_projection) =
256 calculate_mirror_camera_transform_and_projection(
257 camera_transform,
258 camera_projection,
259 mirror_transform,
260 );
261
262 commands.spawn((
263 Camera3d::default(),
264 Camera {
265 order: -1,
266 // Reflecting the model across the mirror will flip the winding of
267 // all the polygons. Therefore, in order to properly backface cull,
268 // we need to turn on `invert_culling`.
269 invert_culling: true,
270 ..default()
271 },
272 RenderTarget::Image(mirror_render_target.clone().into()),
273 mirror_camera_transform,
274 Projection::Perspective(mirror_camera_projection),
275 MirrorCamera,
276 ));
277}
278
279/// Spawns the animated fox.
280///
281/// Note that this doesn't play the animation; that's handled in
282/// [`play_fox_animation`].
283fn spawn_fox(commands: &mut Commands, asset_server: &AssetServer) {
284 commands.spawn((
285 WorldAssetRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_ASSET_PATH))),
286 Transform::from_xyz(-50.0, 0.0, -100.0),
287 ));
288}
289
290/// Spawns the mirror plane mesh and returns its transform.
291fn spawn_mirror(
292 commands: &mut Commands,
293 meshes: &mut Assets<Mesh>,
294 screen_space_texture_materials: &mut Assets<
295 ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>,
296 >,
297 mirror_render_target: Handle<Image>,
298) -> Transform {
299 let mirror_transform = Transform::from_scale(vec3(300.0, 1.0, 150.0))
300 .with_rotation(Quat::from_rotation_x(MIRROR_ROTATION_ANGLE))
301 .with_translation(MIRROR_POSITION);
302
303 commands.spawn((
304 Mesh3d(meshes.add(Plane3d::default().mesh().size(1.0, 1.0))),
305 MeshMaterial3d(screen_space_texture_materials.add(ExtendedMaterial {
306 base: StandardMaterial {
307 base_color: Color::BLACK,
308 emissive: Color::WHITE.into(),
309 emissive_texture: Some(mirror_render_target),
310 perceptual_roughness: 0.0,
311 metallic: 1.0,
312 ..default()
313 },
314 extension: ScreenSpaceTextureExtension { dummy: 0.0 },
315 })),
316 mirror_transform,
317 Mirror,
318 ));
319
320 mirror_transform
321}
322
323/// Spawns the buttons at the bottom of the screen.
324fn spawn_buttons(commands: &mut Commands) {
325 // Spawn the radio buttons that allow the user to select an object to
326 // control.
327 commands.spawn((
328 widgets::main_ui_node(),
329 children![widgets::option_buttons(
330 "Drag Action",
331 &[
332 (DragAction::MoveCamera, "Move Camera"),
333 (DragAction::MoveFox, "Move Fox"),
334 ],
335 )],
336 ));
337}
338
339/// Given the transform and projection of the main camera, returns an
340/// appropriate transform and projection for the mirror camera.
341fn calculate_mirror_camera_transform_and_projection(
342 main_camera_transform: &Transform,
343 main_camera_projection: &PerspectiveProjection,
344 mirror_transform: &Transform,
345) -> (Transform, PerspectiveProjection) {
346 // Calculate the reflection matrix (a.k.a. Householder matrix) that will
347 // reflect the scene across the mirror plane.
348 //
349 // Note that you must calculate this in *matrix* form and only *afterward*
350 // convert to a `Transform` instead of composing `Transform`s. This is
351 // because the reflection matrix has non-uniform scale, and composing
352 // transforms can't always handle composition of matrices with non-uniform
353 // scales.
354 let mirror_camera_transform = Transform::from_matrix(
355 Mat4::from_mat3a(reflection_matrix(Vec3::NEG_Z)) * main_camera_transform.to_matrix(),
356 );
357
358 // Compute the distance from the camera to the mirror plane. This will be
359 // used to calculate the distance to the near clip plane for the mirror
360 // world.
361 let distance_from_camera_to_mirror = InfinitePlane3d::new(mirror_transform.rotation * Vec3::Y)
362 .signed_distance(
363 Isometry3d::IDENTITY,
364 mirror_transform.translation - main_camera_transform.translation,
365 );
366
367 // Compute the normal of the mirror plane in view space.
368 let view_from_world = main_camera_transform.compute_affine().matrix3.inverse();
369 let mirror_projection_plane_normal =
370 (view_from_world * (mirror_transform.rotation * Vec3::NEG_Y)).normalize();
371
372 // Compute the final projection. It should match the main camera projection,
373 // except that `near` and `near_normal` should be set to the updated near
374 // plane and near normal plane as above.
375 let mirror_camera_projection = PerspectiveProjection {
376 near_clip_plane: mirror_projection_plane_normal.extend(distance_from_camera_to_mirror),
377 ..*main_camera_projection
378 };
379
380 (mirror_camera_transform, mirror_camera_projection)
381}
382
383/// A system that resizes the render target image when the user resizes the window.
384///
385/// Since the image that stores the rendered mirror world has the same physical
386/// size as the window, we need to reallocate it and reattach it to the mirror
387/// material whenever the window size changes.
388fn handle_window_resize_messages(
389 windows_query: Query<&Window>,
390 mut mirror_cameras_query: Query<&mut RenderTarget, With<MirrorCamera>>,
391 mut images: ResMut<Assets<Image>>,
392 mut mirror_image: ResMut<MirrorImage>,
393 mut screen_space_texture_materials: ResMut<
394 Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>,
395 >,
396 mut resize_messages: MessageReader<WindowResized>,
397) {
398 // We run at most once, regardless of the number of window resize messages
399 // there were this frame.
400 let Some(resize_message) = resize_messages.read().next() else {
401 return;
402 };
403 let Ok(window) = windows_query.get(resize_message.window) else {
404 return;
405 };
406
407 let window_size = uvec2(window.physical_width(), window.physical_height());
408 let image = create_mirror_texture_image(&mut images, window_size);
409 images.remove(mirror_image.0.id());
410
411 mirror_image.0 = image.clone();
412
413 for mut target in mirror_cameras_query.iter_mut() {
414 *target = image.clone().into();
415 }
416
417 for (_, material) in screen_space_texture_materials.iter_mut() {
418 material.base.emissive_texture = Some(image.clone());
419 }
420}Sourcepub fn physical_height(&self) -> u32
pub fn physical_height(&self) -> u32
The window’s client area height in physical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
235fn create_mirror_texture_resource(
236 commands: &mut Commands,
237 windows_query: &Query<&Window>,
238 images: &mut Assets<Image>,
239) -> Handle<Image> {
240 let window = windows_query.iter().next().expect("No window found");
241 let window_size = uvec2(window.physical_width(), window.physical_height());
242 let image = create_mirror_texture_image(images, window_size);
243 commands.insert_resource(MirrorImage(image.clone()));
244 image
245}
246
247/// Spawns the camera that renders the mirror world.
248fn spawn_mirror_camera(
249 commands: &mut Commands,
250 camera_transform: &Transform,
251 camera_projection: &PerspectiveProjection,
252 mirror_transform: &Transform,
253 mirror_render_target: Handle<Image>,
254) {
255 let (mirror_camera_transform, mirror_camera_projection) =
256 calculate_mirror_camera_transform_and_projection(
257 camera_transform,
258 camera_projection,
259 mirror_transform,
260 );
261
262 commands.spawn((
263 Camera3d::default(),
264 Camera {
265 order: -1,
266 // Reflecting the model across the mirror will flip the winding of
267 // all the polygons. Therefore, in order to properly backface cull,
268 // we need to turn on `invert_culling`.
269 invert_culling: true,
270 ..default()
271 },
272 RenderTarget::Image(mirror_render_target.clone().into()),
273 mirror_camera_transform,
274 Projection::Perspective(mirror_camera_projection),
275 MirrorCamera,
276 ));
277}
278
279/// Spawns the animated fox.
280///
281/// Note that this doesn't play the animation; that's handled in
282/// [`play_fox_animation`].
283fn spawn_fox(commands: &mut Commands, asset_server: &AssetServer) {
284 commands.spawn((
285 WorldAssetRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_ASSET_PATH))),
286 Transform::from_xyz(-50.0, 0.0, -100.0),
287 ));
288}
289
290/// Spawns the mirror plane mesh and returns its transform.
291fn spawn_mirror(
292 commands: &mut Commands,
293 meshes: &mut Assets<Mesh>,
294 screen_space_texture_materials: &mut Assets<
295 ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>,
296 >,
297 mirror_render_target: Handle<Image>,
298) -> Transform {
299 let mirror_transform = Transform::from_scale(vec3(300.0, 1.0, 150.0))
300 .with_rotation(Quat::from_rotation_x(MIRROR_ROTATION_ANGLE))
301 .with_translation(MIRROR_POSITION);
302
303 commands.spawn((
304 Mesh3d(meshes.add(Plane3d::default().mesh().size(1.0, 1.0))),
305 MeshMaterial3d(screen_space_texture_materials.add(ExtendedMaterial {
306 base: StandardMaterial {
307 base_color: Color::BLACK,
308 emissive: Color::WHITE.into(),
309 emissive_texture: Some(mirror_render_target),
310 perceptual_roughness: 0.0,
311 metallic: 1.0,
312 ..default()
313 },
314 extension: ScreenSpaceTextureExtension { dummy: 0.0 },
315 })),
316 mirror_transform,
317 Mirror,
318 ));
319
320 mirror_transform
321}
322
323/// Spawns the buttons at the bottom of the screen.
324fn spawn_buttons(commands: &mut Commands) {
325 // Spawn the radio buttons that allow the user to select an object to
326 // control.
327 commands.spawn((
328 widgets::main_ui_node(),
329 children![widgets::option_buttons(
330 "Drag Action",
331 &[
332 (DragAction::MoveCamera, "Move Camera"),
333 (DragAction::MoveFox, "Move Fox"),
334 ],
335 )],
336 ));
337}
338
339/// Given the transform and projection of the main camera, returns an
340/// appropriate transform and projection for the mirror camera.
341fn calculate_mirror_camera_transform_and_projection(
342 main_camera_transform: &Transform,
343 main_camera_projection: &PerspectiveProjection,
344 mirror_transform: &Transform,
345) -> (Transform, PerspectiveProjection) {
346 // Calculate the reflection matrix (a.k.a. Householder matrix) that will
347 // reflect the scene across the mirror plane.
348 //
349 // Note that you must calculate this in *matrix* form and only *afterward*
350 // convert to a `Transform` instead of composing `Transform`s. This is
351 // because the reflection matrix has non-uniform scale, and composing
352 // transforms can't always handle composition of matrices with non-uniform
353 // scales.
354 let mirror_camera_transform = Transform::from_matrix(
355 Mat4::from_mat3a(reflection_matrix(Vec3::NEG_Z)) * main_camera_transform.to_matrix(),
356 );
357
358 // Compute the distance from the camera to the mirror plane. This will be
359 // used to calculate the distance to the near clip plane for the mirror
360 // world.
361 let distance_from_camera_to_mirror = InfinitePlane3d::new(mirror_transform.rotation * Vec3::Y)
362 .signed_distance(
363 Isometry3d::IDENTITY,
364 mirror_transform.translation - main_camera_transform.translation,
365 );
366
367 // Compute the normal of the mirror plane in view space.
368 let view_from_world = main_camera_transform.compute_affine().matrix3.inverse();
369 let mirror_projection_plane_normal =
370 (view_from_world * (mirror_transform.rotation * Vec3::NEG_Y)).normalize();
371
372 // Compute the final projection. It should match the main camera projection,
373 // except that `near` and `near_normal` should be set to the updated near
374 // plane and near normal plane as above.
375 let mirror_camera_projection = PerspectiveProjection {
376 near_clip_plane: mirror_projection_plane_normal.extend(distance_from_camera_to_mirror),
377 ..*main_camera_projection
378 };
379
380 (mirror_camera_transform, mirror_camera_projection)
381}
382
383/// A system that resizes the render target image when the user resizes the window.
384///
385/// Since the image that stores the rendered mirror world has the same physical
386/// size as the window, we need to reallocate it and reattach it to the mirror
387/// material whenever the window size changes.
388fn handle_window_resize_messages(
389 windows_query: Query<&Window>,
390 mut mirror_cameras_query: Query<&mut RenderTarget, With<MirrorCamera>>,
391 mut images: ResMut<Assets<Image>>,
392 mut mirror_image: ResMut<MirrorImage>,
393 mut screen_space_texture_materials: ResMut<
394 Assets<ExtendedMaterial<StandardMaterial, ScreenSpaceTextureExtension>>,
395 >,
396 mut resize_messages: MessageReader<WindowResized>,
397) {
398 // We run at most once, regardless of the number of window resize messages
399 // there were this frame.
400 let Some(resize_message) = resize_messages.read().next() else {
401 return;
402 };
403 let Ok(window) = windows_query.get(resize_message.window) else {
404 return;
405 };
406
407 let window_size = uvec2(window.physical_width(), window.physical_height());
408 let image = create_mirror_texture_image(&mut images, window_size);
409 images.remove(mirror_image.0.id());
410
411 mirror_image.0 = image.clone();
412
413 for mut target in mirror_cameras_query.iter_mut() {
414 *target = image.clone().into();
415 }
416
417 for (_, material) in screen_space_texture_materials.iter_mut() {
418 material.base.emissive_texture = Some(image.clone());
419 }
420}Sourcepub fn physical_size(&self) -> UVec2
pub fn physical_size(&self) -> UVec2
The window’s client size in physical pixels
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
159fn set_camera_viewports(
160 windows: Query<&Window>,
161 mut window_resized_reader: MessageReader<WindowResized>,
162 mut query: Query<(&CameraPosition, &mut Camera)>,
163) {
164 // We need to dynamically resize the camera's viewports whenever the window size changes
165 // so then each camera always takes up half the screen.
166 // A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
167 for window_resized in window_resized_reader.read() {
168 let window = windows.get(window_resized.window).unwrap();
169 let size = window.physical_size() / 2;
170
171 for (camera_position, mut camera) in &mut query {
172 camera.viewport = Some(Viewport {
173 physical_position: camera_position.pos * size,
174 physical_size: size,
175 ..default()
176 });
177 }
178 }
179}More examples
255fn resize_viewports(
256 window: Single<&Window, With<bevy::window::PrimaryWindow>>,
257 mut viewports: Query<(&mut Camera, &ExampleViewports)>,
258) {
259 let window_size = window.physical_size();
260
261 let small_height = window_size.y / 5;
262 let small_width = window_size.x / 8;
263
264 let large_height = small_height * 4;
265 let large_width = small_width * 4;
266
267 let large_size = UVec2::new(large_width, large_height);
268
269 // Enforce the aspect ratio of the small viewports to ensure the images
270 // appear unstretched
271 let small_dim = small_height.min(small_width);
272 let small_size = UVec2::new(small_dim, small_dim);
273
274 let small_wide_size = UVec2::new(small_dim * 2, small_dim);
275
276 for (mut camera, example_viewport) in viewports.iter_mut() {
277 if camera.viewport.is_none() {
278 camera.viewport = Some(Viewport::default());
279 };
280
281 let Some(viewport) = &mut camera.viewport else {
282 continue;
283 };
284
285 let (size, position) = match example_viewport {
286 ExampleViewports::PerspectiveMain => (large_size, UVec2::new(0, small_height)),
287 ExampleViewports::PerspectiveStretched => (small_size, UVec2::ZERO),
288 ExampleViewports::PerspectiveMoving => (small_size, UVec2::new(small_width, 0)),
289 ExampleViewports::PerspectiveControl => {
290 (small_wide_size, UVec2::new(small_width * 2, 0))
291 }
292 ExampleViewports::OrthographicMain => {
293 (large_size, UVec2::new(large_width, small_height))
294 }
295 ExampleViewports::OrthographicStretched => (small_size, UVec2::new(small_width * 4, 0)),
296 ExampleViewports::OrthographicMoving => (small_size, UVec2::new(small_width * 5, 0)),
297 ExampleViewports::OrthographicControl => {
298 (small_wide_size, UVec2::new(small_width * 6, 0))
299 }
300 };
301
302 viewport.physical_size = size;
303 viewport.physical_position = position;
304 }
305}738 pub fn setup(
739 mut commands: Commands,
740 mut meshes: ResMut<Assets<Mesh>>,
741 mut materials: ResMut<Assets<StandardMaterial>>,
742 window: Single<&Window, With<PrimaryWindow>>,
743 ) {
744 // circular base
745 commands.spawn((
746 Mesh3d(meshes.add(Circle::new(4.0))),
747 MeshMaterial3d(materials.add(Color::WHITE)),
748 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
749 RenderLayers::layer(0).with(1).with(2),
750 DespawnOnExit(CURRENT_SCENE),
751 ));
752
753 // cubes
754 commands.spawn((
755 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
756 MeshMaterial3d(materials.add(Color::srgb(1.0, 0.0, 0.0))),
757 Transform::from_xyz(-1.5, 0.5, 0.0),
758 // No render layer for this one to test the default case
759 DespawnOnExit(CURRENT_SCENE),
760 ));
761 commands.spawn((
762 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
763 MeshMaterial3d(materials.add(Color::srgb(0.0, 1.0, 0.0))),
764 Transform::from_xyz(0.0, 0.5, 0.0),
765 RenderLayers::layer(1),
766 DespawnOnExit(CURRENT_SCENE),
767 ));
768 commands.spawn((
769 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
770 MeshMaterial3d(materials.add(Color::srgb(0.0, 0.0, 1.0))),
771 Transform::from_xyz(1.5, 0.5, 0.0),
772 RenderLayers::layer(2),
773 DespawnOnExit(CURRENT_SCENE),
774 ));
775
776 // Light
777 commands.spawn((
778 PointLight {
779 shadow_maps_enabled: true,
780 ..default()
781 },
782 Transform::from_xyz(4.0, 8.0, 4.0),
783 DespawnOnExit(CURRENT_SCENE),
784 ));
785
786 let window_half_size = window.physical_size() / 2;
787
788 // Split the screen in 4 different viewports with each of them having a specific render
789 // layer
790 for index in 0..4 {
791 let viewport_pos = UVec2::new((index % 2) as u32, (index / 2) as u32);
792 let mut entity_cmds = commands.spawn((
793 Camera3d::default(),
794 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
795 Camera {
796 // Renders cameras with different priorities to prevent ambiguities
797 order: index as isize,
798 viewport: Some(Viewport {
799 physical_position: viewport_pos * window_half_size,
800 physical_size: window_half_size,
801 ..default()
802 }),
803 ..default()
804 },
805 DespawnOnExit(CURRENT_SCENE),
806 ));
807 match index {
808 0 => {}
809 1 => {
810 entity_cmds.insert(RenderLayers::layer(1));
811 }
812 2 => {
813 entity_cmds.insert(RenderLayers::layer(2));
814 }
815 3 => {
816 entity_cmds.insert(RenderLayers::layer(0).with(1).with(2));
817 }
818 _ => warn!("Unexpected index {index}"),
819 }
820 }
821 }102fn setup(
103 mut commands: Commands,
104 windows: Query<&Window>,
105 mut config_store: ResMut<GizmoConfigStore>,
106 mut meshes: ResMut<Assets<Mesh>>,
107 mut materials: ResMut<Assets<StandardMaterial>>,
108) -> Result {
109 let window = windows.single()?;
110 // The camera that the user controls to observe the scene.
111 let free_camera = commands
112 .spawn((
113 Camera3d::default(),
114 FREE_CAMERA_START_TRANSFORM.looking_at(FREE_CAMERA_START_TARGET, Vec3::Y),
115 FreeCamera::default(),
116 ))
117 .id();
118
119 // The camera that we want to debug frustum culling for. This will be rendered
120 // as a picture-in-picture in the lower right ninth of the screen.
121 let my_camera = commands
122 .spawn((
123 Camera3d::default(),
124 Transform::from_xyz(0., 1.5, 0.).looking_at(Vec3::new(1.0, 1.5, 0.), Vec3::Y),
125 Camera {
126 order: 1,
127 // The camera-to-debug's view will be in the lower right ninth of the screen.
128 viewport: Some(Viewport {
129 physical_position: window.physical_size() * 2 / 3,
130 physical_size: window.physical_size() / 3,
131 ..default()
132 }),
133 // Do not write the free camera's view rendering back into the P-I-P
134 msaa_writeback: MsaaWriteback::Off,
135 ..default()
136 },
137 MyCamera,
138 ))
139 .id();
140
141 // Instructions placed on top of the free_camera view
142 commands.spawn((
143 UiTargetCamera(free_camera),
144 Node {
145 width: percent(100),
146 height: percent(100),
147 ..default()
148 },
149 children![(
150 Text::new(
151 "This example utilizes free camera controls i.e. move with WASD and mouse grab to change orientation.\n\
152 Press '1' to move the free camera to where MyCamera is, matching its view frustum.\n\
153 Press '2' to move the free camera to its initial position in the example.",
154 ),
155 Node {
156 position_type: PositionType::Absolute,
157 top: px(12),
158 left: px(12),
159 ..default()
160 },
161 )]
162 ));
163 // Label for the picture-in-picture view of MyCamera
164 commands.spawn((
165 UiTargetCamera(my_camera),
166 Node {
167 width: percent(100),
168 height: percent(100),
169 ..default()
170 },
171 children![(
172 Text::new("View of MyCamera"),
173 Node {
174 position_type: PositionType::Absolute,
175 bottom: px(12),
176 right: px(100),
177 ..default()
178 },
179 )],
180 ));
181
182 // Green Floor Plane
183 commands.spawn((
184 Mesh3d(
185 meshes.add(
186 Plane3d::default()
187 .mesh()
188 .size(SHAPE_RING_RADIUS * 4., SHAPE_RING_RADIUS * 4.),
189 ),
190 ),
191 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
192 ));
193 // Blue Wall Plane
194 commands.spawn((
195 Mesh3d(meshes.add(Plane3d::default().mesh().size(5., 5.))),
196 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.3, 0.5))),
197 Transform::from_xyz(20., 2.5, 10.).with_rotation(Quat::from_rotation_z(PI / 2.)),
198 ));
199 // Light
200 commands.spawn((
201 PointLight {
202 shadow_maps_enabled: true,
203 ..default()
204 },
205 Transform::from_xyz(0.0, 10.0, 0.0),
206 ));
207
208 // Configure all AABB's to have a default color of red
209 let (_, aabb_gizmo_config) = config_store.config_mut::<AabbGizmoConfigGroup>();
210 aabb_gizmo_config.default_color = Some(Color::LinearRgba(LinearRgba::RED));
211
212 // Configure the shapes on the ring that will have their AABB's drawn and updated
213 let white_matl = materials.add(Color::WHITE);
214 let shapes = [
215 meshes.add(Cuboid {
216 half_size: Vec3::new(2., 0.5, 1.),
217 }),
218 meshes.add(Tetrahedron {
219 vertices: [
220 Vec3::new(3., 4., 3.),
221 Vec3::new(-0.5, 4., -0.5),
222 Vec3::new(-0.5, -0.5, 3.),
223 Vec3::new(3., -0.5, -0.5),
224 ],
225 }),
226 meshes.add(Cylinder {
227 radius: 0.1,
228 half_height: 1.5,
229 }),
230 meshes.add(Cuboid {
231 half_size: Vec3::new(1., 0.1, 2.),
232 }),
233 meshes.add(Sphere::default().mesh().ico(5).unwrap()),
234 ];
235 let shapes_len = shapes.len() as f32;
236 let mut shape_ring = commands.spawn((Transform::default(), Visibility::default(), ShapeRing));
237 for (i, shape) in shapes.into_iter().enumerate() {
238 // Space the shapes out evenly along the ring
239 let shape_angle = i as f32 * 2. * PI / shapes_len;
240 let (s, c) = ops::sin_cos(shape_angle);
241 let (x, z) = (SHAPE_RING_RADIUS * c, SHAPE_RING_RADIUS * s);
242 shape_ring.with_child((
243 Mesh3d(shape),
244 MeshMaterial3d(white_matl.clone()),
245 Transform::from_xyz(x, 1.5, z).with_rotation(Quat::from_rotation_x(-PI / 4.)),
246 MyShape,
247 ));
248 }
249
250 // Configure the shape that peeks out of the wall plane
251 let wall_shape = meshes.add(Torus::default());
252 commands.spawn((
253 Mesh3d(wall_shape),
254 MeshMaterial3d(white_matl.clone()),
255 Transform::from_xyz(25., 1.5, 12.5).with_rotation(Quat::from_rotation_x(-PI / 4.)),
256 WallShape,
257 ));
258
259 Ok(())
260}Sourcepub fn scale_factor(&self) -> f32
pub fn scale_factor(&self) -> f32
The window’s scale factor.
Ratio of physical size to logical size, see WindowResolution.
Examples found in repository?
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}Sourcepub fn cursor_position(&self) -> Option<Vec2>
pub fn cursor_position(&self) -> Option<Vec2>
The cursor position in this window in logical pixels.
Returns None if the cursor is outside the window area.
See WindowResolution for an explanation about logical/physical sizes.
Examples found in repository?
205fn get_cursor_world_pos(
206 mut cursor_world_pos: ResMut<CursorWorldPos>,
207 primary_window: Single<&Window, With<PrimaryWindow>>,
208 q_camera: Single<(&Camera, &GlobalTransform)>,
209) {
210 let (main_camera, main_camera_transform) = *q_camera;
211 // Get the cursor position in the world
212 cursor_world_pos.0 = primary_window.cursor_position().and_then(|cursor_pos| {
213 main_camera
214 .viewport_to_world_2d(main_camera_transform, cursor_pos)
215 .ok()
216 });
217}More examples
190fn handle_click(
191 mouse_button_input: Res<ButtonInput<MouseButton>>,
192 camera: Single<(&Camera, &GlobalTransform)>,
193 windows: Query<&Window>,
194 mut commands: Commands,
195) {
196 let Ok(windows) = windows.single() else {
197 return;
198 };
199
200 let (camera, camera_transform) = *camera;
201 if let Some(pos) = windows
202 .cursor_position()
203 .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
204 .map(|ray| ray.origin.truncate())
205 && mouse_button_input.just_pressed(MouseButton::Left)
206 {
207 commands.trigger(ExplodeMines { pos, radius: 1.0 });
208 }
209}22fn draw_cursor(
23 camera_query: Single<(&Camera, &GlobalTransform)>,
24 window: Single<&Window>,
25 mut gizmos: Gizmos,
26) {
27 let (camera, camera_transform) = *camera_query;
28
29 if let Some(cursor_position) = window.cursor_position()
30 // Calculate a world position based on the cursor's position.
31 && let Ok(world_pos) = camera.viewport_to_world_2d(camera_transform, cursor_position)
32 // To test Camera::world_to_viewport, convert result back to viewport space and then back to world space.
33 && let Ok(viewport_check) = camera.world_to_viewport(camera_transform, world_pos.extend(0.0))
34 && let Ok(world_check) = camera.viewport_to_world_2d(camera_transform, viewport_check.xy())
35 {
36 gizmos.circle_2d(world_pos, 10., WHITE);
37 // Should be the same as world_pos
38 gizmos.circle_2d(world_check, 8., RED);
39 }
40}38fn player_movement_system(
39 mut player: Single<&mut Transform, With<Player>>,
40 camera_query: Single<(&Camera, &GlobalTransform)>,
41 window: Single<&Window>,
42) {
43 let (camera, camera_transform) = *camera_query;
44
45 if let Some(cursor_position) = window.cursor_position()
46 // Calculate a world position based on the cursor's position.
47 && let Ok(cursor_world_pos) = camera.viewport_to_world_2d(camera_transform, cursor_position)
48 {
49 // The angle an entity needs to rotate to face a point is defined
50 // by the vector between the two points (Vec2 - Vec2), which we can then
51 // turn into radians using to_angle.
52 //
53 // FRAC_PI_2 is because our sprite's ship is facing "up" so we rotate it an additional 90 degrees
54 // so that it faces the cursor.
55 player.rotation = Quat::from_rotation_z(
56 (cursor_world_pos - player.translation.xy()).to_angle() - FRAC_PI_2,
57 );
58 }
59}13fn draw_cursor(
14 camera_query: Single<(&Camera, &GlobalTransform)>,
15 ground: Single<&GlobalTransform, With<Ground>>,
16 window: Single<&Window>,
17 mut gizmos: Gizmos,
18) {
19 let (camera, camera_transform) = *camera_query;
20
21 if let Some(cursor_position) = window.cursor_position()
22 // Calculate a ray pointing from the camera into the world based on the cursor's position.
23 && let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position)
24 // Calculate if and where the ray is hitting the ground plane.
25 && let Some(point) = ray.plane_intersection_point(ground.translation(), InfinitePlane3d::new(ground.up()))
26 {
27 // Draw a circle just above the ground plane at that position.
28 gizmos.circle(
29 Isometry3d::new(
30 point + ground.up() * 0.01,
31 Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()),
32 ),
33 0.2,
34 Color::WHITE,
35 );
36 }
37}Sourcepub fn physical_cursor_position(&self) -> Option<Vec2>
pub fn physical_cursor_position(&self) -> Option<Vec2>
The cursor position in this window in physical pixels.
Returns None if the cursor is outside the window area.
See WindowResolution for an explanation about logical/physical sizes.
Sourcepub fn set_cursor_position(&mut self, position: Option<Vec2>)
pub fn set_cursor_position(&mut self, position: Option<Vec2>)
Set the cursor position in this window in logical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Sourcepub fn set_physical_cursor_position(&mut self, position: Option<DVec2>)
pub fn set_physical_cursor_position(&mut self, position: Option<DVec2>)
Set the cursor position in this window in physical pixels.
See WindowResolution for an explanation about logical/physical sizes.
Trait Implementations§
Source§impl Component for Window
Required Components: CursorOptions.
impl Component for Window
Required Components: CursorOptions.
A component’s Required Components are inserted whenever it is inserted. Note that this will also insert the required components of the required components, recursively, in depth-first order.
Source§const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table
const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table
Source§type Mutability = Mutable
type Mutability = Mutable
Component<Mutability = Mutable>,
while immutable components will instead have Component<Mutability = Immutable>. Read moreSource§fn register_required_components(
_requiree: ComponentId,
required_components: &mut RequiredComponentsRegistrator<'_, '_>,
)
fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )
Source§fn clone_behavior() -> ComponentCloneBehavior
fn clone_behavior() -> ComponentCloneBehavior
Source§fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Window>>
fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Window>>
ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read moreSource§fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
EntityMapper. This is used to remap entities in contexts like scenes and entity cloning.
When deriving Component, this is populated by annotating fields containing entities with #[entities] Read moreSource§impl<'de> Deserialize<'de> for Window
impl<'de> Deserialize<'de> for Window
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<Window, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<Window, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Source§impl FromReflect for Window
impl FromReflect for Window
Source§fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Window>
fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Window>
Self from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self using,
constructing the value using from_reflect if that fails. Read moreSource§impl GetTypeRegistration for Window
impl GetTypeRegistration for Window
Source§fn get_type_registration() -> TypeRegistration
fn get_type_registration() -> TypeRegistration
TypeRegistration for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl IntoReturn for Window
impl IntoReturn for Window
Source§impl PartialReflect for Window
impl PartialReflect for Window
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn try_apply(
&mut self,
value: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<Window>) -> ReflectOwned
fn reflect_owned(self: Box<Window>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<Window>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<Window>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<Window>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<Window>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn reflect_partial_cmp(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<Ordering>
fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
Self using reflection. Read moreSource§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
Source§fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
PartialReflect, combines reflect_clone and
take in a useful fashion, automatically constructing an appropriate
ReflectCloneError if the downcast fails.Source§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for Window
impl Reflect for Window
Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any. Read moreSource§fn into_reflect(self: Box<Window>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Window>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl Serialize for Window
impl Serialize for Window
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Source§impl Struct for Window
impl Struct for Window
Source§fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>
fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>
name as a &dyn PartialReflect.Source§fn field_mut(
&mut self,
name: &str,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>
name as a
&mut dyn PartialReflect.Source§fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
index as a
&dyn PartialReflect.Source§fn field_at_mut(
&mut self,
index: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
index
as a &mut dyn PartialReflect.Source§fn index_of_name(&self, name: &str) -> Option<usize>
fn index_of_name(&self, name: &str) -> Option<usize>
Source§fn iter_fields(&self) -> FieldIter<'_> ⓘ
fn iter_fields(&self) -> FieldIter<'_> ⓘ
Source§fn to_dynamic_struct(&self) -> DynamicStruct
fn to_dynamic_struct(&self) -> DynamicStruct
DynamicStruct from this struct.Source§fn get_represented_struct_info(&self) -> Option<&'static StructInfo>
fn get_represented_struct_info(&self) -> Option<&'static StructInfo>
None if TypeInfo is not available.Source§impl TypePath for Window
impl TypePath for Window
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
Auto Trait Implementations§
impl Freeze for Window
impl RefUnwindSafe for Window
impl Send for Window
impl Sync for Window
impl Unpin for Window
impl UnsafeUnpin for Window
impl UnwindSafe for Window
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>
Source§fn get_component_ids(
components: &Components,
) -> impl Iterator<Item = Option<ComponentId>>
fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>
Source§impl<C> BundleFromComponents for Cwhere
C: Component,
impl<C> BundleFromComponents for Cwhere
C: Component,
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ConditionalSend for Twhere
T: Send,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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 Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
impl<S, T> Duplex<S> for Twhere
T: FromSample<S> + ToSample<S>,
Source§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
Source§unsafe fn get_components(
ptr: MovingPtr<'_, C>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
) -> <C as DynamicBundle>::Effect
unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect
Source§unsafe fn apply_effect(
_ptr: MovingPtr<'_, MaybeUninit<C>>,
_entity: &mut EntityWorldMut<'_>,
)
unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info.Source§impl<T> ErasedBundleTemplate for T
impl<T> ErasedBundleTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
Clone.Source§impl<T> ErasedComponentTemplate for T
impl<T> ErasedComponentTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
bundle_writer: &mut BundleWriter<'_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>
fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>
Clone.impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromTemplate for T
impl<T> FromTemplate for T
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self using default().
Source§impl<S> GetField for Swhere
S: Struct,
impl<S> GetField for Swhere
S: Struct,
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path. Read moreSource§impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T> HitDataExtra for T
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<G> PatchFromTemplate for Gwhere
G: FromTemplate,
impl<G> PatchFromTemplate for Gwhere
G: FromTemplate,
Source§fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
func, and turns it into a TemplatePatch.Source§impl<T> PatchTemplate for Twhere
T: Template,
impl<T> PatchTemplate for Twhere
T: Template,
Source§fn patch_template<F>(func: F) -> TemplatePatch<F, T>
fn patch_template<F>(func: F) -> TemplatePatch<F, T>
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
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
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
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
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian().impl<T> Reflectable for T
Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
impl<T> Settings for T
Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.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
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.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
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.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
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.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
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.Source§impl<T> Template for T
impl<T> Template for T
Source§fn build_template(
&self,
_context: &mut TemplateContext<'_, '_>,
) -> Result<<T as Template>::Output, BevyError>
fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>
entity context to produce a Template::Output.Source§fn clone_template(&self) -> T
fn clone_template(&self) -> T
Clone.