valence 0.1.0+mc1.19.2

A framework for building Minecraft servers in Rust.
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
//! The player list (tab list).

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};

use bitfield_struct::bitfield;
use uuid::Uuid;

use crate::client::GameMode;
use crate::config::Config;
use crate::player_textures::SignedPlayerTextures;
use crate::protocol::packets::s2c::play::{
    PlayerListAddPlayer, PlayerListHeaderFooter, S2cPlayPacket, UpdatePlayerList,
};
use crate::protocol::packets::Property;
use crate::protocol::VarInt;
use crate::slab_rc::{Key, SlabRc};
use crate::text::Text;

/// A container for all [`PlayerList`]s on a server.
pub struct PlayerLists<C: Config> {
    slab: SlabRc<PlayerList<C>>,
}

/// An identifier for a [`PlayerList`] on the server.
///
/// Player list IDs are refcounted. Once all IDs referring to the same player
/// list are dropped, the player list is automatically deleted.
///
/// The [`Ord`] instance on this type is correct but otherwise unspecified. This
/// is useful for storing IDs in containers such as
/// [`BTreeMap`](std::collections::BTreeMap).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PlayerListId(Key);

impl<C: Config> PlayerLists<C> {
    pub(crate) fn new() -> Self {
        Self {
            slab: SlabRc::new(),
        }
    }

    /// Creates a new player list and returns an exclusive reference to it along
    /// with its ID.
    ///
    /// The player list is automatically removed at the end of the tick once all
    /// IDs to it have been dropped.
    pub fn insert(&mut self, state: C::PlayerListState) -> (PlayerListId, &mut PlayerList<C>) {
        let (key, pl) = self.slab.insert(PlayerList {
            state,
            entries: HashMap::new(),
            removed: HashSet::new(),
            header: Text::default(),
            footer: Text::default(),
            modified_header_or_footer: false,
        });

        (PlayerListId(key), pl)
    }

    /// Returns the number of player lists.
    pub fn len(&self) -> usize {
        self.slab.len()
    }

    /// Returns `true` if there are no player lists.
    pub fn is_empty(&self) -> bool {
        self.slab.len() == 0
    }

    /// Gets a shared reference to the player list with the given player list
    /// ID.
    ///
    /// This operation is infallible because [`PlayerListId`] is refcounted.
    pub fn get(&self, id: &PlayerListId) -> &PlayerList<C> {
        self.slab.get(&id.0)
    }

    /// Gets an exclusive reference to the player list with the given player
    /// list ID.
    ///
    /// This operation is infallible because [`PlayerListId`] is refcounted.
    pub fn get_mut(&mut self, id: &PlayerListId) -> &mut PlayerList<C> {
        self.slab.get_mut(&id.0)
    }

    pub(crate) fn update(&mut self) {
        self.slab.collect_garbage();
        for (_, pl) in self.slab.iter_mut() {
            for entry in pl.entries.values_mut() {
                entry.bits = EntryBits::new();
            }
            pl.removed.clear();
            pl.modified_header_or_footer = false;
        }
    }
}

/// The list of players on a server visible by pressing the tab key by default.
///
/// Each entry in the player list is intended to represent a connected client to
/// the server.
///
/// In addition to a list of players, the player list has a header and a footer
/// which can contain arbitrary text.
pub struct PlayerList<C: Config> {
    /// Custom state
    pub state: C::PlayerListState,
    entries: HashMap<Uuid, PlayerListEntry>,
    removed: HashSet<Uuid>,
    header: Text,
    footer: Text,
    modified_header_or_footer: bool,
}

impl<C: Config> PlayerList<C> {
    /// Inserts a player into the player list.
    ///
    /// If the given UUID conflicts with an existing entry, the entry is
    /// overwritten and `false` is returned. Otherwise, `true` is returned.
    pub fn insert(
        &mut self,
        uuid: Uuid,
        username: impl Into<String>,
        textures: Option<SignedPlayerTextures>,
        game_mode: GameMode,
        ping: i32,
        display_name: impl Into<Option<Text>>,
    ) -> bool {
        match self.entries.entry(uuid) {
            Entry::Occupied(mut oe) => {
                let e = oe.get_mut();
                let username = username.into();

                if e.username() != username || e.textures != textures {
                    self.removed.insert(*oe.key());

                    oe.insert(PlayerListEntry {
                        username,
                        textures,
                        game_mode,
                        ping,
                        display_name: display_name.into(),
                        bits: EntryBits::new().with_created_this_tick(true),
                    });
                } else {
                    e.set_game_mode(game_mode);
                    e.set_ping(ping);
                    e.set_display_name(display_name);
                }
                false
            }
            Entry::Vacant(ve) => {
                ve.insert(PlayerListEntry {
                    username: username.into(),
                    textures,
                    game_mode,
                    ping,
                    display_name: display_name.into(),
                    bits: EntryBits::new().with_created_this_tick(true),
                });
                true
            }
        }
    }

    /// Removes an entry from the player list with the given UUID. Returns
    /// whether the entry was present in the list.
    pub fn remove(&mut self, uuid: Uuid) -> bool {
        if self.entries.remove(&uuid).is_some() {
            self.removed.insert(uuid);
            true
        } else {
            false
        }
    }

    /// Removes all entries from the player list for which `f` returns `true`.
    ///
    /// All entries are visited in an unspecified order.
    pub fn retain(&mut self, mut f: impl FnMut(Uuid, &mut PlayerListEntry) -> bool) {
        self.entries.retain(|&uuid, entry| {
            if !f(uuid, entry) {
                self.removed.insert(uuid);
                false
            } else {
                true
            }
        })
    }

    /// Removes all entries from the player list.
    pub fn clear(&mut self) {
        self.removed.extend(self.entries.drain().map(|p| p.0))
    }

    /// Gets the header part of the player list.
    pub fn header(&self) -> &Text {
        &self.header
    }

    /// Sets the header part of the player list.
    pub fn set_header(&mut self, header: impl Into<Text>) {
        let header = header.into();
        if self.header != header {
            self.header = header;
            self.modified_header_or_footer = true;
        }
    }

    /// Gets the footer part of the player list.
    pub fn footer(&self) -> &Text {
        &self.footer
    }

    /// Sets the footer part of the player list.
    pub fn set_footer(&mut self, footer: impl Into<Text>) {
        let footer = footer.into();
        if self.footer != footer {
            self.footer = footer;
            self.modified_header_or_footer = true;
        }
    }

    /// Returns an iterator over all entries in an unspecified order.
    pub fn entries(&self) -> impl Iterator<Item = (Uuid, &PlayerListEntry)> + '_ {
        self.entries.iter().map(|(k, v)| (*k, v))
    }

    /// Returns a mutable iterator over all entries in an unspecified order.
    pub fn entries_mut(&mut self) -> impl Iterator<Item = (Uuid, &mut PlayerListEntry)> + '_ {
        self.entries.iter_mut().map(|(k, v)| (*k, v))
    }

    pub(crate) fn initial_packets(&self, mut push_packet: impl FnMut(S2cPlayPacket)) {
        let add_player: Vec<_> = self
            .entries
            .iter()
            .map(|(&uuid, e)| PlayerListAddPlayer {
                uuid,
                username: e.username.clone().into(),
                properties: {
                    let mut properties = Vec::new();
                    if let Some(textures) = &e.textures {
                        properties.push(Property {
                            name: "textures".into(),
                            value: base64::encode(textures.payload()),
                            signature: Some(base64::encode(textures.signature())),
                        });
                    }
                    properties
                },
                game_mode: e.game_mode,
                ping: VarInt(e.ping),
                display_name: e.display_name.clone(),
                sig_data: None,
            })
            .collect();

        if !add_player.is_empty() {
            push_packet(UpdatePlayerList::AddPlayer(add_player).into());
        }

        if self.header != Text::default() || self.footer != Text::default() {
            push_packet(
                PlayerListHeaderFooter {
                    header: self.header.clone(),
                    footer: self.footer.clone(),
                }
                .into(),
            );
        }
    }

    pub(crate) fn update_packets(&self, mut push_packet: impl FnMut(S2cPlayPacket)) {
        if !self.removed.is_empty() {
            push_packet(
                UpdatePlayerList::RemovePlayer(self.removed.iter().cloned().collect()).into(),
            );
        }

        let mut add_player = Vec::new();
        let mut game_mode = Vec::new();
        let mut ping = Vec::new();
        let mut display_name = Vec::new();

        for (&uuid, e) in self.entries.iter() {
            if e.bits.created_this_tick() {
                let mut properties = Vec::new();
                if let Some(textures) = &e.textures {
                    properties.push(Property {
                        name: "textures".into(),
                        value: base64::encode(textures.payload()),
                        signature: Some(base64::encode(textures.signature())),
                    });
                }

                add_player.push(PlayerListAddPlayer {
                    uuid,
                    username: e.username.clone().into(),
                    properties,
                    game_mode: e.game_mode,
                    ping: VarInt(e.ping),
                    display_name: e.display_name.clone(),
                    sig_data: None,
                });

                continue;
            }

            if e.bits.modified_game_mode() {
                game_mode.push((uuid, e.game_mode));
            }

            if e.bits.modified_ping() {
                ping.push((uuid, VarInt(e.ping)));
            }

            if e.bits.modified_display_name() {
                display_name.push((uuid, e.display_name.clone()));
            }
        }

        if !add_player.is_empty() {
            push_packet(UpdatePlayerList::AddPlayer(add_player).into());
        }

        if !game_mode.is_empty() {
            push_packet(UpdatePlayerList::UpdateGameMode(game_mode).into());
        }

        if !ping.is_empty() {
            push_packet(UpdatePlayerList::UpdateLatency(ping).into());
        }

        if !display_name.is_empty() {
            push_packet(UpdatePlayerList::UpdateDisplayName(display_name).into());
        }

        if self.modified_header_or_footer {
            push_packet(
                PlayerListHeaderFooter {
                    header: self.header.clone(),
                    footer: self.footer.clone(),
                }
                .into(),
            );
        }
    }

    pub(crate) fn clear_packets(&self, mut push_packet: impl FnMut(S2cPlayPacket)) {
        push_packet(UpdatePlayerList::RemovePlayer(self.entries.keys().cloned().collect()).into());
    }
}

/// Represents a player entry in the [`PlayerList`].
pub struct PlayerListEntry {
    username: String,
    textures: Option<SignedPlayerTextures>,
    game_mode: GameMode,
    ping: i32,
    display_name: Option<Text>,
    bits: EntryBits,
}

#[bitfield(u8)]
struct EntryBits {
    created_this_tick: bool,
    modified_game_mode: bool,
    modified_ping: bool,
    modified_display_name: bool,
    #[bits(4)]
    _pad: u8,
}

impl PlayerListEntry {
    /// Gets the username of this entry.
    pub fn username(&self) -> &str {
        &self.username
    }

    /// Gets the player textures for this entry.
    pub fn textures(&self) -> Option<&SignedPlayerTextures> {
        self.textures.as_ref()
    }

    /// Gets the game mode of this entry.
    pub fn game_mode(&self) -> GameMode {
        self.game_mode
    }

    /// Sets the game mode of this entry.
    pub fn set_game_mode(&mut self, game_mode: GameMode) {
        if self.game_mode != game_mode {
            self.game_mode = game_mode;
            self.bits.set_modified_game_mode(true);
        }
    }

    /// Gets the ping (latency) of this entry measured in milliseconds.
    pub fn ping(&self) -> i32 {
        self.ping
    }

    /// Sets the ping (latency) of this entry measured in milliseconds.
    pub fn set_ping(&mut self, ping: i32) {
        if self.ping != ping {
            self.ping = ping;
            self.bits.set_modified_ping(true);
        }
    }

    /// Gets the display name of this entry.
    pub fn display_name(&self) -> Option<&Text> {
        self.display_name.as_ref()
    }

    /// Sets the display name of this entry.
    pub fn set_display_name(&mut self, display_name: impl Into<Option<Text>>) {
        let display_name = display_name.into();
        if self.display_name != display_name {
            self.display_name = display_name;
            self.bits.set_modified_display_name(true);
        }
    }
}