ghast-entity 0.5.8

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 entity packets, vanilla-exact positions, O(1) lookup
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
//! Unit tests of the modern tracker.

use super::*;

/// The client motion of the motion types stays bounded: entries go when the entity is
/// removed, respawned under its id or has run out, however many come and go.
#[test]
fn client_motions_stay_bounded() {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite as _;
    let pig = data::entity_by_name("pig").unwrap().id;
    static TYPES: std::sync::OnceLock<[u16; 1]> = std::sync::OnceLock::new();
    let types = TYPES.get_or_init(|| [pig]);
    let mut t = Tracker::new(Config::default().with_motion_types(types));
    for x in -2..=2 {
        for z in -2..=2 {
            let mut b = bytes::BytesMut::new();
            b.put_i32(x);
            b.put_i32(z);
            t.apply_body(id::MAP_CHUNK, &b.freeze()).unwrap();
        }
    }
    let spawn = |t: &mut Tracker, eid: i32| {
        let mut b = bytes::BytesMut::new();
        b.put_varint(eid);
        b.put_u128(0x7000 + eid as u128);
        b.put_varint(i32::from(pig));
        for v in [f64::from(eid % 20), 64.0, 0.5] {
            b.put_f64(v);
        }
        LpVec3::from_vec3([0.2, -0.0784, 0.1]).write(&mut b);
        b.put_slice(&[0, 0, 0]);
        b.put_varint(0);
        t.apply_body(id::SPAWN_ENTITY, &b.freeze()).unwrap();
    };
    let remove = |t: &mut Tracker, ids: &[i32]| {
        let mut b = bytes::BytesMut::new();
        b.put_varint(ids.len() as i32);
        for &i in ids {
            b.put_varint(i);
        }
        t.apply_body(id::ENTITY_DESTROY, &b.freeze()).unwrap();
    };
    for round in 0..50 {
        let ids: Vec<i32> = (0..100).map(|k| 10 + round * 100 + k).collect();
        for &i in &ids {
            spawn(&mut t, i);
        }
        // Some respawn under the same id, some are pushed.
        for &i in ids.iter().step_by(7) {
            spawn(&mut t, i);
            t.push_motion(i, [0.05, 0.05]);
        }
        assert!(t.store.motions.len() <= 100, "{}", t.store.motions.len());
        t.tick();
        remove(&mut t, &ids[..50]);
        assert!(t.store.motions.len() <= 50);
        remove(&mut t, &ids[50..]);
        assert!(t.store.motions.is_empty());
    }
    // Left alone, a motion runs out and its entry goes.
    spawn(&mut t, 1);
    for _ in 0..400 {
        t.tick();
    }
    assert!(t.store.motions.is_empty());
    assert_eq!(t.client_motion(1), Some([0.0; 3]));
}

#[test]
fn java_round_and_delta_codec() {
    assert_eq!(jround(2.5), 3);
    assert_eq!(jround(-2.5), -2);
    assert_eq!(jround(-2.500_000_1), -3);
    assert_eq!(jround(0.499_999_999_999_999_94), 0);
    assert_eq!(jround(f64::NAN), 0);
    assert_eq!(jround(-0.5), 0);
    assert_eq!(jround(-0.500_000_000_000_000_1), -1);
    assert_eq!(jround(1e300), i64::MAX);
    assert_eq!(jround(-4.5e15 - 1.0), -4_500_000_000_000_001);
    for i in -2000..2000 {
        let x = f64::from(i) * 0.137_5 + 1e-3 * f64::from(i % 7);
        assert_eq!(jround(x), (x + 0.5).floor() as i64, "{x}");
        assert_eq!(mth_floor(x), x.floor() as i32, "{x}");
    }
    let b = [1.0 / 3.0, -7.25, 1e-9];
    assert_eq!(decode_delta(b, [0; 3]), b);
    let d = decode_delta(b, [4096, 0, -1]);
    assert_eq!(d[0], (1365.0 + 4096.0) / 4096.0);
    assert_eq!(d[1].to_bits(), b[1].to_bits());
    assert_eq!(d[2], -1.0 / 4096.0);
}

fn varint(out: &mut Vec<u8>, v: i32) {
    let mut v = v as u32;
    loop {
        if v < 0x80 {
            out.push(v as u8);
            return;
        }
        out.push((v as u8 & 0x7F) | 0x80);
        v >>= 7;
    }
}

/// Spawns `eid` (type `ty`) and sends it `entries` as one metadata packet.
fn spawn_with(t: &mut Tracker, eid: i32, ty: u16, entries: &[u8]) {
    let mut b = Vec::new();
    varint(&mut b, eid);
    b.extend_from_slice(&(0x1000_u128 + eid as u128).to_be_bytes());
    varint(&mut b, i32::from(ty));
    for c in [0.5, 64.0, 0.5_f64] {
        b.extend_from_slice(&c.to_be_bytes());
    }
    b.extend_from_slice(&[0, 0, 0, 0]); // zero LpVec3, pitch, yaw, head
    varint(&mut b, 0);
    let spawned = t.apply_body(id::SPAWN_ENTITY, &Bytes::from(b)).unwrap();
    assert_eq!(spawned, Applied::Changed);
    let mut m = Vec::new();
    varint(&mut m, eid);
    m.extend_from_slice(entries);
    m.push(0xFF);
    assert_eq!(
        t.apply_body(id::ENTITY_METADATA, &Bytes::from(m)).unwrap(),
        Applied::Changed
    );
}

/// Pins what one tracked entity costs (map slot + heap) so a change cannot silently grow
/// it. A player with what a server sends at spawn (health, skin parts), a zombie with its
/// health.
#[test]
fn bytes_per_tracked_entity() {
    // Health (index 9, float 20.0) and the skin parts byte (index 16).
    let mut player = vec![9, 3];
    player.extend_from_slice(&20.0_f32.to_be_bytes());
    player.extend_from_slice(&[16, 0, 0x7F]);
    let mut zombie = vec![9, 3];
    zombie.extend_from_slice(&20.0_f32.to_be_bytes());
    let mut t = Tracker::new(Config::default().with_player_list(false));
    spawn_with(&mut t, 10, data::PLAYER, &player);
    let ty = |n| data::entity_by_name(n).unwrap().id;
    spawn_with(&mut t, 11, ty("zombie"), &zombie);
    let slot = std::mem::size_of::<(i32, Entity)>();
    let p = t.get(10).unwrap();
    let z = t.get(11).unwrap();
    assert_eq!(p.metadata().len(), 2);
    let (pb, zb) = (slot + p.heap_bytes(), slot + z.heap_bytes());
    eprintln!(
        "slot {slot} B; player {pb} B ({} heap), zombie {zb} B ({} heap)",
        p.heap_bytes(),
        z.heap_bytes()
    );
    // 0.4.3: slot 240 B, metadata block 448 B (four-entry capacity), state 120 B: 808 B.
    // 0.4.8: + 8 B (the client view's pointer).
    assert!(slot <= 184, "{slot}");
    assert!(pb <= 528, "player {pb}");
    assert!(zb <= 416, "zombie {zb}");
    // Without the metadata store (`Config::metadata` off): slot and state only.
    let mut t = Tracker::new(
        Config::default()
            .with_player_list(false)
            .with_metadata(false),
    );
    spawn_with(&mut t, 10, data::PLAYER, &player);
    let p = t.get(10).unwrap();
    assert!(p.metadata().is_empty());
    let lean = slot + p.heap_bytes();
    eprintln!("without the metadata store: player {lean} B");
    assert!(lean <= 304, "player {lean}");
}

fn destroy(t: &mut Tracker, ids: &[i32]) {
    let mut b = Vec::new();
    varint(&mut b, ids.len() as i32);
    for &id in ids {
        varint(&mut b, id);
    }
    t.apply_body(id::ENTITY_DESTROY, &Bytes::from(b)).unwrap();
}

/// A steady crowd with fresh ids does not grow the tables (deletion markers would double
/// them), and a crowd that leaves gives the memory back.
#[test]
fn tables_follow_the_live_crowd() {
    let zombie = data::entity_by_name("zombie").unwrap().id;
    let mut t = Tracker::new(Config::default().with_metadata(false));
    for x in -2..=2 {
        for z in -2..=2 {
            t.mark_column_loaded(x, z);
        }
    }
    let health = [9, 3, 0x41, 0xA0, 0, 0];
    for id in 0..150 {
        spawn_with(&mut t, 100 + id, zombie, &health);
    }
    for id in 150..6000 {
        spawn_with(&mut t, 100 + id, zombie, &health);
        destroy(&mut t, &[100 + id - 150]);
        if id % 97 == 0 {
            t.tick();
        }
    }
    t.tick();
    assert_eq!(t.len(), 150);
    assert!(t.map.capacity() <= 224, "entity map {}", t.map.capacity());
    assert!(
        t.order.capacity() <= 224,
        "tick order {}",
        t.order.capacity()
    );
    for id in 6000..8000 {
        spawn_with(&mut t, 100 + id, zombie, &health);
    }
    let gone: Vec<i32> = (5850..7899).map(|i| 100 + i).collect();
    destroy(&mut t, &gone);
    t.tick();
    assert_eq!(t.len(), 101);
    assert!(t.map.capacity() <= 224, "entity map {}", t.map.capacity());
    assert!(
        t.order.capacity() <= 224,
        "tick order {}",
        t.order.capacity()
    );
}

/// `alive` follows the health with the metadata store off; the store stays empty.
#[test]
fn alive_without_metadata_store() {
    let zombie = data::entity_by_name("zombie").unwrap().id;
    let mut t = Tracker::new(Config::default().with_metadata(false));
    spawn_with(&mut t, 7, zombie, &[9, 3, 0x41, 0xA0, 0, 0]); // 20.0
    assert!(alive(t.get(7).unwrap()));
    let mut zero = vec![9, 3];
    zero.extend_from_slice(&0.0_f32.to_be_bytes());
    let mut m = Vec::new();
    varint(&mut m, 7);
    m.extend_from_slice(&zero);
    m.push(0xFF);
    t.apply_body(id::ENTITY_METADATA, &Bytes::from(m)).unwrap();
    let e = t.get(7).unwrap();
    assert!(!alive(e));
    assert_eq!(health(e), None);
    assert!(e.metadata().is_empty());
    let mut t = Tracker::new(Config::default());
    spawn_with(&mut t, 7, zombie, &zero);
    assert!(!alive(t.get(7).unwrap()));
    assert_eq!(health(t.get(7).unwrap()), Some(0.0));
}

fn mc_string(out: &mut Vec<u8>, v: &str) {
    varint(out, v.len() as i32);
    out.extend_from_slice(v.as_bytes());
}

/// `player_info` adding `(uuid, name, game mode)` entries (actions: add player, game mode).
fn tab_add(t: &mut Tracker, entries: &[(u128, &str, i32)]) {
    let mut b = vec![0b101];
    varint(&mut b, entries.len() as i32);
    for &(u, name, gm) in entries {
        b.extend_from_slice(&u.to_be_bytes());
        mc_string(&mut b, name);
        varint(&mut b, 0); // no properties
        varint(&mut b, gm);
    }
    t.apply_body(id::PLAYER_INFO, &Bytes::from(b)).unwrap();
}

fn tab_game_mode(t: &mut Tracker, u: u128, gm: i32) {
    let mut b = vec![0b100];
    varint(&mut b, 1);
    b.extend_from_slice(&u.to_be_bytes());
    varint(&mut b, gm);
    t.apply_body(id::PLAYER_INFO, &Bytes::from(b)).unwrap();
}

fn tab_remove(t: &mut Tracker, u: u128) {
    let mut b = Vec::new();
    varint(&mut b, 1);
    b.extend_from_slice(&u.to_be_bytes());
    t.apply_body(id::PLAYER_REMOVE, &Bytes::from(b)).unwrap();
}

/// What the entity and tab-list accessors answer, for comparing two trackers.
fn tab_view(t: &Tracker) -> Vec<String> {
    let mut v = vec![format!("len {} tab {}", t.len(), t.tab_len())];
    for id in [10, 11, 12, 13] {
        v.push(match t.get(id) {
            Some(e) => format!(
                "{id}: name {:?} sb {:?} gm {:?} spec {} pick {} ground {}",
                t.player_name(id),
                t.scoreboard_name(e),
                t.game_mode(e),
                t.is_spectator(e),
                t.pickable(e),
                e.on_ground()
            ),
            None => format!("{id}: none"),
        });
    }
    for u in [0x100A_u128, 0x100B, 0x100C, 0x100D] {
        let u = uuid::Uuid::from_u128(u);
        v.push(format!(
            "{u}: {:?} {:?}",
            t.tab_name(&u),
            t.tab_game_mode(&u)
        ));
    }
    v
}

/// The names-only tab list answers every entity question the full list answers.
#[test]
fn names_only_tab_list_matches_the_full_one() {
    let long = "a_very_long_offline_mode_name_x";
    let full = Config::default().with_metadata(false);
    let lite = full.with_player_list(false).with_player_names(true);
    let mut views = Vec::new();
    for config in [full, lite] {
        let mut t = Tracker::new(config);
        assert!(t.wants(id::PLAYER_INFO) && t.wants(id::PLAYER_REMOVE));
        tab_add(&mut t, &[(0x100A, "Alice", 0), (0x100B, long, 1)]);
        spawn_with(&mut t, 10, data::PLAYER, &[]);
        spawn_with(&mut t, 11, data::PLAYER, &[]);
        // No tab entry: vanilla refuses the spawn.
        let mut b = Vec::new();
        varint(&mut b, 12);
        b.extend_from_slice(&0x100C_u128.to_be_bytes());
        varint(&mut b, i32::from(data::PLAYER));
        b.extend_from_slice(&[0; 28]);
        varint(&mut b, 0);
        t.apply_body(id::SPAWN_ENTITY, &Bytes::from(b)).unwrap();
        let mut steps = vec![tab_view(&t)];
        tab_game_mode(&mut t, 0x100A, 3);
        t.tick();
        steps.push(tab_view(&t));
        tab_remove(&mut t, 0x100A);
        tab_remove(&mut t, 0x100B);
        steps.push(tab_view(&t));
        // A new entry with the same UUID: the entity keeps its profile and old entry.
        tab_add(&mut t, &[(0x100A, "Bob", 0)]);
        t.tick();
        steps.push(tab_view(&t));
        views.push(steps);
    }
    for (a, b) in views[0].iter().zip(&views[1]) {
        assert_eq!(a, b);
    }
    let s = &views[1];
    assert!(s[0][3].contains("12: none"), "{:?}", s[0]);
    assert!(s[1][1].contains("spec true pick false"), "{:?}", s[1]);
    assert!(
        s[2][1].contains("sb Some(\"Alice\") gm Some(3)"),
        "{:?}",
        s[2]
    );
    assert!(s[2][2].contains(long), "{:?}", s[2]);
    assert!(
        s[3][1].contains("name Some(\"Bob\") sb Some(\"Alice\") gm Some(3)"),
        "{:?}",
        s[3]
    );
}

/// Bytes per names-only tab entry (map slot, with the table's spare room at 100 entries).
#[test]
fn bytes_per_names_only_tab_entry() {
    let slot = std::mem::size_of::<(uuid::Uuid, crate::store::TabLite)>();
    let full = std::mem::size_of::<(uuid::Uuid, PlayerInfo)>();
    let mut t = Tracker::new(
        Config::default()
            .with_player_list(false)
            .with_player_names(true),
    );
    let names: Vec<String> = (0..100).map(|i| format!("Player_{i:04}")).collect();
    let entries: Vec<(u128, &str, i32)> = names
        .iter()
        .enumerate()
        .map(|(i, n)| (0x5000 + i as u128, n.as_str(), 0))
        .collect();
    tab_add(&mut t, &entries);
    assert_eq!(t.tab_len(), 100);
    assert!(t.store.long_names.is_empty() && t.store.players.is_empty());
    let buckets = (t.store.lite.capacity() * 8 / 7).next_power_of_two();
    let per = (buckets * (slot + 1) + 16) / 100;
    eprintln!(
        "names-only slot {slot} B (full list slot {full} B + heap), {per} B per entry at 100"
    );
    assert!(slot <= 48, "{slot}");
    assert!(per <= 64, "{per}");
}

#[test]
fn tick_order_renumbers_without_reordering() {
    let mut t = Tracker::new(Config::default());
    for id in [5, 3, 9] {
        t.start_ticking(id);
    }
    t.next_seq = u32::MAX - 2;
    t.start_ticking(1);
    t.start_ticking(7); // takes the last number: renumbers after
    let mut v: Vec<(u32, i32)> = t.order.iter().map(|(&i, &q)| (q, i)).collect();
    v.sort_unstable();
    assert_eq!(v, [(1, 5), (2, 3), (3, 9), (4, 1), (5, 7)]);
    t.start_ticking(3); // a member keeps its place
    assert_eq!(t.order[&3], 2);
}

#[test]
fn block_pos_unpacks() {
    let pack =
        |x: i64, y: i64, z: i64| ((x & 0x3FF_FFFF) << 38) | ((z & 0x3FF_FFFF) << 12) | (y & 0xFFF);
    assert_eq!(block_pos(pack(-5, 70, 123)), [-5, 70, 123]);
    assert_eq!(
        block_pos(pack(30_000_000, -64, -30_000_000)),
        [30_000_000, -64, -30_000_000]
    );
}