Skip to content

Commit

Permalink
Move from mio's Token to usize
Browse files Browse the repository at this point in the history
Should make porting to tokio easier, also enables using Token outside of pumpkin crate without mio dependecy
  • Loading branch information
Snowiiii committed Oct 15, 2024
1 parent ffb0fcf commit 8febc50
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 57 deletions.
2 changes: 1 addition & 1 deletion pumpkin/src/client/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ impl Player {
.filter(|player_id| *player_id != self.entity_id())
.collect_vec()
};
let player_token = self.client.token;
let player_token = self.client.id;

// TODO: Figure out better way to get only the players from player_ids
// Also refactor out a better method to get individual advanced state ids
Expand Down
10 changes: 5 additions & 5 deletions pumpkin/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{

use authentication::GameProfile;
use crossbeam::atomic::AtomicCell;
use mio::{event::Event, net::TcpStream, Token};
use mio::{event::Event, net::TcpStream};
use parking_lot::Mutex;
use pumpkin_config::compression::CompressionInfo;
use pumpkin_core::text::TextComponent;
Expand Down Expand Up @@ -99,8 +99,8 @@ pub struct Client {
pub encryption: AtomicBool,
/// Indicates if the client connection is closed.
pub closed: AtomicBool,
/// A unique token identifying the client.
pub token: Token,
/// A unique id identifying the client.
pub id: usize,
/// The underlying TCP connection to the client.
pub connection: Arc<Mutex<TcpStream>>,
/// The client's IP address.
Expand All @@ -122,7 +122,7 @@ pub struct Client {

impl Client {
pub fn new(
token: Token,
id: usize,
connection: TcpStream,
address: SocketAddr,
keep_alive_sender: Arc<tokio::sync::mpsc::Sender<i64>>,
Expand All @@ -132,7 +132,7 @@ impl Client {
gameprofile: Mutex::new(None),
config: Mutex::new(None),
brand: Mutex::new(None),
token,
id,
address: Mutex::new(address),
connection_state: AtomicCell::new(ConnectionState::HandShake),
connection: Arc::new(Mutex::new(connection)),
Expand Down
12 changes: 6 additions & 6 deletions pumpkin/src/client/player_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl Player {
// }
// send new position to all other players
world.broadcast_packet_expect(
&[self.client.token],
&[self.client.id],
&CUpdateEntityPos::new(
entity_id.into(),
x.mul_add(4096.0, -(lastx * 4096.0)) as i16,
Expand Down Expand Up @@ -171,7 +171,7 @@ impl Player {
// send new position to all other players

world.broadcast_packet_expect(
&[self.client.token],
&[self.client.id],
&CUpdateEntityPosRot::new(
entity_id.into(),
x.mul_add(4096.0, -(lastx * 4096.0)) as i16,
Expand All @@ -183,7 +183,7 @@ impl Player {
),
);
world.broadcast_packet_expect(
&[self.client.token],
&[self.client.id],
&CHeadRot::new(entity_id.into(), yaw as u8),
);
player_chunker::update_position(entity, self).await;
Expand Down Expand Up @@ -211,9 +211,9 @@ impl Player {
let world = &entity.world;
let packet =
CUpdateEntityRot::new(entity_id.into(), yaw as u8, pitch as u8, rotation.ground);
world.broadcast_packet_expect(&[self.client.token], &packet);
world.broadcast_packet_expect(&[self.client.id], &packet);
let packet = CHeadRot::new(entity_id.into(), yaw as u8);
world.broadcast_packet_expect(&[self.client.token], &packet);
world.broadcast_packet_expect(&[self.client.id], &packet);
}

pub fn handle_chat_command(&self, server: &Server, command: SChatCommand) {
Expand Down Expand Up @@ -293,7 +293,7 @@ impl Player {
let id = self.entity_id();
let world = &self.living_entity.entity.world;
world.broadcast_packet_expect(
&[self.client.token],
&[self.client.id],
&CEntityAnimation::new(id.into(), animation as u8),
)
}
Expand Down
35 changes: 15 additions & 20 deletions pumpkin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,13 @@ fn main() -> io::Result<()> {
.register(&mut listener, SERVER, Interest::READABLE)?;

// Unique token for each incoming connection.
let mut unique_token = Token(SERVER.0 + 1);
let mut unique_id = SERVER.0 + 1;

let use_console = ADVANCED_CONFIG.commands.use_console;
let rcon = ADVANCED_CONFIG.rcon.clone();

let mut clients: HashMap<Token, Arc<Client>> = HashMap::new();
let mut players: HashMap<Token, Arc<Player>> = HashMap::new();
let mut clients: HashMap<usize, Arc<Client>> = HashMap::new();
let mut players: HashMap<usize, Arc<Player>> = HashMap::new();

let server = Arc::new(Server::new());
log::info!("Started Server took {}ms", time.elapsed().as_millis());
Expand Down Expand Up @@ -212,15 +212,16 @@ fn main() -> io::Result<()> {
scrub_address(&format!("{}", address))
);

let token = next(&mut unique_token);
unique_id += 1;
let id = unique_id;
poll.registry().register(
&mut connection,
token,
Token(id),
Interest::READABLE.add(Interest::WRITABLE),
)?;
let keep_alive = tokio::sync::mpsc::channel(1024);
let client =
Arc::new(Client::new(token, connection, addr, keep_alive.0.into()));
Arc::new(Client::new(id, connection, addr, keep_alive.0.into()));

{
let client = client.clone();
Expand Down Expand Up @@ -253,12 +254,12 @@ fn main() -> io::Result<()> {
}
});
}
clients.insert(token, client);
clients.insert(id, client);
},
// Maybe received an event for a TCP connection.
token => {
// poll Player
if let Some(player) = players.get_mut(&token) {
if let Some(player) = players.get_mut(&token.0) {
player.client.poll(event).await;
let closed = player
.client
Expand All @@ -268,7 +269,7 @@ fn main() -> io::Result<()> {
player.process_packets(&server).await;
}
if closed {
if let Some(player) = players.remove(&token) {
if let Some(player) = players.remove(&token.0) {
player.remove().await;
let connection = &mut player.client.connection.lock();
poll.registry().deregister(connection.by_ref())?;
Expand All @@ -277,7 +278,7 @@ fn main() -> io::Result<()> {
};

// Poll current Clients (non players)
let (done, make_player) = if let Some(client) = clients.get_mut(&token) {
let (done, make_player) = if let Some(client) = clients.get_mut(&token.0) {
client.poll(event).await;
let closed = client.closed.load(std::sync::atomic::Ordering::Relaxed);
if !closed {
Expand All @@ -293,14 +294,14 @@ fn main() -> io::Result<()> {
(false, false)
};
if done || make_player {
if let Some(client) = clients.remove(&token) {
if let Some(client) = clients.remove(&token.0) {
if done {
let connection = &mut client.connection.lock();
poll.registry().deregister(connection.by_ref())?;
} else if make_player {
let token = client.token;
let (player, world) = server.add_player(token, client).await;
players.insert(token, player.clone());
let id = client.id;
let (player, world) = server.add_player(id, client).await;
players.insert(id, player.clone());
world.spawn_player(&BASIC_CONFIG, player).await;
}
}
Expand All @@ -311,9 +312,3 @@ fn main() -> io::Result<()> {
}
})
}

fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}
19 changes: 7 additions & 12 deletions pumpkin/src/rcon/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ impl RCONServer {
.register(&mut listener, SERVER, Interest::READABLE)
.unwrap();

let mut unique_token = Token(SERVER.0 + 1);
let mut unique_id = SERVER.0 + 1;

let mut events = Events::with_capacity(20);

let mut connections: HashMap<Token, RCONClient> = HashMap::new();
let mut connections: HashMap<usize, RCONClient> = HashMap::new();

let password = config.password.clone();

Expand Down Expand Up @@ -77,25 +77,26 @@ impl RCONServer {
break;
}

let token = Self::next(&mut unique_token);
unique_id += 1;
let token = unique_id;
poll.registry()
.register(
&mut connection,
token,
Token(token),
Interest::READABLE.add(Interest::WRITABLE),
)
.unwrap();
connections.insert(token, RCONClient::new(connection, address));
},

token => {
let done = if let Some(client) = connections.get_mut(&token) {
let done = if let Some(client) = connections.get_mut(&token.0) {
client.handle(server, &password).await
} else {
false
};
if done {
if let Some(mut client) = connections.remove(&token) {
if let Some(mut client) = connections.remove(&token.0) {
let config = &ADVANCED_CONFIG.rcon;
if config.logging.log_quit {
log::info!(
Expand All @@ -111,12 +112,6 @@ impl RCONServer {
}
}
}

fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}
}

pub struct RCONClient {
Expand Down
5 changes: 2 additions & 3 deletions pumpkin/src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use connection_cache::{CachedBranding, CachedStatus};
use key_store::KeyStore;
use mio::Token;
use parking_lot::{Mutex, RwLock};
use pumpkin_config::BASIC_CONFIG;
use pumpkin_core::GameMode;
Expand Down Expand Up @@ -91,7 +90,7 @@ impl Server {
}
}

pub async fn add_player(&self, token: Token, client: Arc<Client>) -> (Arc<Player>, Arc<World>) {
pub async fn add_player(&self, id: usize, client: Arc<Client>) -> (Arc<Player>, Arc<World>) {
let entity_id = self.new_entity_id();
let gamemode = match BASIC_CONFIG.default_gamemode {
GameMode::Undefined => GameMode::Survival,
Expand All @@ -102,7 +101,7 @@ impl Server {
let world = &self.worlds[0];

let player = Arc::new(Player::new(client, world.clone(), entity_id, gamemode));
world.add_player(token, player.clone());
world.add_player(id, player.clone());
(player, world.clone())
}

Expand Down
19 changes: 9 additions & 10 deletions pumpkin/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::{
client::Client,
entity::{player::Player, Entity},
};
use mio::Token;
use num_traits::ToPrimitive;
use parking_lot::Mutex;
use pumpkin_config::BasicConfiguration;
Expand Down Expand Up @@ -35,7 +34,7 @@ pub struct World {
/// The underlying level, responsible for chunk management and terrain generation.
pub level: Arc<Mutex<Level>>,
/// A map of active players within the world, keyed by their unique token.
pub current_players: Arc<Mutex<HashMap<Token, Arc<Player>>>>,
pub current_players: Arc<Mutex<HashMap<usize, Arc<Player>>>>,
// TODO: entities
}

Expand Down Expand Up @@ -67,7 +66,7 @@ impl World {
/// Sends the specified packet to every player currently logged in to the server, excluding the players listed in the `except` parameter.
///
/// **Note:** This function acquires a lock on the `current_players` map, ensuring thread safety.
pub fn broadcast_packet_expect<P>(&self, except: &[Token], packet: &P)
pub fn broadcast_packet_expect<P>(&self, except: &[usize], packet: &P)
where
P: ClientPacket,
{
Expand Down Expand Up @@ -142,7 +141,7 @@ impl World {
let current_players = self.current_players.lock();
for (_, playerr) in current_players
.iter()
.filter(|(c, _)| **c != player.client.token)
.filter(|(c, _)| **c != player.client.id)
{
let gameprofile = &playerr.gameprofile;
entries.push(pumpkin_protocol::client::play::Player {
Expand All @@ -165,7 +164,7 @@ impl World {

// spawn player for every client
self.broadcast_packet_expect(
&[player.client.token],
&[player.client.id],
// TODO: add velo
&CSpawnEntity::new(
entity_id.into(),
Expand All @@ -184,7 +183,7 @@ impl World {
),
);
// spawn players for our client
let token = player.client.token;
let token = player.client.id;
for (_, existing_player) in self.current_players.lock().iter().filter(|c| c.0 != &token) {
let entity = &existing_player.living_entity.entity;
let pos = entity.pos.load();
Expand Down Expand Up @@ -275,18 +274,18 @@ impl World {
None
}

pub fn add_player(&self, token: Token, player: Arc<Player>) {
self.current_players.lock().insert(token, player);
pub fn add_player(&self, id: usize, player: Arc<Player>) {
self.current_players.lock().insert(id, player);
}

pub fn remove_player(&self, player: &Player) {
self.current_players
.lock()
.remove(&player.client.token)
.remove(&player.client.id)
.unwrap();
let uuid = player.gameprofile.id;
self.broadcast_packet_expect(
&[player.client.token],
&[player.client.id],
&CRemovePlayerInfo::new(1.into(), &[uuid]),
);
self.remove_entity(&player.living_entity.entity);
Expand Down

0 comments on commit 8febc50

Please sign in to comment.