cargo fmt

main
Elijah C. Voigt 1 year ago
parent fdce4410db
commit a787e0e6c3

@ -1,12 +1,14 @@
use std::f32::consts::PI; use std::f32::consts::PI;
use bevy::{ use bevy::{
input::common_conditions::input_just_pressed, prelude::*, render::{ input::common_conditions::input_just_pressed,
prelude::*,
render::{
camera::RenderTarget, camera::RenderTarget,
render_resource::{ render_resource::{
Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
}, },
} },
}; };
fn main() { fn main() {
@ -15,8 +17,7 @@ fn main() {
.add_systems(Startup, add_texture) .add_systems(Startup, add_texture)
.add_systems( .add_systems(
Update, Update,
rotate_mesh rotate_mesh.run_if(input_just_pressed(KeyCode::Space)),
.run_if(input_just_pressed(KeyCode::Space)),
) )
.run(); .run();
} }

@ -5,9 +5,15 @@ pub(crate) struct CameraPlugin;
impl Plugin for CameraPlugin { impl Plugin for CameraPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(Update, move_editor_fly_camera); app.add_systems(
app.add_systems(Update, rotate_editor_fly_camera); Update,
} move_editor_fly_camera.run_if(any_with_component::<FlyCamera>),
);
app.add_systems(
Update,
rotate_editor_fly_camera.run_if(any_with_component::<FlyCamera>),
);
}
} }
#[derive(Component)] #[derive(Component)]
@ -16,97 +22,102 @@ pub(crate) struct FlyCamera;
/// Fly camera system for moving around like a drone /// Fly camera system for moving around like a drone
/// TODO: Only if key is pressed! /// TODO: Only if key is pressed!
fn move_editor_fly_camera( fn move_editor_fly_camera(
mut cameras: Query<(&Camera, &mut Transform), With<FlyCamera>>, mut cameras: Query<(&Camera, &mut Transform), With<FlyCamera>>,
windows: Query<&Window>, windows: Query<&Window>,
primary_window: Query<Entity, With<PrimaryWindow>>, primary_window: Query<Entity, With<PrimaryWindow>>,
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
time: Res<Time>, time: Res<Time>,
) { ) {
(keys.any_pressed([ (keys.any_pressed([
KeyCode::KeyW, KeyCode::KeyW,
KeyCode::KeyS, KeyCode::KeyS,
KeyCode::KeyA, KeyCode::KeyA,
KeyCode::KeyD, KeyCode::KeyD,
KeyCode::KeyQ, KeyCode::KeyQ,
KeyCode::KeyE KeyCode::KeyE,
])).then(|| { ]))
// Iterate over all cameras .then(|| {
cameras.iter_mut().for_each(|(c, mut t)| { // Iterate over all cameras
// Determine which window this camera is attached to cameras.iter_mut().for_each(|(c, mut t)| {
let target_window = match c.target { // Determine which window this camera is attached to
RenderTarget::Window(wr) => match wr { let target_window = match c.target {
WindowRef::Entity(e) => Some(e), RenderTarget::Window(wr) => match wr {
WindowRef::Primary => Some(primary_window.get_single().unwrap()), WindowRef::Entity(e) => Some(e),
}, WindowRef::Primary => Some(primary_window.get_single().unwrap()),
_ => None, },
}; _ => None,
let window = windows.get(target_window.unwrap()).unwrap(); };
let window = windows.get(target_window.unwrap()).unwrap();
// If the target window is focused // If the target window is focused
window.focused.then(|| { window.focused.then(|| {
let move_speed = 4.0; let move_speed = 4.0;
let mut delta = Vec3::ZERO; let mut delta = Vec3::ZERO;
if keys.pressed(KeyCode::KeyW) { if keys.pressed(KeyCode::KeyW) {
delta += t.forward() * move_speed * time.delta_seconds() delta += t.forward() * move_speed * time.delta_seconds()
} }
if keys.pressed(KeyCode::KeyS) { if keys.pressed(KeyCode::KeyS) {
delta += t.back() * move_speed * time.delta_seconds() delta += t.back() * move_speed * time.delta_seconds()
} }
if keys.pressed(KeyCode::KeyA) { if keys.pressed(KeyCode::KeyA) {
delta += t.left() * move_speed * time.delta_seconds() delta += t.left() * move_speed * time.delta_seconds()
} }
if keys.pressed(KeyCode::KeyD) { if keys.pressed(KeyCode::KeyD) {
delta += t.right() * move_speed * time.delta_seconds() delta += t.right() * move_speed * time.delta_seconds()
} }
if keys.pressed(KeyCode::KeyE) { if keys.pressed(KeyCode::KeyE) {
delta += Vec3::Y * move_speed * time.delta_seconds() delta += Vec3::Y * move_speed * time.delta_seconds()
} }
if keys.pressed(KeyCode::KeyQ) { if keys.pressed(KeyCode::KeyQ) {
delta += Vec3::NEG_Y * move_speed * time.delta_seconds() delta += Vec3::NEG_Y * move_speed * time.delta_seconds()
} }
t.translation += delta; t.translation += delta;
}); });
}); });
}); });
} }
fn rotate_editor_fly_camera( fn rotate_editor_fly_camera(
mut cameras: Query<(&Camera, &mut Transform), With<FlyCamera>>, mut cameras: Query<(&Camera, &mut Transform), With<FlyCamera>>,
windows: Query<&Window>, windows: Query<&Window>,
primary_window: Query<Entity, With<PrimaryWindow>>, primary_window: Query<Entity, With<PrimaryWindow>>,
mouse: Res<ButtonInput<MouseButton>>, mouse: Res<ButtonInput<MouseButton>>,
mut cursor_events: EventReader<CursorMoved>, mut cursor_events: EventReader<CursorMoved>,
) { ) {
(cursor_events.len() > 0).then(|| { (cursor_events.len() > 0).then(|| {
// Iterate over all cameras // Iterate over all cameras
cameras.iter_mut().for_each(|(c, mut t)| { cameras.iter_mut().for_each(|(c, mut t)| {
// Determine which window this camera is attached to // Determine which window this camera is attached to
let target_window = match c.target { let target_window = match c.target {
RenderTarget::Window(wr) => match wr { RenderTarget::Window(wr) => match wr {
WindowRef::Entity(e) => Some(e), WindowRef::Entity(e) => Some(e),
WindowRef::Primary => Some(primary_window.get_single().unwrap()), WindowRef::Primary => Some(primary_window.get_single().unwrap()),
}, },
_ => None, _ => None,
}; };
let window = windows.get(target_window.unwrap()).unwrap(); let window = windows.get(target_window.unwrap()).unwrap();
if mouse.pressed(MouseButton::Middle) { if mouse.pressed(MouseButton::Middle) {
cursor_events.read().filter_map(|CursorMoved { delta, window, .. }| { cursor_events
(*window == target_window.unwrap()).then_some(delta) .read()
}).for_each(|delta| { .filter_map(|CursorMoved { delta, window, .. }| {
if let Some(Vec2 { x, y }) = delta { (*window == target_window.unwrap()).then_some(delta)
// Cribbing from bevy_flycam })
// Link: https://github.com/sburris0/bevy_flycam/blob/baffe50e0961ad1491d467fa6ab5551f9f21db8f/src/lib.rs#L145-L151 .for_each(|delta| {
let (mut yaw, mut pitch, _) = t.rotation.to_euler(EulerRot::YXZ); if let Some(Vec2 { x, y }) = delta {
let window_scale = window.height().min(window.width()); // Cribbing from bevy_flycam
let sensitivity = 0.00012; // Link: https://github.com/sburris0/bevy_flycam/blob/baffe50e0961ad1491d467fa6ab5551f9f21db8f/src/lib.rs#L145-L151
pitch -= (sensitivity * y * window_scale).to_radians(); let (mut yaw, mut pitch, _) = t.rotation.to_euler(EulerRot::YXZ);
yaw -= (sensitivity * x * window_scale).to_radians(); let window_scale = window.height().min(window.width());
t.rotation = Quat::from_axis_angle(Vec3::Y, yaw) * Quat::from_axis_angle(Vec3::X, pitch); let sensitivity = 0.00012;
} pitch -= (sensitivity * y * window_scale).to_radians();
}); yaw -= (sensitivity * x * window_scale).to_radians();
} else { t.rotation = Quat::from_axis_angle(Vec3::Y, yaw)
cursor_events.clear(); * Quat::from_axis_angle(Vec3::X, pitch);
} }
}); });
}); } else {
} cursor_events.clear();
}
});
});
}

@ -5,117 +5,118 @@ pub(crate) struct EditorPlugin;
impl Plugin for EditorPlugin { impl Plugin for EditorPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_state::<EditorState>(); app.init_state::<EditorState>();
app.add_systems(Startup, init_editor); app.add_systems(Startup, init_editor);
app.add_systems(Update, toggle_editor.run_if(input_just_pressed(KeyCode::F3))); app.add_systems(
app.add_systems(OnEnter(EditorState::Open), open_editor); Update,
app.add_systems(OnExit(EditorState::Open), close_editor); toggle_editor.run_if(input_just_pressed(KeyCode::F3)),
app.add_systems(Update, origin_directions.run_if(in_state(EditorState::Open))); );
app.add_systems(Update, world_plane.run_if(in_state(EditorState::Open))); app.add_systems(OnEnter(EditorState::Open), open_editor);
} app.add_systems(OnExit(EditorState::Open), close_editor);
app.add_systems(
Update,
origin_directions.run_if(in_state(EditorState::Open)),
);
app.add_systems(Update, world_plane.run_if(in_state(EditorState::Open)));
}
} }
/// State tracking if the editor is open /// State tracking if the editor is open
#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default, Component)] #[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default, Component)]
enum EditorState { enum EditorState {
#[default] #[default]
Closed, Closed,
Open, Open,
} }
#[derive(Component)] #[derive(Component)]
struct Editor; struct Editor;
/// Spawns all base editor entities including window, camera, and UI elements /// Spawns all base editor entities including window, camera, and UI elements
fn init_editor( fn init_editor(mut commands: Commands) {
mut commands: Commands // Spawn root editor entity hierarchy
) { commands
// Spawn root editor entity hierarchy .spawn(SpatialBundle { ..default() })
commands.spawn(SpatialBundle { ..default() }) .with_children(|parent| {
.with_children(|parent| { let editor_window = parent
.spawn((
let editor_window = parent.spawn(( Editor,
Editor, Window {
Window { title: "Editor".into(),
title: "Editor".into(), name: Some("Editor".into()),
name: Some("Editor".into()), visible: false,
visible: false, ..default()
..default() },
}, ))
)).id(); .id();
// Spawn editor camera // Spawn editor camera
let _editor_camera = parent.spawn(( let _editor_camera = parent
Editor, .spawn((
FlyCamera, Editor,
Camera3dBundle { FlyCamera,
camera: Camera { Camera3dBundle {
target: RenderTarget::Window(WindowRef::Entity(editor_window)), camera: Camera {
..default() target: RenderTarget::Window(WindowRef::Entity(editor_window)),
}, ..default()
transform: Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y), },
..default() transform: Transform::from_xyz(1.0, 1.0, 1.0)
}, .looking_at(Vec3::ZERO, Vec3::Y),
)).id(); ..default()
}); },
))
.id();
});
} }
fn open_editor( fn open_editor(mut ws: Query<&mut Window, With<Editor>>) {
mut ws: Query<&mut Window, With<Editor>>, ws.iter_mut().for_each(|mut w| {
) { w.visible = true;
ws.iter_mut().for_each(|mut w| { });
w.visible = true;
});
} }
fn close_editor( fn close_editor(mut ws: Query<&mut Window, With<Editor>>) {
mut ws: Query<&mut Window, With<Editor>>, ws.iter_mut().for_each(|mut w| {
) { w.visible = false;
ws.iter_mut().for_each(|mut w| { });
w.visible = false;
});
} }
fn toggle_editor( fn toggle_editor(
state: Res<State<EditorState>>, state: Res<State<EditorState>>,
mut next_state: ResMut<NextState<EditorState>>, mut next_state: ResMut<NextState<EditorState>>,
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut catch: Local<bool>, mut catch: Local<bool>,
) { ) {
if keys.pressed(KeyCode::F3) && !*catch { if keys.pressed(KeyCode::F3) && !*catch {
*catch = true; *catch = true;
match state.get() { match state.get() {
EditorState::Open => next_state.set(EditorState::Closed), EditorState::Open => next_state.set(EditorState::Closed),
EditorState::Closed => next_state.set(EditorState::Open), EditorState::Closed => next_state.set(EditorState::Open),
} }
} else { } else {
*catch = false; *catch = false;
} }
} }
fn origin_directions( fn origin_directions(mut gizmos: Gizmos) {
mut gizmos: Gizmos gizmos.arrow(Vec3::ZERO, Vec3::X, Color::RED);
) { gizmos.arrow(Vec3::ZERO, Vec3::Y, Color::GREEN);
gizmos.arrow(Vec3::ZERO, Vec3::X, Color::RED); gizmos.arrow(Vec3::ZERO, Vec3::Z, Color::BLUE);
gizmos.arrow(Vec3::ZERO, Vec3::Y, Color::GREEN);
gizmos.arrow(Vec3::ZERO, Vec3::Z, Color::BLUE);
} }
fn world_plane( fn world_plane(mut gizmos: Gizmos) {
mut gizmos: Gizmos (-10..=10).into_iter().for_each(|x| {
) { (-10..=10).into_iter().for_each(|z| {
(-10..=10).into_iter().for_each(|x| { {
(-10..=10).into_iter().for_each(|z| { let start = Vec3::new(x as f32, 0.0, -10.0);
{ let end = Vec3::new(x as f32, 0.0, 10.0);
let start = Vec3::new(x as f32, 0.0, -10.0); gizmos.line(start, end, Color::GRAY);
let end = Vec3::new(x as f32, 0.0, 10.0); }
gizmos.line(start, end, Color::GRAY); {
} let start = Vec3::new(-10.0, 0.0, z as f32);
{ let end = Vec3::new(10.0, 0.0, z as f32);
let start = Vec3::new(-10.0, 0.0, z as f32); gizmos.line(start, end, Color::GRAY);
let end = Vec3::new(10.0, 0.0, z as f32); }
gizmos.line(start, end, Color::GRAY); });
} });
}); }
});
}

@ -141,22 +141,20 @@ fn move_die(
}| { }| {
match state { match state {
ButtonState::Pressed => { ButtonState::Pressed => {
q.iter_mut().for_each(|mut t| { q.iter_mut().for_each(|mut t| match key_code {
match key_code { KeyCode::ArrowLeft => {
KeyCode::ArrowLeft => { t.translation -= Vec3::X * time.delta_seconds() * 1000.0
t.translation -= Vec3::X * time.delta_seconds() * 1000.0
}
KeyCode::ArrowRight => {
t.translation += Vec3::X * time.delta_seconds() * 1000.0
}
KeyCode::ArrowDown => {
t.translation -= Vec3::Y * time.delta_seconds() * 1000.0
}
KeyCode::ArrowUp => {
t.translation += Vec3::Y * time.delta_seconds() * 1000.0
}
_ => (),
} }
KeyCode::ArrowRight => {
t.translation += Vec3::X * time.delta_seconds() * 1000.0
}
KeyCode::ArrowDown => {
t.translation -= Vec3::Y * time.delta_seconds() * 1000.0
}
KeyCode::ArrowUp => {
t.translation += Vec3::Y * time.delta_seconds() * 1000.0
}
_ => (),
}); });
} }
_ => (), _ => (),

@ -29,13 +29,14 @@ use crate::prelude::*;
fn main() { fn main() {
let mut app = App::new(); let mut app = App::new();
app.add_plugins(bevy::DefaultPlugins app.add_plugins(
.set(low_latency_window_plugin()) bevy::DefaultPlugins
.set(WindowPlugin { .set(low_latency_window_plugin())
exit_condition: ExitCondition::OnPrimaryClosed, .set(WindowPlugin {
close_when_requested: false, exit_condition: ExitCondition::OnPrimaryClosed,
..default() close_when_requested: false,
}) ..default()
}),
); );
app.add_plugins(bevy_mod_picking::DefaultPickingPlugins); app.add_plugins(bevy_mod_picking::DefaultPickingPlugins);
app.add_plugins(menu::MenuPlugin); app.add_plugins(menu::MenuPlugin);
@ -43,8 +44,9 @@ fn main() {
app.add_plugins(game::GamePlugin); app.add_plugins(game::GamePlugin);
app.add_plugins(editor::EditorPlugin); app.add_plugins(editor::EditorPlugin);
app.add_plugins(camera::CameraPlugin); app.add_plugins(camera::CameraPlugin);
app.add_systems(Update, app.add_systems(
handle_window_close.run_if(on_event::<WindowCloseRequested>()) Update,
handle_window_close.run_if(on_event::<WindowCloseRequested>()),
); );
app.run(); app.run();
} }
@ -75,12 +77,9 @@ fn handle_window_close(
if primary.contains(*window) { if primary.contains(*window) {
commands.entity(*window).remove::<Window>(); commands.entity(*window).remove::<Window>();
} else { } else {
secondary secondary.get_mut(*window).iter_mut().for_each(|w| {
.get_mut(*window) w.visible = false;
.iter_mut() });
.for_each(|w| {
w.visible = false;
});
} }
}); });
} }

@ -2,6 +2,7 @@ pub(crate) use std::fmt::Debug;
/// Bevy imports /// Bevy imports
pub(crate) use bevy::ecs::system::EntityCommand; pub(crate) use bevy::ecs::system::EntityCommand;
pub(crate) use bevy::input::common_conditions::input_just_pressed;
pub(crate) use bevy::input::keyboard::KeyboardInput; pub(crate) use bevy::input::keyboard::KeyboardInput;
pub(crate) use bevy::input::ButtonState; pub(crate) use bevy::input::ButtonState;
pub(crate) use bevy::prelude::*; pub(crate) use bevy::prelude::*;
@ -9,14 +10,14 @@ pub(crate) use bevy::render::camera::RenderTarget;
pub(crate) use bevy::render::render_resource::{ pub(crate) use bevy::render::render_resource::{
Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
}; };
pub(crate) use bevy::window::ExitCondition;
pub(crate) use bevy::window::WindowRef; pub(crate) use bevy::window::WindowRef;
pub(crate) use bevy::window::{PrimaryWindow, WindowCloseRequested}; pub(crate) use bevy::window::{PrimaryWindow, WindowCloseRequested};
pub(crate) use bevy::window::ExitCondition;
pub(crate) use bevy::input::common_conditions::input_just_pressed;
/// Bevy Plugins /// Bevy Plugins
pub(crate) use bevy_mod_picking::prelude::*; pub(crate) use bevy_mod_picking::prelude::*;
pub(crate) use crate::camera::FlyCamera;
/// Intra-project imports /// Intra-project imports
pub(crate) use crate::ecs::schedule::common_conditions::*; pub(crate) use crate::ecs::schedule::common_conditions::*;
pub(crate) use crate::game::GameChoice; pub(crate) use crate::game::GameChoice;
@ -30,4 +31,3 @@ pub(crate) use crate::ui::style::UiStyle;
pub(crate) use crate::ui::title::UiTitle; pub(crate) use crate::ui::title::UiTitle;
pub(crate) use crate::ui::EmitEvent; pub(crate) use crate::ui::EmitEvent;
pub(crate) use crate::ui::SetState; pub(crate) use crate::ui::SetState;
pub(crate) use crate::camera::FlyCamera;

Loading…
Cancel
Save