82 lines
2.0 KiB
Rust
82 lines
2.0 KiB
Rust
use bevy::camera::RenderTarget;
|
|
use bevy::camera::visibility::RenderLayers;
|
|
use bevy::prelude::*;
|
|
use bevy::render::render_resource::TextureFormat;
|
|
|
|
use crate::config::{SCREEN_ASPECT, SCREEN_HEIGHT, SCREEN_WIDTH};
|
|
use crate::gameplay::camera::MainCamera;
|
|
|
|
#[derive(Component)]
|
|
pub struct DisplayScreen;
|
|
|
|
#[derive(Component)]
|
|
pub struct DisplayImage;
|
|
|
|
fn spawn_virtual_screen(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
|
|
let game_image = images.add(Image::new_target_texture(
|
|
SCREEN_WIDTH as u32,
|
|
SCREEN_HEIGHT as u32,
|
|
TextureFormat::Rgba8Unorm,
|
|
Some(TextureFormat::Rgba8UnormSrgb),
|
|
));
|
|
|
|
commands.spawn((
|
|
Camera2d,
|
|
MainCamera,
|
|
IsDefaultUiCamera,
|
|
Camera {
|
|
order: -1,
|
|
clear_color: Color::BLACK.into(),
|
|
..default()
|
|
},
|
|
RenderTarget::Image(game_image.clone().into()),
|
|
));
|
|
|
|
commands.spawn((
|
|
DisplayScreen,
|
|
Camera2d,
|
|
Camera {
|
|
order: 0,
|
|
clear_color: Color::BLACK.into(),
|
|
..default()
|
|
},
|
|
RenderLayers::layer(1),
|
|
));
|
|
|
|
commands.spawn((
|
|
DisplayImage,
|
|
Sprite::from_image(game_image),
|
|
Transform::default(),
|
|
RenderLayers::layer(1),
|
|
));
|
|
}
|
|
|
|
fn fit_display_screen(
|
|
window: Single<&Window>,
|
|
mut sprite: Single<&mut Sprite, With<DisplayImage>>,
|
|
) {
|
|
let scale_factor = window.scale_factor();
|
|
|
|
let win = Vec2::new(
|
|
window.physical_width() as f32 / scale_factor,
|
|
window.physical_height() as f32 / scale_factor,
|
|
);
|
|
|
|
let size = if win.x / win.y > SCREEN_ASPECT {
|
|
Vec2::new(win.y * SCREEN_ASPECT, win.y)
|
|
} else {
|
|
Vec2::new(win.x, win.x / SCREEN_ASPECT)
|
|
};
|
|
|
|
sprite.custom_size = Some(size);
|
|
}
|
|
|
|
pub struct ScreenPlugin;
|
|
|
|
impl Plugin for ScreenPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.add_systems(Startup, spawn_virtual_screen)
|
|
.add_systems(Update, fit_display_screen);
|
|
}
|
|
}
|