ghast-client 0.5.6

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
//! Modern versions: vehicles and mounts the player rides (boats, minecarts, living mounts):
//! equipment, the vehicles-only tracker, passengers, the server's moves and the left mount.

use super::*;

impl ModernSim {
    /// `entity_equipment` of a mount: its saddle slot (slot 7; any item there counts as a saddle,
    /// the item's `equippable` component is not checked); a happy ghast's harness (its body
    /// slot 6, the same way).
    pub(super) fn mount_equipment(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let id = r.read_varint()?;
        let Some(k) = self.own.mounts.iter().position(|m| m.id == id) else {
            return Ok(());
        };
        let p: cb::EntityEquipment = raw.decode_as()?;
        let steer_slot = if self.own.mounts[k].ty == EntityIds::get().happy_ghast {
            6
        } else {
            7
        };
        for e in &p.equipments {
            if e.slot == steer_slot {
                let saddled = e.item.item_count > 0;
                self.own.mounts[k].saddled = saddled;
                if let Some(Riding::Mount { id: rid, mount, .. }) = &mut self.riding
                    && *rid == id
                {
                    mount.set_saddled(saddled);
                }
            }
        }
        Ok(())
    }

    /// The vehicles-only tracker, started on the first vehicle seen without entity tracking
    /// (from the session's join packets and the loaded columns, like a tracker started late).
    pub(super) fn vehicle_tracker_mut(&mut self) -> &mut super::entity::Tracker {
        if self.vehicles.is_none() {
            let mut t = super::entity::Tracker::new(
                ghast_entity::Config::default()
                    .with_metadata(false)
                    .with_equipment(false)
                    .with_effects(false)
                    .with_events(false)
                    .with_motion_types(EntityIds::motion_types()),
            );
            self.session.replay(|r| {
                let _ = t.apply(r);
            });
            for (c, _) in self.world.columns().iter() {
                t.mark_column_loaded(c.x, c.z);
            }
            self.vehicles = Some(Box::new(t));
            self.filter_dirty = true;
        }
        self.vehicles.as_mut().unwrap()
    }

    /// `ClientLevel.tickNonPassenger` of the mount the player left (it ticks after the player):
    /// it slows down and is pushed off the player. Gone with its parking.
    #[cold]
    #[inline(never)]
    pub(super) fn tick_left_mount(&mut self) {
        if !self.parked.is_some_and(|p| p.living) {
            self.left_mount = None;
            return;
        }
        let Some(m) = &mut self.left_mount else {
            return;
        };
        let p = &self.player;
        let view = self
            .world
            .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        m.set_game_time(level_time(self.piston_clock, p.age));
        m.tick_alone::<Rules, _>(&view, p, &self.ext);
    }

    /// The parked boat ends when the server moved it (its tracked position changed) or it is
    /// gone.
    pub(super) fn check_parked(&mut self) {
        if let Some(k) = self.parked {
            let now = self
                .vehicle_tracker()
                .and_then(|t| t.get(k.id))
                .map(|e| e.position());
            if now != k.tracked {
                self.parked = None;
            }
        }
    }

    /// The ground flag of the last position packet of entity `id` (false when not tracked).
    pub(super) fn tracked_on_ground(&self, id: i32) -> bool {
        self.vehicle_tracker()
            .and_then(|t| t.get(id))
            .is_some_and(|e| e.on_ground())
    }

    /// The first passenger of a passenger list is no player (26.3: then nobody steers a boat).
    /// Without the tracker the type is unknown: taken as a player.
    fn front_not_player(&self, passengers: &[i32]) -> bool {
        let Some(&first) = passengers.first() else {
            return false;
        };
        first != self.own.id
            && self
                .vehicle_tracker()
                .and_then(|t| t.get(first))
                .is_some_and(|e| !e.is_player())
    }

    /// A position packet (teleport, relative move, position sync) after the tracker took it:
    /// a running dash clock of an unridden mount, and the vehicle the player rides (a teleport's
    /// motion and ground flag, also of a steered mount, a jump too far to interpolate; the ground
    /// flag of the other packets for one it does not steer).
    #[cold]
    #[inline(never)]
    pub(super) fn vehicle_moved(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        let id = ghast_protocol::Reader::new(&raw.body).read_varint()?;
        let on_ground = self.tracked_on_ground(id);
        if self.own.dash_watch {
            self.own.mount_moved(id, on_ground, self.player.age);
        }
        let teleport = if raw.id == cb::id::ENTITY_TELEPORT {
            Some(raw.decode_as::<cb::EntityTeleport>()?)
        } else {
            None
        };
        let p = &mut self.player;
        match &mut self.riding {
            Some(Riding::Mount { id: v, mount, .. })
                if *v == id && (teleport.is_some() || !mount.controlled()) =>
            {
                // A teleport sets the motion and ground flag of a steered mount too (its
                // position is interpolated); relative moves of it are only the packet base.
                if let Some(t) = &teleport {
                    let (delta, to) = teleport_values(t, mount.vel(), mount.pos());
                    mount.server_teleport(delta, t.on_ground);
                    if far(mount.pos(), to) {
                        mount.server_snap(to, t.yaw, t.pitch);
                        mount.position_passenger(p);
                    }
                } else {
                    mount.server_on_ground(on_ground);
                }
            }
            Some(Riding::Boat { id: v, boat })
                if *v == id && (teleport.is_some() || !boat.controlled()) =>
            {
                if let Some(t) = &teleport {
                    let (delta, to) = teleport_values(t, boat.vel(), boat.pos());
                    boat.server_teleport(delta, t.on_ground);
                    if far(boat.pos(), to) {
                        boat.server_snap(to, t.yaw, t.pitch);
                        boat.position_passenger(p);
                    }
                } else {
                    boat.server_on_ground(on_ground);
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// The tracker that knows the vehicles: the full one, else the vehicles-only one.
    pub(super) fn vehicle_tracker(&self) -> Option<&super::entity::Tracker> {
        self.entities.as_ref().or(self.vehicles.as_deref())
    }

    /// `set_passengers` and `move_vehicle` (the server's vehicle correction).
    pub(super) fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        if raw.id == cb::id::VEHICLE_MOVE {
            // handleMoveVehicle: only for the vehicle this client controls; answered at once.
            let reply = match &mut self.riding {
                Some(Riding::Boat { boat, .. }) => {
                    let p: cb::VehicleMove = raw.decode_as()?;
                    Some(boat.server_move([p.x, p.y, p.z], p.yaw, p.pitch))
                }
                Some(Riding::Mount { mount, .. }) => {
                    let p: cb::VehicleMove = raw.decode_as()?;
                    mount.server_move([p.x, p.y, p.z], p.yaw, p.pitch)
                }
                _ => None,
            };
            {
                if let Some(ghast_physics::Packet::MoveVehicle {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                }) = reply
                {
                    self.reply = Some(Outbound::VehicleMove {
                        pos: Vec3::new(pos[0], pos[1], pos[2]),
                        yaw,
                        pitch,
                        on_ground,
                    });
                }
            }
            return Ok(());
        }
        if let Some(v) = &mut self.vehicles {
            v.apply(raw)?;
        }
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let vehicle = r.read_varint()?;
        let riding_it = self.riding.as_ref().is_some_and(|v| v.id() == vehicle);
        let Some(t) = self.vehicle_tracker() else {
            return Ok(());
        };
        if !riding_it && t.get(vehicle).is_none() {
            return Ok(());
        }
        let p: cb::SetPassengers = raw.decode_as()?;
        let on = p.passengers.contains(&self.own.id);
        if on && !riding_it {
            // startRiding, on a vehicle the client knows (position and rotation as it holds
            // them). A vehicle without modelled physics (living mounts) keeps the walking
            // player, as before.
            let ride = t.get(vehicle).and_then(|e| {
                let kind = super::entity::entity_type(e).and_then(|t| vehicle_kind(t.name))?;
                Some(match kind {
                    VehicleKind::Boat(k) => {
                        let mut b = modern::Boat::new(k, e.position(), e.yaw(), e.pitch());
                        // A motion packet since the boat's last tick (an unridden boat's tick
                        // zeroes it) and the last position packet's ground flag.
                        b.set_watched_state(
                            t.client_motion(vehicle).unwrap_or([0.0; 3]),
                            e.on_ground(),
                        );
                        Riding::Boat {
                            id: vehicle,
                            boat: Box::new(b),
                        }
                    }
                    VehicleKind::Mount(k) => {
                        // The mount the player left, still where it was left: ride it on.
                        let left = self
                            .left_mount
                            .as_ref()
                            .filter(|_| self.parked.is_some_and(|p| p.id == vehicle && p.living))
                            .map(|m| (**m).clone());
                        let fresh = left.is_none();
                        let mut m = left.unwrap_or_else(|| {
                            let mut m = modern::Mount::new(k, e.position(), e.yaw(), e.pitch());
                            // The client copy's own motion and the last position packet's
                            // ground flag: the first ridden tick starts from them.
                            m.set_watched_state(
                                t.client_motion(vehicle).unwrap_or([0.0; 3]),
                                e.on_ground(),
                            );
                            m
                        });
                        m.set_rider_sticks(self.own.sticks.0, self.own.sticks.1);
                        if let Some(f) = self.own.mounts.iter().find(|m| m.id == vehicle) {
                            if fresh {
                                m.set_camel_sitting(f.camel_pose.0);
                                m.set_last_pose_change_tick(f.camel_pose.1);
                            }
                            if fresh {
                                // The entity the client has been ticking: its first tick is
                                // over, a dash cooldown ran on since the server's DASH.
                                let now = self.player.age;
                                if now != f.spawned {
                                    m.mark_ticked();
                                }
                                let (cd, on) = f.dash_now(now);
                                m.set_dash_state(cd, on);
                            }
                            if let Some(b) = f.boost.filter(|_| fresh) {
                                // Boosted before the boarding: the boost has not ticked yet
                                // (a boost that ticked on a mount forgotten since starts over).
                                m.set_boost_time(b);
                            }
                            m.set_saddled(f.saddled);
                            m.set_horse_flags(f.flags);
                            m.set_stays_still(f.stays_still);
                            for a in &f.attrs {
                                let mods: Vec<(ModifierId, f64, u8)> = a
                                    .modifiers
                                    .iter()
                                    .map(|(id, amount, op)| {
                                        (ModifierId::new(id), *amount, *op as u8)
                                    })
                                    .collect();
                                m.apply_attribute(a.name, a.base, &mods);
                            }
                        }
                        // The player's seat among the passengers (only the first one steers).
                        if let Some(k) = p.passengers.iter().position(|&x| x == self.own.id) {
                            m.set_seat(k);
                        }
                        m.set_passenger_count(p.passengers.len());
                        Riding::Mount {
                            id: vehicle,
                            mount: Box::new(m),
                            tracked: Some(e.position()),
                        }
                    }
                    VehicleKind::Cart => Riding::Seat { id: vehicle },
                })
            });
            let front_not_player = self.front_not_player(&p.passengers);
            let ride = ride.map(|mut r| {
                if let Riding::Boat { boat, .. } = &mut r
                    && let Some(k) = p.passengers.iter().position(|&x| x == self.own.id)
                {
                    boat.set_passengers(k, p.passengers.len());
                    boat.set_front_not_player(front_not_player);
                }
                r
            });
            if let Some(ride) = ride {
                self.parked = None;
                self.left_mount = None;
                match &ride {
                    Riding::Boat { boat, .. } => boat.board(&mut self.player),
                    Riding::Seat { .. } => modern::Seat::board(&mut self.player),
                    Riding::Mount { mount, .. } => mount.board(&mut self.player),
                }
                log::debug!("riding {vehicle}");
                // Steered from now on: the vehicle's packets later in this batch find it
                // authoritative (relative moves are only the packet base).
                let steers = match &ride {
                    Riding::Mount { mount, .. } => mount.controlled(),
                    Riding::Boat { boat, .. } => boat.controlled(),
                    Riding::Seat { .. } => false,
                };
                if steers {
                    if let Some(t) = &mut self.entities {
                        t.set_steered(Some(vehicle));
                    }
                    if let Some(v) = &mut self.vehicles {
                        v.set_steered(Some(vehicle));
                    }
                }
                self.riding = Some(ride);
            }
        } else if on {
            // Still on it: the passenger list changed (the player's seat, who steers).
            let front_not_player = self.front_not_player(&p.passengers);
            let k = p.passengers.iter().position(|&x| x == self.own.id);
            match (&mut self.riding, k) {
                (Some(Riding::Mount { mount, .. }), Some(k)) => {
                    mount.set_seat(k);
                    mount.set_passenger_count(p.passengers.len());
                }
                (Some(Riding::Boat { boat, .. }), Some(k)) => {
                    boat.set_passengers(k, p.passengers.len());
                    boat.set_front_not_player(front_not_player);
                }
                _ => {}
            }
        } else if !on && riding_it {
            // Off the vehicle (the server teleports the player afterwards).
            log::debug!("left vehicle {vehicle}");
            for t in [self.entities.as_mut(), self.vehicles.as_deref_mut()]
                .into_iter()
                .flatten()
            {
                t.set_steered(None);
            }
            // The client moved a boat or a controlled mount: it stays where the player left it
            // (no server move follows) until the server moves it.
            let left = match self.riding.take() {
                Some(Riding::Boat { id, boat }) => {
                    Some((id, boat.pos(), boat.bounding_box(), false))
                }
                Some(Riding::Mount { id, mut mount, .. }) => {
                    modern::Mount::dismount(&mut self.ext);
                    // Others still aboard: it is not pushed off the player.
                    mount.set_passenger_count(p.passengers.len());
                    let left = Some((id, mount.pos(), mount.bounding_box(), true));
                    self.left_mount = Some(mount);
                    left
                }
                _ => None,
            };
            if let Some((id, pos, b, living)) = left {
                self.parked = Some(Parked {
                    id,
                    pos,
                    bb: [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                    tracked: self
                        .vehicle_tracker()
                        .and_then(|t| t.get(id))
                        .map(|e| e.position()),
                    living,
                });
            }
            // The extended tick runs once more (what the ride left in `ext` is read there).
            self.ext_active = true;
        }
        Ok(())
    }

    /// `set_entity_motion` of the vehicle the player rides (`lerpMotion` sets the motion of a
    /// mount or boat the player steers too: there is no authority check).
    #[cold]
    #[inline(never)]
    pub(super) fn vehicle_motion(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        let p: cb::EntityVelocity = raw.decode_as()?;
        let v = p.velocity.to_vec3();
        match &mut self.riding {
            Some(Riding::Mount { id, mount, .. }) if *id == p.entity_id => mount.server_motion(v),
            Some(Riding::Boat { id, boat }) if *id == p.entity_id => boat.server_motion(v),
            _ => {}
        }
        Ok(())
    }
}