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

Added Sensible Default ggrs::Config type GgrsConfig #73

Merged
merged 2 commits into from
Oct 19, 2023
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
26 changes: 10 additions & 16 deletions examples/box_game/box_game.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use bevy::{prelude::*, utils::HashMap};
use bevy_ggrs::{
AddRollbackCommandExtension, LocalInputs, LocalPlayers, PlayerInputs, Rollback, Session,
AddRollbackCommandExtension, GgrsConfig, LocalInputs, LocalPlayers, PlayerInputs, Rollback,
Session,
};
use bytemuck::{Pod, Zeroable};
use ggrs::Config;
use std::{hash::Hash, net::SocketAddr};
use std::hash::Hash;

const BLUE: Color = Color::rgb(0.8, 0.6, 0.2);
const ORANGE: Color = Color::rgb(0., 0.35, 0.8);
Expand All @@ -23,18 +23,12 @@ const FRICTION: f32 = 0.9;
const PLANE_SIZE: f32 = 5.0;
const CUBE_SIZE: f32 = 0.2;

/// You need to define a config struct to bundle all the generics of GGRS. You can safely ignore `State` and leave it as u8 for all GGRS functionality.
/// TODO: Find a way to hide the state type.
#[derive(Debug)]
pub struct GgrsConfig;
impl Config for GgrsConfig {
type Input = BoxInput;
type State = u8;
type Address = SocketAddr;
}
// You need to define a config struct to bundle all the generics of GGRS. bevy_ggrs provides a sensible default in `GgrsConfig`.
// (optional) You can define a type here for brevity.
pub type BoxConfig = GgrsConfig<BoxInput>;

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, Pod, Zeroable)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Pod, Zeroable)]
pub struct BoxInput {
pub inp: u8,
}
Expand Down Expand Up @@ -85,14 +79,14 @@ pub fn read_local_inputs(
local_inputs.insert(*handle, BoxInput { inp: input });
}

commands.insert_resource(LocalInputs::<GgrsConfig>(local_inputs));
commands.insert_resource(LocalInputs::<BoxConfig>(local_inputs));
}

pub fn setup_system(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
session: Res<Session<GgrsConfig>>,
session: Res<Session<BoxConfig>>,
) {
let num_players = match &*session {
Session::SyncTest(s) => s.num_players(),
Expand Down Expand Up @@ -166,7 +160,7 @@ pub fn increase_frame_system(mut frame_count: ResMut<FrameCount>) {
#[allow(dead_code)]
pub fn move_cube_system(
mut query: Query<(&mut Transform, &mut Velocity, &Player), With<Rollback>>,
inputs: Res<PlayerInputs<GgrsConfig>>,
inputs: Res<PlayerInputs<BoxConfig>>,
) {
for (mut t, mut v, p) in query.iter_mut() {
let input = inputs[p.handle].0.inp;
Expand Down
8 changes: 4 additions & 4 deletions examples/box_game/box_game_p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
assert!(num_players > 0);

// create a GGRS session
let mut sess_build = SessionBuilder::<GgrsConfig>::new()
let mut sess_build = SessionBuilder::<BoxConfig>::new()
.with_num_players(num_players)
.with_desync_detection_mode(ggrs::DesyncDetection::On { interval: 10 }) // (optional) set how often to exchange state checksums
.with_max_prediction_window(12) // (optional) set max prediction window
Expand Down Expand Up @@ -58,7 +58,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let sess = sess_build.start_p2p_session(socket)?;

App::new()
.add_plugins(GgrsPlugin::<GgrsConfig>::default())
.add_plugins(GgrsPlugin::<BoxConfig>::default())
// define frequency of rollback game logic update
.set_rollback_schedule_fps(FPS)
// this system will be executed as part of input reading
Expand Down Expand Up @@ -95,7 +95,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

fn print_events_system(mut session: ResMut<Session<GgrsConfig>>) {
fn print_events_system(mut session: ResMut<Session<BoxConfig>>) {
match session.as_mut() {
Session::P2P(s) => {
for event in s.events() {
Expand All @@ -115,7 +115,7 @@ fn print_events_system(mut session: ResMut<Session<GgrsConfig>>) {
fn print_network_stats_system(
time: Res<Time>,
mut timer: ResMut<NetworkStatsTimer>,
p2p_session: Option<Res<Session<GgrsConfig>>>,
p2p_session: Option<Res<Session<BoxConfig>>>,
) {
// print only when timer runs out
if timer.0.tick(time.delta()).just_finished() {
Expand Down
8 changes: 4 additions & 4 deletions examples/box_game/box_game_spectator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// create a GGRS session

let socket = UdpNonBlockingSocket::bind_to_port(opt.local_port)?;
let sess = SessionBuilder::<GgrsConfig>::new()
let sess = SessionBuilder::<BoxConfig>::new()
.with_num_players(opt.num_players)
.start_spectator_session(opt.host, socket);

App::new()
.add_plugins(GgrsPlugin::<GgrsConfig>::default())
.add_plugins(GgrsPlugin::<BoxConfig>::default())
// define frequency of rollback game logic update
.set_rollback_schedule_fps(FPS)
// this system will be executed as part of input reading
Expand Down Expand Up @@ -66,7 +66,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

fn print_events_system(mut session: ResMut<Session<GgrsConfig>>) {
fn print_events_system(mut session: ResMut<Session<BoxConfig>>) {
match session.as_mut() {
Session::Spectator(s) => {
for event in s.events() {
Expand All @@ -80,7 +80,7 @@ fn print_events_system(mut session: ResMut<Session<GgrsConfig>>) {
fn print_network_stats_system(
time: Res<Time>,
mut timer: ResMut<NetworkStatsTimer>,
p2p_session: Option<Res<Session<GgrsConfig>>>,
p2p_session: Option<Res<Session<BoxConfig>>>,
) {
// print only when timer runs out
if timer.0.tick(time.delta()).just_finished() {
Expand Down
4 changes: 2 additions & 2 deletions examples/box_game/box_game_synctest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
assert!(opt.num_players > 0);

// create a GGRS session
let mut sess_build = SessionBuilder::<GgrsConfig>::new()
let mut sess_build = SessionBuilder::<BoxConfig>::new()
.with_num_players(opt.num_players)
.with_check_distance(opt.check_distance)
.with_input_delay(2); // (optional) set input delay for the local player
Expand All @@ -36,7 +36,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let sess = sess_build.start_synctest_session()?;

App::new()
.add_plugins(GgrsPlugin::<GgrsConfig>::default())
.add_plugins(GgrsPlugin::<BoxConfig>::default())
// define frequency of rollback game logic update
.set_rollback_schedule_fps(FPS)
// this system will be executed as part of input reading
Expand Down
27 changes: 24 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use bevy::{
};
use ggrs::{Config, InputStatus, P2PSession, PlayerHandle, SpectatorSession, SyncTestSession};
use parking_lot::RwLock;
use std::{marker::PhantomData, sync::Arc};
use std::{fmt::Debug, hash::Hash, marker::PhantomData, net::SocketAddr, sync::Arc};
use world_snapshot::RollbackSnapshots;

pub use ggrs;
Expand All @@ -22,12 +22,33 @@ pub(crate) mod world_snapshot;

pub mod prelude {
pub use crate::{
AddRollbackCommandExtension, GgrsApp, GgrsPlugin, GgrsSchedule, PlayerInputs, ReadInputs,
Rollback, Session,
AddRollbackCommandExtension, GgrsApp, GgrsConfig, GgrsPlugin, GgrsSchedule, PlayerInputs,
ReadInputs, Rollback, Session,
};
pub use ggrs::{GGRSEvent as GgrsEvent, PlayerType, SessionBuilder};
}

/// A sensible default [GGRS Config](`ggrs::Config`) type suitable for most applications.
///
/// If you require a more specialized configuration, you can create your own type implementing
/// [`Config`](`ggrs::Config`).
#[derive(Debug)]
pub struct GgrsConfig<Input, Address = SocketAddr, State = u8> {
_phantom: PhantomData<(Input, Address, State)>,
}

impl<Input, Address, State> Config for GgrsConfig<Input, Address, State>
where
Self: 'static,
Input: Send + Sync + PartialEq + bytemuck::Pod,
Address: Send + Sync + Debug + Hash + Eq + Clone,
State: Send + Sync + Clone,
{
type Input = Input;
type State = State;
type Address = Address;
}

const DEFAULT_FPS: usize = 60;

#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone)]
Expand Down