move some stuff out of testbed into lyra-game

This commit is contained in:
SeanOMik 2024-03-22 22:55:22 -04:00
parent 0f11fe2e6d
commit 763d51ae36
Signed by: SeanOMik
GPG Key ID: FEC9E2FC15235964
4 changed files with 103 additions and 190 deletions

View File

@ -13,4 +13,3 @@ lyra-engine = { path = "../../", version = "0.0.1" }
anyhow = "1.0.75"
async-std = "1.12.0"
tracing = "0.1.37"
fps_counter = "2.0.0"

View File

@ -1,106 +0,0 @@
use lyra_engine::{
ecs::{query::{Res, View}, Component}, game::Game, input::ActionHandler, math::{EulerRot, Quat, Vec3}, plugin::Plugin, scene::CameraComponent, DeltaTime
};
/* enum FreeFlyCameraActions {
MoveForwardBackward,
MoveLeftRight,
MoveUpDown,
LookLeftRight,
LookUpDown,
LookRoll,
} */
#[derive(Clone, Component)]
pub struct FreeFlyCamera {
pub speed: f32,
pub slow_speed_factor: f32,
pub look_speed: f32,
pub mouse_sensitivity: f32,
pub look_with_keys: bool,
}
impl Default for FreeFlyCamera {
fn default() -> Self {
Self {
speed: 4.0,
slow_speed_factor: 0.25,
look_speed: 0.5,
mouse_sensitivity: 0.9,
look_with_keys: false,
}
}
}
impl FreeFlyCamera {
#[allow(dead_code)]
pub fn new(speed: f32, slow_speed_factor: f32, look_speed: f32, mouse_sensitivity: f32, look_with_keys: bool) -> Self {
Self {
speed,
slow_speed_factor,
look_speed,
mouse_sensitivity,
look_with_keys,
}
}
}
pub fn free_fly_camera_controller(delta_time: Res<DeltaTime>, handler: Res<ActionHandler>, view: View<(&mut CameraComponent, &FreeFlyCamera)>) -> anyhow::Result<()> {
let delta_time = **delta_time;
for (mut cam, fly) in view.into_iter() {
let forward = cam.transform.forward();
let left = cam.transform.left();
let up = Vec3::Y;
let move_y = handler.get_axis_modifier("MoveUpDown").unwrap_or(0.0);
let move_x = handler.get_axis_modifier("MoveLeftRight").unwrap_or(0.0);
let move_z = handler.get_axis_modifier("MoveForwardBackward").unwrap_or(0.0);
let mut velocity = Vec3::ZERO;
velocity += move_y * up;
velocity += move_x * left;
velocity += move_z * forward;
if velocity != Vec3::ZERO {
cam.transform.translation += velocity.normalize() * fly.speed * delta_time; // TODO: speeding up
}
let motion_x = handler.get_axis_modifier("LookLeftRight").unwrap_or(0.0);
let motion_y = handler.get_axis_modifier("LookUpDown").unwrap_or(0.0);
let motion_z = handler.get_axis_modifier("LookRoll").unwrap_or(0.0);
let mut camera_rot = Vec3::ZERO;
camera_rot.y -= motion_x * fly.mouse_sensitivity;
camera_rot.x -= motion_y * fly.mouse_sensitivity;
camera_rot.z -= motion_z * fly.mouse_sensitivity;
if camera_rot != Vec3::ZERO {
let look_velocity = camera_rot * fly.look_speed * delta_time;
let (mut y, mut x, _) = cam.transform.rotation.to_euler(EulerRot::YXZ);
x += look_velocity.x;
y += look_velocity.y;
x = x.clamp(-1.54, 1.54);
// rotation is not commutative, keep this order to avoid unintended roll
cam.transform.rotation = Quat::from_axis_angle(Vec3::Y, y)
* Quat::from_axis_angle(Vec3::X, x);
}
if handler.was_action_just_pressed("Debug") {
cam.debug = !cam.debug;
}
}
Ok(())
}
/// A plugin that adds the free fly camera controller system to the world. It is expected that
/// there is a [`FreeFlyCamera`] in the world, if there isn't, the camera would not move.
pub struct FreeFlyCameraPlugin;
impl Plugin for FreeFlyCameraPlugin {
fn setup(&self, game: &mut Game) {
game.with_system("free_fly_camera_system", free_fly_camera_controller, &[]);
}
}

View File

@ -1,29 +1,8 @@
use std::{cell::Ref, ptr::NonNull};
use std::ptr::NonNull;
use lyra_engine::{assets::gltf::Gltf, change_tracker::Ct, ecs::{query::{QueryBorrow, ViewState}, system::{BatchedSystem, Criteria, CriteriaSchedule, IntoSystem}, Component, World}, game::Game, input::{Action, ActionHandler, ActionKind, ActionMapping, ActionMappingId, ActionSource, InputActionPlugin, KeyCode, LayoutId, MouseAxis, MouseInput}, math::{self, Quat, Transform, Vec3}, render::{light::{directional::DirectionalLight, PointLight, SpotLight}, window::{CursorGrabMode, WindowOptions}}, scene::CameraComponent, DeltaTime};
use lyra_engine::{assets::gltf::Gltf, change_tracker::Ct, ecs::{query::{QueryBorrow, Res, View, ViewState}, system::{BatchedSystem, Criteria, CriteriaSchedule, IntoSystem}, Component, World}, game::Game, input::{Action, ActionHandler, ActionKind, ActionMapping, ActionMappingId, ActionSource, InputActionPlugin, KeyCode, LayoutId, MouseAxis, MouseInput}, math::{self, Quat, Transform, Vec3}, render::{light::{directional::DirectionalLight, PointLight, SpotLight}, window::{CursorGrabMode, WindowOptions}}, scene::{CameraComponent, FreeFlyCamera, FreeFlyCameraPlugin, ACTLBL_LOOK_LEFT_RIGHT, ACTLBL_LOOK_ROLL, ACTLBL_LOOK_UP_DOWN, ACTLBL_MOVE_FORWARD_BACKWARD, ACTLBL_MOVE_LEFT_RIGHT, ACTLBL_MOVE_UP_DOWN}, DeltaTime};
use lyra_engine::assets::ResourceManager;
mod free_fly_camera;
use free_fly_camera::{FreeFlyCameraPlugin, FreeFlyCamera};
#[derive(Clone, Copy, Hash, Debug)]
pub enum ActionLabel {
MoveForwardBackward,
MoveLeftRight,
MoveUpDown,
LookLeftRight,
LookUpDown,
LookRoll,
}
const ACTLBL_MOVE_UP_DOWN: &str = "MoveUpDown";
const ACTLBL_MOVE_LEFT_RIGHT: &str = "MoveLeftRight";
const ACTLBL_MOVE_FORWARD_BACKWARD: &str = "MoveForwardBackward";
const ACTLBL_LOOK_LEFT_RIGHT: &str = "LookLeftRight";
const ACTLBL_LOOK_UP_DOWN: &str = "LookUpDown";
const ACTLBL_LOOK_ROLL: &str = "LookRoll";
const ACTLBL_DEBUG: &str = "Debug";
struct FixedTimestep {
max_tps: u32,
fixed_time: f32,
@ -254,52 +233,18 @@ async fn main() {
Ok(())
};
#[allow(unused_variables)]
let fps_system = |world: &mut World| -> anyhow::Result<()> {
let mut counter = world.get_resource_mut::<fps_counter::FPSCounter>();
let camera_debug_plugin = move |game: &mut Game| {
let sys = |handler: Res<ActionHandler>, view: View<&mut CameraComponent>| -> anyhow::Result<()> {
if handler.was_action_just_pressed("Debug") {
for mut cam in view.into_iter() {
cam.debug = !cam.debug;
}
}
let fps = counter.tick();
Ok(())
};
println!("FPS: {fps}");
Ok(())
};
let _fps_plugin = move |game: &mut Game| {
let world = game.world_mut();
world.add_resource(fps_counter::FPSCounter::new());
};
let spin_system = |world: &mut World| -> anyhow::Result<()> {
const SPEED: f32 = 4.0;
let delta_time = **world.get_resource::<DeltaTime>();
for (mut transform, _) in world.view_iter::<(&mut Transform, &CubeFlag)>() {
let t = &mut transform;
t.rotate_y(math::Angle::Degrees(SPEED * delta_time));
}
for (mut transform, _s) in world.view_iter::<(&mut Transform, &mut SpotLight)>() {
let t = &mut transform;
t.rotate_x(math::Angle::Degrees(SPEED * delta_time));
}
Ok(())
};
let jiggle_plugin = move |game: &mut Game| {
/* game.world_mut().add_resource(TpsAccumulator(0.0));
let mut sys = BatchedSystem::new();
sys.with_criteria(FixedTimestep::new(45));
sys.with_system(spin_system.into_system()); */
/* let mut camera = CameraComponent::new_3d();
camera.transform.translation += math::Vec3::new(0.0, 0.0, 5.5);
world.spawn(( camera, FreeFlyCamera::default() )); */
//sys.with_system(fps_system);
//game.with_system("fixed", sys, &[]);
//fps_plugin(game);
game.with_system("camera_debug_trigger", sys, &[]);
};
let action_handler_plugin = |game: &mut Game| {
@ -312,7 +257,7 @@ async fn main() {
.add_action(ACTLBL_LOOK_LEFT_RIGHT, Action::new(ActionKind::Axis))
.add_action(ACTLBL_LOOK_UP_DOWN, Action::new(ActionKind::Axis))
.add_action(ACTLBL_LOOK_ROLL, Action::new(ActionKind::Axis))
.add_action(ACTLBL_DEBUG, Action::new(ActionKind::Button))
.add_action("Debug", Action::new(ActionKind::Button))
.add_mapping(ActionMapping::builder(LayoutId::from(0), ActionMappingId::from(0))
.bind(ACTLBL_MOVE_FORWARD_BACKWARD, &[
@ -343,7 +288,7 @@ async fn main() {
ActionSource::Keyboard(KeyCode::E).into_binding_modifier(-1.0),
ActionSource::Keyboard(KeyCode::Q).into_binding_modifier(1.0),
])
.bind(ACTLBL_DEBUG, &[
.bind("Debug", &[
ActionSource::Keyboard(KeyCode::B).into_binding(),
])
.finish()
@ -375,7 +320,7 @@ async fn main() {
.with_plugin(action_handler_plugin)
//.with_plugin(script_test_plugin)
//.with_plugin(fps_plugin)
.with_plugin(jiggle_plugin)
.with_plugin(camera_debug_plugin)
.with_plugin(FreeFlyCameraPlugin)
.run().await;
}

View File

@ -1,28 +1,103 @@
use lyra_ecs::Component;
use glam::{EulerRot, Quat, Vec3};
use lyra_ecs::{query::{Res, View}, Component};
use crate::{math::{Angle, Transform}, render::camera::CameraProjectionMode};
use crate::{game::Game, input::ActionHandler, plugin::Plugin, DeltaTime};
use super::CameraComponent;
pub const ACTLBL_MOVE_UP_DOWN: &str = "MoveUpDown";
pub const ACTLBL_MOVE_LEFT_RIGHT: &str = "MoveLeftRight";
pub const ACTLBL_MOVE_FORWARD_BACKWARD: &str = "MoveForwardBackward";
pub const ACTLBL_LOOK_LEFT_RIGHT: &str = "LookLeftRight";
pub const ACTLBL_LOOK_UP_DOWN: &str = "LookUpDown";
pub const ACTLBL_LOOK_ROLL: &str = "LookRoll";
#[derive(Clone, Component)]
pub struct FreeFlyCamera {
pub transform: Transform,
pub fov: Angle,
pub mode: CameraProjectionMode,
pub speed: f32,
pub slow_speed_factor: f32,
pub look_speed: f32,
pub mouse_sensitivity: f32,
pub look_with_keys: bool,
}
impl Default for FreeFlyCamera {
fn default() -> Self {
Self::new()
Self {
speed: 4.0,
slow_speed_factor: 0.25,
look_speed: 0.5,
mouse_sensitivity: 0.9,
look_with_keys: false,
}
}
}
impl FreeFlyCamera {
pub fn new() -> Self {
#[allow(dead_code)]
pub fn new(speed: f32, slow_speed_factor: f32, look_speed: f32, mouse_sensitivity: f32, look_with_keys: bool) -> Self {
Self {
transform: Transform::default(),
fov: Angle::Degrees(45.0),
mode: CameraProjectionMode::Perspective,
speed: 1.5,
speed,
slow_speed_factor,
look_speed,
mouse_sensitivity,
look_with_keys,
}
}
}
pub fn free_fly_camera_controller(delta_time: Res<DeltaTime>, handler: Res<ActionHandler>, view: View<(&mut CameraComponent, &FreeFlyCamera)>) -> anyhow::Result<()> {
let delta_time = **delta_time;
for (mut cam, fly) in view.into_iter() {
let forward = cam.transform.forward();
let left = cam.transform.left();
let up = Vec3::Y;
let move_y = handler.get_axis_modifier(ACTLBL_MOVE_UP_DOWN).unwrap_or(0.0);
let move_x = handler.get_axis_modifier(ACTLBL_MOVE_LEFT_RIGHT).unwrap_or(0.0);
let move_z = handler.get_axis_modifier(ACTLBL_MOVE_FORWARD_BACKWARD).unwrap_or(0.0);
let mut velocity = Vec3::ZERO;
velocity += move_y * up;
velocity += move_x * left;
velocity += move_z * forward;
if velocity != Vec3::ZERO {
cam.transform.translation += velocity.normalize() * fly.speed * delta_time; // TODO: speeding up
}
let motion_x = handler.get_axis_modifier(ACTLBL_LOOK_LEFT_RIGHT).unwrap_or(0.0);
let motion_y = handler.get_axis_modifier(ACTLBL_LOOK_UP_DOWN).unwrap_or(0.0);
let motion_z = handler.get_axis_modifier(ACTLBL_LOOK_ROLL).unwrap_or(0.0);
let mut camera_rot = Vec3::ZERO;
camera_rot.y -= motion_x * fly.mouse_sensitivity;
camera_rot.x -= motion_y * fly.mouse_sensitivity;
camera_rot.z -= motion_z * fly.mouse_sensitivity;
if camera_rot != Vec3::ZERO {
let look_velocity = camera_rot * fly.look_speed * delta_time;
let (mut y, mut x, _) = cam.transform.rotation.to_euler(EulerRot::YXZ);
x += look_velocity.x;
y += look_velocity.y;
x = x.clamp(-1.54, 1.54);
// rotation is not commutative, keep this order to avoid unintended roll
cam.transform.rotation = Quat::from_axis_angle(Vec3::Y, y)
* Quat::from_axis_angle(Vec3::X, x);
}
}
Ok(())
}
/// A plugin that adds the free fly camera controller system to the world. It is expected that
/// there is a [`FreeFlyCamera`] in the world, if there isn't, the camera would not move.
pub struct FreeFlyCameraPlugin;
impl Plugin for FreeFlyCameraPlugin {
fn setup(&self, game: &mut Game) {
game.with_system("free_fly_camera_system", free_fly_camera_controller, &[]);
}
}