Skip to content

Commit

Permalink
minor memory usage optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
mat-1 committed Feb 23, 2025
1 parent 34f53ba commit f8130c3
Show file tree
Hide file tree
Showing 12 changed files with 141 additions and 10 deletions.
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 ---

Expand Down
7 changes: 7 additions & 0 deletions azalea-buf/src/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::{
collections::HashMap,
hash::Hash,
io::{Cursor, Read},
sync::Arc,
};

use byteorder::{BE, ReadBytesExt};
Expand Down Expand Up @@ -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)?))
}
}
7 changes: 7 additions & 0 deletions azalea-buf/src/write.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{
collections::HashMap,
io::{self, Write},
sync::Arc,
};

use byteorder::{BigEndian, WriteBytesExt};
Expand Down Expand Up @@ -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)
}
}
3 changes: 2 additions & 1 deletion azalea-client/src/disconnect.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion azalea-client/src/test_simulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions azalea-language/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ license.workspace = true
repository.workspace = true

[dependencies]
compact_str = { workspace = true, features = ["serde"] }
serde.workspace = true
serde_json.workspace = true
4 changes: 3 additions & 1 deletion azalea-language/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
14 changes: 11 additions & 3 deletions azalea-physics/src/fluids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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 {
Expand Down
12 changes: 10 additions & 2 deletions azalea-protocol/src/packets/game/c_level_chunk_with_light.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use azalea_buf::AzBuf;
use azalea_protocol_macros::ClientboundGamePacket;
use simdnbt::owned::Nbt;
Expand All @@ -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>,
}

Expand Down
1 change: 1 addition & 0 deletions azalea-world/src/chunk_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!"
Expand Down
68 changes: 66 additions & 2 deletions azalea/examples/testbot/commands/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -200,13 +204,73 @@ 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());
});

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
}));
}

0 comments on commit f8130c3

Please sign in to comment.