ghast-physics 0.5.5

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
//! The generic non-living entity of 1.16.5: the parts of vanilla's `Entity` that projectiles,
//! item entities, experience orbs, primed TNT and falling blocks share — position and box,
//! `Entity.move` with its landing and inside-block effects, the fluid update, fire and damage as
//! far as they decide a removal, the push out of blocks, and the block ray of a projectile.
//!
//! Every side-dependent step reads a [`Side`]; no step reads the player's state (the player keeps
//! its own copies in `player.rs`).

use ghast_data::FluidKind;
use ghast_data::v1_16_5::{Block, BlockState};

use super::blocks::{
    Shape, ShapeCtx, bamboo_box, collision_boxes, collision_shape, fluid, is_bed, state_at,
    velocity_multiplier,
};
use super::collide::{BorderShape, Collider, NoEntities, bx, contract, offset};
use super::fluid::{V3, ceil, height, region_loaded, update_in_fluid_as};
use crate::math::{Aabb, floor, sqrt_f64_as_f32};
use crate::nonliving::{LegacyRandom, Side};
use crate::pick::{BlockHit, Cells, Direction, PlacedShape};
use crate::world::BlockView;

/// How damage changes an entity (only what decides its removal is modelled).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Health {
    /// Damage changes nothing (projectiles, TNT, falling blocks).
    None,
    /// An item entity (5 health; a fire-proof item ignores fire damage).
    Item,
    /// An experience orb (5 health).
    Orb,
}

/// A damage source as far as the health models read it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Damage {
    Lava,
    OnFire,
    Cactus,
}

/// The `Entity` fields the non-living 1.16.5 entities read and write.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Body {
    pub pos: V3,
    /// `prevX, prevY, prevZ` (set when the world ticks the entity).
    pub old: V3,
    pub vel: V3,
    pub bb: Aabb,
    pub width: f32,
    pub height: f32,
    pub eye_height: f32,
    pub yaw: f32,
    pub pitch: f32,
    pub yaw_o: f32,
    pub pitch_o: f32,
    pub on_ground: bool,
    pub hcol: bool,
    pub vcol: bool,
    pub fall: f32,
    /// `movementMultiplier` (cobwebs).
    pub stuck: V3,
    /// `touchingWater`.
    pub in_water: bool,
    pub water_height: f64,
    pub lava_height: f64,
    /// The eyes are in water (`isSubmergedIn(WATER)`).
    pub eye_in_water: bool,
    pub first_update: bool,
    pub no_gravity: bool,
    pub no_clip: bool,
    pub removed: bool,
    /// `age` (counted by the world before each tick).
    pub age: i32,
    pub fire_ticks: i32,
    pub fire_immune: bool,
    pub health: i32,
    pub health_model: Health,
    /// `onSwimmingStart` draws its sound and particles (an orb's does nothing).
    pub splashes: bool,
    pub rng: LegacyRandom,
}

impl Body {
    pub(crate) fn new(pos: V3, vel: V3, width: f32, height: f32, eye_height: f32) -> Body {
        let mut b = Body {
            pos,
            old: pos,
            vel,
            bb: Aabb::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
            width,
            height,
            eye_height,
            yaw: 0.0,
            pitch: 0.0,
            yaw_o: 0.0,
            pitch_o: 0.0,
            on_ground: false,
            hcol: false,
            vcol: false,
            fall: 0.0,
            stuck: V3::ZERO,
            in_water: false,
            water_height: 0.0,
            lava_height: 0.0,
            eye_in_water: false,
            first_update: true,
            no_gravity: false,
            no_clip: false,
            removed: false,
            age: 0,
            fire_ticks: -1,
            fire_immune: false,
            health: 5,
            health_model: Health::None,
            splashes: true,
            rng: LegacyRandom::new(0),
        };
        b.set_position(pos);
        b
    }

    /// `EntityDimensions.getBoxAt(pos)`.
    pub(crate) fn box_at(&self, p: V3) -> Aabb {
        let f = f64::from(self.width / 2.0);
        bx(
            p.x - f,
            p.y,
            p.z - f,
            p.x + f,
            p.y + f64::from(self.height),
            p.z + f,
        )
    }

    /// `Entity.setPosition`: the position and the box made there.
    pub(crate) fn set_position(&mut self, p: V3) {
        self.pos = p;
        self.bb = self.box_at(p);
    }

    /// `moveToBoundingBoxCenter`.
    fn move_to_box_center(&mut self) {
        let b = self.bb;
        self.pos = V3::new(
            (b.min_x + b.max_x) / 2.0,
            b.min_y,
            (b.min_z + b.max_z) / 2.0,
        );
    }

    /// `ClientWorld.tickEntity` before the entity's own tick: previous position and rotation,
    /// `age++`.
    pub(crate) fn start_tick(&mut self) {
        self.old = self.pos;
        self.yaw_o = self.yaw;
        self.pitch_o = self.pitch;
        self.age += 1;
    }

    /// `getBlockPos()`.
    pub(crate) fn block_pos(&self) -> [i32; 3] {
        [floor(self.pos.x), floor(self.pos.y), floor(self.pos.z)]
    }

    /// `isInLava()`: not on the first update.
    pub(crate) fn in_lava(&self) -> bool {
        !self.first_update && self.lava_height > 0.0
    }

    /// The shape context of the entity (`ShapeContext.of(entity)`).
    pub(crate) fn ctx(&self) -> ShapeCtx {
        ShapeCtx {
            min_y: self.pos.y,
            descending: false,
        }
    }

    /// `isOnFire()` (a client never learns the burning flag of these entities from the server
    /// in the modelled ticks).
    fn on_fire(&self) -> bool {
        !self.fire_immune && self.fire_ticks > 0
    }

    /// `damage(source, amount)` of the kinds whose health can run out.
    pub(crate) fn damage(&mut self, source: Damage, amount: i32) {
        let fire = matches!(source, Damage::Lava | Damage::OnFire);
        match self.health_model {
            Health::None => {}
            Health::Item if fire && self.fire_immune => {}
            Health::Item | Health::Orb => {
                self.health -= amount;
                if self.health <= 0 {
                    self.removed = true;
                }
            }
        }
    }
}

/// `x * k` per axis of a plain `Vec3d`.
#[inline]
pub(crate) fn mul(v: V3, x: f64, y: f64, z: f64) -> V3 {
    V3::new(v.x * x, v.y * y, v.z * z)
}

/// `squaredHorizontalLength`.
#[inline]
pub(crate) fn horizontal_sqr(v: V3) -> f64 {
    v.x * v.x + v.z * v.z
}

// ---------------------------------------------------------------------------------------------
// Fluids, fire and the base tick

/// `Entity.updateWaterState`: water contact (splash draws when entering), the water and lava
/// pushes, the fluid heights. Returns whether it touches water or lava.
pub(crate) fn update_water_state<W: BlockView<State = BlockState>>(b: &mut Body, w: &W) -> bool {
    let mut v = b.vel;
    let water = update_in_fluid_as::<W, false>(w, &b.bb, FluidKind::Water, 0.014, true, &mut v);
    b.vel = v;
    if water.touching {
        if !b.in_water && !b.first_update && b.splashes {
            b.rng.splash(b.width);
        }
        b.fall = 0.0;
        b.in_water = true;
        b.fire_ticks = 0;
    } else {
        b.in_water = false;
    }
    b.water_height = water.height;
    let mut v = b.vel;
    let lava = update_in_fluid_as::<W, false>(
        w,
        &b.bb,
        FluidKind::Lava,
        0.002_333_333_333_333_333_5,
        true,
        &mut v,
    );
    b.vel = v;
    b.lava_height = lava.height;
    b.in_water || lava.touching
}

/// `updateSubmergedInWaterState`: the fluid at the eyes (less 1/9).
fn update_submerged<W: BlockView<State = BlockState>>(b: &mut Body, w: &W) {
    let d = b.pos.y + f64::from(b.eye_height) - f64::from(0.111_111_11f32);
    let p = [floor(b.pos.x), floor(d), floor(b.pos.z)];
    b.eye_in_water = match fluid(state_at(w, p[0], p[1], p[2])) {
        Some(f) if f.kind == FluidKind::Water => {
            f64::from(p[1] as f32 + height(w, p[0], p[1], p[2], f)) > d
        }
        _ => false,
    };
}

/// `Entity.baseTick` of these entities: fluids, fire, lava (fire, damage, the fall distance
/// halved), the removal under the world, the end of the first update.
pub(crate) fn base_tick<W: BlockView<State = BlockState>>(b: &mut Body, w: &W, side: Side) {
    update_water_state(b, w);
    update_submerged(b, w);
    if side == Side::Client {
        b.fire_ticks = 0;
    } else if b.fire_ticks > 0 {
        if b.fire_immune {
            b.fire_ticks -= 4;
            if b.fire_ticks < 0 {
                b.fire_ticks = 0;
            }
        } else {
            if b.fire_ticks % 20 == 0 && !b.in_lava() {
                b.damage(Damage::OnFire, 1);
            }
            b.fire_ticks -= 1;
        }
    }
    if b.in_lava() {
        if !b.fire_immune {
            if b.fire_ticks < 300 {
                b.fire_ticks = 300;
            }
            b.damage(Damage::Lava, 4);
        }
        b.fall *= 0.5;
    }
    if b.pos.y < -64.0 {
        b.removed = true;
    }
    b.first_update = false;
}

// ---------------------------------------------------------------------------------------------
// Entity.move

/// `Entity.move(SELF, movement)` of a non-living entity (no step-up, no climbing sounds: none of
/// these entities can climb).
pub(crate) fn entity_move<W: BlockView<State = BlockState>>(b: &mut Body, w: &W, movement: V3) {
    if b.no_clip {
        b.bb = offset(&b.bb, movement.x, movement.y, movement.z);
        b.move_to_box_center();
        return;
    }
    let mut m = movement;
    let s = b.stuck;
    if s.x * s.x + s.y * s.y + s.z * s.z > 1.0e-7 {
        m = mul(m, s.x, s.y, s.z);
        b.stuck = V3::ZERO;
        b.vel = V3::ZERO;
    }
    let border = BorderShape::new(&w.world_border());
    let col = Collider {
        w,
        border: &border,
        ctx: b.ctx(),
        entities: NoEntities,
    };
    let v = col.adjust(m, &b.bb, b.on_ground, 0.0);
    if v.length_sq() > 1.0e-7 {
        b.bb = offset(&b.bb, v.x, v.y, v.z);
        b.move_to_box_center();
    }
    let approx = |a: f64, c: f64| (c - a).abs() < f64::from(1.0e-5f32);
    b.hcol = !approx(m.x, v.x) || !approx(m.z, v.z);
    b.vcol = m.y != v.y;
    b.on_ground = b.vcol && m.y < 0.0;
    let lp = landing_pos(b, w);
    let landed = state_at(w, lp[0], lp[1], lp[2]);
    // fall: no block's onLandedUpon moves these entities.
    if b.on_ground {
        b.fall = 0.0;
    } else if v.y < 0.0 {
        b.fall = (f64::from(b.fall) - v.y) as f32;
    }
    let old = b.vel;
    if m.x != v.x {
        b.vel = V3::new(0.0, old.y, old.z);
    }
    if m.z != v.z {
        b.vel = V3::new(old.x, old.y, 0.0);
    }
    let block = landed.block();
    if m.y != v.y {
        // Block.onEntityLand: slime and beds bounce a non-living entity with 0.8 of the factor.
        let c = b.vel;
        if block == Block::SLIME_BLOCK {
            if c.y < 0.0 {
                b.vel = V3::new(c.x, -c.y * 0.8, c.z);
            }
        } else if is_bed(landed) {
            if c.y < 0.0 {
                b.vel = V3::new(c.x, -c.y * f64::from(0.66f32) * 0.8, c.z);
            }
        } else {
            b.vel = V3::new(c.x, c.y * 0.0, c.z);
        }
    }
    if b.on_ground && block == Block::SLIME_BLOCK {
        let c = b.vel;
        let d = c.y.abs();
        if d < 0.1 {
            let e = 0.4 + d * 0.2;
            b.vel = V3::new(c.x * e, c.y, c.z * e);
        }
    }
    check_block_collision(b, w);
    let k = f64::from(speed_factor(b, w));
    b.vel = V3::new(b.vel.x * k, b.vel.y, b.vel.z * k);
    // Fire: no fire or lava around ends the burning; a wet burning entity is put out (a sound).
    if b.fire_ticks <= 0 && !fire_or_lava_in(w, &contract(&b.bb, 0.001)) {
        b.fire_ticks = -1;
    }
    if is_wet(b, w) && b.on_fire() {
        b.rng.next_float();
        b.rng.next_float();
        b.fire_ticks = -1;
    }
}

/// `getLandingPos()`.
fn landing_pos<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> [i32; 3] {
    let p = [
        floor(b.pos.x),
        floor(b.pos.y - f64::from(0.2f32)),
        floor(b.pos.z),
    ];
    if state_at(w, p[0], p[1], p[2]).is_air() {
        let below = state_at(w, p[0], p[1] - 1, p[2]);
        let f = super::blocks::flags(below);
        if f.contains(ghast_data::PhysicsFlags::FENCE)
            || f.contains(ghast_data::PhysicsFlags::WALL)
            || f.contains(ghast_data::PhysicsFlags::FENCE_GATE)
        {
            return [p[0], p[1] - 1, p[2]];
        }
    }
    p
}

/// `getVelocityMultiplier()`.
fn speed_factor<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> f32 {
    let p = b.block_pos();
    let here = state_at(w, p[0], p[1], p[2]);
    let f = velocity_multiplier(here);
    let block = here.block();
    if block == Block::WATER || block == Block::BUBBLE_COLUMN || f != 1.0 {
        return f;
    }
    let y = floor(b.bb.min_y - 0.500_000_1);
    velocity_multiplier(state_at(w, p[0], y, p[2]))
}

/// `isWet()` (no rain is modelled): touching water or inside a bubble column.
fn is_wet<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> bool {
    if b.in_water {
        return true;
    }
    let p = b.block_pos();
    state_at(w, p[0], p[1], p[2]).block() == Block::BUBBLE_COLUMN
}

/// Any fire or lava block in the box (`World.method_29556(box)`).
fn fire_or_lava_in<W: BlockView<State = BlockState>>(w: &W, bb: &Aabb) -> bool {
    let (x0, x1) = (floor(bb.min_x), ceil(bb.max_x));
    let (y0, y1) = (floor(bb.min_y), ceil(bb.max_y));
    let (z0, z1) = (floor(bb.min_z), ceil(bb.max_z));
    if !region_loaded(w, x0, y0, z0, x1, y1, z1) {
        return false;
    }
    for x in x0..x1 {
        for y in y0..y1 {
            for z in z0..z1 {
                let b = state_at(w, x, y, z).block();
                if b == Block::FIRE || b == Block::SOUL_FIRE || b == Block::LAVA {
                    return true;
                }
            }
        }
    }
    false
}

/// `Entity.checkBlockCollision`: every block the box (shrunk by 0.001) is in, its
/// `onEntityCollision` as far as it moves or damages these entities.
pub(crate) fn check_block_collision<W: BlockView<State = BlockState>>(b: &mut Body, w: &W) {
    let bb = b.bb;
    let (x0, y0, z0) = (
        floor(bb.min_x + 0.001),
        floor(bb.min_y + 0.001),
        floor(bb.min_z + 0.001),
    );
    let (x1, y1, z1) = (
        floor(bb.max_x - 0.001),
        floor(bb.max_y - 0.001),
        floor(bb.max_z - 0.001),
    );
    if !region_loaded(w, x0, y0, z0, x1, y1, z1) {
        return;
    }
    for x in x0..=x1 {
        for y in y0..=y1 {
            for z in z0..=z1 {
                let s = state_at(w, x, y, z);
                let block = s.block();
                if block == Block::COBWEB {
                    b.fall = 0.0;
                    b.stuck = V3::new(0.25, f64::from(0.05f32), 0.25);
                } else if block == Block::HONEY_BLOCK {
                    if honey_sliding(b, [x, y, z]) {
                        let v = b.vel;
                        if v.y < -0.13 {
                            let d = -0.05 / v.y;
                            b.vel = V3::new(v.x * d, -0.05, v.z * d);
                        } else {
                            b.vel = V3::new(v.x, -0.05, v.z);
                        }
                        b.fall = 0.0;
                    }
                } else if block == Block::BUBBLE_COLUMN {
                    let drag = s.get(ghast_data::v1_16_5::Property::Drag) == Some("true");
                    let v = b.vel;
                    if state_at(w, x, y + 1, z).is_air() {
                        let d = if drag {
                            crate::math::java_max(-0.9, v.y - 0.03)
                        } else {
                            crate::math::java_min(1.8, v.y + 0.1)
                        };
                        b.vel = V3::new(v.x, d, v.z);
                    } else {
                        let d = if drag {
                            crate::math::java_max(-0.3, v.y - 0.03)
                        } else {
                            crate::math::java_min(0.7, v.y + 0.06)
                        };
                        b.vel = V3::new(v.x, d, v.z);
                        b.fall = 0.0;
                    }
                } else if block == Block::CACTUS {
                    b.damage(Damage::Cactus, 1);
                }
            }
        }
    }
}

/// `HoneyBlock.isSliding`.
fn honey_sliding(b: &Body, pos: [i32; 3]) -> bool {
    if b.on_ground {
        return false;
    }
    if b.pos.y > f64::from(pos[1]) + 0.9375 - 1.0e-7 {
        return false;
    }
    if b.vel.y >= -0.08 {
        return false;
    }
    let d = (f64::from(pos[0]) + 0.5 - b.pos.x).abs();
    let e = (f64::from(pos[2]) + 0.5 - b.pos.z).abs();
    let f = 0.4375 + f64::from(b.width / 2.0);
    d + 1.0e-7 > f || e + 1.0e-7 > f
}

// ---------------------------------------------------------------------------------------------
// Space queries

/// `world.isSpaceEmpty(entity)`: no block shape (in the entity's context), no world-border wall
/// overlaps the entity's box.
pub(crate) fn space_empty_for<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> bool {
    let border = BorderShape::new(&w.world_border());
    let col = Collider {
        w,
        border: &border,
        ctx: b.ctx(),
        entities: NoEntities,
    };
    col.is_space_empty(&b.bb, &b.bb)
}

/// `world.isSpaceEmpty(box)` with no entity: block shapes in the empty context only.
pub(crate) fn space_empty<W: BlockView<State = BlockState>>(w: &W, query: &Aabb) -> bool {
    let wb = w.world_border();
    let border = BorderShape::new(&wb);
    // No entity: the border is never part of the query, and the empty context sees every
    // scaffolding as stable.
    let inside = Aabb::new(wb.center_x, 0.0, wb.center_z, wb.center_x, 0.0, wb.center_z);
    let col = Collider {
        w,
        border: &border,
        ctx: ShapeCtx {
            min_y: f64::INFINITY,
            descending: false,
        },
        entities: NoEntities,
    };
    col.is_space_empty(&inside, query)
}

/// `Entity.pushOutOfBlocks(x, y, z)` (one random draw).
pub(crate) fn push_out_of_blocks<W: BlockView<State = BlockState>>(
    b: &mut Body,
    w: &W,
    x: f64,
    y: f64,
    z: f64,
) {
    let p = [floor(x), floor(y), floor(z)];
    let d = [
        x - f64::from(p[0]),
        y - f64::from(p[1]),
        z - f64::from(p[2]),
    ];
    // North, south, west, east, up: (axis, positive, offset).
    const DIRS: [(usize, bool, [i32; 3]); 5] = [
        (2, false, [0, 0, -1]),
        (2, true, [0, 0, 1]),
        (0, false, [-1, 0, 0]),
        (0, true, [1, 0, 0]),
        (1, true, [0, 1, 0]),
    ];
    let mut best = (1, true);
    let mut closest = f64::MAX;
    for (axis, positive, o) in DIRS {
        if !state_at(w, p[0] + o[0], p[1] + o[1], p[2] + o[2]).full_cube() {
            let e = d[axis];
            let f = if positive { 1.0 - e } else { e };
            if f < closest {
                closest = f;
                best = (axis, positive);
            }
        }
    }
    let g = b.rng.next_float() * 0.2 + 0.1;
    let h = if best.1 { 1.0f32 } else { -1.0 };
    let s = b.vel.scale(0.75);
    let v = f64::from(h * g);
    b.vel = match best.0 {
        0 => V3::new(v, s.y, s.z),
        1 => V3::new(s.x, v, s.z),
        _ => V3::new(s.x, s.y, v),
    };
}

/// The block's collision shape (empty context) holds the point (an arrow in its block).
pub(crate) fn collision_holds(s: BlockState, pos: [i32; 3], p: V3) -> bool {
    let contains = |a: &Aabb| {
        p.x >= a.min_x
            && p.x < a.max_x
            && p.y >= a.min_y
            && p.y < a.max_y
            && p.z >= a.min_z
            && p.z < a.max_z
    };
    if s.block() == Block::BAMBOO {
        return contains(&bamboo_box(pos[0], pos[2]).at(pos[0], pos[1], pos[2]));
    }
    if s.scaffolding_shapes().is_none() && s.voxel_shape().empty {
        return false;
    }
    collision_boxes(s, pos[1], None)
        .iter()
        .any(|a| contains(&a.at(pos[0], pos[1], pos[2])))
}

// ---------------------------------------------------------------------------------------------
// The block ray

static BAMBOO_XZ: [f64; 2] = [0.406_25, 0.593_75];
static BAMBOO_Y: [f64; 2] = [0.0, 1.0];
static BAMBOO_BOX: [Aabb; 1] = [Aabb::new(0.406_25, 0.0, 0.406_25, 0.593_75, 1.0, 0.593_75)];

/// A collision table entry as a ray grid.
fn voxel_cells(
    r: &'static ghast_data::v1_16_5::VoxelShapeRef,
    boxes: &'static [Aabb],
) -> Cells<'static> {
    Cells {
        cube: r.class == ghast_data::v1_16_5::VoxelClass::Simple,
        sizes: r.sizes,
        xs: r.xs,
        ys: r.ys,
        zs: r.zs,
        cells: r.cells,
        empty: r.empty,
        boxes,
    }
}

/// The collision shape of `s` at `p` against the segment (`VoxelShape.raycast`).
fn clip_collision(
    s: BlockState,
    p: [i32; 3],
    ctx: &ShapeCtx,
    from: [f64; 3],
    to: [f64; 3],
) -> Option<BlockHit> {
    if s.block() == Block::BAMBOO {
        let (ox, oz) = {
            let b = bamboo_box(p[0], p[2]);
            (b.min_x - BAMBOO_XZ[0], b.min_z - BAMBOO_XZ[0])
        };
        let cells = Cells {
            cube: false,
            sizes: [1, 1, 1],
            xs: &BAMBOO_XZ,
            ys: &BAMBOO_Y,
            zs: &BAMBOO_XZ,
            cells: &[1],
            empty: false,
            boxes: &BAMBOO_BOX,
        };
        return crate::pick::clip_cells(&cells, Some([ox, 0.0, oz]), from, to, p);
    }
    let (r, boxes) = match s.scaffolding_shapes() {
        Some(sc) => {
            // The same variant choice as the collision shape.
            match collision_shape(s, p[0], p[1], p[2], Some(ctx)) {
                Shape::Empty => return None,
                Shape::Grid { .. } => {
                    let above = ctx.min_y > f64::from(p[1]) + 1.0 - f64::from(1.0e-5f32);
                    if above && !ctx.descending {
                        (sc.stable_voxel, sc.stable)
                    } else {
                        (sc.bottom_voxel, sc.bottom)
                    }
                }
            }
        }
        None => (s.voxel_shape(), s.shape()),
    };
    crate::pick::clip_cells(&voxel_cells(r, boxes), None, from, to, p)
}

/// The fluid shape of a source fluid block (`FluidHandling.SOURCE_ONLY`) against the segment.
fn clip_source_fluid<W: BlockView<State = BlockState>>(
    w: &W,
    s: BlockState,
    p: [i32; 3],
    from: [f64; 3],
    to: [f64; 3],
) -> Option<BlockHit> {
    let f = fluid(s)?;
    if f.falling || f.amount != 8 {
        return None;
    }
    let h = f64::from(height(w, p[0], p[1], p[2], f));
    let boxes = [Aabb::new(0.0, 0.0, 0.0, 1.0, h, 1.0)];
    let cells = Cells {
        cube: false,
        sizes: [1, 1, 1],
        xs: &[0.0, 1.0],
        ys: &[0.0, h],
        zs: &[0.0, 1.0],
        cells: &[1],
        empty: false,
        boxes: &boxes,
    };
    crate::pick::clip_cells(&cells, None, from, to, p)
}

/// `World.raycast(new RaycastContext(from, to, COLLIDER, fluids, entity))`: the first block whose
/// collision shape (in the entity's context) the segment hits, re-faced by a nearer raycast-shape
/// hit (and, with `source_fluids`, the nearer of that and a source fluid's shape); else a miss at
/// `to`.
pub(crate) fn clip<W: BlockView<State = BlockState>>(
    w: &W,
    from: V3,
    to: V3,
    ctx: &ShapeCtx,
    source_fluids: bool,
) -> BlockHit {
    let (f, t) = ([from.x, from.y, from.z], [to.x, to.y, to.z]);
    crate::pick::traverse(f, t, |p| {
        let s = state_at(w, p[0], p[1], p[2]);
        let block = clip_collision(s, p, ctx, f, t).map(|mut hit| {
            let inter = PlacedShape::fixed(s.raycast_shape());
            if let Some(o) = crate::pick::clip_shape(&inter, f, t, p)
                && crate::pick::length_sqr(o.location, f) < crate::pick::length_sqr(hit.location, f)
            {
                hit.face = o.face;
            }
            hit
        });
        let liquid = if source_fluids {
            clip_source_fluid(w, s, p, f, t)
        } else {
            None
        };
        let dist =
            |h: &Option<BlockHit>| h.map_or(f64::MAX, |h| crate::pick::length_sqr(h.location, f));
        if dist(&block) <= dist(&liquid) {
            block
        } else {
            liquid
        }
    })
    .unwrap_or_else(|| {
        BlockHit::miss(
            t,
            Direction::approximate_nearest(f[0] - t[0], f[1] - t[1], f[2] - t[2]),
        )
    })
}

/// `MathHelper.sqrt(squaredHorizontalLength(v))`.
#[inline]
pub(crate) fn horizontal_len(v: V3) -> f64 {
    f64::from(sqrt_f64_as_f32(horizontal_sqr(v)))
}