azalea_world/world.rs
1use std::{
2 collections::{HashMap, HashSet},
3 fmt::{self, Debug},
4};
5
6use azalea_block::{BlockState, fluid_state::FluidState};
7use azalea_core::position::{BlockPos, ChunkPos};
8use azalea_registry::registry_holder::RegistryHolder;
9use bevy_ecs::entity::Entity;
10use nohash_hasher::IntMap;
11
12use crate::{ChunkStorage, PartialChunkStorage, biome_id::BiomeId};
13
14/// A reference to a slice of the world, as seen by an individual client.
15///
16/// A `PartialWorld` will typically be owned by a client, and it holds strong
17/// references to chunks and entities in a [`World`]s.
18///
19/// In other words, this type holds the chunks and entities that are within
20/// render distance for a client. The same chunk/entity may be referenced by
21/// more than one `PartialWorld`.
22pub struct PartialWorld {
23 pub chunks: PartialChunkStorage,
24 /// Some metadata about entities, like what entities are in certain chunks.
25 /// This does not contain the entity data itself, that's in the ECS.
26 pub entity_infos: PartialEntityInfos,
27}
28
29impl PartialWorld {
30 pub fn new(chunk_radius: u32, owner_entity: Option<Entity>) -> Self {
31 PartialWorld {
32 chunks: PartialChunkStorage::new(chunk_radius),
33 entity_infos: PartialEntityInfos::new(owner_entity),
34 }
35 }
36
37 /// Clears the internal references to chunks in the [`PartialWorld`] and
38 /// resets the view center.
39 pub fn reset(&mut self) {
40 self.chunks = PartialChunkStorage::new(self.chunks.chunk_radius);
41 }
42}
43
44#[deprecated = "moved to `azalea_core::entity_id::MinecraftEntityId`."]
45pub type MinecraftEntityId = azalea_core::entity_id::MinecraftEntityId;
46
47/// Keep track of certain metadatas that are only relevant for this partial
48/// world.
49#[derive(Debug, Default)]
50pub struct PartialEntityInfos {
51 /// The entity ID of the player that owns this partial world.
52 ///
53 /// This will make `RelativeEntityUpdate` pretend this entity doesn't exist
54 /// so it doesn't get modified from outside sources.
55 pub owner_entity: Option<Entity>,
56 /// A counter for each entity that tracks how many updates we've observed
57 /// for it.
58 ///
59 /// This is used for shared worlds (i.e. swarms), to make sure we don't
60 /// update entities twice on accident.
61 pub updates_received: IntMap<azalea_core::entity_id::MinecraftEntityId, u32>,
62 // ^ note: using MinecraftEntityId for entity ids is acceptable here since
63 // there's no chance of collisions
64}
65
66impl PartialEntityInfos {
67 pub fn new(owner_entity: Option<Entity>) -> Self {
68 Self {
69 owner_entity,
70 updates_received: IntMap::default(),
71 }
72 }
73}
74
75/// A Minecraft world, sometimes referred to as a dimension.
76///
77/// This is the most commonly used type to interact with the world that a client
78/// is in. In here, all chunks are stored as weak pointers, which means that
79/// clients in different areas of the same world can share the same `World`
80/// instance.
81///
82/// Also see [`PartialWorld`].
83///
84/// Note that this is distinct from Bevy's `World` type, which contains all of
85/// the data for every client. When referring to the Bevy `World` within Azalea,
86/// the term "ECS" is generally used instead.
87#[derive(Debug, Default)]
88#[doc(alias("instance", "dimension", "level"))]
89pub struct World {
90 pub chunks: ChunkStorage,
91
92 /// An index of all the entities we know are in the chunks of the world
93 pub entities_by_chunk: HashMap<ChunkPos, HashSet<Entity>>,
94
95 /// An index of Minecraft entity IDs to Azalea ECS entities.
96 ///
97 /// You should avoid using this (particularly if you're using swarms) and
98 /// instead use `azalea_entity::EntityIdIndex`, since some servers may
99 /// give different entity IDs for the same entities to different
100 /// players.
101 pub entity_by_id: IntMap<azalea_core::entity_id::MinecraftEntityId, Entity>,
102
103 pub registries: RegistryHolder,
104}
105
106#[deprecated = "renamed to `World`."]
107pub type Instance = World;
108
109impl World {
110 /// Get the block at the given position, or `None` if it's outside of the
111 /// world that we have loaded.
112 pub fn get_block_state(&self, pos: BlockPos) -> Option<BlockState> {
113 self.chunks.get_block_state(pos)
114 }
115
116 /// Similar to [`Self::get_block_state`], but returns data about the fluid
117 /// at the position, including for waterlogged blocks.
118 pub fn get_fluid_state(&self, pos: BlockPos) -> Option<FluidState> {
119 self.chunks.get_block_state(pos).map(FluidState::from)
120 }
121
122 /// Get the [`BiomeId`] at the given position.
123 ///
124 /// You can then use [`BiomeId::into_biome`] or
125 /// `Client::with_resolved_registry` to get data from this biome.
126 ///
127 /// Note that biomes are internally stored as 4x4x4 blocks, so if you're
128 /// writing code that searches for a specific biome it'll probably be more
129 /// efficient to avoid scanning every single block.
130 pub fn get_biome_id(&self, pos: BlockPos) -> Option<BiomeId> {
131 self.chunks.get_biome_id(pos)
132 }
133
134 pub fn set_block_state(&self, pos: BlockPos, state: BlockState) -> Option<BlockState> {
135 self.chunks.set_block_state(pos, state)
136 }
137}
138
139impl Debug for PartialWorld {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f.debug_struct("PartialWorld")
142 .field("chunks", &self.chunks)
143 .field("entity_infos", &self.entity_infos)
144 .finish()
145 }
146}
147
148impl Default for PartialWorld {
149 /// Creates a completely self-contained [`PartialWorld`]. This is only for
150 /// testing and shouldn't be used in actual code!
151 fn default() -> Self {
152 let chunk_storage = PartialChunkStorage::default();
153 let entity_storage = PartialEntityInfos::default();
154 Self {
155 chunks: chunk_storage,
156 entity_infos: entity_storage,
157 }
158 }
159}
160
161impl From<ChunkStorage> for World {
162 /// Make an empty world from this `ChunkStorage`. This is meant to be a
163 /// convenience function for tests.
164 fn from(chunks: ChunkStorage) -> Self {
165 Self {
166 chunks,
167 entities_by_chunk: HashMap::new(),
168 entity_by_id: IntMap::default(),
169 registries: RegistryHolder::default(),
170 }
171 }
172}