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

minor memory usage optimizations

This commit is contained in:
mat 2025-02-23 03:10:21 +00:00
parent 34f53baf85
commit f8130c3c92
12 changed files with 141 additions and 10 deletions

31
Cargo.lock generated
View file

@ -449,6 +449,7 @@ dependencies = [
name = "azalea-language"
version = "0.11.0+mc1.21.4"
dependencies = [
"compact_str",
"serde",
"serde_json",
]
@ -823,6 +824,15 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "castaway"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5"
dependencies = [
"rustversion",
]
[[package]]
name = "cc"
version = "1.2.15"
@ -951,6 +961,21 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "compact_str"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b79c4069c6cad78e2e0cdfcbd26275770669fb39fd308a752dc110e83b9af32"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"serde",
"static_assertions",
]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@ -2907,6 +2932,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "subtle"
version = "2.6.1"

View file

@ -80,6 +80,7 @@ hickory-resolver = { version = "0.24.3", default-features = false }
uuid = "1.12.1"
num-format = "0.4.4"
indexmap = "2.7.1"
compact_str = "0.8.1"
# --- Profile Settings ---

View file

@ -3,6 +3,7 @@ use std::{
collections::HashMap,
hash::Hash,
io::{Cursor, Read},
sync::Arc,
};
use byteorder::{BE, ReadBytesExt};
@ -423,3 +424,9 @@ impl<A: AzaleaRead, B: AzaleaRead> AzaleaRead for (A, B) {
Ok((A::azalea_read(buf)?, B::azalea_read(buf)?))
}
}
impl<T: AzaleaRead> AzaleaRead for Arc<T> {
fn azalea_read(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
Ok(Arc::new(T::azalea_read(buf)?))
}
}

View file

@ -1,6 +1,7 @@
use std::{
collections::HashMap,
io::{self, Write},
sync::Arc,
};
use byteorder::{BigEndian, WriteBytesExt};
@ -298,3 +299,9 @@ impl<A: AzaleaWrite, B: AzaleaWrite> AzaleaWrite for (A, B) {
self.1.azalea_write(buf)
}
}
impl<T: AzaleaWrite> AzaleaWrite for Arc<T> {
fn azalea_write(&self, buf: &mut impl Write) -> Result<(), io::Error> {
T::azalea_write(&**self, buf)
}
}

View file

@ -1,7 +1,7 @@
//! Disconnect a client from the server.
use azalea_chat::FormattedText;
use azalea_entity::{EntityBundle, LocalEntity, metadata::PlayerMetadataBundle};
use azalea_entity::{EntityBundle, InLoadedChunk, LocalEntity, metadata::PlayerMetadataBundle};
use bevy_app::{App, Plugin, PostUpdate};
use bevy_ecs::{
component::Component,
@ -57,6 +57,7 @@ pub fn remove_components_from_disconnected_players(
.remove::<EntityBundle>()
.remove::<InstanceHolder>()
.remove::<PlayerMetadataBundle>()
.remove::<InLoadedChunk>()
// this makes it close the tcp connection
.remove::<RawConnection>()
// swarm detects when this tx gets dropped to fire SwarmEvent::Disconnect

View file

@ -257,7 +257,7 @@ pub fn make_basic_empty_chunk(
z: pos.z,
chunk_data: ClientboundLevelChunkPacketData {
heightmaps: Nbt::None,
data: chunk_bytes,
data: chunk_bytes.into(),
block_entities: vec![],
},
light_data: ClientboundLightUpdatePacketData::default(),

View file

@ -7,5 +7,6 @@ license.workspace = true
repository.workspace = true
[dependencies]
compact_str = { workspace = true, features = ["serde"] }
serde.workspace = true
serde_json.workspace = true

View file

@ -2,7 +2,9 @@
use std::{collections::HashMap, sync::LazyLock};
pub static STORAGE: LazyLock<HashMap<String, String>> =
use compact_str::CompactString;
pub static STORAGE: LazyLock<HashMap<CompactString, CompactString>> =
LazyLock::new(|| serde_json::from_str(include_str!("en_us.json")).unwrap());
pub fn get(key: &str) -> Option<&str> {

View file

@ -5,6 +5,7 @@ use azalea_block::{
use azalea_core::{
direction::Direction,
position::{BlockPos, Vec3},
resource_location::ResourceLocation,
};
use azalea_entity::{InLoadedChunk, LocalEntity, Physics, Position};
use azalea_world::{Instance, InstanceContainer, InstanceName};
@ -31,11 +32,18 @@ pub fn update_in_water_state_and_do_fluid_pushing(
update_in_water_state_and_do_water_current_pushing(&mut physics, &world, position);
// right now doing registries.dimension_type() clones the entire registry which
// is very inefficient, so for now we're doing this instead
let is_ultrawarm = world
.registries
.dimension_type()
.and_then(|d| d.map.get(instance_name).map(|d| d.ultrawarm))
== Some(Some(true));
.map
.get(&ResourceLocation::new("minecraft:dimension_type"))
.and_then(|d| {
d.get(&**instance_name)
.map(|d| d.byte("ultrawarm") != Some(0))
})
.unwrap_or_default();
let lava_push_factor = if is_ultrawarm {
0.007
} else {

View file

@ -1,3 +1,5 @@
use std::sync::Arc;
use azalea_buf::AzBuf;
use azalea_protocol_macros::ClientboundGamePacket;
use simdnbt::owned::Nbt;
@ -16,8 +18,14 @@ pub struct ClientboundLevelChunkWithLight {
#[derive(Clone, Debug, AzBuf)]
pub struct ClientboundLevelChunkPacketData {
pub heightmaps: Nbt,
// we can't parse the data in azalea-protocol because it depends on context from other packets
pub data: Vec<u8>,
/// The raw chunk sections.
///
/// We can't parse the data in azalea-protocol because it depends on context
/// from other packets
///
/// This is an Arc because it's often very big and we want it to be cheap to
/// clone.
pub data: Arc<Vec<u8>>,
pub block_entities: Vec<BlockEntity>,
}

View file

@ -448,6 +448,7 @@ impl AzaleaRead for Section {
let block_count = u16::azalea_read(buf)?;
// this is commented out because the vanilla server is wrong
// ^ this comment was written ages ago. needs more investigation.
// assert!(
// block_count <= 16 * 16 * 16,
// "A section has more blocks than what should be possible. This is a bug!"

View file

@ -5,11 +5,15 @@ use std::{env, fs::File, io::Write, thread, time::Duration};
use azalea::{
BlockPos,
brigadier::prelude::*,
chunks::ReceiveChunkEvent,
entity::{LookDirection, Position},
interact::HitResultComponent,
packet_handling::game,
pathfinder::{ExecutingPath, Pathfinder},
world::MinecraftEntityId,
};
use azalea_world::InstanceContainer;
use bevy_ecs::event::Events;
use parking_lot::Mutex;
use super::{CommandSource, Ctx};
@ -200,8 +204,53 @@ pub fn register(commands: &mut CommandDispatcher<Mutex<CommandSource>>) {
writeln!(report).unwrap();
for (info, _) in ecs.iter_resources() {
writeln!(report, "Resource: {}", info.name()).unwrap();
writeln!(report, "- Size: {} bytes", info.layout().size()).unwrap();
let name = info.name();
writeln!(report, "Resource: {name}").unwrap();
// writeln!(report, "- Size: {} bytes",
// info.layout().size()).unwrap();
match name {
"azalea_world::container::InstanceContainer" => {
let instance_container = ecs.resource::<InstanceContainer>();
for (instance_name, instance) in &instance_container.instances {
writeln!(report, "- Name: {}", instance_name).unwrap();
writeln!(report, "- Reference count: {}", instance.strong_count())
.unwrap();
if let Some(instance) = instance.upgrade() {
let instance = instance.read();
let strong_chunks = instance
.chunks
.map
.iter()
.filter(|(_, v)| v.strong_count() > 0)
.count();
writeln!(
report,
"- Chunks: {} strongly referenced, {} in map",
strong_chunks,
instance.chunks.map.len()
)
.unwrap();
writeln!(
report,
"- Entities: {}",
instance.entities_by_chunk.len()
)
.unwrap();
}
}
}
"bevy_ecs::event::collections::Events<azalea_client::packet_handling::game::PacketEvent>" => {
let events = ecs.resource::<Events<game::PacketEvent>>();
writeln!(report, "- Event count: {}", events.len()).unwrap();
}
"bevy_ecs::event::collections::Events<azalea_client::chunks::ReceiveChunkEvent>" => {
let events = ecs.resource::<Events<ReceiveChunkEvent>>();
writeln!(report, "- Event count: {}", events.len()).unwrap();
}
_ => {}
}
}
println!("\x1b[1mWrote report to {}\x1b[m", report_path.display());
@ -209,4 +258,19 @@ pub fn register(commands: &mut CommandDispatcher<Mutex<CommandSource>>) {
1
}));
commands.register(literal("exit").executes(|ctx: &Ctx| {
let source = ctx.source.lock();
source.reply("bye!");
source.bot.disconnect();
thread::spawn(move || {
thread::sleep(Duration::from_secs(1));
std::process::exit(0);
});
1
}));
}