bevy_window_as_ui_root/
lib.rs1use bevy_app::{App, Plugin, Update};
30use bevy_camera::{Camera, Camera2d, RenderTarget};
31use bevy_ecs::{
32 component::Component,
33 lifecycle::HookContext,
34 query::{Changed, With, Without},
35 system::{Commands, Query},
36 world::DeferredWorld,
37};
38use bevy_ecs::{entity::Entity, query::Has, schedule::IntoScheduleConfigs};
39use bevy_ui::{ComputedNode, Node, UiTargetCamera, Val};
40use bevy_window::{Window, WindowRef};
41
42pub struct WindowAsUiRootPlugin;
44
45impl Plugin for WindowAsUiRootPlugin {
46 fn build(&self, app: &mut App) {
47 app.add_systems(Update, (update_resizable, update_size).chain());
48 }
49}
50
51#[derive(Component, Clone, Copy)]
53#[relationship(relationship_target = AlsoClose)]
54pub struct CloseWith(pub Entity);
55
56#[doc(hidden)]
57#[derive(Component, Clone)]
58#[relationship_target(relationship = CloseWith, linked_spawn)]
59pub struct AlsoClose(Vec<Entity>);
60
61#[derive(Component, Clone, Copy, Default)]
69#[require(Window, Node, Camera2d, Camera)]
70#[component(on_add = add_hook)]
71pub struct WindowAsUiRoot;
72
73fn add_hook(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
74 let mut camera = world.get_mut::<Camera>(entity).unwrap();
75 camera.target = RenderTarget::Window(WindowRef::Entity(entity));
76 world
77 .commands()
78 .get_entity(entity)
79 .unwrap()
80 .insert(UiTargetCamera(entity));
81}
82
83#[derive(Component)]
84struct Resizable;
85
86fn update_size(
87 mut windows: Query<
88 (&ComputedNode, &mut Window),
89 (
90 Changed<ComputedNode>,
91 With<WindowAsUiRoot>,
92 Without<Resizable>,
93 ),
94 >,
95) {
96 for (computed_node, mut window) in &mut windows {
97 let size = computed_node.size();
98 if size.x <= 0.0 || size.y <= 0.0 {
99 continue;
100 }
101 window.resolution.set(size.x, size.y);
102 }
103}
104
105fn update_resizable(
106 mut commands: Commands,
107 mut windows: Query<
108 (Entity, &Node, &mut Window, Has<Resizable>),
109 (Changed<Node>, With<WindowAsUiRoot>),
110 >,
111) {
112 for (entity, node, mut window, has_resizable_component) in &mut windows {
113 let resizable = !matches!(node.width, Val::Px(_) | Val::Auto)
114 && !matches!(node.height, Val::Px(_) | Val::Auto);
115
116 if window.resizable != resizable {
117 window.resizable = resizable;
118 }
119
120 if has_resizable_component != resizable {
121 let mut entity_commands = commands.get_entity(entity).unwrap();
122 if resizable {
123 entity_commands.insert(Resizable);
124 } else {
125 entity_commands.remove::<Resizable>();
126 }
127 }
128 }
129}