Skip to main content

azalea_physics/collision/
world_collisions.rs

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