Network players keep advancements, statistics and a recipe book on the server

Single player on its server thread, LAN guests and dedicated server players
are network players, and the server gave them none of these:

- PlayerAdvancements: each player's progress loads from and saves to
  players/advancements/<uuid>.json (an integrated server's owner keeps
  single player's file). The game's triggers, awards and the advancement
  commands work on the player the game acts for (as_guest swaps the
  progress in), every tick runs the tick, location and inventory triggers,
  and flushDirty sends ClientboundUpdateAdvancementsPacket with what became
  visible or hidden and the progress that changed. A player who has been
  here gets their saved advancements in the first packet; a new one gets
  the same first tick as before. Announcements go to everyone
  (PlayerList.broadcastSystemMessage).
- ServerStatsCounter: per-tick and movement statistics are counted for each
  player, saved to players/stats/<uuid>.json, follow the scoreboard
  criteria under the player's name, and go out in
  ClientboundAwardStatsPacket when the client asks (REQUEST_STATS), all of
  them the first time.
- ServerRecipeBook: the player file's recipeBook is kept, sent on joining
  (settings and every known recipe), and recipes unlocked later go out in
  ClientboundRecipeBookAddPacket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 06:53:44 +02:00
parent 99d5ebea1a
commit 6154eb95c3
11 changed files with 683 additions and 181 deletions
+58
View File
@@ -175,6 +175,53 @@ fn parse(id: &str, v: &Value) -> Option<Advancement> {
})
}
/// `CriterionProgress`'s date as saved, "yyyy-MM-dd HH:mm:ss Z", in UTC.
pub fn date_text(unix_secs: i64) -> String {
let days = unix_secs.div_euclid(86400);
let rem = unix_secs.rem_euclid(86400);
// Civil from days (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
/// A saved date back to milliseconds since the epoch (the network form of
/// `CriterionProgress`), the zone offset applied.
pub fn date_millis(text: &str) -> Option<i64> {
let (date, rest) = text.trim().split_once(' ')?;
let (time, zone) = rest.split_once(' ').unwrap_or((rest, "+0000"));
let mut d = date.split('-').map(|v| v.parse::<i64>().ok());
let (y, m, day) = (d.next()??, d.next()??, d.next()??);
let mut t = time.split(':').map(|v| v.parse::<i64>().ok());
let (h, min, sec) = (t.next()??, t.next()??, t.next()??);
let sign = if zone.starts_with('-') { -1 } else { 1 };
let zone = zone.trim_start_matches(['+', '-']);
let offset =
zone.get(0..2)?.parse::<i64>().ok()? * 3600 + zone.get(2..4)?.parse::<i64>().ok()? * 60;
// Days from civil (Howard Hinnant's algorithm).
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some((days * 86400 + h * 3600 + min * 60 + sec - sign * offset) * 1000)
}
/// The player's progress: advancement -> criterion -> obtained date.
#[derive(Default, Clone)]
pub struct Progress {
@@ -1059,4 +1106,15 @@ mod tests {
assert_eq!(l[4], Some((1, 2.0)));
assert_eq!(l[1], Some((2, 2.0)));
}
#[test]
fn saved_dates_read_back_to_their_instant() {
for secs in [0, 951_782_400, 1_792_216_800, 4_107_542_399] {
assert_eq!(date_millis(&date_text(secs)), Some(secs * 1000));
}
assert_eq!(
date_millis("2026-10-17 07:30:00 +0200"),
date_millis("2026-10-17 05:30:00 +0000")
);
assert_eq!(date_millis("not a date"), None);
}
}
+60 -50
View File
@@ -11,7 +11,7 @@ use horizon_client::{
};
use serde_json::Value;
use std::{
collections::{BTreeMap, VecDeque},
collections::{BTreeMap, BTreeSet, VecDeque},
sync::Arc,
time::Instant,
};
@@ -78,7 +78,13 @@ pub(super) struct AdvState {
/// Awards skip the toast (`/advancement grant ... everything`).
pub(super) quiet: bool,
/// The inventory last seen by `inventory_changed`.
last_inventory: u64,
pub(super) last_inventory: u64,
/// While the game acts for a network player (`as_guest`): the
/// advancements whose progress changed (`progressChanged`), the recipes
/// unlocked and the announcements, for their client and everyone's.
pub(super) changed: BTreeSet<usize>,
pub(super) unlocked: Vec<String>,
pub(super) announced: Vec<Text>,
}
/// The game's world for predicates.
struct View<'a, 'g>(&'a Game<'g>);
@@ -171,29 +177,10 @@ impl adv::World for View<'_, '_> {
}
}
fn now_text() -> String {
// "yyyy-MM-dd HH:mm:ss Z" in UTC.
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()) as i64;
let days = secs.div_euclid(86400);
let rem = secs.rem_euclid(86400);
// Civil from days (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
adv::date_text(secs)
}
impl Game<'_> {
/// `ItemPredicate.test` (the `item_filter` of a filtered item modifier).
@@ -217,30 +204,30 @@ pub(super) fn item_view(s: &ItemStack) -> ItemView {
}
impl Game<'_> {
fn adv_path(&self) -> Option<std::path::PathBuf> {
let uuid = self.level.player_uuid?;
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
Some(
self.world_root
.join("players/advancements")
.join(format!("{text}.json")),
)
Some(super::stats::player_json(
&self.world_root,
"advancements",
self.level.player_uuid?,
))
}
pub(super) fn load_advancements(&mut self) {
if self.adv.loaded || self.remote.is_some() {
return;
}
self.adv.loaded = true;
/// A server with no player of its own and nobody it acts for: there is
/// no player for advancements and statistics.
pub(super) fn no_player_here(&self) -> bool {
self.options.dedicated.is_some() && self.lan_acting.is_none()
}
/// The advancement tree, loaded once.
pub(super) fn advancement_tree(&mut self) -> Arc<Tree> {
if self.adv.tree.list.is_empty() {
self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data")));
}
self.adv.tree.clone()
}
pub(super) fn load_advancements(&mut self) {
if self.adv.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
self.adv.loaded = true;
self.advancement_tree();
let progress = self
.adv_path()
.and_then(|p| std::fs::read_to_string(p).ok())
@@ -254,7 +241,7 @@ impl Game<'_> {
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
}
pub(super) fn save_advancements(&self) {
if !self.adv.loaded || self.remote.is_some() {
if !self.adv.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
let Some(path) = self.adv_path() else {
@@ -376,7 +363,7 @@ impl Game<'_> {
/// `SimpleCriterionTrigger.trigger`: test each open criterion of the
/// trigger and award what it completes.
pub(super) fn trigger(&mut self, name: &str, test: impl Fn(&Value, &dyn adv::World) -> bool) {
if self.remote.is_some() {
if self.remote.is_some() || self.no_player_here() {
return;
}
self.load_advancements();
@@ -403,15 +390,27 @@ impl Game<'_> {
let a = &tree.list[ai];
let was = self.adv.progress.done(a);
self.adv.progress.grant(&a.id, &a.criteria[ci].name, &date);
self.progress_changed(ai);
if !was && self.adv.progress.done(a) {
self.award(ai);
}
}
}
/// `PlayerAdvancements.progressChanged`, kept for a network player's client.
fn progress_changed(&mut self, index: usize) {
if self.lan_acting.is_some() {
self.adv.changed.insert(index);
}
}
/// After `ServerRecipeBook.addRecipes`: the toast and the
/// `recipe_unlocked` trigger of each recipe now known.
pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) {
self.recipe_toast(unlocked);
if self.lan_acting.is_some() {
// A network player's client gets them in ClientboundRecipeBookAddPacket.
self.adv.unlocked.extend_from_slice(unlocked);
} else {
self.recipe_toast(unlocked);
}
for r in unlocked {
let r = r.clone();
self.trigger("minecraft:recipe_unlocked", move |c, _| {
@@ -453,7 +452,8 @@ impl Game<'_> {
}
}
if let Some(d) = &a.display {
if d.show_toast && !self.adv.quiet {
// A network player's client shows its own toast.
if d.show_toast && !self.adv.quiet && self.lan_acting.is_none() {
self.adv.toasts.push_back(Toast {
icon: d.icon.clone(),
frame: d.frame,
@@ -471,10 +471,18 @@ impl Game<'_> {
Frame::Challenge => "chat.type.advancement.challenge",
};
let name = adv_name(a);
self.system_message(Text::translate(
key,
&[Text::literal(super::chat::PLAYER_NAME), name],
));
// PlayerList.broadcastSystemMessage: everyone hears of a
// network player's advancement.
match self.lan_acting_name.clone() {
Some(player) => self
.adv
.announced
.push(Text::translate(key, &[Text::literal(&player), name])),
None => self.system_message(Text::translate(
key,
&[Text::literal(super::chat::PLAYER_NAME), name],
)),
}
}
}
self.recipe_unlocked(&unlocked);
@@ -820,6 +828,7 @@ impl Game<'_> {
let was = self.adv.progress.done(a);
if self.adv.progress.grant(&a.id, c, &date) {
changed = true;
self.progress_changed(index);
if !was && self.adv.progress.done(a) {
self.award(index);
}
@@ -831,6 +840,7 @@ impl Game<'_> {
pub(super) fn revoke_advancement(&mut self, index: usize, criterion: Option<&str>) -> bool {
let tree = self.adv.tree.clone();
let a = &tree.list[index];
self.progress_changed(index);
match criterion {
Some(c) => self.adv.progress.revoke(&a.id, c),
None => {
@@ -1073,6 +1073,13 @@ impl Game<'_> {
for g in &h.hub.guests {
horizon_client::lan::playerdata::save(g, &self.world_root);
}
}
if let Some(h) = self.lan.as_ref() {
for g in &h.hub.guests {
self.save_guest_records(h, g);
}
}
if let Some(h) = self.lan.as_mut() {
let conns: Vec<u32> = h.hub.guests.iter().map(|g| g.conn).collect();
for conn in conns {
h.hub.kick(
+72
View File
@@ -557,6 +557,75 @@ impl Game<'_> {
} else {
playerdata::save(guest, &self.world_root);
}
self.save_guest_records(host, guest);
}
/// The file name of a player's advancements and statistics: an
/// integrated server's owner keeps single player's.
fn records_uuid(&self, host: &LanHost, uuid: u128) -> Option<[i32; 4]> {
if host.owner.as_ref().is_some_and(|o| o.uuid == uuid) {
self.level.player_uuid
} else {
Some(playerdata::uuid_ints(uuid))
}
}
/// `PlayerAdvancements.save` and `ServerStatsCounter.save` of a network player.
pub(super) fn save_guest_records(
&self,
host: &LanHost,
guest: &horizon_client::lan::guest::Guest,
) {
if !guest.placed || self.adv.tree.list.is_empty() {
return;
}
let Some(uuid) = self.records_uuid(host, guest.uuid) else {
return;
};
let path = super::stats::player_json(&self.world_root, "advancements", uuid);
let json = guest
.advancements
.to_json(&self.adv.tree, horizon_world::DATA_VERSION);
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(text) = serde_json::to_string_pretty(&json) {
let _ = std::fs::write(path, text);
}
if let Some(play) = host.play.get(&guest.conn) {
play.stats
.write(&super::stats::player_json(&self.world_root, "stats", uuid));
}
}
/// `PlayerAdvancements.load` and `ServerStatsCounter.parseLocal` of a
/// network player who joined; every statistic goes out on the first
/// request (`PlayerList.placeNewPlayer`'s `markAllDirty`).
fn load_guest_records(&mut self, host: &mut LanHost, conn: u32) {
let Some(uuid) = host
.hub
.guest(conn)
.and_then(|g| self.records_uuid(host, g.uuid))
else {
return;
};
let tree = self.advancement_tree();
let path = super::stats::player_json(&self.world_root, "advancements", uuid);
let saved = std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok());
if let Some(g) = host.hub.guest_mut(conn)
&& let Some(json) = saved
{
let mut progress = horizon_client::advancements::Progress::from_json(&json);
// PlayerAdvancements.applyFrom: advancements this server lacks are dropped.
progress
.criteria
.retain(|id, _| tree.by_id.contains_key(id));
g.advancements = progress;
g.advancements_loaded = true;
}
let mut stats =
super::stats::Stats::read(&super::stats::player_json(&self.world_root, "stats", uuid));
stats.mark_all_dirty();
host.play.entry(conn).or_default().stats = stats;
}
/// The integrated server's owner into the world's player, for `Level::write`.
pub(super) fn store_owner(&mut self) {
@@ -568,6 +637,7 @@ impl Game<'_> {
};
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) {
playerdata::store(g, &mut self.level);
self.save_guest_records(host, g);
}
}
@@ -756,6 +826,7 @@ impl Game<'_> {
self.lan_crafting_left(&mut host, &mut guest);
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
host.play.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
"INFO",
@@ -820,6 +891,7 @@ impl Game<'_> {
g.health = 20.0;
g.food = 20;
}
self.load_guest_records(host, conn);
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
@@ -51,6 +51,9 @@ pub(super) struct GuestPlay {
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// What the guest's body was given for its effects and enchantments.
potions: super::potions::BodyPotions,
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
pub(super) stats: super::stats::Stats,
last_inventory: u64,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -165,6 +168,15 @@ impl Game<'_> {
let host_ender = self.ender_open;
self.close_ender_chest();
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
// The guest's advancements, recipe book and statistics.
self.advancement_tree();
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
std::mem::swap(&mut self.stats, &mut play.stats);
let adv_loaded = std::mem::replace(&mut self.adv.loaded, true);
let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory);
self.lan_acting = Some(conn);
self.lan_acting_name = Some(g.name.clone());
self.lan_acting_uuid = Some(g.uuid);
@@ -200,6 +212,15 @@ impl Game<'_> {
}
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
std::mem::swap(&mut self.stats, &mut play.stats);
self.adv.loaded = adv_loaded;
play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory);
let stat_events = std::mem::take(&mut play.stats.events);
let name = g.name.clone();
self.potions.swap_player(&mut g.effects, &mut play.potions);
if let Some(key) = host_ender {
self.world
@@ -244,6 +265,7 @@ impl Game<'_> {
host.hub.set_game_mode(conn, new_mode);
}
host.play.insert(conn, play);
self.stat_criteria_changed(&name, stat_events);
if let Some(pos) = opened
&& !self.lan_open_container(host, conn, pos)
&& !host.hub.guests[i].spectator()
@@ -578,6 +600,15 @@ impl Game<'_> {
self.guest_suggestions(host, conn, &payload);
}
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
// ServerStatsCounter.sendStats.
S::ClientCommand(c) if c.action == 1 => {
let stats = host
.play
.get_mut(&conn)
.map(|p| p.stats.take_dirty())
.unwrap_or_default();
host.hub.send_stats(conn, &stats);
}
S::PickItemFromBlock(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let item = self.res.facts.get(state).item.clone();
@@ -848,6 +879,7 @@ impl Game<'_> {
/// Per tick, for every guest: dig, use items, pick up drops, die.
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
self.lan_merchant_tick(host);
self.announce_guest_advancements(host);
let conns: Vec<u32> = host
.hub
.guests
@@ -891,6 +923,14 @@ impl Game<'_> {
}
self.guest_delayed_destroy(host, conn);
self.guest_server_tick(host, conn);
// Player.tick's statistics and ServerPlayer.tick's triggers, then
// PlayerAdvancements.flushDirty.
let sleeping = host.hub.guests[gi].sleeping;
self.as_guest(host, conn, |g| {
g.count_tick_stats(sleeping);
g.tick_advancements();
});
host.hub.flush_progress(conn);
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
let g = &mut host.hub.guests[gi];
@@ -909,6 +949,18 @@ impl Game<'_> {
}
}
/// `PlayerList.broadcastSystemMessage` of the advancements guests made
/// (their own actions, commands and ticks).
fn announce_guest_advancements(&mut self, host: &mut LanHost) {
for text in std::mem::take(&mut self.adv.announced) {
host.hub
.system_message(horizon_client::lan::data::component_nbt(&text.component()));
if self.options.dedicated.is_none() {
self.system_message(text);
}
}
}
/// The guest's body on the server each tick: ServerPlayer.tick's damage
/// clock and Entity.baseTick's fluid phase (burning), then for each move
/// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump
@@ -956,6 +1008,7 @@ impl Game<'_> {
w.player.health.advance_clock();
let _ = w.fluid_base_tick();
w.player.ground.on_ground = from_ground;
let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect();
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
@@ -980,6 +1033,11 @@ impl Game<'_> {
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let mut events = std::mem::take(&mut w.player.events);
// ServerGamePacketListenerImpl.handleMovePlayer:
// Player.checkMovementStatistics for each move.
for d in travelled {
game.movement_stats(Vec3::new(d[0], d[1], d[2]));
}
// LivingEntity.baseTick ends with tickEffects.
game.tick_mob_effects();
let Some(player) = game.player.as_mut() else {
+21 -8
View File
@@ -303,20 +303,33 @@ impl Game<'_> {
// ---- criteria ----------------------------------------------------------
/// `ServerStatsCounter.setValue`'s scoreboard side: the objectives of
/// each changed statistic's criteria follow it for the player `name`.
pub(super) fn stat_criteria_changed(
&mut self,
name: &str,
events: Vec<(String, String, Option<i32>)>,
) {
let board = &mut self.score.board;
if board.objectives.is_empty() {
return;
}
for (ty, key, amount) in events {
let criteria = sb::stat_criteria(&ty, &key);
if board.has_objectives_for(&criteria) {
board.for_all_objectives(&criteria, name, |v| {
amount.map_or(0, |n| v.wrapping_add(n))
});
}
}
}
/// `ServerPlayer.doTick` score updates and the statistic criteria.
pub(super) fn tick_scoreboard(&mut self) {
self.load_scoreboard();
let events = std::mem::take(&mut self.stats.events);
self.stat_criteria_changed(PLAYER_NAME, events);
let board = &mut self.score.board;
if !board.objectives.is_empty() {
for (ty, key, amount) in events {
let criteria = sb::stat_criteria(&ty, &key);
if board.has_objectives_for(&criteria) {
board.for_all_objectives(&criteria, PLAYER_NAME, |v| {
amount.map_or(0, |n| v.wrapping_add(n))
});
}
}
let display = self.player_display_comp();
if let Some(p) = self.player.as_mut() {
let health_and_absorption = p.health.health() + p.health.absorption();
+98 -46
View File
@@ -3,8 +3,12 @@
//! killed by, saved to `players/stats/<uuid>.json`, plus the phantom
//! spawner that reads the time since rest (`PhantomSpawner`).
use super::{Dim, Game};
use horizon_core::geometry::Vec3;
use horizon_core::random::RandomSource;
use std::collections::BTreeMap;
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
};
/// `stats[type][key]`, with `type` and `key` namespaced ids.
#[derive(Default)]
@@ -16,6 +20,8 @@ pub(super) struct Stats {
/// Statistic changes (type, key, amount; `None` = reset) for the
/// scoreboard criteria to follow.
pub(super) events: Vec<(String, String, Option<i32>)>,
/// Changed since the client was last sent them (`StatsCounter`'s dirty set).
pub(super) dirty: BTreeSet<(String, String)>,
}
impl Stats {
pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) {
@@ -28,6 +34,8 @@ impl Stats {
*v = v.saturating_add(n);
self.events
.push((format!("minecraft:{ty}"), key.to_owned(), Some(n)));
self.dirty
.insert((format!("minecraft:{ty}"), key.to_owned()));
}
pub(super) fn get(&self, ty: &str, key: &str) -> i32 {
self.values
@@ -40,52 +48,51 @@ impl Stats {
if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) {
m.insert(key.to_owned(), 0);
}
self.dirty
.insert((format!("minecraft:{ty}"), key.to_owned()));
self.events
.push((format!("minecraft:{ty}"), key.to_owned(), None));
}
pub(super) fn custom(&mut self, key: &str, n: i32) {
self.add("custom", &format!("minecraft:{key}"), n);
}
}
impl Game<'_> {
fn stats_path(&self) -> Option<std::path::PathBuf> {
let uuid = self.level.player_uuid?;
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
Some(
self.world_root
.join("players/stats")
.join(format!("{text}.json")),
)
/// `ServerStatsCounter.markAllDirty`: everything goes out on the next request.
pub(super) fn mark_all_dirty(&mut self) {
self.dirty = self
.values
.iter()
.flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone())))
.collect();
}
/// `ServerStatsCounter.parseLocal`.
pub(super) fn load_stats(&mut self) {
if self.stats.loaded || self.remote.is_some() {
return;
}
self.stats.loaded = true;
let Some(path) = self.stats_path() else {
return;
/// `ServerStatsCounter.sendStats`' entries: the dirty statistics and
/// their values, the set cleared.
pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> {
std::mem::take(&mut self.dirty)
.into_iter()
.map(|(ty, key)| {
let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied();
(ty, key, v.unwrap_or(0))
})
.collect()
}
/// `ServerStatsCounter.parseLocal`: the counters of a stats file.
pub(super) fn read(path: &Path) -> Self {
let mut stats = Self {
loaded: true,
..Self::default()
};
let Ok(text) = std::fs::read_to_string(path) else {
return;
let Some(json) = std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
else {
return stats;
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
return;
};
if let Some(stats) = json.get("stats").and_then(|s| s.as_object()) {
for (ty, entries) in stats {
if let Some(all) = json.get("stats").and_then(|s| s.as_object()) {
for (ty, entries) in all {
let Some(entries) = entries.as_object() else {
continue;
};
let map = self.stats.values.entry(ty.clone()).or_default();
let map = stats.values.entry(ty.clone()).or_default();
for (key, v) in entries {
if let Some(n) = v.as_i64() {
map.insert(key.clone(), n as i32);
@@ -93,17 +100,11 @@ impl Game<'_> {
}
}
}
stats
}
/// `ServerStatsCounter.save`.
pub(super) fn save_stats(&self) {
if !self.stats.loaded || self.remote.is_some() {
return;
}
let Some(path) = self.stats_path() else {
return;
};
pub(super) fn write(&self, path: &Path) {
let stats: serde_json::Map<String, serde_json::Value> = self
.stats
.values
.iter()
.filter(|(_, m)| !m.is_empty())
@@ -124,9 +125,55 @@ impl Game<'_> {
let _ = std::fs::write(path, text);
}
}
}
/// `players/<dir>/<uuid>.json` of a world (advancements, stats).
pub(super) fn player_json(world: &Path, dir: &str, uuid: [i32; 4]) -> PathBuf {
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
world.join("players").join(dir).join(format!("{text}.json"))
}
impl Game<'_> {
fn stats_path(&self) -> Option<PathBuf> {
Some(player_json(
&self.world_root,
"stats",
self.level.player_uuid?,
))
}
/// `ServerStatsCounter.parseLocal`.
pub(super) fn load_stats(&mut self) {
if self.stats.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
self.stats.loaded = true;
if let Some(path) = self.stats_path() {
self.stats.values = Stats::read(&path).values;
}
}
/// `ServerStatsCounter.save`.
pub(super) fn save_stats(&self) {
if !self.stats.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
if let Some(path) = self.stats_path() {
self.stats.write(&path);
}
}
/// The per-tick counters (`Player.tick`/`ServerPlayer.tick` awardStat).
pub(super) fn tick_stats(&mut self) {
self.load_stats();
self.count_tick_stats(self.sleeping.is_some());
self.tick_movement_stats();
}
/// `Player.tick`'s counters for the player in `self.player`.
pub(super) fn count_tick_stats(&mut self, sleeping: bool) {
let Some(p) = self.player.as_ref() else {
return;
};
@@ -137,21 +184,26 @@ impl Game<'_> {
s.custom("total_world_time", 1);
if alive {
s.custom("time_since_death", 1);
if self.sleeping.is_none() {
if !sleeping {
s.custom("time_since_rest", 1);
}
}
if crouching {
s.custom("sneak_time", 1);
}
self.tick_movement_stats();
}
/// `Player.checkMovementStatistics` / `checkRidingStatistics`.
fn tick_movement_stats(&mut self) {
let Some(p) = self.player.as_ref() else {
return;
};
let d = p.position.subtract(self.previous_position);
self.movement_stats(d);
}
/// `Player.checkMovementStatistics` / `checkRidingStatistics` for one move.
pub(super) fn movement_stats(&mut self, d: Vec3) {
let Some(p) = self.player.as_ref() else {
return;
};
let horizontal = ((d.x * d.x + d.z * d.z).sqrt() * 100.0).round() as i32;
let total = ((d.x * d.x + d.y * d.y + d.z * d.z).sqrt() * 100.0).round() as i32;
// Teleports are not travel.
+198 -66
View File
@@ -4,11 +4,14 @@
//! ClientboundRecipeBookAddPacket) and the advancements the player may see go
//! out in ClientboundUpdateAdvancementsPacket (PlayerAdvancements.flushDirty).
use super::data::{SyncData, json_to_nbt};
use crate::{advancements::Tree, recipe_book::RecipeIndex};
use crate::{
advancements::{Progress, Tree},
recipe_book::{RecipeIndex, Settings},
};
use horizon_protocol::buf::Writer;
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
collections::{BTreeMap, BTreeSet, HashMap},
path::Path,
};
@@ -54,8 +57,16 @@ impl ServerAdvancements {
}
}
/// The first tick of a player without advancements.
pub fn first_tick(&self, sync: &SyncData, now_millis: i64) -> FirstTick {
/// The first tick of a player without advancements: the criteria
/// `minecraft:tick` meets go into `progress` and the recipes their
/// advancements reward into `book`.
pub fn first_tick(
&self,
sync: &SyncData,
now_millis: i64,
progress: &mut Progress,
book: &mut Settings,
) -> FirstTick {
// CriteriaTriggers.TICK: the criteria it meets, and what they complete.
let mut obtained: Vec<Vec<&str>> = vec![Vec::new(); self.tree.list.len()];
for (i, a) in self.tree.list.iter().enumerate() {
@@ -77,25 +88,24 @@ impl ServerAdvancements {
.all(|group| group.iter().any(|c| got.contains(&c.as_str())))
})
.collect();
let date = crate::advancements::date_text(now_millis.div_euclid(1000));
for (a, got) in self.tree.list.iter().zip(&obtained) {
for c in got {
progress.grant(&a.id, c, &date);
}
}
// AdvancementRewards.grant: the recipes, in the advancements' order.
let mut entries = Vec::new();
for (i, a) in self.tree.list.iter().enumerate() {
if !done[i] {
continue;
}
book.add_recipes(&self.displays, &a.rewards.recipes);
for id in &a.rewards.recipes {
entries.extend(self.book_entries(id, sync));
entries.extend(self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT));
}
}
let recipe_book_add = (!entries.is_empty()).then(|| {
let mut w = Writer::new();
w.varint(entries.len() as i32);
for e in entries {
w.data.extend(e);
}
w.bool(false); // not a replacement
w.data
});
let recipe_book_add = (!entries.is_empty()).then(|| book_add(entries, false));
// flushDirty: every advancement the player may see, and its progress.
let visible = self.tree.visible(&self.kids, |i| done[i]);
let shown: Vec<usize> = (0..self.tree.list.len()).filter(|i| visible[*i]).collect();
@@ -103,60 +113,14 @@ impl ServerAdvancements {
w.bool(true); // the first packet resets the client's advancements
w.varint(shown.len() as i32);
for &i in &shown {
let a = &self.tree.list[i];
w.string(&a.id);
w.bool(a.parent.is_some());
if let Some(p) = &a.parent {
w.string(p);
}
w.bool(a.display.is_some());
if let Some(d) = &a.display {
w.nbt(&json_to_nbt(&d.title));
w.nbt(&json_to_nbt(&d.description));
w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0));
w.varint(1);
w.varint(0);
w.varint(0);
w.varint(match d.frame {
crate::advancements::Frame::Task => 0,
crate::advancements::Frame::Challenge => 1,
crate::advancements::Frame::Goal => 2,
});
w.i32(
i32::from(d.background.is_some())
| i32::from(d.show_toast) << 1
| i32::from(d.hidden) << 2,
);
if let Some(b) = &d.background {
w.string(b);
}
}
w.varint(a.requirements.len() as i32);
for group in &a.requirements {
w.varint(group.len() as i32);
for c in group {
w.string(c);
}
}
w.bool(false); // sends_telemetry_event
let (x, y) = self.layout[i].unwrap_or((0, 0.0));
w.f32(x as f32);
w.f32(y);
self.write_advancement(&mut w, i, sync);
}
w.varint(0); // nothing removed
w.varint(shown.len() as i32);
for &i in &shown {
let a = &self.tree.list[i];
w.string(&a.id);
w.varint(a.criteria.len() as i32);
for c in &a.criteria {
w.string(&c.name);
let got = obtained[i].contains(&c.name.as_str());
w.bool(got);
if got {
w.i64(now_millis);
}
}
self.write_progress(&mut w, i, |c| {
obtained[i].contains(&c).then_some(now_millis)
});
}
w.bool(true); // show the advancements
FirstTick {
@@ -165,9 +129,162 @@ impl ServerAdvancements {
}
}
/// `PlayerAdvancements.flushDirty`: the advancements that became visible
/// or hidden since `visible` (which it updates; empty before the first
/// packet, which resets the client's and carries everything visible) and
/// the progress of the `changed` ones still visible. None when there is
/// nothing to send.
pub fn update(
&self,
sync: &SyncData,
progress: &Progress,
visible: &mut Vec<bool>,
changed: &BTreeSet<usize>,
show: bool,
) -> Option<Vec<u8>> {
let n = self.tree.list.len();
let first = visible.len() != n;
let now = self
.tree
.visible(&self.kids, |i| progress.done(&self.tree.list[i]));
let was = |i: usize| !first && visible[i];
let added: Vec<usize> = (0..n).filter(|&i| now[i] && !was(i)).collect();
let removed: Vec<usize> = (0..n).filter(|&i| !now[i] && was(i)).collect();
let progressed: Vec<usize> = if first {
(0..n).filter(|&i| now[i]).collect()
} else {
changed
.iter()
.copied()
.filter(|&i| i < n && now[i])
.collect()
};
*visible = now;
if !first && added.is_empty() && removed.is_empty() && progressed.is_empty() {
return None;
}
let mut w = Writer::new();
w.bool(first);
w.varint(added.len() as i32);
for &i in &added {
self.write_advancement(&mut w, i, sync);
}
w.varint(removed.len() as i32);
for &i in &removed {
w.string(&self.tree.list[i].id);
}
w.varint(progressed.len() as i32);
for &i in &progressed {
let id = &self.tree.list[i].id;
self.write_progress(&mut w, i, |c| {
progress
.criteria
.get(id)
.and_then(|m| m.get(c))
.map(|date| crate::advancements::date_millis(date).unwrap_or(0))
});
}
w.bool(show);
Some(w.data)
}
/// Which advancements a player with `progress` may see.
pub fn visibility(&self, progress: &Progress) -> Vec<bool> {
self.tree
.visible(&self.kids, |i| progress.done(&self.tree.list[i]))
}
/// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`.
fn write_advancement(&self, w: &mut Writer, i: usize, sync: &SyncData) {
let a = &self.tree.list[i];
w.string(&a.id);
w.bool(a.parent.is_some());
if let Some(p) = &a.parent {
w.string(p);
}
w.bool(a.display.is_some());
if let Some(d) = &a.display {
w.nbt(&json_to_nbt(&d.title));
w.nbt(&json_to_nbt(&d.description));
w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0));
w.varint(1);
w.varint(0);
w.varint(0);
w.varint(match d.frame {
crate::advancements::Frame::Task => 0,
crate::advancements::Frame::Challenge => 1,
crate::advancements::Frame::Goal => 2,
});
w.i32(
i32::from(d.background.is_some())
| i32::from(d.show_toast) << 1
| i32::from(d.hidden) << 2,
);
if let Some(b) = &d.background {
w.string(b);
}
}
w.varint(a.requirements.len() as i32);
for group in &a.requirements {
w.varint(group.len() as i32);
for c in group {
w.string(c);
}
}
w.bool(false); // sends_telemetry_event
let (x, y) = self.layout[i].unwrap_or((0, 0.0));
w.f32(x as f32);
w.f32(y);
}
/// An `AdvancementProgress`: each criterion and when it was obtained.
fn write_progress(&self, w: &mut Writer, i: usize, obtained: impl Fn(&str) -> Option<i64>) {
let a = &self.tree.list[i];
w.string(&a.id);
w.varint(a.criteria.len() as i32);
for c in &a.criteria {
w.string(&c.name);
let at = obtained(&c.name);
w.bool(at.is_some());
if let Some(at) = at {
w.i64(at);
}
}
}
/// `ServerRecipeBook.addRecipes`' packet for recipes just unlocked:
/// each display, with its notification and highlighted. None when no
/// recipe has a display.
pub fn recipes_added(&self, ids: &[String], sync: &SyncData) -> Option<Vec<u8>> {
let entries: Vec<Vec<u8>> = ids
.iter()
.flat_map(|id| self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT))
.collect();
(!entries.is_empty()).then(|| book_add(entries, false))
}
/// `ServerRecipeBook.sendInitialRecipeBook`: every known recipe, without
/// notifications, highlighted while not yet displayed, replacing the
/// client's book.
pub fn initial_recipe_book(&self, book: &Settings, sync: &SyncData) -> Vec<u8> {
let entries: Vec<Vec<u8>> = book
.recipes
.iter()
.flat_map(|id| {
let highlight = if book.to_be_displayed.contains(id) {
2
} else {
0
};
self.book_entries(id, sync, highlight)
})
.collect();
book_add(entries, true)
}
/// ClientboundRecipeBookAddPacket.Entry for each display of a recipe:
/// highlighted, and with a notification unless the recipe turns it off.
fn book_entries(&self, id: &str, sync: &SyncData) -> Vec<Vec<u8>> {
fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec<Vec<u8>> {
let Some(r) = self.recipes.get(id) else {
return Vec::new();
};
@@ -245,12 +362,27 @@ impl ServerAdvancements {
for v in placed {
holder_set(&mut w, v, &item);
}
// The notification only where the recipe shows one.
let notify = r["show_notification"].as_bool().unwrap_or(true);
w.i8(i8::from(notify) | 2);
w.i8(if notify { flags } else { flags & !1 });
vec![w.data]
}
}
/// ClientboundRecipeBookAddPacket.Entry flags: notification, highlight.
const NOTIFY_AND_HIGHLIGHT: i8 = 1 | 2;
/// ClientboundRecipeBookAddPacket: the entries, then whether they replace the book.
fn book_add(entries: Vec<Vec<u8>>, replace: bool) -> Vec<u8> {
let mut w = Writer::new();
w.varint(entries.len() as i32);
for e in entries {
w.data.extend(e);
}
w.bool(replace);
w.data
}
/// ShapedRecipePattern.shrink: the pattern without blank border rows and columns.
fn shrink(rows: &[Value]) -> Vec<Vec<char>> {
let rows: Vec<Vec<char>> = rows
+19
View File
@@ -136,6 +136,19 @@ pub struct Guest {
pub drag: Option<(u8, Vec<usize>)>,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
/// `ServerPlayer.recipeBook`.
pub recipe_book: crate::recipe_book::Settings,
/// `PlayerAdvancements`: the criteria obtained, whether they came from
/// the player's file, the advancements the client was last told it may
/// see (empty before the first packet), and those whose progress
/// changed since (`progressChanged`).
pub advancements: crate::advancements::Progress,
pub advancements_loaded: bool,
pub advancements_visible: Vec<bool>,
pub advancements_changed: std::collections::BTreeSet<usize>,
/// Recipes unlocked since the client was last told
/// (`ServerRecipeBook.addRecipes` sends them).
pub recipes_unlocked: Vec<String>,
}
impl Guest {
@@ -214,6 +227,12 @@ impl Guest {
next_window: 0,
drag: None,
saved: None,
recipe_book: Default::default(),
advancements: Default::default(),
advancements_loaded: false,
advancements_visible: Vec::new(),
advancements_changed: Default::default(),
recipes_unlocked: Vec::new(),
}
}
pub fn send(&self, packet: &play::Clientbound) {
+90 -11
View File
@@ -509,12 +509,18 @@ impl Hub {
g.send(&raw(ids::UPDATE_RECIPES, self.sync.recipes.clone()));
// PlayerList.sendPlayerPermissionLevel, then the recipe book.
self.send_permission_level(i);
// ServerRecipeBook.sendInitialRecipeBook: each book's open and
// filtering flags, then every known recipe.
let g = &self.guests[i];
let book = &g.recipe_book;
let settings = (0..4)
.flat_map(|b| [u8::from(book.open[b]), u8::from(book.filtering[b])])
.collect();
g.send(&raw(ids::RECIPE_BOOK_SETTINGS, settings));
g.send(&raw(
ids::RECIPE_BOOK_SETTINGS,
vec![0; 8], // four books, each closed and unfiltered
ids::RECIPE_BOOK_ADD,
self.sync.advancements.initial_recipe_book(book, &self.sync),
));
g.send(&raw(ids::RECIPE_BOOK_ADD, vec![0, 1])); // no entries, replace
// The others hear of the newcomer before it joins the list.
self.broadcast_except(
conn,
@@ -1408,15 +1414,29 @@ impl Hub {
id: g.entity_id,
values: vec![(9, serializer::FLOAT, Value::Float(g.health))],
}));
// ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty.
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let first = self.sync.advancements.first_tick(&self.sync, now);
if let Some(add) = first.recipe_book_add {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
// ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty. A
// player who has been here has had the tick's criteria already.
if !g.advancements_loaded {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let sync = self.sync.clone();
let g = &mut self.guests[i];
let first = sync.advancements.first_tick(
&sync,
now,
&mut g.advancements,
&mut g.recipe_book,
);
if let Some(add) = first.recipe_book_add {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
}
g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements));
g.advancements_visible = sync.advancements.visibility(&g.advancements);
g.advancements_changed.clear();
} else {
self.flush_advancements(i, true);
}
g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements));
}
let health = {
let g = &self.guests[i];
@@ -1467,6 +1487,65 @@ impl Hub {
}
}
/// `PlayerAdvancements.flushDirty` and the recipes the player unlocked
/// since (`ServerRecipeBook.addRecipes`), once the player's first tick
/// has sent their advancements.
pub fn flush_progress(&mut self, conn: u32) {
if let Some(i) = self.guests.iter().position(|g| g.conn == conn)
&& self.guests[i].sent_health.is_some()
{
self.flush_advancements(i, true);
}
}
fn flush_advancements(&mut self, i: usize, show: bool) {
let sync = self.sync.clone();
let g = &mut self.guests[i];
let unlocked = std::mem::take(&mut g.recipes_unlocked);
if let Some(add) = sync.advancements.recipes_added(&unlocked, &sync) {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
}
let changed = std::mem::take(&mut g.advancements_changed);
if let Some(update) = sync.advancements.update(
&sync,
&g.advancements,
&mut g.advancements_visible,
&changed,
show,
) {
g.send(&raw(ids::UPDATE_ADVANCEMENTS, update));
}
}
/// ClientboundAwardStatsPacket (`ServerStatsCounter.sendStats`): each
/// statistic as its type and value by network id (`Stat.STREAM_CODEC`),
/// then its count. Statistics the registries don't know are left out.
pub fn send_stats(&self, conn: u32, stats: &[(String, String, i32)]) {
let known: Vec<(i32, i32, i32)> = stats
.iter()
.filter_map(|(ty, key, count)| {
let values = match ty.as_str() {
"minecraft:mined" => "minecraft:block",
"minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type",
"minecraft:custom" => "minecraft:custom_stat",
_ => "minecraft:item",
};
Some((
self.sync.id("minecraft:stat_type", ty)?,
self.sync.id(values, key)?,
*count,
))
})
.collect();
let mut w = horizon_protocol::buf::Writer::new();
w.varint(known.len() as i32);
for (ty, value, count) in known {
w.varint(ty);
w.varint(value);
w.varint(count);
}
self.send_to(conn, &raw(ids::AWARD_STATS, w.data));
}
// ---- incoming ------------------------------------------------------
/// The squared movement past 1.0E-5F (handlePlayerKnownMovement).
@@ -70,6 +70,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
@@ -126,6 +127,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.selected_slot = guest.selected as i32;
level.on_ground = guest.on_ground;
level.player_extra = guest.saved.clone();
level.recipe_book = guest.recipe_book.clone();
level.ender_items = guest.ender_items.clone();
level.inventory.clear();
level.inventory_components.clear();