1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00

Fix some clippy warnings

This commit is contained in:
mat 2022-06-19 22:01:54 -05:00
parent d674633e85
commit c9a070f711
10 changed files with 83 additions and 46 deletions

16
Cargo.lock generated
View file

@ -109,6 +109,7 @@ dependencies = [
"azalea-entity", "azalea-entity",
"azalea-protocol", "azalea-protocol",
"azalea-world", "azalea-world",
"owning_ref",
"tokio", "tokio",
] ]
@ -891,6 +892,15 @@ version = "11.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "owning_ref"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ff55baddef9e4ad00f88b6c743a2a8062d4c6ade126c2a528644b8e444d52ce"
dependencies = [
"stable_deref_trait",
]
[[package]] [[package]]
name = "packet-macros" name = "packet-macros"
version = "0.1.0" version = "0.1.0"
@ -1239,6 +1249,12 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.96" version = "1.0.96"

View file

@ -12,4 +12,5 @@ azalea-crypto = {path = "../azalea-crypto"}
azalea-entity = {path = "../azalea-entity"} azalea-entity = {path = "../azalea-entity"}
azalea-protocol = {path = "../azalea-protocol"} azalea-protocol = {path = "../azalea-protocol"}
azalea-world = {path = "../azalea-world"} azalea-world = {path = "../azalea-world"}
owning_ref = "0.4.1"
tokio = {version = "1.18.0", features = ["sync"]} tokio = {version = "1.18.0", features = ["sync"]}

View file

@ -1,12 +1,5 @@
use crate::Client; use crate::Client;
use azalea_protocol::{ use azalea_protocol::ServerAddress;
packets::game::{
clientbound_player_chat_packet::ClientboundPlayerChatPacket,
clientbound_system_chat_packet::ClientboundSystemChatPacket,
},
ServerAddress,
};
use std::fmt::Debug;
///! Connect to Minecraft servers. ///! Connect to Minecraft servers.

View file

@ -20,7 +20,8 @@ use azalea_protocol::{
}, },
resolver, ServerAddress, resolver, ServerAddress,
}; };
use azalea_world::{ChunkStorage, EntityStorage, World}; use azalea_world::World;
use owning_ref::OwningRef;
use std::{ use std::{
fmt::Debug, fmt::Debug,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
@ -42,7 +43,7 @@ pub enum Event {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ChatPacket { pub enum ChatPacket {
System(ClientboundSystemChatPacket), System(ClientboundSystemChatPacket),
Player(ClientboundPlayerChatPacket), Player(Box<ClientboundPlayerChatPacket>),
} }
// impl ChatPacket { // impl ChatPacket {
@ -65,6 +66,7 @@ pub struct Client {
/// Whether we should ignore errors when decoding packets. /// Whether we should ignore errors when decoding packets.
const IGNORE_ERRORS: bool = !cfg!(debug_assertions); const IGNORE_ERRORS: bool = !cfg!(debug_assertions);
#[derive(Debug)]
struct HandleError(String); struct HandleError(String);
impl Client { impl Client {
@ -172,9 +174,17 @@ impl Client {
loop { loop {
let r = conn.lock().await.read().await; let r = conn.lock().await.read().await;
match r { match r {
Ok(packet) => { Ok(packet) => match Self::handle(&packet, &tx, &state, &conn).await {
Self::handle(&packet, &tx, &state, &conn).await; Ok(_) => {}
Err(e) => {
println!("Error handling packet: {:?}", e);
if IGNORE_ERRORS {
continue;
} else {
panic!("Error handling packet: {:?}", e);
} }
}
},
Err(e) => { Err(e) => {
if IGNORE_ERRORS { if IGNORE_ERRORS {
println!("Error: {:?}", e); println!("Error: {:?}", e);
@ -242,7 +252,9 @@ impl Client {
.expect("name is not a string") .expect("name is not a string")
== p.dimension_type.to_string() == p.dimension_type.to_string()
}) })
.expect(&format!("No dimension_type with name {}", p.dimension_type)) .unwrap_or_else(|| {
panic!("No dimension_type with name {}", p.dimension_type)
})
.as_compound() .as_compound()
.unwrap() .unwrap()
.get("element") .get("element")
@ -256,13 +268,11 @@ impl Client {
.expect("height tag is not an int")) .expect("height tag is not an int"))
.try_into() .try_into()
.expect("height is not a u32"); .expect("height is not a u32");
let min_y = (*dimension_type let min_y = *dimension_type
.get("min_y") .get("min_y")
.expect("No min_y tag") .expect("No min_y tag")
.as_int() .as_int()
.expect("min_y tag is not an int")) .expect("min_y tag is not an int");
.try_into()
.expect("min_y is not an i32");
state.world = Some(World::new(16, height, min_y)); state.world = Some(World::new(16, height, min_y));
} }
@ -308,7 +318,7 @@ impl Client {
GamePacket::ClientboundUpdateRecipesPacket(_p) => { GamePacket::ClientboundUpdateRecipesPacket(_p) => {
println!("Got update recipes packet"); println!("Got update recipes packet");
} }
GamePacket::ClientboundEntityEventPacket(p) => { GamePacket::ClientboundEntityEventPacket(_p) => {
// println!("Got entity event packet {:?}", p); // println!("Got entity event packet {:?}", p);
} }
GamePacket::ClientboundRecipePacket(_p) => { GamePacket::ClientboundRecipePacket(_p) => {
@ -356,13 +366,13 @@ impl Client {
.expect("World doesn't exist! We should've gotten a login packet by now.") .expect("World doesn't exist! We should've gotten a login packet by now.")
.add_entity(entity); .add_entity(entity);
} }
GamePacket::ClientboundSetEntityDataPacket(p) => { GamePacket::ClientboundSetEntityDataPacket(_p) => {
// println!("Got set entity data packet {:?}", p); // println!("Got set entity data packet {:?}", p);
} }
GamePacket::ClientboundUpdateAttributesPacket(p) => { GamePacket::ClientboundUpdateAttributesPacket(_p) => {
// println!("Got update attributes packet {:?}", p); // println!("Got update attributes packet {:?}", p);
} }
GamePacket::ClientboundEntityVelocityPacket(p) => { GamePacket::ClientboundEntityVelocityPacket(_p) => {
// println!("Got entity velocity packet {:?}", p); // println!("Got entity velocity packet {:?}", p);
} }
GamePacket::ClientboundSetEntityLinkPacket(p) => { GamePacket::ClientboundSetEntityLinkPacket(p) => {
@ -389,9 +399,9 @@ impl Client {
GamePacket::ClientboundSetExperiencePacket(p) => { GamePacket::ClientboundSetExperiencePacket(p) => {
println!("Got set experience packet {:?}", p); println!("Got set experience packet {:?}", p);
} }
GamePacket::ClientboundTeleportEntityPacket(p) => { GamePacket::ClientboundTeleportEntityPacket(_p) => {
// println!("Got teleport entity packet {:?}", p); // println!("Got teleport entity packet {:?}", p);
let state_lock = state.lock()?; // let state_lock = state.lock()?;
// let entity = state_lock // let entity = state_lock
// .world // .world
@ -407,13 +417,13 @@ impl Client {
GamePacket::ClientboundUpdateAdvancementsPacket(p) => { GamePacket::ClientboundUpdateAdvancementsPacket(p) => {
println!("Got update advancements packet {:?}", p); println!("Got update advancements packet {:?}", p);
} }
GamePacket::ClientboundRotateHeadPacket(p) => { GamePacket::ClientboundRotateHeadPacket(_p) => {
// println!("Got rotate head packet {:?}", p); // println!("Got rotate head packet {:?}", p);
} }
GamePacket::ClientboundMoveEntityPosPacket(p) => { GamePacket::ClientboundMoveEntityPosPacket(_p) => {
// println!("Got move entity pos packet {:?}", p); // println!("Got move entity pos packet {:?}", p);
} }
GamePacket::ClientboundMoveEntityPosRotPacket(p) => { GamePacket::ClientboundMoveEntityPosRotPacket(_p) => {
// println!("Got move entity pos rot packet {:?}", p); // println!("Got move entity pos rot packet {:?}", p);
} }
GamePacket::ClientboundMoveEntityRotPacket(p) => { GamePacket::ClientboundMoveEntityRotPacket(p) => {
@ -431,7 +441,8 @@ impl Client {
} }
GamePacket::ClientboundPlayerChatPacket(p) => { GamePacket::ClientboundPlayerChatPacket(p) => {
println!("Got player chat packet {:?}", p); println!("Got player chat packet {:?}", p);
tx.send(Event::Chat(ChatPacket::Player(p.clone()))).unwrap(); tx.send(Event::Chat(ChatPacket::Player(Box::new(p.clone()))))
.unwrap();
} }
GamePacket::ClientboundSystemChatPacket(p) => { GamePacket::ClientboundSystemChatPacket(p) => {
println!("Got system chat packet {:?}", p); println!("Got system chat packet {:?}", p);
@ -475,6 +486,16 @@ impl Client {
pub async fn next(&mut self) -> Option<Event> { pub async fn next(&mut self) -> Option<Event> {
self.event_receiver.recv().await self.event_receiver.recv().await
} }
/// Gets the `World` the client is in.
///
/// This is basically a shortcut for `let world = client.state.lock().unwrap().world.as_ref().unwrap()`.
/// If the client hasn't received a login packet yet, this will panic.
pub fn world(&self) -> OwningRef<std::sync::MutexGuard<ClientState>, World> {
let state_lock: std::sync::MutexGuard<ClientState> = self.state.lock().unwrap();
let state_lock_ref = OwningRef::new(state_lock);
state_lock_ref.map(|state| state.world.as_ref().expect("World doesn't exist!"))
}
} }
impl<T> From<std::sync::PoisonError<T>> for HandleError { impl<T> From<std::sync::PoisonError<T>> for HandleError {

View file

@ -1,4 +1,4 @@
use azalea_core::{ChunkPos, EntityPos}; use azalea_core::EntityPos;
#[cfg(feature = "protocol")] #[cfg(feature = "protocol")]
use azalea_protocol::packets::game::clientbound_add_entity_packet::ClientboundAddEntityPacket; use azalea_protocol::packets::game::clientbound_add_entity_packet::ClientboundAddEntityPacket;
use uuid::Uuid; use uuid::Uuid;

View file

@ -107,7 +107,7 @@ impl BitStorage {
// assert!(bits >= 1 && bits <= 32); // assert!(bits >= 1 && bits <= 32);
if let Some(data) = &data { if let Some(data) = &data {
if data.len() == 0 { if data.is_empty() {
// TODO: make 0 bit storage actually work // TODO: make 0 bit storage actually work
return Ok(BitStorage::default()); return Ok(BitStorage::default());
} }
@ -162,7 +162,7 @@ impl BitStorage {
// return (int)(var3 >> var5 & this.mask); // return (int)(var3 >> var5 & this.mask);
assert!( assert!(
index <= self.size - 1, index < self.size,
"Index {} out of bounds (max is {})", "Index {} out of bounds (max is {})",
index, index,
self.size - 1 self.size - 1
@ -181,7 +181,7 @@ impl BitStorage {
// int var6 = (var1 - var3 * this.valuesPerLong) * this.bits; // int var6 = (var1 - var3 * this.valuesPerLong) * this.bits;
// this.data[var3] = var4 & ~(this.mask << var6) | ((long)var2 & this.mask) << var6; // this.data[var3] = var4 & ~(this.mask << var6) | ((long)var2 & this.mask) << var6;
assert!(index <= self.size - 1); assert!(index < self.size);
assert!(value <= self.mask); assert!(value <= self.mask);
let cell_index = self.cell_index(index as u64); let cell_index = self.cell_index(index as u64);
let cell = &mut self.data[cell_index as usize]; let cell = &mut self.data[cell_index as usize];

View file

@ -60,10 +60,9 @@ impl ChunkStorage {
let chunk_pos = ChunkPos::from(pos); let chunk_pos = ChunkPos::from(pos);
println!("chunk_pos {:?} block_pos {:?}", chunk_pos, pos); println!("chunk_pos {:?} block_pos {:?}", chunk_pos, pos);
let chunk = &self[&chunk_pos]; let chunk = &self[&chunk_pos];
match chunk { chunk
Some(chunk) => Some(chunk.lock().unwrap().get(&ChunkBlockPos::from(pos), min_y)), .as_ref()
None => None, .map(|chunk| chunk.lock().unwrap().get(&ChunkBlockPos::from(pos), min_y))
}
} }
pub fn replace_with_packet_data( pub fn replace_with_packet_data(
@ -137,8 +136,7 @@ impl Chunk {
// TODO: make sure the section exists // TODO: make sure the section exists
let section = &self.sections[section_index as usize]; let section = &self.sections[section_index as usize];
let chunk_section_pos = ChunkSectionBlockPos::from(pos); let chunk_section_pos = ChunkSectionBlockPos::from(pos);
let block_state = section.get(chunk_section_pos); section.get(chunk_section_pos)
block_state
} }
} }

View file

@ -34,7 +34,7 @@ impl EntityStorage {
pub fn remove_by_id(&mut self, id: u32) { pub fn remove_by_id(&mut self, id: u32) {
if let Some(entity) = self.by_id.remove(&id) { if let Some(entity) = self.by_id.remove(&id) {
let entity_chunk = ChunkPos::from(entity.pos()); let entity_chunk = ChunkPos::from(entity.pos());
if let None = self.by_chunk.remove(&entity_chunk) { if self.by_chunk.remove(&entity_chunk).is_none() {
warn!("Tried to remove entity with id {id} from chunk {entity_chunk:?} but it was not found."); warn!("Tried to remove entity with id {id} from chunk {entity_chunk:?} but it was not found.");
} }
} else { } else {
@ -80,3 +80,9 @@ impl EntityStorage {
.insert(entity_id); .insert(entity_id);
} }
} }
impl Default for EntityStorage {
fn default() -> Self {
Self::new()
}
}

View file

@ -6,14 +6,13 @@ mod entity;
mod palette; mod palette;
use azalea_block::BlockState; use azalea_block::BlockState;
use azalea_core::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos, EntityPos}; use azalea_core::{BlockPos, ChunkPos, EntityPos};
use azalea_entity::Entity; use azalea_entity::Entity;
use azalea_protocol::mc_buf::{McBufReadable, McBufWritable};
pub use bit_storage::BitStorage; pub use bit_storage::BitStorage;
pub use chunk::{Chunk, ChunkStorage}; pub use chunk::{Chunk, ChunkStorage};
pub use entity::EntityStorage; pub use entity::EntityStorage;
use std::{ use std::{
io::{Read, Write}, io::Read,
ops::{Index, IndexMut}, ops::{Index, IndexMut},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@ -61,7 +60,7 @@ impl World {
let entity = self let entity = self
.entity_storage .entity_storage
.get_mut_by_id(entity_id) .get_mut_by_id(entity_id)
.ok_or("Moving entity that doesn't exist".to_string())?; .ok_or_else(|| "Moving entity that doesn't exist".to_string())?;
let old_chunk = ChunkPos::from(entity.pos()); let old_chunk = ChunkPos::from(entity.pos());
let new_chunk = ChunkPos::from(&new_pos); let new_chunk = ChunkPos::from(&new_pos);
// this is fine because we update the chunk below // this is fine because we update the chunk below

View file

@ -1,4 +1,5 @@
use azalea_client::{Account, Event}; use azalea_client::{Account, Event};
use azalea_core::BlockPos;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -20,9 +21,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// TODO: have a "loaded" or "ready" event that fires when all chunks are loaded // TODO: have a "loaded" or "ready" event that fires when all chunks are loaded
Event::Login => {} Event::Login => {}
Event::Chat(_p) => { Event::Chat(_p) => {
let state = client.state.lock().unwrap(); let world = client.world();
let world = state.world.as_ref().unwrap(); world.get_block_state(&BlockPos::new(0, 0, 0)).unwrap();
println!("{:#?}", world); // let world = state.world.as_ref().unwrap();
// world.
// println!("{:#?}", world);
// world.get_block_state(state.player.entity.pos); // world.get_block_state(state.player.entity.pos);
// println!("{}", p.message.to_ansi(None)); // println!("{}", p.message.to_ansi(None));
// if p.message.to_ansi(None) == "<py5> ok" { // if p.message.to_ansi(None) == "<py5> ok" {