aboutsummaryrefslogtreecommitdiff
path: root/azalea-physics/src/clip.rs
blob: af853821ea1988ddd697d3ec31df0c77fc4a8837 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use std::{borrow::Cow, collections::HashSet};

use azalea_block::{
    BlockState,
    fluid_state::{FluidKind, FluidState},
};
use azalea_core::{
    aabb::Aabb,
    direction::{Axis, Direction},
    hit_result::BlockHitResult,
    math::{self, EPSILON, lerp},
    position::{BlockPos, Vec3},
};
use azalea_registry::{builtin::BlockKind, tags};
use azalea_world::ChunkStorage;

use crate::collision::{BlockWithShape, EMPTY_SHAPE, VoxelShape};

#[derive(Clone, Debug)]
pub struct ClipContext {
    pub from: Vec3,
    pub to: Vec3,
    pub block_shape_type: BlockShapeType,
    pub fluid_pick_type: FluidPickType,
    // pub collision_context: EntityCollisionContext,
}
impl ClipContext {
    /// Get the shape of given block, using the type of shape set in
    /// [`Self::block_shape_type`].
    pub fn block_shape(&self, block_state: BlockState, pos: BlockPos) -> Cow<'static, VoxelShape> {
        // minecraft passes in the world and blockpos to this function but it's not
        // actually necessary. it is for fluid_shape though
        match self.block_shape_type {
            BlockShapeType::Collider => block_state.collision_shape(pos),
            BlockShapeType::Outline => block_state.outline_shape(pos),
            BlockShapeType::Visual => block_state.collision_shape(pos),
            BlockShapeType::FallDamageResetting => {
                if tags::blocks::FALL_DAMAGE_RESETTING.contains(&BlockKind::from(block_state)) {
                    block_state.collision_shape(pos)
                } else {
                    Cow::Borrowed(&EMPTY_SHAPE)
                }
            }
        }
    }

    pub fn fluid_shape(
        &self,
        fluid_state: FluidState,
        world: &ChunkStorage,
        pos: BlockPos,
    ) -> &VoxelShape {
        if self.fluid_pick_type.can_pick(&fluid_state) {
            crate::collision::fluid_shape(&fluid_state, world, pos)
        } else {
            &EMPTY_SHAPE
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum BlockShapeType {
    /// The shape that's used for collision.
    Collider,
    /// The block outline that renders when your cursor is over a block.
    Outline,
    /// Used by entities when considering their line of sight.
    ///
    /// TODO: visual block shape isn't implemented (it'll just return the
    /// collider shape), that's correct for most blocks though
    Visual,
    FallDamageResetting,
}
#[derive(Clone, Copy, Debug)]
pub enum FluidPickType {
    None,
    SourceOnly,
    Any,
    Water,
}
impl FluidPickType {
    pub fn can_pick(&self, fluid_state: &FluidState) -> bool {
        match self {
            Self::None => false,
            Self::SourceOnly => fluid_state.amount == 8,
            Self::Any => fluid_state.kind != FluidKind::Empty,
            Self::Water => fluid_state.kind == FluidKind::Water,
        }
    }
}

pub fn clip(chunk_storage: &ChunkStorage, context: ClipContext) -> BlockHitResult {
    traverse_blocks(
        context.from,
        context.to,
        context,
        |ctx, block_pos| {
            let block_state = chunk_storage.get_block_state(block_pos).unwrap_or_default();
            let fluid_state = FluidState::from(block_state);

            let block_shape = ctx.block_shape(block_state, block_pos);
            let interaction_clip = clip_with_interaction_override(
                ctx.from,
                ctx.to,
                block_pos,
                &block_shape,
                block_state,
            );
            let fluid_shape = ctx.fluid_shape(fluid_state, chunk_storage, block_pos);
            let fluid_clip = fluid_shape.clip(ctx.from, ctx.to, block_pos);

            let distance_to_interaction = interaction_clip
                .as_ref()
                .map(|hit| ctx.from.distance_squared_to(hit.location))
                .unwrap_or(f64::MAX);
            let distance_to_fluid = fluid_clip
                .as_ref()
                .map(|hit| ctx.from.distance_squared_to(hit.location))
                .unwrap_or(f64::MAX);

            if distance_to_interaction <= distance_to_fluid {
                interaction_clip
            } else {
                fluid_clip
            }
        },
        |context| {
            let vec = context.from - context.to;
            BlockHitResult::miss(context.to, Direction::nearest(vec))
        },
    )
}

fn clip_with_interaction_override(
    from: Vec3,
    to: Vec3,
    block_pos: BlockPos,
    block_shape: &VoxelShape,
    _block_state: BlockState,
) -> Option<BlockHitResult> {
    let block_hit_result = block_shape.clip(from, to, block_pos);

    if let Some(block_hit_result) = block_hit_result {
        // TODO: minecraft calls .getInteractionShape here
        // getInteractionShape is empty for almost every shape except cauldons,
        // compostors, hoppers, and scaffolding.
        let interaction_shape = &*EMPTY_SHAPE;
        let interaction_hit_result = interaction_shape.clip(from, to, block_pos);
        if let Some(interaction_hit_result) = interaction_hit_result
            && interaction_hit_result.location.distance_squared_to(from)
                < block_hit_result.location.distance_squared_to(from)
        {
            return Some(block_hit_result.with_direction(interaction_hit_result.direction));
        }

        Some(block_hit_result)
    } else {
        None
    }
}

pub fn traverse_blocks<C, T>(
    from: Vec3,
    to: Vec3,
    context: C,
    get_hit_result: impl Fn(&C, BlockPos) -> Option<T>,
    get_miss_result: impl Fn(&C) -> T,
) -> T {
    if from == to {
        return get_miss_result(&context);
    }

    let right_after_end = Vec3 {
        x: lerp(-EPSILON, to.x, from.x),
        y: lerp(-EPSILON, to.y, from.y),
        z: lerp(-EPSILON, to.z, from.z),
    };

    let right_before_start = Vec3 {
        x: lerp(-EPSILON, from.x, to.x),
        y: lerp(-EPSILON, from.y, to.y),
        z: lerp(-EPSILON, from.z, to.z),
    };

    let mut current_block = BlockPos::from(right_before_start);
    if let Some(data) = get_hit_result(&context, current_block) {
        return data;
    }

    let vec = right_after_end - right_before_start;

    let vec_sign = Vec3 {
        x: math::sign(vec.x),
        y: math::sign(vec.y),
        z: math::sign(vec.z),
    };

    #[rustfmt::skip]
    let percentage_step = Vec3 {
        x: if vec_sign.x == 0. { f64::MAX } else { vec_sign.x / vec.x },
        y: if vec_sign.y == 0. { f64::MAX } else { vec_sign.y / vec.y },
        z: if vec_sign.z == 0. { f64::MAX } else { vec_sign.z / vec.z },
    };

    let mut percentage = Vec3 {
        x: percentage_step.x
            * if vec_sign.x > 0. {
                1. - math::fract(right_before_start.x)
            } else {
                math::fract(right_before_start.x)
            },
        y: percentage_step.y
            * if vec_sign.y > 0. {
                1. - math::fract(right_before_start.y)
            } else {
                math::fract(right_before_start.y)
            },
        z: percentage_step.z
            * if vec_sign.z > 0. {
                1. - math::fract(right_before_start.z)
            } else {
                math::fract(right_before_start.z)
            },
    };

    loop {
        if percentage.x > 1. && percentage.y > 1. && percentage.z > 1. {
            return get_miss_result(&context);
        }

        if percentage.x < percentage.y {
            if percentage.x < percentage.z {
                current_block.x += vec_sign.x as i32;
                percentage.x += percentage_step.x;
            } else {
                current_block.z += vec_sign.z as i32;
                percentage.z += percentage_step.z;
            }
        } else if percentage.y < percentage.z {
            current_block.y += vec_sign.y as i32;
            percentage.y += percentage_step.y;
        } else {
            current_block.z += vec_sign.z as i32;
            percentage.z += percentage_step.z;
        }

        if let Some(data) = get_hit_result(&context, current_block) {
            return data;
        }
    }
}

pub fn box_traverse_blocks(from: Vec3, to: Vec3, aabb: &Aabb) -> HashSet<BlockPos> {
    let delta = to - from;
    let traversed_blocks = BlockPos::between_closed_aabb(aabb);
    if delta.length_squared() < (0.99999_f32 * 0.99999) as f64 {
        return traversed_blocks.into_iter().collect();
    }

    let mut traversed_and_collided_blocks = HashSet::new();
    let target_min_pos = aabb.min;
    let from_min_pos = target_min_pos - delta;
    add_collisions_along_travel(
        &mut traversed_and_collided_blocks,
        from_min_pos,
        target_min_pos,
        *aabb,
    );
    traversed_and_collided_blocks.extend(traversed_blocks);
    traversed_and_collided_blocks
}

pub fn add_collisions_along_travel(
    collisions: &mut HashSet<BlockPos>,
    from: Vec3,
    to: Vec3,
    aabb: Aabb,
) {
    let delta = to - from;
    let mut min_x = from.x.floor() as i32;
    let mut min_y = from.y.floor() as i32;
    let mut min_z = from.z.floor() as i32;
    let direction_x = math::sign_as_int(delta.x);
    let direction_y = math::sign_as_int(delta.y);
    let direction_z = math::sign_as_int(delta.z);
    let step_x = if direction_x == 0 {
        f64::MAX
    } else {
        direction_x as f64 / delta.x
    };
    let step_y = if direction_y == 0 {
        f64::MAX
    } else {
        direction_y as f64 / delta.y
    };
    let step_z = if direction_z == 0 {
        f64::MAX
    } else {
        direction_z as f64 / delta.z
    };
    let mut cur_x = step_x
        * if direction_x > 0 {
            1. - math::fract(from.x)
        } else {
            math::fract(from.x)
        };
    let mut cur_y = step_y
        * if direction_y > 0 {
            1. - math::fract(from.y)
        } else {
            math::fract(from.y)
        };
    let mut cur_z = step_z
        * if direction_z > 0 {
            1. - math::fract(from.z)
        } else {
            math::fract(from.z)
        };
    let mut step_count = 0;

    while cur_x <= 1. || cur_y <= 1. || cur_z <= 1. {
        if cur_x < cur_y {
            if cur_x < cur_z {
                min_x += direction_x;
                cur_x += step_x;
            } else {
                min_z += direction_z;
                cur_z += step_z;
            }
        } else if cur_y < cur_z {
            min_y += direction_y;
            cur_y += step_y;
        } else {
            min_z += direction_z;
            cur_z += step_z;
        }

        if step_count > 16 {
            break;
        }
        step_count += 1;

        let Some(clip_location) = Aabb::clip_with_from_and_to(
            Vec3::new(min_x as f64, min_y as f64, min_z as f64),
            Vec3::new((min_x + 1) as f64, (min_y + 1) as f64, (min_z + 1) as f64),
            from,
            to,
        ) else {
            continue;
        };

        let initial_max_x = clip_location
            .x
            .clamp(min_x as f64 + 1.0E-5, min_x as f64 + 1.0 - 1.0E-5);
        let initial_max_y = clip_location
            .y
            .clamp(min_y as f64 + 1.0E-5, min_y as f64 + 1.0 - 1.0E-5);
        let initial_max_z = clip_location
            .z
            .clamp(min_z as f64 + 1.0E-5, min_z as f64 + 1.0 - 1.0E-5);
        let max_x = (initial_max_x + aabb.get_size(Axis::X)).floor() as i32;
        let max_y = (initial_max_y + aabb.get_size(Axis::Y)).floor() as i32;
        let max_z = (initial_max_z + aabb.get_size(Axis::Z)).floor() as i32;

        for x in min_x..=max_x {
            for y in min_y..=max_y {
                for z in min_z..=max_z {
                    collisions.insert(BlockPos::new(x, y, z));
                }
            }
        }
    }
}