Client/Server Feature Split (#63)

This commit is contained in:
PROMETHIA-27
2025-09-26 21:59:08 -04:00
committed by GitHub
parent 7f6c00b5d6
commit 2f5d154d26
30 changed files with 674 additions and 271 deletions

View File

@@ -1,16 +1,25 @@
use crate::config::ServerConfig;
use bevy::prelude::*;
use lightyear::prelude::{
server::{NetcodeConfig, NetcodeServer, ServerUdpIo},
server::{NetcodeConfig, NetcodeServer, ServerUdpIo, Started},
*,
};
use shared::{heads_database::HeadsDatabase, tb_entities::SpawnPoint, utils::commands::IsServer};
use shared::{GameState, global_observer, heads_database::HeadsDatabase, tb_entities::SpawnPoint};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
pub fn plugin(app: &mut App) {
app.init_resource::<IsServer>();
app.add_systems(Startup, (start_server, setup_timeout_timer));
app.add_systems(
Update,
(
notify_started.run_if(in_state(GameState::Playing)),
run_timeout,
),
);
app.add_systems(Startup, start_server);
app.add_observer(handle_new_client);
global_observer!(app, handle_new_client);
global_observer!(app, close_on_disconnect);
global_observer!(app, cancel_timeout);
}
fn handle_new_client(
@@ -34,17 +43,52 @@ fn handle_new_client(
Ok(())
}
fn close_on_disconnect(
_trigger: Trigger<OnRemove, Connected>,
config: Res<ServerConfig>,
mut writer: EventWriter<AppExit>,
) {
if config.close_on_client_disconnect {
writer.write(AppExit::Success);
}
}
fn start_server(mut commands: Commands) -> Result {
let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 25565);
commands
.spawn((
Name::from("Server"),
LocalAddr(server_addr),
ServerUdpIo::default(),
NetcodeServer::new(NetcodeConfig::default()),
))
.trigger(server::Start);
let mut commands = commands.spawn((
Name::from("Server"),
LocalAddr(server_addr),
ServerUdpIo::default(),
NetcodeServer::new(NetcodeConfig::default()),
));
commands.trigger(server::Start);
Ok(())
}
fn notify_started(started: Query<&Started>, mut notified: Local<bool>) {
if !*notified && !started.is_empty() {
println!("hedz.server_started");
*notified = true;
}
}
#[derive(Resource)]
struct TimeoutTimer(f32);
fn setup_timeout_timer(mut commands: Commands, config: Res<ServerConfig>) {
commands.insert_resource(TimeoutTimer(config.timeout));
}
fn run_timeout(mut timer: ResMut<TimeoutTimer>, mut writer: EventWriter<AppExit>, time: Res<Time>) {
timer.0 -= time.delta_secs();
if timer.0 <= 0.0 {
writer.write(AppExit::Success);
}
}
fn cancel_timeout(_trigger: Trigger<OnAdd, Connected>, mut timer: ResMut<TimeoutTimer>) {
timer.0 = f32::INFINITY;
}