ghast-physics 0.5.3

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Projectiles of the modern versions (26.1, 26.2, 26.3): thrown items, arrows, hurting
//! projectiles (fireballs, wither skulls, wind charges) and the fishing bobber, each ticked as the
//! server and as a client tick it, checked bit for bit against the vanilla oracle
//! (`tests/golden/<v>/projectiles.jsonl.gz`).
//!
//! A [`Projectile`] is the entity's state; [`tick_projectile`] runs one tick of it in a world for
//! a [`Side`] and returns the block hit of that tick (vanilla's `clipIncludingBorder` result, the
//! block, face and exact point); [`run_projectile`] ticks until the first block hit (or removal).
//! No entity is hit: which entity a projectile hits is the server's decision and needs the other
//! entities, which this module does not see.
//!
//! What the sides do differently (all from the vanilla tick):
//!
//! * thrown items and hurting projectiles: the server removes them on their first block hit; a
//!   client keeps ticking its copy from the hit point (it then hits the same face every tick) until
//!   the server's removal arrives;
//! * arrows: in the ground, only the server counts the despawn timer and lets an arrow fall when
//!   its block is gone (`shouldFall`); both sides stick on a hit;
//! * hurting projectiles: the server removes one whose block position is in an unloaded chunk;
//!   a wind charge more than 30 blocks above the build height explodes there;
//! * the fishing bobber: the server removes it when the owner is gone, does not hold a rod or is
//!   more than 32 blocks away; in water only the client's bobbing is modelled (the server's
//!   bite timers draw from the same random every tick, see [`Projectile::bobbing`]).
//!
//! Version rows: the projectile tick is the same in 26.1, 26.2 and 26.3 except where the shared
//! [`Rules`] items say otherwise (a bobber's collision response with 26.2's restitution).

pub use super::body::Side;
use super::body::{
    self, Body, InsideRules, LegacyRandom, MoveRules, atan2, degrees, lerp_rotation, with_env,
};
use super::fluid::kind;
use super::math::{V3, contains};
use super::rules::Rules;
use super::rules::shared::state_flags as sf;
use crate::math::Aabb;
use crate::pick::{BlockHit, Direction};
use crate::world::BlockView;

/// The kinds of projectile.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ProjectileKind {
    /// `snowball` (gravity 0.03).
    Snowball,
    /// `egg` (gravity 0.03).
    Egg,
    /// `ender_pearl` (gravity 0.03).
    EnderPearl,
    /// `experience_bottle` (gravity 0.07).
    ExperienceBottle,
    /// `splash_potion` (gravity 0.05).
    SplashPotion,
    /// `lingering_potion` (gravity 0.05).
    LingeringPotion,
    /// `wind_charge` (no gravity, no drag, no acceleration; its box sits 0.15 below its position).
    WindCharge,
    /// `arrow` (gravity 0.05, water inertia 0.6).
    Arrow,
    /// `spectral_arrow`.
    SpectralArrow,
    /// `trident` (water inertia 0.99; not the loyalty return).
    Trident,
    /// `small_fireball` (inertia 0.95).
    SmallFireball,
    /// `fireball` (the ghast's large fireball).
    LargeFireball,
    /// `dragon_fireball`.
    DragonFireball,
    /// `wither_skull` (a dangerous one: inertia 0.73).
    WitherSkull,
    /// `fishing_bobber`.
    FishingBobber,
}

/// What a kind's tick is.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Family {
    Thrown,
    Hurting,
    Arrow,
    Bobber,
}

impl ProjectileKind {
    /// Every kind.
    pub const ALL: [ProjectileKind; 15] = [
        ProjectileKind::Snowball,
        ProjectileKind::Egg,
        ProjectileKind::EnderPearl,
        ProjectileKind::ExperienceBottle,
        ProjectileKind::SplashPotion,
        ProjectileKind::LingeringPotion,
        ProjectileKind::WindCharge,
        ProjectileKind::Arrow,
        ProjectileKind::SpectralArrow,
        ProjectileKind::Trident,
        ProjectileKind::SmallFireball,
        ProjectileKind::LargeFireball,
        ProjectileKind::DragonFireball,
        ProjectileKind::WitherSkull,
        ProjectileKind::FishingBobber,
    ];

    /// The entity type id without namespace (`"snowball"`, `"fireball"`, ...).
    #[must_use]
    pub const fn entity_name(self) -> &'static str {
        match self {
            ProjectileKind::Snowball => "snowball",
            ProjectileKind::Egg => "egg",
            ProjectileKind::EnderPearl => "ender_pearl",
            ProjectileKind::ExperienceBottle => "experience_bottle",
            ProjectileKind::SplashPotion => "splash_potion",
            ProjectileKind::LingeringPotion => "lingering_potion",
            ProjectileKind::WindCharge => "wind_charge",
            ProjectileKind::Arrow => "arrow",
            ProjectileKind::SpectralArrow => "spectral_arrow",
            ProjectileKind::Trident => "trident",
            ProjectileKind::SmallFireball => "small_fireball",
            ProjectileKind::LargeFireball => "fireball",
            ProjectileKind::DragonFireball => "dragon_fireball",
            ProjectileKind::WitherSkull => "wither_skull",
            ProjectileKind::FishingBobber => "fishing_bobber",
        }
    }

    /// The kind of an entity type id (with or without the `minecraft:` namespace).
    #[must_use]
    pub fn from_entity_name(name: &str) -> Option<ProjectileKind> {
        let name = name.strip_prefix("minecraft:").unwrap_or(name);
        ProjectileKind::ALL
            .into_iter()
            .find(|k| k.entity_name() == name)
    }

    fn family(self) -> Family {
        match self {
            ProjectileKind::Snowball
            | ProjectileKind::Egg
            | ProjectileKind::EnderPearl
            | ProjectileKind::ExperienceBottle
            | ProjectileKind::SplashPotion
            | ProjectileKind::LingeringPotion => Family::Thrown,
            ProjectileKind::WindCharge
            | ProjectileKind::SmallFireball
            | ProjectileKind::LargeFireball
            | ProjectileKind::DragonFireball
            | ProjectileKind::WitherSkull => Family::Hurting,
            ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident => {
                Family::Arrow
            }
            ProjectileKind::FishingBobber => Family::Bobber,
        }
    }

    /// Box width and height of the entity type.
    #[must_use]
    pub const fn dimensions(self) -> (f32, f32) {
        match self {
            ProjectileKind::WindCharge
            | ProjectileKind::SmallFireball
            | ProjectileKind::WitherSkull => (0.3125, 0.3125),
            ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident => {
                (0.5, 0.5)
            }
            ProjectileKind::LargeFireball | ProjectileKind::DragonFireball => (1.0, 1.0),
            _ => (0.25, 0.25),
        }
    }

    /// Eye height of the entity type (the fluid sweep reads it).
    fn eye_height(self) -> f32 {
        match self {
            ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident => 0.13,
            _ => self.dimensions().1 * 0.85,
        }
    }

    /// The gravity added each tick (`getDefaultGravity`).
    #[must_use]
    pub const fn gravity(self) -> f64 {
        match self {
            ProjectileKind::Snowball | ProjectileKind::Egg | ProjectileKind::EnderPearl => 0.03,
            ProjectileKind::ExperienceBottle => 0.07,
            ProjectileKind::SplashPotion | ProjectileKind::LingeringPotion => 0.05,
            ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident => 0.05,
            _ => 0.0,
        }
    }

    /// The acceleration power a hurting projectile starts with (`accelerationPower`: 0.1, a wind
    /// charge 0); 0 for the other kinds.
    #[must_use]
    pub const fn default_acceleration_power(self) -> f64 {
        match self {
            ProjectileKind::SmallFireball
            | ProjectileKind::LargeFireball
            | ProjectileKind::DragonFireball
            | ProjectileKind::WitherSkull => 0.1,
            _ => 0.0,
        }
    }
}

/// The fishing bobber's own state (`FishingHook`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum BobberState {
    /// Flying (until it lands in water).
    #[default]
    Flying,
    /// Floating in water.
    Bobbing,
}

/// A projectile's state. Create it with [`Projectile::new`] from the add-entity packet's position
/// and motion (or a launch, [`super::launch`]); tick it with [`tick_projectile`].
#[derive(Clone, Debug)]
pub struct Projectile {
    kind: ProjectileKind,
    b: Body,
    accel: f64,
    dangerous: bool,
    in_ground: bool,
    in_ground_time: i32,
    life: i32,
    /// `lastState` of an arrow (its id, [`Rules::state_id`]); `None`: none, or not comparable.
    last_state: Option<Option<u32>>,
    bobber: BobberState,
    owner: Option<[f64; 3]>,
    owner_holds_rod: bool,
    out_of_water: i32,
}

/// One tick's block hit (vanilla `BlockHitResult` of the projectile's clip).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ProjectileHit {
    /// The block.
    pub pos: [i32; 3],
    /// The face hit.
    pub face: Direction,
    /// The exact point.
    pub location: [f64; 3],
    /// The segment started inside the block's shape.
    pub inside: bool,
    /// The world border cut the segment (`pos` is then the block at the cut).
    pub border: bool,
}

/// The first block hit of [`run_projectile`] and the tick it happened (1 = the first tick run).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Impact {
    /// Tick number of the hit, counted from 1.
    pub tick: u32,
    /// The hit.
    pub hit: ProjectileHit,
}

impl Projectile {
    /// A projectile at `pos` moving by `vel` per tick, rotation 0, as freshly spawned (first tick
    /// pending, not on the ground, the kind's default acceleration power, entity random seed 0).
    #[must_use]
    pub fn new(kind: ProjectileKind, pos: [f64; 3], vel: [f64; 3]) -> Projectile {
        let (w, h) = kind.dimensions();
        let mut b = Body::new(V3::of(pos), V3::of(vel), w, h, kind.eye_height());
        if kind == ProjectileKind::WindCharge {
            b.box_drop = 0.15;
            b.set_pos(V3::of(pos));
        }
        Projectile {
            kind,
            b,
            accel: kind.default_acceleration_power(),
            dangerous: false,
            in_ground: false,
            in_ground_time: 0,
            life: 0,
            last_state: None,
            bobber: BobberState::Flying,
            owner: None,
            owner_holds_rod: true,
            out_of_water: 0,
        }
    }

    /// The rotation (yaw, pitch in degrees).
    #[must_use]
    pub fn with_rotation(mut self, yaw: f32, pitch: f32) -> Projectile {
        self.b.yaw = yaw;
        self.b.pitch = pitch;
        self.b.yaw_o = yaw;
        self.b.pitch_o = pitch;
        self
    }

    /// A hurting projectile's acceleration power (`accelerationPower`; a server sets it when it
    /// shoots, a client keeps the type's default, [`ProjectileKind::default_acceleration_power`]).
    #[must_use]
    pub fn with_acceleration_power(mut self, power: f64) -> Projectile {
        self.accel = power;
        self
    }

    /// A dangerous (blue) wither skull (inertia 0.73).
    #[must_use]
    pub fn with_dangerous(mut self, dangerous: bool) -> Projectile {
        self.dangerous = dangerous;
        self
    }

    /// The seed of the entity's random (`RandomSource.create(seed)`): an arrow's sounds and fall,
    /// the bobber's bobbing draw from it. A server's seed is unknown to a client.
    #[must_use]
    pub fn with_random_seed(mut self, seed: i64) -> Projectile {
        self.b.rng = LegacyRandom::new(seed);
        self
    }

    /// The on-ground flag (projectiles other than the bobber never change it).
    #[must_use]
    pub fn with_on_ground(mut self, on_ground: bool) -> Projectile {
        self.b.on_ground = on_ground;
        self
    }

    /// The fall distance (the bobber's collision context reads it).
    #[must_use]
    pub fn with_fall_distance(mut self, fall: f64) -> Projectile {
        self.b.fall = fall;
        self
    }

    /// A bobber's owner (its position and whether it holds a fishing rod); without one the
    /// bobber is removed on its first tick.
    #[must_use]
    pub fn with_owner(mut self, pos: Option<[f64; 3]>, holds_rod: bool) -> Projectile {
        self.owner = pos;
        self.owner_holds_rod = holds_rod;
        self
    }

    /// Moves the bobber's owner (call before each tick when the owner moves).
    pub fn set_owner_pos(&mut self, pos: Option<[f64; 3]>) {
        self.owner = pos;
    }

    /// Sets the position (the box follows), keeping the rest of the state: what a client copy
    /// does when a server packet moves the entity between its ticks.
    pub fn set_pos(&mut self, pos: [f64; 3]) {
        self.b.set_pos(V3::of(pos));
    }

    /// Sets the motion (`setDeltaMovement`), keeping the rest of the state.
    pub fn set_vel(&mut self, vel: [f64; 3]) {
        self.b.vel = V3::of(vel);
    }

    /// Sets the rotation (`setYRot`, `setXRot`; the previous rotation is taken when the next
    /// tick starts).
    pub fn set_rotation(&mut self, yaw: f32, pitch: f32) {
        self.b.yaw = yaw;
        self.b.pitch = pitch;
    }

    /// Sets the on-ground flag.
    pub fn set_on_ground(&mut self, on_ground: bool) {
        self.b.on_ground = on_ground;
    }

    /// The position and rotation before this tick's interpolation step: a client takes the old
    /// position and rotation (`setOldPosAndRot`) before its `commonTick` interpolation step
    /// moves an interpolated entity (a fishing bobber), and the tick's rotation lerps from
    /// there. The next tick starts from these instead of the current ones (once).
    pub fn set_interpolation_start(&mut self, pos: [f64; 3], yaw: f32, pitch: f32) {
        self.b.pending_old = Some((V3::of(pos), yaw, pitch));
    }

    /// The movements `Entity.move` made in the last tick, in order (`recordMovement`: a 26.3
    /// client moves an interpolated entity's interpolation target along with them; at most four
    /// are kept).
    #[must_use]
    pub fn moved_last_tick(&self) -> &[[f64; 3]] {
        &self.b.moved[..usize::from(self.b.moved_n)]
    }

    /// Sets whether an arrow is stuck in a block (26.x: the `IN_GROUND` entity data a server
    /// sends; a motion packet with a non-zero motion clears it, `AbstractArrow.lerpMotion`).
    pub fn set_in_ground(&mut self, in_ground: bool) {
        self.in_ground = in_ground;
    }

    /// Sets a hurting projectile's acceleration power (the `projectile_power` packet).
    pub fn set_acceleration_power(&mut self, power: f64) {
        self.accel = power;
    }

    /// Sets whether a wither skull is dangerous (its entity data).
    pub fn set_dangerous(&mut self, dangerous: bool) {
        self.dangerous = dangerous;
    }

    /// The kind.
    #[must_use]
    pub fn kind(&self) -> ProjectileKind {
        self.kind
    }

    /// Position.
    #[must_use]
    pub fn pos(&self) -> [f64; 3] {
        self.b.pos.arr()
    }

    /// Motion per tick (`getDeltaMovement`).
    #[must_use]
    pub fn vel(&self) -> [f64; 3] {
        self.b.vel.arr()
    }

    /// Yaw in degrees (derived from the motion).
    #[must_use]
    pub fn yaw(&self) -> f32 {
        self.b.yaw
    }

    /// Pitch in degrees.
    #[must_use]
    pub fn pitch(&self) -> f32 {
        self.b.pitch
    }

    /// The bounding box.
    #[must_use]
    pub fn bounding_box(&self) -> Aabb {
        self.b.bb
    }

    /// The on-ground flag.
    #[must_use]
    pub fn on_ground(&self) -> bool {
        self.b.on_ground
    }

    /// `isInWater()` (as of the last fluid update).
    #[must_use]
    pub fn in_water(&self) -> bool {
        self.b.in_water
    }

    /// An arrow stuck in a block.
    #[must_use]
    pub fn in_ground(&self) -> bool {
        self.in_ground
    }

    /// Ticks an arrow has been in the ground.
    #[must_use]
    pub fn in_ground_time(&self) -> i32 {
        self.in_ground_time
    }

    /// An arrow's despawn timer (server: counts in the ground) / a bobber's ticks on the ground.
    #[must_use]
    pub fn life(&self) -> i32 {
        self.life
    }

    /// The bobber's state.
    #[must_use]
    pub fn bobbing(&self) -> BobberState {
        self.bobber
    }

    /// A hurting projectile's acceleration power.
    #[must_use]
    pub fn acceleration_power(&self) -> f64 {
        self.accel
    }

    /// The entity was removed (by the side that ticked it).
    #[must_use]
    pub fn removed(&self) -> bool {
        self.b.removed
    }

    /// The tick count (`tickCount`).
    #[must_use]
    pub fn tick_count(&self) -> i32 {
        self.b.tick_count
    }
}

/// One tick of a projectile (`tickNonPassenger` then the kind's `tick`). Returns this tick's block
/// hit, if any. A removed projectile does not tick.
pub fn tick_projectile<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    world: &W,
) -> Option<ProjectileHit> {
    if p.b.removed {
        return None;
    }
    with_env::<R, W, _>(world, |w| match p.kind.family() {
        Family::Thrown => thrown::<R, W>(p, side, w),
        Family::Hurting => hurting::<R, W>(p, side, w),
        Family::Arrow => arrow::<R, W>(p, side, w),
        Family::Bobber => bobber::<R, W>(p, side, w),
    })
}

/// Ticks until the first block hit, the removal of the projectile, or `max_ticks` ticks; returns
/// the first hit and its tick.
pub fn run_projectile<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    world: &W,
    max_ticks: u32,
) -> Option<Impact> {
    for t in 1..=max_ticks {
        if p.b.removed {
            return None;
        }
        if let Some(hit) = tick_projectile::<R, W>(p, side, world) {
            return Some(Impact { tick: t, hit });
        }
    }
    None
}

const PROJECTILE_INSIDE: InsideRules = InsideRules {
    projectile_bubbles: true,
    no_bubbles: false,
};

fn to_hit(h: BlockHit, border: bool) -> Option<ProjectileHit> {
    h.is_block().then_some(ProjectileHit {
        pos: h.pos,
        face: h.face,
        location: h.location,
        inside: h.inside,
        border,
    })
}

/// `Projectile.updateRotation` (towards the motion, from the rotation the tick started with).
fn update_rotation(b: &mut Body) {
    let v = b.vel;
    let sd = v.horizontal_sqr().sqrt();
    b.pitch = lerp_rotation(b.pitch_o, degrees(atan2(v.y, sd)));
    b.yaw = lerp_rotation(b.yaw_o, degrees(atan2(v.x, v.z)));
}

/// `ThrowableProjectile.tick`.
fn thrown<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    w: &body::Env<'_, R, W>,
) -> Option<ProjectileHit> {
    // An ender pearl answers bubble columns as any entity does (clamped), the other kinds with
    // the projectile's unclamped pushes.
    let ir = InsideRules {
        projectile_bubbles: p.kind != ProjectileKind::EnderPearl,
        no_bubbles: false,
    };
    let b = &mut p.b;
    b.start_tick();
    if b.first_tick {
        // handleFirstTickBubbleColumn: every bubble column the box touches, as precise.
        let bb = b.bb;
        let (x0, y0, z0) = (
            super::math::floor(bb.min_x),
            super::math::floor(bb.min_y),
            super::math::floor(bb.min_z),
        );
        let (x1, y1, z1) = (
            super::math::floor(bb.max_x),
            super::math::floor(bb.max_y),
            super::math::floor(bb.max_z),
        );
        for z in z0..=z1 {
            for y in y0..=y1 {
                for x in x0..=x1 {
                    let s = w.state(x, y, z);
                    let ph = R::phys(s);
                    if ph.kind() == super::rules::shared::BlockKind::BubbleColumn as u8 {
                        let above = R::phys(w.state(x, y + 1, z));
                        let nothing_above = (above.flags() & sf::EMPTY != 0
                            && above.flags() & sf::CONTEXT == 0
                            || above.flags() & sf::CONTEXT != 0
                                && above.kind()
                                    == super::rules::shared::BlockKind::PowderSnow as u8)
                            && kind(above.fluid()) == 0;
                        body::bubble_column(b, ph.aux() & 1 != 0, nothing_above, ir);
                    }
                }
            }
        }
    }
    b.apply_gravity(p.kind.gravity());
    let inertia: f32 = if b.in_water { 0.8 } else { 0.99 };
    b.vel = b.vel.scale(f64::from(inertia));
    let ctx = b.ctx();
    let (hit, border) = body::clip::<R, W>(w, b.pos, b.pos.add(b.vel), &ctx);
    let next = if hit.is_block() {
        V3::of(hit.location)
    } else {
        b.pos.add(b.vel)
    };
    b.set_pos(next);
    update_rotation(b);
    body::apply_effects_from_blocks::<R, W>(b, w, ir);
    body::base_tick::<R, W>(b, w, true, true);
    let hit = to_hit(hit, border);
    if hit.is_some() && side == Side::Server {
        b.removed = true;
    }
    hit
}

/// `AbstractHurtingProjectile.tick` (and `AbstractWindCharge.tick`).
fn hurting<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    w: &body::Env<'_, R, W>,
) -> Option<ProjectileHit> {
    let wind = p.kind == ProjectileKind::WindCharge;
    let b = &mut p.b;
    b.start_tick();
    if wind && side == Side::Server && b.block_pos()[1] > w.max_y + 30 {
        b.removed = true;
        return None;
    }
    let (air, liquid): (f32, f32) = if wind {
        (1.0, 1.0)
    } else if p.kind == ProjectileKind::WitherSkull && p.dangerous {
        (0.73, 0.8)
    } else {
        (0.95, 0.8)
    };
    let inertia = if b.in_water { liquid } else { air };
    let v = b.vel;
    b.vel = v
        .add(v.normalize().scale(p.accel))
        .scale(f64::from(inertia));
    let bp = b.block_pos();
    if side == Side::Server && !w.w.is_chunk_loaded(bp[0] >> 4, bp[2] >> 4) {
        b.removed = true;
        return None;
    }
    let ctx = b.ctx();
    let (hit, border) = body::clip::<R, W>(w, b.pos, b.pos.add(b.vel), &ctx);
    let next = if hit.is_block() {
        V3::of(hit.location)
    } else {
        b.pos.add(b.vel)
    };
    rotate_towards_movement(b);
    b.set_pos(next);
    body::apply_effects_from_blocks::<R, W>(b, w, PROJECTILE_INSIDE);
    body::base_tick::<R, W>(b, w, true, true);
    let hit = to_hit(hit, border);
    if hit.is_some() && side == Side::Server {
        b.removed = true;
    }
    hit
}

/// `ProjectileUtil.rotateTowardsMovement(entity, 0.2F)`.
fn rotate_towards_movement(b: &mut Body) {
    let v = b.vel;
    if v.length_sqr() == 0.0 {
        return;
    }
    let sd = v.horizontal_sqr().sqrt();
    let yaw = degrees(atan2(v.z, v.x)) + 90.0;
    let pitch = degrees(atan2(sd, v.y)) - 90.0;
    while pitch - b.pitch_o < -180.0 {
        b.pitch_o -= 360.0;
    }
    while pitch - b.pitch_o >= 180.0 {
        b.pitch_o += 360.0;
    }
    while yaw - b.yaw_o < -180.0 {
        b.yaw_o -= 360.0;
    }
    while yaw - b.yaw_o >= 180.0 {
        b.yaw_o += 360.0;
    }
    b.pitch = b.pitch_o + 0.2 * (pitch - b.pitch_o);
    b.yaw = b.yaw_o + 0.2 * (yaw - b.yaw_o);
}

/// `AbstractArrow.tick`.
fn arrow<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    w: &body::Env<'_, R, W>,
) -> Option<ProjectileHit> {
    let water_inertia: f32 = if p.kind == ProjectileKind::Trident {
        0.99
    } else {
        0.6
    };
    let b = &mut p.b;
    b.start_tick();
    let movement = b.vel;
    let bp = b.block_pos();
    let bs = w.state(bp[0], bp[1], bp[2]);
    if R::phys(bs).flags() & sf::AIR == 0 {
        // The collision shape of the block it is in (empty context) holding its position.
        let mut inside = false;
        match super::collide::placed_shape::<R>(bs, bp[0], bp[1], bp[2], None) {
            Some(super::collide::Placed::Cube(o)) => {
                inside = contains(
                    &Aabb::new(o[0], o[1], o[2], o[0] + 1.0, o[1] + 1.0, o[2] + 1.0),
                    b.pos,
                );
            }
            Some(sh @ super::collide::Placed::Shape(..)) => {
                sh.for_boxes(|bb| {
                    if contains(&bb, b.pos) {
                        inside = true;
                        return false;
                    }
                    true
                });
            }
            _ => {}
        }
        if inside {
            b.vel = V3::ZERO;
            p.in_ground = true;
        }
    }
    if p.in_ground {
        if side == Side::Server {
            let changed = match p.last_state {
                Some(Some(id)) => R::state_id(bs) != Some(id),
                _ => true,
            };
            let probe = super::math::inflate(
                &Aabb::new(b.pos.x, b.pos.y, b.pos.z, b.pos.x, b.pos.y, b.pos.z),
                0.06,
                0.06,
                0.06,
            );
            if changed && body::no_collision_empty::<R, W>(w, &probe) {
                // startFalling
                p.in_ground = false;
                let (fx, fy, fz) = (
                    b.rng.next_float() * 0.2,
                    b.rng.next_float() * 0.2,
                    b.rng.next_float() * 0.2,
                );
                b.vel = b.vel.mul(f64::from(fx), f64::from(fy), f64::from(fz));
                p.life = 0;
            } else {
                p.life += 1;
                if p.life >= 1200 {
                    b.removed = true;
                }
            }
        }
        p.in_ground_time += 1;
        if !b.removed {
            let ir = InsideRules {
                projectile_bubbles: true,
                no_bubbles: p.in_ground,
            };
            body::apply_effects_from_blocks::<R, W>(b, w, ir);
        }
        return None;
    }
    p.in_ground_time = 0;
    let origin = b.pos;
    if b.in_water {
        b.vel = b.vel.scale(f64::from(water_inertia));
    }
    let yaw = degrees(atan2(movement.x, movement.z));
    let pitch = degrees(atan2(movement.y, movement.horizontal_sqr().sqrt()));
    b.pitch = lerp_rotation(b.pitch, pitch);
    b.yaw = lerp_rotation(b.yaw, yaw);
    let ctx = b.ctx();
    let (hit, border) = body::clip::<R, W>(w, origin, origin.add(movement), &ctx);
    // stepMoveAndHit (no entities): to the hit point or the segment's end.
    b.set_pos(V3::of(hit.location));
    body::apply_effects_between::<R, W>(b, w, origin, V3::of(hit.location), PROJECTILE_INSIDE);
    let result = to_hit(hit, border);
    if hit.is_block() && !b.removed {
        // onHitBlock
        p.last_state = Some(R::state_id(w.state(hit.pos[0], hit.pos[1], hit.pos[2])));
        let v = b.vel;
        let sign = |x: f64| {
            if x > 0.0 {
                1.0
            } else if x < 0.0 {
                -1.0
            } else {
                x
            }
        };
        let off = V3::new(sign(v.x), sign(v.y), sign(v.z)).scale(f64::from(0.05f32));
        let at = b.pos.sub(off);
        b.set_pos(at);
        b.vel = V3::ZERO;
        b.rng.next_float();
        p.in_ground = true;
    }
    if !b.in_water {
        b.vel = b.vel.scale(f64::from(0.99f32));
    }
    if !p.in_ground {
        b.apply_gravity(p.kind.gravity());
    }
    body::base_tick::<R, W>(b, w, !p.in_ground, true);
    result
}

/// `FishingHook.tick` (no hooked entity, no bite).
fn bobber<R: Rules, W: BlockView<State = R::State>>(
    p: &mut Projectile,
    side: Side,
    w: &body::Env<'_, R, W>,
) -> Option<ProjectileHit> {
    let b = &mut p.b;
    b.start_tick();
    body::base_tick::<R, W>(b, w, true, true);
    let Some(owner) = p.owner else {
        b.removed = true;
        return None;
    };
    if side == Side::Server {
        let d = b.pos.dist_sqr(V3::of(owner));
        if !p.owner_holds_rod || d > 1024.0 {
            b.removed = true;
            return None;
        }
    }
    if b.on_ground {
        p.life += 1;
        if p.life >= 1200 {
            b.removed = true;
            return None;
        }
    } else {
        p.life = 0;
    }
    let bp = b.block_pos();
    let f = w.fluid(bp[0], bp[1], bp[2]);
    let liquid: f32 = if kind(f) == 1 {
        w.fluid_height(bp[0], bp[1], bp[2], f)
    } else {
        0.0
    };
    let in_water = liquid > 0.0;
    let mut result = None;
    match p.bobber {
        BobberState::Flying => {
            if in_water {
                b.vel = b.vel.mul(0.3, 0.2, 0.3);
                p.bobber = BobberState::Bobbing;
                return None;
            }
            let ctx = b.ctx();
            let (hit, border) = body::clip::<R, W>(w, b.pos, b.pos.add(b.vel), &ctx);
            if hit.is_block() {
                // onHitBlock: the motion's length becomes the hit's squared distance.
                let l = V3::of(hit.location);
                let d = l.dist_sqr(b.pos);
                b.vel = b.vel.normalize().scale(d);
                result = to_hit(hit, border);
            }
        }
        BobberState::Bobbing => {
            let v = b.vel;
            let mut force = b.pos.y + v.y - f64::from(bp[1]) - f64::from(liquid);
            if force.abs() < 0.01 {
                // Math.signum: 0 stays 0.
                let sign = if force > 0.0 {
                    1.0
                } else if force < 0.0 {
                    -1.0
                } else {
                    force
                };
                force += sign * 0.1;
            }
            let r = f64::from(b.rng.next_float());
            b.vel = V3::new(v.x * 0.9, v.y - force * r * 0.2, v.z * 0.9);
            if in_water {
                p.out_of_water = (p.out_of_water - 1).max(0);
            } else {
                p.out_of_water = (p.out_of_water + 1).min(10);
            }
        }
    }
    let gravity = if R::BOBBER_DEFAULT_GRAVITY {
        f64::from(0.03f32)
    } else {
        0.0
    };
    if kind(f) != 1 && !b.on_ground {
        let sink = if R::BOBBER_DEFAULT_GRAVITY {
            gravity
        } else {
            0.03
        };
        b.vel = b.vel.add(V3::new(0.0, -sink, 0.0));
    }
    let authoritative = side == Side::Server;
    let mr = MoveRules {
        authoritative,
        simulate: authoritative || R::SIMULATED_ON_CLIENT,
        gravity,
        air_drag: 0.98,
    };
    let v = b.vel;
    body::entity_move::<R, W>(b, w, v, mr);
    body::apply_effects_from_blocks::<R, W>(b, w, PROJECTILE_INSIDE);
    update_rotation(b);
    if p.bobber == BobberState::Flying && (b.on_ground || b.hcol) {
        b.vel = V3::ZERO;
    }
    b.vel = b.vel.scale(0.92);
    result
}