Skip to content
Open
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
7 changes: 6 additions & 1 deletion src/ecs/components.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use bevy::prelude::{Bundle, Component, Entity, Resource};
use bevy::{
math::Vec3,
prelude::{Bundle, Component, Entity, Resource},
};
use std::collections::HashMap;

#[derive(Default, Component)]
Expand All @@ -14,6 +17,7 @@ pub struct MoveInput {
pub x: f32,
pub y: f32,
pub z: f32,
pub prev_move: Vec3,
}

#[derive(Bundle)]
Expand All @@ -31,6 +35,7 @@ impl Default for PlayerBundle {
x: 0.0,
y: 0.0,
z: 0.0,
prev_move: Vec3::ZERO,
},
v_velocity: VerticalVelocity(0.0),
}
Expand Down
12 changes: 9 additions & 3 deletions src/ecs/systems/handle_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,21 @@ pub fn handle_character_movement(
Option<&KinematicCharacterControllerOutput>,
)>,
) {
let delta_time = time.delta_seconds();
// let delta_time = time.delta_seconds();
for (mut controller, mut move_input, mut v_velocity, output) in query.iter_mut() {
let mut movement = Vec3::new(move_input.x, 0.0, move_input.z) * VELOCITY_MUL;

if movement == Vec3::ZERO && move_input.prev_move != Vec3::ZERO {
movement = move_input.prev_move;
move_input.prev_move = Vec3::ZERO;
} else {
move_input.prev_move = movement;
}

if output.map(|o| o.grounded).unwrap_or(false) {
v_velocity.0 = move_input.y * JUMP_SPEED;
} else {
v_velocity.0 -= GRAVITY * delta_time * controller.custom_mass.unwrap_or(1.0);
v_velocity.0 -= GRAVITY * time.delta_seconds() * controller.custom_mass.unwrap_or(1.0);
}

move_input.x = 0.0;
Expand All @@ -47,7 +54,6 @@ pub fn handle_look_events(
mut query: Query<&mut Transform>,
) {
for event in look_events.read() {
tracing::info!("Look event: {:?}", event);
if let Ok(mut transform) = query.get_mut(event.entity) {
transform.rotation = Quat::from_vec4(event.direction);
}
Expand Down
15 changes: 15 additions & 0 deletions src/ecs/systems/handle_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,29 @@ use crate::{
server::{
channel::DefaultChannel,
message_in::{MessageIn, MessageInType},
message_out::MessageOut,
server::{DenariaServer, ServerEvent},
},
};

use super::setup::Tick;

pub fn handle_server_events(
mut server: ResMut<DenariaServer>,
mut disconnect_event: EventWriter<DisconnectEvent>,
mut tick: ResMut<Tick>,
) {
if tick.0 == u16::MAX {
tick.0 = 2;
} else {
tick.0 += 1;
}

if tick.0 % 60 == 0 {
let message = MessageOut::tick_sync_message(tick.0);
server.broadcast_message(DefaultChannel::Unreliable, message.data);
}

server.update(TICK_DELTA);
server.process_server_transport_messages();

Expand Down
7 changes: 5 additions & 2 deletions src/ecs/systems/on_change.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use bevy::{
math::{Quat, Vec3},
prelude::{Added, Changed, Query, ResMut, Transform},
prelude::{Added, Changed, Query, Res, ResMut, Transform},
};

use crate::{
ecs::components::Player,
server::{channel::DefaultChannel, message_out::MessageOut, server::DenariaServer},
};

use super::setup::Tick;

// Gets the Position component of all Entities whose Velocity has changed since the last run of the System
pub fn on_transform_change(
query: Query<(&Player, &Transform), Changed<Transform>>,
mut server: ResMut<DenariaServer>,
tick: Res<Tick>,
) {
let mut positions: Vec<(Vec3, String)> = vec![];
let mut rotations: Vec<(Quat, String)> = vec![];
Expand All @@ -21,7 +24,7 @@ pub fn on_transform_change(
rotations.push((transform.rotation, player.id.clone()));
}
if positions.len() > 0 {
if let Some(position_message) = MessageOut::position_message(positions) {
if let Some(position_message) = MessageOut::position_message(positions, tick.0) {
server.broadcast_message(DefaultChannel::Unreliable, position_message.data);
}
if let Some(rotation_message) = MessageOut::rotation_message(rotations) {
Expand Down
5 changes: 4 additions & 1 deletion src/ecs/systems/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,17 @@ use crate::ecs::{
events::{DisconnectEvent, JumpEvent, LookEvent, MoveEvent, SpawnEvent},
};

#[derive(Debug, Resource)]
pub struct Tick(pub u16);

pub fn setup(mut commands: Commands) {
let objects: Vec<LevelObject> = vec![];

let level_objects = LevelObjects { objects };

commands.insert_resource(PlayerLookup::new());
commands.insert_resource(level_objects);

commands.insert_resource(Tick(0));
commands.insert_resource(Events::<SpawnEvent>::default());
commands.insert_resource(Events::<DisconnectEvent>::default());
commands.insert_resource(Events::<LookEvent>::default());
Expand Down
20 changes: 19 additions & 1 deletion src/server/message_out.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl MessageOut {
with_header
}

pub fn position_message(positions: Vec<(Vec3, String)>) -> Option<MessageOut> {
pub fn position_message(positions: Vec<(Vec3, String)>, tick: u16) -> Option<MessageOut> {
let position_details: Vec<PositionDetails> = positions
.iter()
.map(|(position, player_id)| {
Expand All @@ -35,6 +35,7 @@ impl MessageOut {

if positions.len() > 0 {
let position_event = PositionMessageOut {
tick,
positions: position_details,
};

Expand Down Expand Up @@ -119,6 +120,16 @@ impl MessageOut {
data: serialized,
})
}

pub fn tick_sync_message(tick: u16) -> MessageOut {
let tick_sync_event = TickSyncMessageOut { tick };
let mut serialized = bincode::serialize(&tick_sync_event).unwrap();
serialized.insert(0, 11); // Tick Sync Message Type 11
MessageOut {
event_type: MessageOutType::TickSync,
data: serialized,
}
}
}

fn normalize_player_id(player_id: &str) -> [u8; 16] {
Expand All @@ -135,10 +146,12 @@ pub enum MessageOutType {
Position = 1,
Rotation = 2,
Disconnect = 10,
TickSync = 11,
}

#[derive(Serialize, Deserialize, Debug)]
struct PositionMessageOut {
tick: u16,
positions: Vec<PositionDetails>,
}

Expand Down Expand Up @@ -199,3 +212,8 @@ struct SpawnDetails {
position: Vec3,
rotation: Vec4,
}

#[derive(Serialize, Deserialize, Debug)]
struct TickSyncMessageOut {
tick: u16,
}
11 changes: 5 additions & 6 deletions src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ pub fn new_session(
std::env::var("ENABLE_DEBUG_CAM").is_ok_and(|v| v.to_lowercase() == "true");

if !enable_debug_metrics && !enable_debug_cam {
app.add_plugins(MinimalPlugins.set(ScheduleRunnerPlugin::run_loop(
Duration::from_secs_f64(1.0 / 30.0),
)));
app.add_plugins(MinimalPlugins)
.insert_resource(Time::<Fixed>::from_hz(30.0));
} else {
app.add_plugins(DefaultPlugins)
.add_plugins(FrameTimeDiagnosticsPlugin)
Expand All @@ -81,12 +80,12 @@ pub fn new_session(
app.add_plugins(RapierPhysicsPlugin::<NoUserData>::default())
.add_systems(Startup, (setup, setup_level).chain())
.add_systems(
PreUpdate,
FixedPreUpdate,
(handle_server_events, handle_server_messages).chain(),
)
.add_systems(PostUpdate, handle_outgoing_messages)
.add_systems(FixedPostUpdate, handle_outgoing_messages)
.add_systems(
Update,
FixedUpdate,
(
(
handle_character_movement,
Expand Down