ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
//! Fishing: the bot's own fishing bobber as the vanilla client knows it, and the bite.
//!
//! A right click with a fishing rod (a plain item use, [`crate::TickContext::set_buttons`]) makes
//! the server throw a bobber; the next right click while it is out reels it in (the server
//! retrieves it: a fish when it bit, the hooked entity pulled, nothing otherwise). Everything
//! the client learns about the bobber comes from entity packets, so this needs entity tracking
//! ([`crate::Interests::ENTITIES`] or the lean [`crate::Interests::ENTITY_TRACKING`]); without
//! it [`crate::TickContext::fishing`] is always `None` and no [`FishingEvent`] is queued.
//!
//! # Which bobber is ours
//!
//! The server spawns the bobber with its owner's entity id as the spawn's object data (1.8.9
//! `spawn_entity` type 90, 1.12.2 type 90, 1.16.5 and 26.x the `fishing_bobber` entity type);
//! the vanilla client's spawn handler then makes it `player.fishing` (`fishHook` on 1.8 – 1.16)
//! of that player. A bobber whose owner is our entity is ours, the newest one replacing an older
//! one. The client drops it when the server removes the entity (`remove_entities` / destroy:
//! the reel-in, the rod no longer held, more than 32 blocks away, the owner gone — all decided
//! by the server), when the tracker forgets it (respawn, dimension change, configuration) and
//! when vanilla's own client tick removes it (a bobber lying on the ground for 1200 ticks;
//! modelled only with [`crate::Interests::ENTITY_PHYSICS`]).
//!
//! # The bite
//!
//! - **1.16.5 and 26.x: exact.** The server sets the bobber's synced `biting` flag
//!   (`FishingBobberEntity.CAUGHT_FISH`, 26.x `FishingHook.DATA_BITING`) when a fish bites
//!   and clears it when the fish gets away; [`FishingEvent::Bite`] and
//!   [`FishingEvent::BiteEnded`] follow the entity data packet, and [`Bobber::biting`] is the
//!   flag. A reel-in while it is set catches the fish.
//! - **1.8.9 and 1.12.2: heuristic.** These servers send no bite flag. At the bite the server
//!   plays the bobber splash sound at the bobber (1.8.9 `named_sound_effect` `random.splash`,
//!   which no other vanilla 1.8.9 code plays; 1.12.2 `sound_effect` id 153,
//!   `entity.bobber.splash`, played only by the bite) and pulls the bobber down (a velocity
//!   update). ghast reports a [`FishingEvent::Bite`] for such a sound when it is within 2 blocks
//!   of our bobber's tracked position and no other tracked bobber is nearer to it. The sound
//!   packets are read only while we have a bobber (the packet filter takes them in then). The
//!   fish stays on the hook for 10 – 30 ticks (1.8.9) or 20 – 40 ticks (1.12.2) after the
//!   splash; [`Bobber::biting`] stays set for the shortest of those windows (10 / 20 ticks) and
//!   no [`FishingEvent::BiteEnded`] is reported. A plugin that silences or moves the sound
//!   hides the bite.
//!
//! # State
//!
//! [`Bobber::state`] is vanilla's `FishHookState` as the client would see it: hooked while the
//! server's synced hooked-entity id is set (1.12.2+; 1.8.9 servers do not send it, so a 1.8.9
//! bobber is never `Hooked`), bobbing from the first tick its position holds water, flying
//! before. [`Bobber::position`] is the tracker's position of the bobber: the server's position
//! packets, or with [`crate::Interests::ENTITY_PHYSICS`] the client's own simulation of it
//! (which on 1.12.2 and 1.16.5, like vanilla, ignores the server's position packets).
//!
//! # Cost
//!
//! Nothing per tick while there is no bobber of ours: a spawn packet of another type is
//! dismissed by its type. With a bobber, one tracker lookup and one block read per tick.

/// The bot's own fishing bobber ([`crate::TickContext::fishing`]).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Bobber {
    /// The bobber's entity id.
    pub id: i32,
    /// Its tracked position.
    pub position: [f64; 3],
    /// Flying, bobbing or hooked (see the module docs).
    pub state: BobberState,
    /// The entity the server hooked it to (1.12.2+), if any.
    pub hooked: Option<i32>,
    /// A fish is on the hook: exact on 1.16.5 and 26.x, a window after the splash sound on
    /// 1.8.9 and 1.12.2 (see the module docs).
    pub biting: bool,
    /// Client ticks since the bobber appeared.
    pub age: u32,
}

/// The state of the bot's bobber (vanilla `FishHookState`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BobberState {
    /// Thrown, not in water yet.
    Flying,
    /// It reached water (it stays bobbing after that, as vanilla's state does).
    Bobbing,
    /// The server hooked it to an entity ([`Bobber::hooked`]).
    Hooked,
}

/// A change of the bot's own bobber, in arrival order ([`crate::TickEvents::fishing`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FishingEvent {
    /// Our bobber appeared (the server threw it after our rod use).
    Cast {
        /// The bobber's entity id.
        id: i32,
    },
    /// A fish bit: reel in now ([`Bobber::biting`]).
    Bite {
        /// The bobber's entity id.
        id: i32,
    },
    /// The fish got away (1.16.5 and 26.x: the server cleared the bite flag).
    BiteEnded {
        /// The bobber's entity id.
        id: i32,
    },
    /// The server hooked the bobber to an entity (1.12.2+).
    Hooked {
        /// The bobber's entity id.
        id: i32,
        /// The hooked entity's id.
        entity: i32,
    },
    /// The bobber let go of the entity it was hooked to.
    Unhooked {
        /// The bobber's entity id.
        id: i32,
    },
    /// Our bobber is gone (reeled in, removed by the server, or forgotten with the tracker).
    Gone {
        /// The bobber's entity id.
        id: i32,
    },
}

impl FishingEvent {
    /// The bobber's entity id.
    #[must_use]
    pub fn bobber(&self) -> i32 {
        match *self {
            FishingEvent::Cast { id }
            | FishingEvent::Bite { id }
            | FishingEvent::BiteEnded { id }
            | FishingEvent::Hooked { id, .. }
            | FishingEvent::Unhooked { id }
            | FishingEvent::Gone { id } => id,
        }
    }
}

/// How a version tells the client about a bite ([`bite_signal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BiteSignal {
    /// The bobber's synced `biting` entity data (1.16.5, 26.x): exact.
    EntityData,
    /// The bobber splash sound at the bobber (1.8.9, 1.12.2): a heuristic.
    SplashSound,
}

/// How `version` signals a bite (see the module docs).
#[must_use]
pub fn bite_signal(version: crate::GameVersion) -> BiteSignal {
    if version.protocol() < 735 {
        BiteSignal::SplashSound
    } else {
        BiteSignal::EntityData
    }
}

/// Most fishing events kept between two behaviour ticks.
const MAX_EVENTS: usize = 64;

/// Squared distance within which a splash sound belongs to our bobber (2 blocks).
#[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
const SOUND_RANGE_SQ: f64 = 4.0;

/// The per-version sim's record of our bobber (crate-internal).
#[derive(Debug, Default)]
pub(crate) struct Fishing {
    bobber: Option<Bobber>,
    /// The raw synced hooked-entity value (entity id + 1, 0 = none).
    hooked_raw: i32,
    /// Legacy: ticks left of the bite window after the splash.
    bite_left: u8,
    events: Vec<FishingEvent>,
}

impl Fishing {
    /// We have a bobber (the per-tick and per-packet work runs only then).
    #[inline(always)]
    pub(crate) fn active(&self) -> bool {
        self.bobber.is_some()
    }

    /// Our bobber's id.
    #[inline]
    pub(crate) fn id(&self) -> Option<i32> {
        self.bobber.map(|b| b.id)
    }

    /// The bobber.
    #[inline]
    pub(crate) fn bobber(&self) -> Option<&Bobber> {
        self.bobber.as_ref()
    }

    /// Events are waiting for the behaviour.
    #[inline(always)]
    pub(crate) fn has_events(&self) -> bool {
        !self.events.is_empty()
    }

    /// Moves the events into `out`.
    pub(crate) fn drain(&mut self, out: &mut Vec<FishingEvent>) {
        out.append(&mut self.events);
    }

    fn push(&mut self, e: FishingEvent) {
        if self.events.len() < MAX_EVENTS {
            self.events.push(e);
        }
    }

    /// A bobber spawned with `owner` as its owner; ours when `owner == own_id`. Returns whether
    /// we had no bobber before and have one now (the packet filter grows).
    pub(crate) fn spawned(&mut self, id: i32, owner: i32, own_id: i32, pos: [f64; 3]) -> bool {
        if let Some(old) = self.bobber
            && old.id == id
        {
            // A re-spawn of the same id is a new entity.
            self.push(FishingEvent::Gone { id });
            self.bobber = None;
        }
        if owner != own_id {
            return false;
        }
        let was = self.bobber.is_some();
        if let Some(old) = self.bobber.take() {
            // player.fishing is the newest bobber.
            self.push(FishingEvent::Gone { id: old.id });
        }
        self.hooked_raw = 0;
        self.bite_left = 0;
        self.bobber = Some(Bobber {
            id,
            position: pos,
            state: BobberState::Flying,
            hooked: None,
            biting: false,
            age: 0,
        });
        self.push(FishingEvent::Cast { id });
        !was
    }

    /// Forgets the bobber (the tracker forgot it, or the server removed it). Returns whether
    /// we had one (the packet filter shrinks).
    pub(crate) fn gone(&mut self) -> bool {
        match self.bobber.take() {
            Some(b) => {
                self.push(FishingEvent::Gone { id: b.id });
                true
            }
            None => false,
        }
    }

    /// The synced hooked-entity value of our bobber (entity id + 1, 0 = none).
    #[cfg_attr(
        not(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern)),
        allow(dead_code)
    )]
    pub(crate) fn hooked(&mut self, raw: i32) {
        let Some(b) = &mut self.bobber else {
            return;
        };
        if raw == self.hooked_raw {
            return;
        }
        self.hooked_raw = raw;
        let id = b.id;
        if raw > 0 {
            b.hooked = Some(raw - 1);
            b.state = BobberState::Hooked;
            self.push(FishingEvent::Hooked {
                id,
                entity: raw - 1,
            });
        } else {
            b.hooked = None;
            // HOOKED_IN_ENTITY -> FLYING when the entity is gone.
            b.state = BobberState::Flying;
            self.push(FishingEvent::Unhooked { id });
        }
    }

    /// The synced `biting` flag of our bobber (1.16.5, 26.x).
    #[cfg_attr(not(any(feature = "v1_16_5", ghast_modern)), allow(dead_code))]
    pub(crate) fn biting(&mut self, on: bool) {
        let Some(b) = &mut self.bobber else {
            return;
        };
        if b.biting == on {
            return;
        }
        b.biting = on;
        let id = b.id;
        self.push(if on {
            FishingEvent::Bite { id }
        } else {
            FishingEvent::BiteEnded { id }
        });
    }

    /// A splash sound at `pos` (1.8.9, 1.12.2): our bite when it is within 2 blocks of our
    /// bobber and no other bobber in `others` is nearer. `window` is the version's shortest
    /// hook time.
    #[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
    pub(crate) fn splash(
        &mut self,
        pos: [f64; 3],
        others: impl Iterator<Item = [f64; 3]>,
        window: u8,
    ) {
        let Some(b) = &mut self.bobber else {
            return;
        };
        let d = dist_sq(pos, b.position);
        if d > SOUND_RANGE_SQ {
            return;
        }
        let mut others = others;
        if others.any(|o| dist_sq(pos, o) < d) {
            return;
        }
        let id = b.id;
        let new = !b.biting;
        b.biting = true;
        self.bite_left = window;
        if new {
            self.push(FishingEvent::Bite { id });
        }
    }

    /// One client tick with a bobber: its tracked position (`None`: the tracker no longer
    /// has it) and whether its position holds water (`in_water`). Returns whether the bobber
    /// went away (the packet filter shrinks).
    pub(crate) fn tick(
        &mut self,
        pos: Option<[f64; 3]>,
        in_water: impl FnOnce([f64; 3]) -> bool,
    ) -> bool {
        let Some(b) = &mut self.bobber else {
            return false;
        };
        let Some(pos) = pos else {
            return self.gone();
        };
        b.position = pos;
        b.age = b.age.saturating_add(1);
        if b.state == BobberState::Flying && b.hooked.is_none() && in_water(pos) {
            b.state = BobberState::Bobbing;
        }
        if self.bite_left > 0 {
            self.bite_left -= 1;
            if self.bite_left == 0 {
                b.biting = false;
            }
        }
        false
    }
}

#[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
fn dist_sq(a: [f64; 3], b: [f64; 3]) -> f64 {
    let (x, y, z) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]);
    x * x + y * y + z * z
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn own_bobber_lifecycle() {
        let mut f = Fishing::default();
        assert!(!f.spawned(10, 7, 5, [0.0; 3]), "another player's bobber");
        assert!(!f.active());
        assert!(f.spawned(11, 5, 5, [1.0, 64.0, 1.0]));
        assert_eq!(f.id(), Some(11));
        assert!(!f.tick(Some([1.0, 63.5, 1.0]), |_| true));
        assert_eq!(f.bobber().unwrap().state, BobberState::Bobbing);
        f.biting(true);
        f.biting(true);
        f.biting(false);
        f.hooked(43);
        assert_eq!(f.bobber().unwrap().hooked, Some(42));
        f.hooked(0);
        assert!(f.tick(None, |_| false));
        assert!(!f.active());
        let mut ev = Vec::new();
        f.drain(&mut ev);
        assert_eq!(
            ev,
            [
                FishingEvent::Cast { id: 11 },
                FishingEvent::Bite { id: 11 },
                FishingEvent::BiteEnded { id: 11 },
                FishingEvent::Hooked { id: 11, entity: 42 },
                FishingEvent::Unhooked { id: 11 },
                FishingEvent::Gone { id: 11 },
            ]
        );
    }

    #[test]
    fn splash_window() {
        let mut f = Fishing::default();
        f.spawned(3, 1, 1, [0.5, 62.9, 0.5]);
        // too far
        f.splash([4.0, 63.0, 0.5], std::iter::empty(), 10);
        assert!(!f.bobber().unwrap().biting);
        // another bobber is nearer
        f.splash([0.5, 63.0, 1.5], [[0.5, 63.0, 1.6]].into_iter(), 10);
        assert!(!f.bobber().unwrap().biting);
        f.splash([0.5, 63.0, 0.5], [[3.0, 63.0, 3.0]].into_iter(), 10);
        assert!(f.bobber().unwrap().biting);
        for _ in 0..9 {
            f.tick(Some([0.5, 62.9, 0.5]), |_| true);
        }
        assert!(f.bobber().unwrap().biting);
        f.tick(Some([0.5, 62.9, 0.5]), |_| true);
        assert!(!f.bobber().unwrap().biting);
        let mut ev = Vec::new();
        f.drain(&mut ev);
        assert_eq!(
            ev,
            [FishingEvent::Cast { id: 3 }, FishingEvent::Bite { id: 3 }]
        );
    }

    #[test]
    fn signals() {
        use crate::GameVersion as V;
        assert_eq!(bite_signal(V::V1_8_9), BiteSignal::SplashSound);
        assert_eq!(bite_signal(V::V1_12_2), BiteSignal::SplashSound);
        assert_eq!(bite_signal(V::V1_16_5), BiteSignal::EntityData);
        assert_eq!(bite_signal(V::V26_1), BiteSignal::EntityData);
    }
}