Add pumpkin-world

also refactor player
This commit is contained in:
Snowiiii committed 2024-08-04 00:29:20 +02:00
1 parent 31aa333410
commit ae69bbc7f1
20 files changed
+342 -268

No files matched your search

+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
pumpkin-world = { path = "../pumpkin-world"}
pumpkin-protocol = { path = "../pumpkin-protocol"}
pumpkin-registry = { path = "../pumpkin-registry"}
+14 -2
View File
@@ -10,6 +10,7 @@ use crate::{
};
use mio::{event::Event, net::TcpStream, Token};
use player_packet::PlayerPacketProcessor;
use pumpkin_protocol::{
client::{config::CConfigDisconnect, login::CLoginDisconnect},
packet_decoder::PacketDecoder,
@@ -18,6 +19,7 @@ use pumpkin_protocol::{
config::{SAcknowledgeFinishConfig, SClientInformation, SKnownPacks, SPluginMessage},
handshake::SHandShake,
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
play::SConfirmTeleport,
status::{SPingRequest, SStatusRequest},
},
ClientPacket, ConnectionState, PacketError, RawPacket, ServerPacket,
@@ -186,8 +188,8 @@ impl Client {
),
},
pumpkin_protocol::ConnectionState::Play => {
if let Some(player) = &mut self.player {
player.handle_packet(server, packet);
if self.player.is_some() {
self.handle_play_packet(server, packet);
} else {
// should be impossible
self.kick("no player in play state?")
@@ -197,6 +199,16 @@ impl Client {
}
}
pub fn handle_play_packet(&mut self, server: &mut Server, packet: &mut RawPacket) {
let bytebuf = &mut packet.bytebuf;
match packet.id {
SConfirmTeleport::PACKET_ID => {
self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf))
}
_ => log::error!("Failed to handle player packet id {}", packet.id),
}
}
// Reads the connection until our buffer of len 4096 is full, then decode
/// Close connection when an error occurs
pub fn poll(&mut self, server: &mut Server, event: &Event) {
+18 -2
View File
@@ -2,12 +2,28 @@ use pumpkin_protocol::server::play::SConfirmTeleport;
use crate::{entity::player::Player, server::Server};
use super::Client;
// implement player packets
pub trait PlayerPacketProcessor {
fn handle_confirm_teleport(&mut self, server: &mut Server, confirm_teleport: SConfirmTeleport);
}
impl PlayerPacketProcessor for Player {
fn handle_confirm_teleport(&mut self, server: &mut Server, confirm_teleport: SConfirmTeleport) {
impl PlayerPacketProcessor for Client {
fn handle_confirm_teleport(
&mut self,
_server: &mut Server,
confirm_teleport: SConfirmTeleport,
) {
let player = self.player.as_mut().unwrap();
if let Some(id) = player.awaiting_teleport {
if id == confirm_teleport.teleport_id {
} else {
log::warn!("Teleport id does not match, Weird but okay");
}
player.awaiting_teleport = None;
} else {
self.kick("Send Teleport confirm, but we did not teleport")
}
}
}
+2 -8
View File
@@ -62,13 +62,10 @@ impl AdvancedConfiguration {
pub fn load<P: AsRef<Path>>(path: P) -> AdvancedConfiguration {
if path.as_ref().exists() {
let toml = std::fs::read_to_string(path).expect("Couldn't read configuration");
let configuration: AdvancedConfiguration =
toml::from_str(toml.as_str()).expect("Couldn't parse");
configuration
toml::from_str(toml.as_str()).expect("Couldn't parse")
} else {
let config = AdvancedConfiguration::default();
let toml = toml::to_string(&config).expect("Couldn't create toml!");
std::fs::write(path, toml).expect("Couldn't save configuration");
config
}
@@ -79,13 +76,10 @@ impl BasicConfiguration {
pub fn load<P: AsRef<Path>>(path: P) -> BasicConfiguration {
if path.as_ref().exists() {
let toml = std::fs::read_to_string(path).expect("Couldn't read configuration");
let configuration: BasicConfiguration =
toml::from_str(toml.as_str()).expect("Couldn't parse");
configuration
toml::from_str(toml.as_str()).expect("Couldn't parse")
} else {
let config = BasicConfiguration::default();
let toml = toml::to_string(&config).expect("Couldn't create toml!");
std::fs::write(path, toml).expect("Couldn't save configuration");
config
}
+8 -14
View File
@@ -1,31 +1,25 @@
use pumpkin_protocol::{server::play::SConfirmTeleport, RawPacket, ServerPacket, VarInt};
use crate::{client::player_packet::PlayerPacketProcessor, server::Server};
use pumpkin_protocol::VarInt;
use super::{Entity, EntityId};
pub struct Player {
pub entity: Entity,
// Current awaiting teleport id, None if did not teleport
pub awaiting_teleport: Option<VarInt>,
}
impl Player {
pub fn new(entity: Entity) -> Self {
Self { entity }
Self {
entity,
awaiting_teleport: None,
}
}
pub fn entity_id(&self) -> EntityId {
self.entity.entity_id
}
pub fn handle_packet(&mut self, server: &mut Server, packet: &mut RawPacket) {
let bytebuf = &mut packet.bytebuf;
match packet.id {
SConfirmTeleport::PACKET_ID => {
self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf))
}
_ => log::error!("Failed to handle Player packet, id {}", packet.id),
}
}
}
pub enum Hand {
-1
View File
@@ -14,7 +14,6 @@ pub mod configuration;
pub mod entity;
pub mod server;
pub mod util;
pub mod world;
#[cfg(not(target_os = "wasi"))]
fn main() -> io::Result<()> {
-174
View File
@@ -1,174 +0,0 @@
use crate::{
entity::player::GameMode,
protocol::{bytebuf::ByteBuffer, ClientPacket, VarInt},
};
pub struct SetHeldItem {
slot: i8,
}
impl SetHeldItem {
pub fn new(slot: i8) -> Self {
Self { slot }
}
}
impl ClientPacket for SetHeldItem {
const PACKET_ID: VarInt = 0x53;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i8(self.slot);
}
}
pub struct CPlayerAbilities {
flags: i8,
flying_speed: f32,
field_of_view: f32,
}
impl CPlayerAbilities {
pub fn new(flags: i8, flying_speed: f32, field_of_view: f32) -> Self {
Self {
flags,
flying_speed,
field_of_view,
}
}
}
impl ClientPacket for CPlayerAbilities {
const PACKET_ID: VarInt = 0x38;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i8(self.flags);
bytebuf.put_f32(self.flying_speed);
bytebuf.put_f32(self.field_of_view);
}
}
pub struct CChangeDifficulty {
difficulty: u8,
locked: bool,
}
impl CChangeDifficulty {
pub fn new(difficulty: u8, locked: bool) -> Self {
Self { difficulty, locked }
}
}
impl ClientPacket for CChangeDifficulty {
const PACKET_ID: VarInt = 0x0B;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_u8(self.difficulty);
bytebuf.put_bool(self.locked);
}
}
pub struct CLogin {
entity_id: i32,
is_hardcore: bool,
dimension_count: VarInt,
dimension_names: Vec<String>,
max_players: VarInt,
view_distance: VarInt,
simulated_distance: VarInt,
reduced_debug_info: bool,
enabled_respawn_screen: bool,
limited_crafting: bool,
dimension_type: VarInt,
dimension_name: String,
hashed_seed: i64,
game_mode: GameMode,
previous_gamemode: GameMode,
debug: bool,
is_flat: bool,
has_death_loc: bool,
death_dimension_name: Option<String>,
death_loc: Option<String>, // POSITION NOT STRING
portal_cooldown: VarInt,
enforce_secure_chat: bool,
}
impl CLogin {
#[allow(clippy::too_many_arguments)]
pub fn new(
entity_id: i32,
is_hardcore: bool,
dimension_count: VarInt,
dimension_names: Vec<String>,
max_players: VarInt,
view_distance: VarInt,
simulated_distance: VarInt,
reduced_debug_info: bool,
enabled_respawn_screen: bool,
limited_crafting: bool,
dimension_type: VarInt,
dimension_name: String,
hashed_seed: i64,
game_mode: GameMode,
previous_gamemode: GameMode,
debug: bool,
is_flat: bool,
has_death_loc: bool,
death_dimension_name: Option<String>,
death_loc: Option<String>,
portal_cooldown: VarInt,
enforce_secure_chat: bool,
) -> Self {
Self {
entity_id,
is_hardcore,
dimension_count,
dimension_names,
max_players,
view_distance,
simulated_distance,
reduced_debug_info,
enabled_respawn_screen,
limited_crafting,
dimension_type,
dimension_name,
hashed_seed,
game_mode,
previous_gamemode,
debug,
is_flat,
has_death_loc,
death_dimension_name,
death_loc,
portal_cooldown,
enforce_secure_chat,
}
}
}
impl ClientPacket for CLogin {
const PACKET_ID: VarInt = 0x2B;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i32(self.entity_id);
bytebuf.put_bool(self.is_hardcore);
bytebuf.put_var_int(self.dimension_count);
bytebuf.put_string_array(self.dimension_names.as_slice());
bytebuf.put_var_int(self.max_players);
bytebuf.put_var_int(self.view_distance);
bytebuf.put_var_int(self.simulated_distance);
bytebuf.put_bool(self.reduced_debug_info);
bytebuf.put_bool(self.enabled_respawn_screen);
bytebuf.put_bool(self.limited_crafting);
bytebuf.put_var_int(self.dimension_type);
bytebuf.put_string(&self.dimension_name);
bytebuf.put_i64(self.hashed_seed);
bytebuf.put_u8(self.game_mode.to_byte() as u8);
bytebuf.put_i8(self.previous_gamemode.to_byte());
bytebuf.put_bool(self.debug);
bytebuf.put_bool(self.is_flat);
bytebuf.put_bool(self.has_death_loc);
bytebuf.put_option(&self.death_dimension_name, |buf, v| buf.put_string(v));
bytebuf.put_option(&self.death_loc, |buf, v| buf.put_string(v));
bytebuf.put_var_int(self.portal_cooldown);
bytebuf.put_bool(self.enforce_secure_chat);
}
}
+31 -12
View File
@@ -1,5 +1,6 @@
use std::{
io::Cursor,
rc::Rc,
sync::atomic::{AtomicI32, Ordering},
};
@@ -8,9 +9,13 @@ use mio::{event::Event, Poll};
use pumpkin_protocol::{
client::{
config::CPluginMessage,
play::{CGameEvent, CLogin, CSyncPlayerPostion},
play::{CChunkDataUpdateLight, CGameEvent, CLogin, CSyncPlayerPostion, SkyLight},
},
PacketError, Players, Sample, StatusResponse, VarInt, VarInt32, Version,
BitSet, PacketError, Players, Sample, StatusResponse, VarInt, VarInt32, Version,
};
use pumpkin_world::{
chunk::{TestChunk, SKY_LIGHT_ARRAYS},
World,
};
use rsa::{rand_core::OsRng, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
use serde::{Deserialize, Serialize};
@@ -22,7 +27,6 @@ use crate::{
player::{GameMode, Player},
Entity, EntityId,
},
world::World,
};
pub struct Server {
@@ -37,8 +41,7 @@ pub struct Server {
/// the maximum amount of players that can join the Server
pub max_players: u32,
pub world: World,
// pub world: World,
pub status_response: StatusResponse,
// We cache the json response here so we don't parse it every time someone makes a Status request.
// Keep in mind that we must parse this again, when the StatusResponse changes which usally happen when a player joins or leaves
@@ -72,7 +75,7 @@ impl Server {
Self {
// 0 is invalid
entity_id: 2.into(),
world: World::new(),
// world: World::load(""),
online_mode: config.0.online_mode,
encryption: config.1.encryption,
compression_threshold: None, // 256
@@ -96,11 +99,9 @@ impl Server {
// todo: do this in a world
pub fn spawn_player(&mut self, client: &mut Client) {
dbg!("spawning player");
let player = Player {
entity: Entity {
entity_id: self.new_entity_id(),
},
};
let player = Player::new(Entity {
entity_id: self.new_entity_id(),
});
client
.send_packet(CLogin::new(
@@ -137,11 +138,29 @@ impl Server {
.send_packet(CGameEvent::new(13, 0.0))
.unwrap_or_else(|e| client.kick(&e.to_string()));
Server::spawn_test_chunk(client);
client.player = Some(player);
}
// todo: do this in a world
fn spawn_test_chunk(client: &Client) {}
fn spawn_test_chunk(client: &mut Client) {
let test_chunk = TestChunk::new();
client
.send_packet(CChunkDataUpdateLight::new(
10,
10,
test_chunk.heightmap,
Vec::new(),
Vec::new(),
BitSet(0, Vec::new()),
BitSet(0, Vec::new()),
BitSet(0, Vec::new()),
Vec::new(),
Vec::new(),
))
.unwrap_or_else(|e| client.kick(&e.to_string()))
}
// move to world
pub fn new_entity_id(&self) -> EntityId {
-19
View File
@@ -1,19 +0,0 @@
use crate::entity::player::Player;
pub struct World {
pub players: Vec<Player>,
}
impl Default for World {
fn default() -> Self {
Self::new()
}
}
impl World {
pub fn new() -> Self {
Self {
players: Vec::new(),
}
}
}