Move from mio's Token to usize

Should make porting to tokio easier, also enables using Token outside of pumpkin crate without mio dependecy
This commit is contained in:
Snowiiii 2024-10-15 13:22:02 +02:00
parent ffb0fcf4f0
commit 8febc5035d
7 changed files with 45 additions and 57 deletions

View File

@ -388,7 +388,7 @@ impl Player {
.filter(|player_id| *player_id != self.entity_id()) .filter(|player_id| *player_id != self.entity_id())
.collect_vec() .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 // 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 // Also refactor out a better method to get individual advanced state ids

View File

@ -14,7 +14,7 @@ use crate::{
use authentication::GameProfile; use authentication::GameProfile;
use crossbeam::atomic::AtomicCell; use crossbeam::atomic::AtomicCell;
use mio::{event::Event, net::TcpStream, Token}; use mio::{event::Event, net::TcpStream};
use parking_lot::Mutex; use parking_lot::Mutex;
use pumpkin_config::compression::CompressionInfo; use pumpkin_config::compression::CompressionInfo;
use pumpkin_core::text::TextComponent; use pumpkin_core::text::TextComponent;
@ -99,8 +99,8 @@ pub struct Client {
pub encryption: AtomicBool, pub encryption: AtomicBool,
/// Indicates if the client connection is closed. /// Indicates if the client connection is closed.
pub closed: AtomicBool, pub closed: AtomicBool,
/// A unique token identifying the client. /// A unique id identifying the client.
pub token: Token, pub id: usize,
/// The underlying TCP connection to the client. /// The underlying TCP connection to the client.
pub connection: Arc<Mutex<TcpStream>>, pub connection: Arc<Mutex<TcpStream>>,
/// The client's IP address. /// The client's IP address.
@ -122,7 +122,7 @@ pub struct Client {
impl Client { impl Client {
pub fn new( pub fn new(
token: Token, id: usize,
connection: TcpStream, connection: TcpStream,
address: SocketAddr, address: SocketAddr,
keep_alive_sender: Arc<tokio::sync::mpsc::Sender<i64>>, keep_alive_sender: Arc<tokio::sync::mpsc::Sender<i64>>,
@ -132,7 +132,7 @@ impl Client {
gameprofile: Mutex::new(None), gameprofile: Mutex::new(None),
config: Mutex::new(None), config: Mutex::new(None),
brand: Mutex::new(None), brand: Mutex::new(None),
token, id,
address: Mutex::new(address), address: Mutex::new(address),
connection_state: AtomicCell::new(ConnectionState::HandShake), connection_state: AtomicCell::new(ConnectionState::HandShake),
connection: Arc::new(Mutex::new(connection)), connection: Arc::new(Mutex::new(connection)),

View File

@ -105,7 +105,7 @@ impl Player {
// } // }
// send new position to all other players // send new position to all other players
world.broadcast_packet_expect( world.broadcast_packet_expect(
&[self.client.token], &[self.client.id],
&CUpdateEntityPos::new( &CUpdateEntityPos::new(
entity_id.into(), entity_id.into(),
x.mul_add(4096.0, -(lastx * 4096.0)) as i16, x.mul_add(4096.0, -(lastx * 4096.0)) as i16,
@ -171,7 +171,7 @@ impl Player {
// send new position to all other players // send new position to all other players
world.broadcast_packet_expect( world.broadcast_packet_expect(
&[self.client.token], &[self.client.id],
&CUpdateEntityPosRot::new( &CUpdateEntityPosRot::new(
entity_id.into(), entity_id.into(),
x.mul_add(4096.0, -(lastx * 4096.0)) as i16, x.mul_add(4096.0, -(lastx * 4096.0)) as i16,
@ -183,7 +183,7 @@ impl Player {
), ),
); );
world.broadcast_packet_expect( world.broadcast_packet_expect(
&[self.client.token], &[self.client.id],
&CHeadRot::new(entity_id.into(), yaw as u8), &CHeadRot::new(entity_id.into(), yaw as u8),
); );
player_chunker::update_position(entity, self).await; player_chunker::update_position(entity, self).await;
@ -211,9 +211,9 @@ impl Player {
let world = &entity.world; let world = &entity.world;
let packet = let packet =
CUpdateEntityRot::new(entity_id.into(), yaw as u8, pitch as u8, rotation.ground); 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); 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) { pub fn handle_chat_command(&self, server: &Server, command: SChatCommand) {
@ -293,7 +293,7 @@ impl Player {
let id = self.entity_id(); let id = self.entity_id();
let world = &self.living_entity.entity.world; let world = &self.living_entity.entity.world;
world.broadcast_packet_expect( world.broadcast_packet_expect(
&[self.client.token], &[self.client.id],
&CEntityAnimation::new(id.into(), animation as u8), &CEntityAnimation::new(id.into(), animation as u8),
) )
} }

View File

@ -136,13 +136,13 @@ fn main() -> io::Result<()> {
.register(&mut listener, SERVER, Interest::READABLE)?; .register(&mut listener, SERVER, Interest::READABLE)?;
// Unique token for each incoming connection. // 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 use_console = ADVANCED_CONFIG.commands.use_console;
let rcon = ADVANCED_CONFIG.rcon.clone(); let rcon = ADVANCED_CONFIG.rcon.clone();
let mut clients: HashMap<Token, Arc<Client>> = HashMap::new(); let mut clients: HashMap<usize, Arc<Client>> = HashMap::new();
let mut players: HashMap<Token, Arc<Player>> = HashMap::new(); let mut players: HashMap<usize, Arc<Player>> = HashMap::new();
let server = Arc::new(Server::new()); let server = Arc::new(Server::new());
log::info!("Started Server took {}ms", time.elapsed().as_millis()); log::info!("Started Server took {}ms", time.elapsed().as_millis());
@ -212,15 +212,16 @@ fn main() -> io::Result<()> {
scrub_address(&format!("{}", address)) scrub_address(&format!("{}", address))
); );
let token = next(&mut unique_token); unique_id += 1;
let id = unique_id;
poll.registry().register( poll.registry().register(
&mut connection, &mut connection,
token, Token(id),
Interest::READABLE.add(Interest::WRITABLE), Interest::READABLE.add(Interest::WRITABLE),
)?; )?;
let keep_alive = tokio::sync::mpsc::channel(1024); let keep_alive = tokio::sync::mpsc::channel(1024);
let client = 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(); let client = client.clone();
@ -253,12 +254,12 @@ fn main() -> io::Result<()> {
} }
}); });
} }
clients.insert(token, client); clients.insert(id, client);
}, },
// Maybe received an event for a TCP connection. // Maybe received an event for a TCP connection.
token => { token => {
// poll Player // poll Player
if let Some(player) = players.get_mut(&token) { if let Some(player) = players.get_mut(&token.0) {
player.client.poll(event).await; player.client.poll(event).await;
let closed = player let closed = player
.client .client
@ -268,7 +269,7 @@ fn main() -> io::Result<()> {
player.process_packets(&server).await; player.process_packets(&server).await;
} }
if closed { if closed {
if let Some(player) = players.remove(&token) { if let Some(player) = players.remove(&token.0) {
player.remove().await; player.remove().await;
let connection = &mut player.client.connection.lock(); let connection = &mut player.client.connection.lock();
poll.registry().deregister(connection.by_ref())?; poll.registry().deregister(connection.by_ref())?;
@ -277,7 +278,7 @@ fn main() -> io::Result<()> {
}; };
// Poll current Clients (non players) // 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; client.poll(event).await;
let closed = client.closed.load(std::sync::atomic::Ordering::Relaxed); let closed = client.closed.load(std::sync::atomic::Ordering::Relaxed);
if !closed { if !closed {
@ -293,14 +294,14 @@ fn main() -> io::Result<()> {
(false, false) (false, false)
}; };
if done || make_player { if done || make_player {
if let Some(client) = clients.remove(&token) { if let Some(client) = clients.remove(&token.0) {
if done { if done {
let connection = &mut client.connection.lock(); let connection = &mut client.connection.lock();
poll.registry().deregister(connection.by_ref())?; poll.registry().deregister(connection.by_ref())?;
} else if make_player { } else if make_player {
let token = client.token; let id = client.id;
let (player, world) = server.add_player(token, client).await; let (player, world) = server.add_player(id, client).await;
players.insert(token, player.clone()); players.insert(id, player.clone());
world.spawn_player(&BASIC_CONFIG, player).await; world.spawn_player(&BASIC_CONFIG, player).await;
} }
} }
@ -311,9 +312,3 @@ fn main() -> io::Result<()> {
} }
}) })
} }
fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}

View File

@ -40,11 +40,11 @@ impl RCONServer {
.register(&mut listener, SERVER, Interest::READABLE) .register(&mut listener, SERVER, Interest::READABLE)
.unwrap(); .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 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(); let password = config.password.clone();
@ -77,11 +77,12 @@ impl RCONServer {
break; break;
} }
let token = Self::next(&mut unique_token); unique_id += 1;
let token = unique_id;
poll.registry() poll.registry()
.register( .register(
&mut connection, &mut connection,
token, Token(token),
Interest::READABLE.add(Interest::WRITABLE), Interest::READABLE.add(Interest::WRITABLE),
) )
.unwrap(); .unwrap();
@ -89,13 +90,13 @@ impl RCONServer {
}, },
token => { 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 client.handle(server, &password).await
} else { } else {
false false
}; };
if done { if done {
if let Some(mut client) = connections.remove(&token) { if let Some(mut client) = connections.remove(&token.0) {
let config = &ADVANCED_CONFIG.rcon; let config = &ADVANCED_CONFIG.rcon;
if config.logging.log_quit { if config.logging.log_quit {
log::info!( log::info!(
@ -111,12 +112,6 @@ impl RCONServer {
} }
} }
} }
fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}
} }
pub struct RCONClient { pub struct RCONClient {

View File

@ -1,6 +1,5 @@
use connection_cache::{CachedBranding, CachedStatus}; use connection_cache::{CachedBranding, CachedStatus};
use key_store::KeyStore; use key_store::KeyStore;
use mio::Token;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use pumpkin_config::BASIC_CONFIG; use pumpkin_config::BASIC_CONFIG;
use pumpkin_core::GameMode; use pumpkin_core::GameMode;
@ -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 entity_id = self.new_entity_id();
let gamemode = match BASIC_CONFIG.default_gamemode { let gamemode = match BASIC_CONFIG.default_gamemode {
GameMode::Undefined => GameMode::Survival, GameMode::Undefined => GameMode::Survival,
@ -102,7 +101,7 @@ impl Server {
let world = &self.worlds[0]; let world = &self.worlds[0];
let player = Arc::new(Player::new(client, world.clone(), entity_id, gamemode)); 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()) (player, world.clone())
} }

View File

@ -6,7 +6,6 @@ use crate::{
client::Client, client::Client,
entity::{player::Player, Entity}, entity::{player::Player, Entity},
}; };
use mio::Token;
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use parking_lot::Mutex; use parking_lot::Mutex;
use pumpkin_config::BasicConfiguration; use pumpkin_config::BasicConfiguration;
@ -35,7 +34,7 @@ pub struct World {
/// The underlying level, responsible for chunk management and terrain generation. /// The underlying level, responsible for chunk management and terrain generation.
pub level: Arc<Mutex<Level>>, pub level: Arc<Mutex<Level>>,
/// A map of active players within the world, keyed by their unique token. /// 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 // TODO: entities
} }
@ -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. /// 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. /// **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 where
P: ClientPacket, P: ClientPacket,
{ {
@ -142,7 +141,7 @@ impl World {
let current_players = self.current_players.lock(); let current_players = self.current_players.lock();
for (_, playerr) in current_players for (_, playerr) in current_players
.iter() .iter()
.filter(|(c, _)| **c != player.client.token) .filter(|(c, _)| **c != player.client.id)
{ {
let gameprofile = &playerr.gameprofile; let gameprofile = &playerr.gameprofile;
entries.push(pumpkin_protocol::client::play::Player { entries.push(pumpkin_protocol::client::play::Player {
@ -165,7 +164,7 @@ impl World {
// spawn player for every client // spawn player for every client
self.broadcast_packet_expect( self.broadcast_packet_expect(
&[player.client.token], &[player.client.id],
// TODO: add velo // TODO: add velo
&CSpawnEntity::new( &CSpawnEntity::new(
entity_id.into(), entity_id.into(),
@ -184,7 +183,7 @@ impl World {
), ),
); );
// spawn players for our client // 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) { for (_, existing_player) in self.current_players.lock().iter().filter(|c| c.0 != &token) {
let entity = &existing_player.living_entity.entity; let entity = &existing_player.living_entity.entity;
let pos = entity.pos.load(); let pos = entity.pos.load();
@ -275,18 +274,18 @@ impl World {
None None
} }
pub fn add_player(&self, token: Token, player: Arc<Player>) { pub fn add_player(&self, id: usize, player: Arc<Player>) {
self.current_players.lock().insert(token, player); self.current_players.lock().insert(id, player);
} }
pub fn remove_player(&self, player: &Player) { pub fn remove_player(&self, player: &Player) {
self.current_players self.current_players
.lock() .lock()
.remove(&player.client.token) .remove(&player.client.id)
.unwrap(); .unwrap();
let uuid = player.gameprofile.id; let uuid = player.gameprofile.id;
self.broadcast_packet_expect( self.broadcast_packet_expect(
&[player.client.token], &[player.client.id],
&CRemovePlayerInfo::new(1.into(), &[uuid]), &CRemovePlayerInfo::new(1.into(), &[uuid]),
); );
self.remove_entity(&player.living_entity.entity); self.remove_entity(&player.living_entity.entity);