Skip to main content

azalea_entity/
lib.rs

1#![doc = include_str!("../README.md")]
2#![allow(clippy::derived_hash_with_manual_eq)]
3
4pub mod attributes;
5mod data;
6pub mod dimensions;
7pub mod effects;
8pub mod inventory;
9#[cfg(feature = "bevy_ecs")]
10pub mod metadata;
11pub mod mining;
12#[cfg(feature = "bevy_ecs")]
13mod plugin;
14pub mod vec_delta_codec;
15
16#[doc(hidden)]
17pub mod particle {
18    #[deprecated = "moved to `azalea_registry::registry_holder::particle::Particle`."]
19    pub type Particle = azalea_registry::holder::particle::Particle;
20}
21
22use std::{
23    f64::consts::PI,
24    fmt::{self, Debug},
25    hash::{Hash, Hasher},
26};
27
28pub use attributes::Attributes;
29use azalea_block::fluid_state::FluidKind;
30use azalea_buf::AzBuf;
31use azalea_core::{
32    aabb::Aabb,
33    math,
34    position::{BlockPos, ChunkPos, Vec3},
35};
36use azalea_registry::builtin::EntityKind;
37pub use data::*;
38use derive_more::{Deref, DerefMut};
39pub use effects::{ActiveEffects, MobEffectData};
40use uuid::Uuid;
41use vec_delta_codec::VecDeltaCodec;
42
43use self::attributes::AttributeInstance;
44use crate::dimensions::EntityDimensions;
45#[cfg(feature = "bevy_ecs")]
46pub use crate::plugin::*;
47
48pub fn move_relative(
49    physics: &mut Physics,
50    direction: LookDirection,
51    speed: f32,
52    acceleration: Vec3,
53) {
54    let input_vector = input_vector(direction, speed, acceleration);
55    physics.velocity += input_vector;
56}
57
58pub fn input_vector(direction: LookDirection, speed: f32, acceleration: Vec3) -> Vec3 {
59    let distance = acceleration.length_squared();
60    if distance < 1.0e-7 {
61        return Vec3::ZERO;
62    }
63    let acceleration = if distance > 1. {
64        acceleration.normalize()
65    } else {
66        acceleration
67    }
68    .scale(speed as f64);
69    let y_rot = math::sin(direction.y_rot * (PI / 180.) as f32);
70    let x_rot = math::cos(direction.y_rot * (PI / 180.) as f32);
71    Vec3 {
72        x: acceleration.x * (x_rot as f64) - acceleration.z * (y_rot as f64),
73        y: acceleration.y,
74        z: acceleration.z * (x_rot as f64) + acceleration.x * (y_rot as f64),
75    }
76}
77
78pub fn view_vector(look_direction: LookDirection) -> Vec3 {
79    let x_rot = look_direction.x_rot * 0.017453292;
80    let y_rot = -look_direction.y_rot * 0.017453292;
81    let y_rot_cos = math::cos(y_rot);
82    let y_rot_sin = math::sin(y_rot);
83    let x_rot_cos = math::cos(x_rot);
84    let x_rot_sin = math::sin(x_rot);
85    Vec3 {
86        x: (y_rot_sin * x_rot_cos) as f64,
87        y: (-x_rot_sin) as f64,
88        z: (y_rot_cos * x_rot_cos) as f64,
89    }
90}
91
92/// The Minecraft UUID of the entity.
93///
94/// For players, this is their actual player UUID, and for other entities it's
95/// just random.
96#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
97#[derive(Clone, Copy, Default, Deref, DerefMut, PartialEq)]
98pub struct EntityUuid(Uuid);
99impl EntityUuid {
100    pub fn new(uuid: Uuid) -> Self {
101        Self(uuid)
102    }
103}
104impl Debug for EntityUuid {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        (self.0).fmt(f)
107    }
108}
109
110/// The position of the entity right now.
111///
112/// If this is being used as an ECS component then you are free to modify it,
113/// because there are systems that will update the indexes automatically.
114///
115/// Its value is set to a default of [`Vec3::ZERO`] when it receives the login
116/// packet, its true position may be set ticks later.
117#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
118#[derive(Clone, Copy, Debug, Default, Deref, DerefMut, PartialEq)]
119pub struct Position(Vec3);
120impl Position {
121    pub fn new(pos: Vec3) -> Self {
122        Self(pos)
123    }
124}
125impl From<&Position> for Vec3 {
126    fn from(value: &Position) -> Self {
127        value.0
128    }
129}
130impl From<Position> for ChunkPos {
131    fn from(value: Position) -> Self {
132        ChunkPos::from(&value.0)
133    }
134}
135impl From<Position> for BlockPos {
136    fn from(value: Position) -> Self {
137        BlockPos::from(&value.0)
138    }
139}
140impl From<&Position> for ChunkPos {
141    fn from(value: &Position) -> Self {
142        ChunkPos::from(value.0)
143    }
144}
145impl From<&Position> for BlockPos {
146    fn from(value: &Position) -> Self {
147        BlockPos::from(value.0)
148    }
149}
150
151/// The direction that an entity is looking, in degrees.
152///
153/// To avoid flagging anticheats, consider using [`Self::update`] when updating
154/// the values of this struct.
155#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
156#[derive(AzBuf, Clone, Copy, Debug, Default, PartialEq)]
157pub struct LookDirection {
158    /// Left and right. AKA yaw. In degrees.
159    y_rot: f32,
160    /// Up and down. AKA pitch. In degrees.
161    x_rot: f32,
162}
163
164impl LookDirection {
165    /// Create a new look direction and clamp the `x_rot` to the allowed values.
166    pub fn new(y_rot: f32, x_rot: f32) -> Self {
167        Self { y_rot, x_rot }.clamped()
168    }
169    /// Returns yaw (left and right) in degrees.
170    ///
171    /// Minecraft allows this to go outside of ±360°, so it won't necessarily be
172    /// in any range.
173    pub fn y_rot(&self) -> f32 {
174        self.y_rot
175    }
176    /// Returns pitch (up and down) in degrees.
177    ///
178    /// Clamped to ±90°.
179    pub fn x_rot(&self) -> f32 {
180        self.x_rot
181    }
182
183    /// Update this look direction to the new value.
184    ///
185    /// This handles relative rotations correctly and with the default Minecraft
186    /// sensitivity to avoid triggering anticheats.
187    pub fn update(&mut self, new: LookDirection) {
188        self.update_with_sensitivity(new, 1.);
189    }
190    /// Update the `y_rot` (yaw) to the given value, in degrees.
191    ///
192    /// This is a shortcut for [`Self::update`] while keeping the `x_rot` the
193    /// same.
194    pub fn update_y_rot(&mut self, new_y_rot: f32) {
195        self.update(LookDirection {
196            y_rot: new_y_rot,
197            x_rot: self.x_rot,
198        });
199    }
200    /// Update the `x_rot` (pitch) to the given value, in degrees.
201    ///
202    /// This is a shortcut for [`Self::update`] while keeping the `y_rot` the
203    /// same.
204    pub fn update_x_rot(&mut self, new_x_rot: f32) {
205        self.update(LookDirection {
206            y_rot: self.y_rot,
207            x_rot: new_x_rot,
208        });
209    }
210
211    /// Update this look direction to the new value, using the given
212    /// sensitivity value.
213    ///
214    /// Consider using [`Self::update`] instead, which uses 1.0 as the
215    /// sensitivity (equivalent to 100% sensitivity in Minecraft).
216    pub fn update_with_sensitivity(&mut self, new: LookDirection, sensitivity: f32) {
217        let mut delta_y_rot = new.y_rot.rem_euclid(360.) - self.y_rot.rem_euclid(360.);
218        let delta_x_rot = new.x_rot - self.x_rot;
219
220        if delta_y_rot > 180. {
221            delta_y_rot -= 360.;
222        } else if delta_y_rot < -180. {
223            delta_y_rot += 360.;
224        }
225
226        let sensitivity = sensitivity * 0.15;
227        let delta_y_rot = (delta_y_rot / sensitivity).round() * sensitivity;
228        let delta_x_rot = (delta_x_rot / sensitivity).round() * sensitivity;
229
230        self.y_rot += delta_y_rot;
231        self.x_rot += delta_x_rot;
232    }
233
234    /// Force the [`Self::x_rot`] to be between -90 and 90 degrees, and return
235    /// the new look direction.
236    #[must_use]
237    pub fn clamped(mut self) -> Self {
238        self.x_rot = self.x_rot.clamp(-90., 90.);
239        self
240    }
241}
242
243impl From<LookDirection> for (f32, f32) {
244    fn from(value: LookDirection) -> Self {
245        (value.y_rot, value.x_rot)
246    }
247}
248impl From<(f32, f32)> for LookDirection {
249    fn from((y_rot, x_rot): (f32, f32)) -> Self {
250        Self { y_rot, x_rot }
251    }
252}
253
254impl Hash for LookDirection {
255    fn hash<H: Hasher>(&self, state: &mut H) {
256        self.y_rot.to_bits().hash(state);
257        self.x_rot.to_bits().hash(state);
258    }
259}
260impl Eq for LookDirection {}
261
262/// The physics data relating to the entity, such as position, velocity, and
263/// bounding box.
264#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
265#[derive(Clone, Debug, Default)]
266pub struct Physics {
267    /// How fast the entity is moving. Sometimes referred to as the delta
268    /// movement.
269    ///
270    /// Note that our Y velocity will be approximately -0.0784 when we're on the
271    /// ground due to how Minecraft applies gravity.
272    pub velocity: Vec3,
273    pub vec_delta_codec: VecDeltaCodec,
274
275    /// The position of the entity before it moved this tick.
276    ///
277    /// This is set immediately before physics is done.
278    pub old_position: Vec3,
279
280    /// The acceleration here is the force that will be attempted to be added to
281    /// the entity's velocity next tick.
282    ///
283    /// You should typically not set this yourself, since it's controlled by how
284    /// the entity is trying to move.
285    pub x_acceleration: f32,
286    pub y_acceleration: f32,
287    pub z_acceleration: f32,
288
289    on_ground: bool,
290    last_on_ground: bool,
291
292    /// The number of ticks until we jump again, if the jump key is being held.
293    ///
294    /// This must be 0 for us to be able to jump. Sets to 10 when we do a jump
295    /// and sets to 0 if we're not trying to jump.
296    pub no_jump_delay: u32,
297
298    /// The bounding box of the entity.
299    ///
300    /// This is more than just width and height, unlike dimensions.
301    pub bounding_box: Aabb,
302
303    pub has_impulse: bool,
304
305    pub horizontal_collision: bool,
306    // TODO: implement minor_horizontal_collision
307    pub minor_horizontal_collision: bool,
308    pub vertical_collision: bool,
309
310    pub water_fluid_height: f64,
311    pub lava_fluid_height: f64,
312    pub was_touching_water: bool,
313
314    pub fall_distance: f64,
315    // TODO: implement remaining_fire_ticks
316    pub remaining_fire_ticks: i32,
317}
318
319impl Physics {
320    pub fn new(dimensions: &EntityDimensions, pos: Vec3) -> Self {
321        Self {
322            velocity: Vec3::ZERO,
323            vec_delta_codec: VecDeltaCodec::new(pos),
324
325            old_position: pos,
326
327            x_acceleration: 0.,
328            y_acceleration: 0.,
329            z_acceleration: 0.,
330
331            on_ground: false,
332            last_on_ground: false,
333
334            no_jump_delay: 0,
335
336            bounding_box: dimensions.make_bounding_box(pos),
337
338            has_impulse: false,
339
340            horizontal_collision: false,
341            minor_horizontal_collision: false,
342            vertical_collision: false,
343
344            water_fluid_height: 0.,
345            lava_fluid_height: 0.,
346            was_touching_water: false,
347
348            fall_distance: 0.,
349            remaining_fire_ticks: 0,
350        }
351    }
352
353    pub fn on_ground(&self) -> bool {
354        self.on_ground
355    }
356    /// Updates [`Self::on_ground`] and [`Self::last_on_ground`].
357    pub fn set_on_ground(&mut self, on_ground: bool) {
358        self.last_on_ground = self.on_ground;
359        self.on_ground = on_ground;
360    }
361
362    /// The last value of the on_ground value.
363    ///
364    /// This is used by Azalea internally for physics, it might not work as you
365    /// expect since it can be influenced by packets sent by the server.
366    pub fn last_on_ground(&self) -> bool {
367        self.last_on_ground
368    }
369    pub fn set_last_on_ground(&mut self, last_on_ground: bool) {
370        self.last_on_ground = last_on_ground;
371    }
372
373    pub fn reset_fall_distance(&mut self) {
374        self.fall_distance = 0.;
375    }
376    pub fn clear_fire(&mut self) {
377        self.remaining_fire_ticks = 0;
378    }
379
380    pub fn is_in_water(&self) -> bool {
381        self.was_touching_water
382    }
383    pub fn is_in_lava(&self) -> bool {
384        // TODO: also check `!this.firstTick &&`
385        self.lava_fluid_height > 0.
386    }
387
388    pub fn set_old_pos(&mut self, pos: Position) {
389        self.old_position = *pos;
390    }
391}
392
393impl Attributes {
394    pub fn new(_entity_kind: EntityKind) -> Self {
395        // TODO: do the correct defaults for everything, some
396        // entities have different defaults
397        Attributes {
398            movement_speed: AttributeInstance::new(0.1f32 as f64),
399            sneaking_speed: AttributeInstance::new(0.3),
400            attack_speed: AttributeInstance::new(4.0),
401            water_movement_efficiency: AttributeInstance::new(0.0),
402            mining_efficiency: AttributeInstance::new(0.0),
403            block_interaction_range: AttributeInstance::new(4.5),
404            entity_interaction_range: AttributeInstance::new(3.0),
405            step_height: AttributeInstance::new(0.6),
406            block_break_speed: AttributeInstance::new(1.0),
407        }
408    }
409}
410
411/// The abilities that a player has, such as flying or being able to instantly
412/// break blocks.
413///
414/// This should only be present on local players.
415#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
416#[derive(Clone, Debug, Default)]
417pub struct PlayerAbilities {
418    pub invulnerable: bool,
419    pub flying: bool,
420    pub can_fly: bool,
421    /// Whether the player can instantly break blocks and can duplicate blocks
422    /// in their inventory.
423    pub instant_break: bool,
424
425    pub flying_speed: f32,
426    /// Used for the fov
427    pub walking_speed: f32,
428}
429
430/// The type of fluid that is at an entity's eye position, while also accounting
431/// for fluid height.
432///
433/// This is only updated for [`AbstractLiving`] entities.
434///
435/// [`AbstractLiving`]: metadata::AbstractLiving
436#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
437#[derive(Clone, Copy, Debug, Deref, DerefMut, PartialEq)]
438pub struct FluidOnEyes(FluidKind);