Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract examples CameraController into a module #11338

Merged
merged 2 commits into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 15 additions & 127 deletions examples/3d/shadow_biases.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
//! Demonstrates how shadow biases affect shadows in a 3d scene.

use std::f32::consts::PI;
#[path = "../helpers/camera_controller.rs"]
mod camera_controller;

use bevy::{input::mouse::MouseMotion, pbr::ShadowFilteringMethod, prelude::*};
use bevy::{pbr::ShadowFilteringMethod, prelude::*};
use camera_controller::{CameraController, CameraControllerPlugin};

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(CameraControllerPlugin)
.add_systems(Startup, setup)
.add_systems(
Update,
Expand All @@ -16,7 +19,6 @@ fn main() {
adjust_point_light_biases,
toggle_light,
adjust_directional_light_biases,
camera_controller,
),
)
.run();
Expand Down Expand Up @@ -135,8 +137,6 @@ fn setup(
.with_children(|c| {
c.spawn(TextBundle::from_sections([
TextSection::new("Controls:\n", style.clone()),
TextSection::new("WSAD - forward/back/strafe left/right\n", style.clone()),
TextSection::new("E / Q - up / down\n", style.clone()),
TextSection::new("R / Z - reset biases to default / zero\n", style.clone()),
TextSection::new(
"L - switch between directional and point lights [",
Expand Down Expand Up @@ -195,15 +195,15 @@ fn toggle_light(
if input.just_pressed(KeyCode::KeyL) {
for mut light in &mut point_lights {
light.intensity = if light.intensity == 0.0 {
example_text.single_mut().sections[5].value = "PointLight".to_string();
example_text.single_mut().sections[3].value = "PointLight".to_string();
100000000.0
} else {
0.0
};
}
for mut light in &mut directional_lights {
light.illuminance = if light.illuminance == 0.0 {
example_text.single_mut().sections[5].value = "DirectionalLight".to_string();
example_text.single_mut().sections[3].value = "DirectionalLight".to_string();
100000.0
} else {
0.0
Expand Down Expand Up @@ -241,9 +241,9 @@ fn adjust_light_position(
for mut light in &mut lights {
light.translation += offset;
light.look_at(Vec3::ZERO, Vec3::Y);
example_text.sections[23].value = format!("{:.1},", light.translation.x);
example_text.sections[24].value = format!(" {:.1},", light.translation.y);
example_text.sections[25].value = format!(" {:.1}", light.translation.z);
example_text.sections[21].value = format!("{:.1},", light.translation.x);
example_text.sections[22].value = format!(" {:.1},", light.translation.y);
example_text.sections[23].value = format!(" {:.1}", light.translation.z);
}
}
}
Expand All @@ -270,7 +270,7 @@ fn cycle_filter_methods(
ShadowFilteringMethod::Hardware2x2
}
};
example_text.single_mut().sections[8].value = filter_method_string;
example_text.single_mut().sections[6].value = filter_method_string;
}
}
}
Expand Down Expand Up @@ -304,8 +304,8 @@ fn adjust_point_light_biases(
light.shadow_normal_bias = 0.0;
}

example_text.single_mut().sections[11].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[14].value = format!("{:.1}", light.shadow_normal_bias);
example_text.single_mut().sections[9].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[12].value = format!("{:.1}", light.shadow_normal_bias);
}
}

Expand Down Expand Up @@ -338,119 +338,7 @@ fn adjust_directional_light_biases(
light.shadow_normal_bias = 0.0;
}

example_text.single_mut().sections[17].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[20].value = format!("{:.1}", light.shadow_normal_bias);
}
}

#[derive(Component)]
struct CameraController {
pub enabled: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}

impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
sensitivity: 0.5,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
walk_speed: 10.0,
run_speed: 30.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}

fn camera_controller(
time: Res<Time>,
mut mouse_events: EventReader<MouseMotion>,
key_input: Res<ButtonInput<KeyCode>>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();

// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}

for (mut transform, mut options) in &mut query {
if !options.enabled {
continue;
}

// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(options.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(options.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(options.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(options.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(options.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(options.key_down) {
axis_input.y -= 1.0;
}

// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(options.key_run) {
options.run_speed
} else {
options.walk_speed
};
options.velocity = axis_input.normalize() * max_speed;
} else {
let friction = options.friction.clamp(0.0, 1.0);
options.velocity *= 1.0 - friction;
if options.velocity.length_squared() < 1e-6 {
options.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += options.velocity.x * dt * right
+ options.velocity.y * dt * Vec3::Y
+ options.velocity.z * dt * forward;

if mouse_delta != Vec2::ZERO {
// Apply look update
options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
.clamp(-PI / 2., PI / 2.);
options.yaw -= mouse_delta.x * options.sensitivity * dt;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
}
example_text.single_mut().sections[15].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[18].value = format!("{:.1}", light.shadow_normal_bias);
}
}
138 changes: 5 additions & 133 deletions examples/3d/skybox.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
//! Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats

#[path = "../helpers/camera_controller.rs"]
mod camera_controller;

use bevy::{
asset::LoadState,
core_pipeline::Skybox,
input::mouse::MouseMotion,
prelude::*,
render::{
render_resource::{TextureViewDescriptor, TextureViewDimension},
renderer::RenderDevice,
texture::CompressedImageFormats,
},
};
use camera_controller::{CameraController, CameraControllerPlugin};
use std::f32::consts::PI;

const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[
Expand All @@ -35,13 +38,13 @@ const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(CameraControllerPlugin)
.add_systems(Startup, setup)
.add_systems(
Update,
(
cycle_cubemap_asset,
asset_loaded.after(cycle_cubemap_asset),
camera_controller,
animate_light_direction,
),
)
Expand Down Expand Up @@ -169,134 +172,3 @@ fn animate_light_direction(
transform.rotate_y(time.delta_seconds() * 0.5);
}
}

#[derive(Component)]
pub struct CameraController {
pub enabled: bool,
pub initialized: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub mouse_key_enable_mouse: MouseButton,
pub keyboard_key_enable_mouse: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}

impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
initialized: false,
sensitivity: 0.5,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
mouse_key_enable_mouse: MouseButton::Left,
keyboard_key_enable_mouse: KeyCode::KeyM,
walk_speed: 2.0,
run_speed: 6.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}

pub fn camera_controller(
time: Res<Time>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut move_toggled: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();

if let Ok((mut transform, mut options)) = query.get_single_mut() {
if !options.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
options.yaw = yaw;
options.pitch = pitch;
options.initialized = true;
}
if !options.enabled {
return;
}

// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(options.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(options.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(options.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(options.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(options.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(options.key_down) {
axis_input.y -= 1.0;
}
if key_input.just_pressed(options.keyboard_key_enable_mouse) {
*move_toggled = !*move_toggled;
}

// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(options.key_run) {
options.run_speed
} else {
options.walk_speed
};
options.velocity = axis_input.normalize() * max_speed;
} else {
let friction = options.friction.clamp(0.0, 1.0);
options.velocity *= 1.0 - friction;
if options.velocity.length_squared() < 1e-6 {
options.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += options.velocity.x * dt * right
+ options.velocity.y * dt * Vec3::Y
+ options.velocity.z * dt * forward;

// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if mouse_button_input.pressed(options.mouse_key_enable_mouse) || *move_toggled {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
}

if mouse_delta != Vec2::ZERO {
// Apply look update
options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
.clamp(-PI / 2., PI / 2.);
options.yaw -= mouse_delta.x * options.sensitivity * dt;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
}
}
}
Loading