Skip to main content

azalea_physics/collision_impl/
world_collisions.rs

1use std::{borrow::Cow, collections::HashSet, sync::Arc};
2
3use azalea_block::{BlockState, fluid_state::FluidState};
4use azalea_core::{
5    aabb::Aabb,
6    cursor3d::{Cursor3d, CursorIteration, CursorIterationType},
7    math::EPSILON,
8    position::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos, ChunkSectionPos, Vec3},
9};
10use azalea_physics_collision::{
11    BlockWithShape,
12    shape::{BLOCK_SHAPE, Shapes, VoxelShape},
13};
14use azalea_registry::item::ItemStack;
15use azalea_world::{Chunk, World};
16use bevy_ecs::entity::Entity;
17use parking_lot::RwLock;
18
19pub fn get_block_collisions(world: &World, aabb: &Aabb) -> Vec<VoxelShape> {
20    let mut state = BlockCollisionsState::new(world, aabb, EntityCollisionContext::of(None));
21    let mut block_collisions = Vec::new();
22
23    let initial_chunk_pos = ChunkPos::from(state.cursor.origin());
24    let initial_chunk = world.chunks.get(&initial_chunk_pos);
25    let initial_chunk = initial_chunk.as_deref().map(RwLock::read);
26
27    while let Some(item) = state.cursor.next() {
28        state.compute_next(
29            item,
30            &mut block_collisions,
31            initial_chunk_pos,
32            initial_chunk.as_deref(),
33        );
34    }
35
36    block_collisions
37}
38
39pub fn get_block_and_liquid_collisions(world: &World, aabb: &Aabb) -> Vec<VoxelShape> {
40    let mut state = BlockCollisionsState::new(
41        world,
42        aabb,
43        EntityCollisionContext::of(None).with_include_liquids(true),
44    );
45    let mut block_collisions = Vec::new();
46
47    let initial_chunk_pos = ChunkPos::from(state.cursor.origin());
48    let initial_chunk = world.chunks.get(&initial_chunk_pos);
49    let initial_chunk = initial_chunk.as_deref().map(RwLock::read);
50
51    while let Some(item) = state.cursor.next() {
52        state.compute_next(
53            item,
54            &mut block_collisions,
55            initial_chunk_pos,
56            initial_chunk.as_deref(),
57        );
58    }
59
60    block_collisions
61}
62
63pub struct BlockCollisionsState<'a> {
64    pub world: &'a World,
65    pub aabb: &'a Aabb,
66    pub entity_shape: VoxelShape,
67    pub cursor: Cursor3d,
68
69    _context: EntityCollisionContext,
70
71    cached_sections: Vec<(ChunkSectionPos, azalea_world::Section)>,
72    cached_block_shapes: Vec<(BlockState, &'static VoxelShape)>,
73}
74
75impl<'a> BlockCollisionsState<'a> {
76    fn compute_next(
77        &mut self,
78        item: CursorIteration,
79        block_collisions: &mut Vec<VoxelShape>,
80        initial_chunk_pos: ChunkPos,
81        initial_chunk: Option<&Chunk>,
82    ) {
83        if item.iteration_type == CursorIterationType::Corner {
84            return;
85        }
86
87        let item_chunk_pos = ChunkPos::from(item.pos);
88        let block_state: BlockState = if item_chunk_pos == initial_chunk_pos {
89            initial_chunk
90                .and_then(|chunk| {
91                    chunk.get_block_state(&ChunkBlockPos::from(item.pos), self.world.chunks.min_y())
92                })
93                .unwrap_or(BlockState::AIR)
94        } else {
95            self.get_block_state(item.pos)
96        };
97
98        if block_state.is_air() {
99            // fast path since we can't collide with air
100            return;
101        }
102
103        // TODO: if self.only_suffocating_blocks, return if the block isn't
104        // suffocating
105
106        // if it's a full block do a faster collision check
107        if block_state.is_collision_shape_full() {
108            if !self.aabb.intersects_aabb(&Aabb {
109                min: item.pos.to_vec3_floored(),
110                max: (item.pos + 1).to_vec3_floored(),
111            }) {
112                return;
113            }
114
115            block_collisions.push(BLOCK_SHAPE.move_relative(item.pos.to_vec3_floored()));
116            return;
117        }
118
119        let block_shape = self.get_block_shape(block_state, item.pos);
120
121        let block_shape = block_shape.move_relative(item.pos.to_vec3_floored());
122        // if the entity shape and block shape don't collide, continue
123        if !Shapes::matches_anywhere(&block_shape, &self.entity_shape, |a, b| a && b) {
124            return;
125        }
126
127        block_collisions.push(block_shape);
128    }
129
130    pub fn new(world: &'a World, aabb: &'a Aabb, context: EntityCollisionContext) -> Self {
131        let origin = BlockPos {
132            x: (aabb.min.x - EPSILON).floor() as i32 - 1,
133            y: (aabb.min.y - EPSILON).floor() as i32 - 1,
134            z: (aabb.min.z - EPSILON).floor() as i32 - 1,
135        };
136
137        let end = BlockPos {
138            x: (aabb.max.x + EPSILON).floor() as i32 + 1,
139            y: (aabb.max.y + EPSILON).floor() as i32 + 1,
140            z: (aabb.max.z + EPSILON).floor() as i32 + 1,
141        };
142
143        let cursor = Cursor3d::new(origin, end);
144
145        Self {
146            world,
147            aabb,
148            entity_shape: VoxelShape::from(aabb),
149            cursor,
150
151            _context: context,
152
153            cached_sections: Vec::new(),
154            cached_block_shapes: Vec::new(),
155        }
156    }
157
158    fn get_chunk(&self, block_x: i32, block_z: i32) -> Option<Arc<RwLock<Chunk>>> {
159        let chunk_x = ChunkSectionPos::block_to_section_coord(block_x);
160        let chunk_z = ChunkSectionPos::block_to_section_coord(block_z);
161        let chunk_pos = ChunkPos::new(chunk_x, chunk_z);
162
163        // TODO: minecraft caches chunk here
164        // ```
165        // int chunkX = SectionPos.blockToSectionCoord(blockX);
166        // int chunkZ = SectionPos.blockToSectionCoord(blockZ);
167        // long chunkPosLong = ChunkPos.asLong(chunkX, chunkZ);
168        // if (this.cachedBlockGetter != null && this.cachedBlockGetterPos == var5) {
169        //     return this.cachedBlockGetter;
170        // } else {
171        //    BlockGetter var7 = this.collisionGetter.getChunkForCollisions(chunkX, chunkZ);
172        //    this.cachedBlockGetter = var7;
173        //    this.cachedBlockGetterPos =
174        //    chunkPosLong;
175        //    return var7;
176        // }
177        // ```
178
179        self.world.chunks.get(&chunk_pos)
180    }
181
182    fn get_block_state(&mut self, block_pos: BlockPos) -> BlockState {
183        if block_pos.y < self.world.chunks.min_y() {
184            // below the world
185            return BlockState::AIR;
186        }
187
188        let section_pos = ChunkSectionPos::from(block_pos);
189        let section_block_pos = ChunkSectionBlockPos::from(block_pos);
190
191        for (cached_section_pos, cached_section) in &self.cached_sections {
192            if section_pos == *cached_section_pos {
193                return cached_section.get_block_state(section_block_pos);
194            }
195        }
196
197        let chunk = self.get_chunk(block_pos.x, block_pos.z);
198        let Some(chunk) = chunk else {
199            return BlockState::AIR;
200        };
201        let chunk = chunk.read();
202
203        let sections = &chunk.sections;
204        let section_index =
205            azalea_world::chunk::section_index(block_pos.y, self.world.chunks.min_y()) as usize;
206
207        let Some(section) = sections.get(section_index) else {
208            return BlockState::AIR;
209        };
210
211        self.cached_sections.push((section_pos, section.clone()));
212
213        section.get_block_state(section_block_pos)
214    }
215
216    fn get_block_shape(
217        &mut self,
218        block_state: BlockState,
219        pos: BlockPos,
220    ) -> Cow<'static, VoxelShape> {
221        // TODO (2026-05-06): does this cache still help? i'm pretty sure
222        // getting shapes has been optimized since this cache was implemented
223        for (cached_block_state, cached_shape) in &self.cached_block_shapes {
224            if block_state == *cached_block_state {
225                return Cow::Borrowed(cached_shape);
226            }
227        }
228
229        let shape = block_state.collision_shape(pos);
230        // if it has a random offset then we can't cache them, and it'll be a
231        // Cow::Owned
232        if let Cow::Borrowed(shape) = shape {
233            self.cached_block_shapes.push((block_state, shape));
234        }
235
236        shape
237    }
238}
239
240pub struct EntityCollisionContext {
241    pub descending: bool,
242    pub entity_bottom: f64,
243    pub held_item: ItemStack,
244    can_stand_on_fluid_predicate: CanStandOnFluidPredicate,
245    pub entity: Option<Entity>,
246}
247
248impl EntityCollisionContext {
249    pub fn of(entity: Option<Entity>) -> Self {
250        Self {
251            descending: false,
252            entity_bottom: 0.0,
253            held_item: ItemStack::Empty,
254            can_stand_on_fluid_predicate: CanStandOnFluidPredicate::PassToEntity,
255            entity,
256        }
257    }
258    pub fn with_include_liquids(mut self, include_liquids: bool) -> Self {
259        self.can_stand_on_fluid_predicate = if include_liquids {
260            CanStandOnFluidPredicate::AlwaysTrue
261        } else {
262            CanStandOnFluidPredicate::PassToEntity
263        };
264        self
265    }
266
267    pub fn can_stand_on_fluid(&self, above: &FluidState, target: &FluidState) -> bool {
268        self.can_stand_on_fluid_predicate.matches(target) && !above.is_same_kind(target)
269    }
270}
271
272enum CanStandOnFluidPredicate {
273    PassToEntity,
274    AlwaysTrue,
275}
276impl CanStandOnFluidPredicate {
277    pub fn matches(&self, _state: &FluidState) -> bool {
278        match self {
279            Self::AlwaysTrue => true,
280            // minecraft sometimes returns true for striders here, false for
281            // every other entity though
282            Self::PassToEntity => false,
283        }
284    }
285}
286
287/// This basically gets all the chunks that an entity colliding with
288/// that bounding box could be in.
289///
290/// This is forEachAccessibleNonEmptySection in vanilla Minecraft because they
291/// sort entities into sections instead of just chunks. In theory this might be
292/// a performance loss for Azalea. If this ever turns out to be a bottleneck,
293/// then maybe you should try having it do that instead.
294pub fn for_entities_in_chunks_colliding_with(
295    world: &World,
296    aabb: &Aabb,
297    mut consumer: impl FnMut(ChunkPos, &HashSet<Entity>),
298) {
299    let min_section = ChunkSectionPos::from(aabb.min - Vec3::new(2., 4., 2.));
300    let max_section = ChunkSectionPos::from(aabb.max + Vec3::new(2., 0., 2.));
301
302    let min_chunk = ChunkPos::from(min_section);
303    let max_chunk = ChunkPos::from(max_section);
304
305    for chunk_x in min_chunk.x..=max_chunk.x {
306        for chunk_z in min_chunk.z..=max_chunk.z {
307            let chunk_pos = ChunkPos::new(chunk_x, chunk_z);
308            if let Some(entities) = world.entities_by_chunk.get(&chunk_pos) {
309                consumer(chunk_pos, entities);
310            }
311        }
312    }
313}