Merge pull request #901 from ludovic111/integ/sh7
🤖 Agent: Merged after the real verify passed; checks in the description.
This commit is contained in:
@@ -101,6 +101,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
sprinting: false,
|
||||
equipment: Default::default(),
|
||||
health: 20.0,
|
||||
attributes: Vec::new(),
|
||||
};
|
||||
loop {
|
||||
world.game_time += 1;
|
||||
|
||||
@@ -343,7 +343,7 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false),
|
||||
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false),
|
||||
cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary",
|
||||
"With raw, the reply also lists every frame time in milliseconds (frame_ms).",
|
||||
"The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).",
|
||||
["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false),
|
||||
];
|
||||
|
||||
|
||||
@@ -336,73 +336,8 @@ impl PlayerEffects {
|
||||
pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> {
|
||||
let mut out = Vec::new();
|
||||
for e in &self.list {
|
||||
let level = f64::from(e.amplifier + 1);
|
||||
let m = match e.id {
|
||||
"speed" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.speed",
|
||||
0.2,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"slowness" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.slowness",
|
||||
-0.15,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"haste" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.haste",
|
||||
0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"mining_fatigue" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.mining_fatigue",
|
||||
-0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"strength" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.strength",
|
||||
3.0,
|
||||
"add_value",
|
||||
)),
|
||||
"weakness" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.weakness",
|
||||
-4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"jump_boost" => Some((
|
||||
"minecraft:safe_fall_distance",
|
||||
"minecraft:effect.jump_boost",
|
||||
1.0,
|
||||
"add_value",
|
||||
)),
|
||||
"health_boost" => Some((
|
||||
"minecraft:max_health",
|
||||
"minecraft:effect.health_boost",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"absorption" => Some((
|
||||
"minecraft:max_absorption",
|
||||
"minecraft:effect.absorption",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
|
||||
"unluck" => Some((
|
||||
"minecraft:luck",
|
||||
"minecraft:effect.unluck",
|
||||
-1.0,
|
||||
"add_value",
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((a, id, amount, op)) = m {
|
||||
out.push((a, id, amount * level, op));
|
||||
if let Some((a, id, amount, op)) = effect_modifier(e.id) {
|
||||
out.push((a, id, amount * f64::from(e.amplifier + 1), op));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -445,6 +380,76 @@ impl StatusFlags {
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute modifier an effect adds at amplifier 0
|
||||
/// (`MobEffect.addAttributeModifier`): (attribute, id, amount, operation).
|
||||
/// Each level multiplies the amount (`amplifier + 1`).
|
||||
pub fn effect_modifier(effect: &str) -> Option<(&'static str, &'static str, f64, &'static str)> {
|
||||
match effect {
|
||||
"speed" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.speed",
|
||||
0.2,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"slowness" => Some((
|
||||
"minecraft:movement_speed",
|
||||
"minecraft:effect.slowness",
|
||||
-0.15,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"haste" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.haste",
|
||||
0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"mining_fatigue" => Some((
|
||||
"minecraft:attack_speed",
|
||||
"minecraft:effect.mining_fatigue",
|
||||
-0.1,
|
||||
"add_multiplied_total",
|
||||
)),
|
||||
"strength" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.strength",
|
||||
3.0,
|
||||
"add_value",
|
||||
)),
|
||||
"weakness" => Some((
|
||||
"minecraft:attack_damage",
|
||||
"minecraft:effect.weakness",
|
||||
-4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"jump_boost" => Some((
|
||||
"minecraft:safe_fall_distance",
|
||||
"minecraft:effect.jump_boost",
|
||||
1.0,
|
||||
"add_value",
|
||||
)),
|
||||
"health_boost" => Some((
|
||||
"minecraft:max_health",
|
||||
"minecraft:effect.health_boost",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"absorption" => Some((
|
||||
"minecraft:max_absorption",
|
||||
"minecraft:effect.absorption",
|
||||
4.0,
|
||||
"add_value",
|
||||
)),
|
||||
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
|
||||
"unluck" => Some((
|
||||
"minecraft:luck",
|
||||
"minecraft:effect.unluck",
|
||||
-1.0,
|
||||
"add_value",
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -840,9 +840,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.species(),
|
||||
crate::mobs::Species::Slime | crate::mobs::Species::MagmaCube
|
||||
) {
|
||||
let health = m.health;
|
||||
// AbstractCubeMob.readAdditionalSaveData: the size's attributes, then
|
||||
// the saved health, the max health when there is none.
|
||||
crate::mobs::cube::set_size(&mut m, number(tag.get("Size")).unwrap_or(0) as i32 + 1);
|
||||
m.health = health;
|
||||
if let Some(h) = float(tag.get("Health")) {
|
||||
m.health = h as f32;
|
||||
}
|
||||
m.extra.flag2 = flag(tag, "wasOnGround");
|
||||
}
|
||||
// Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby
|
||||
|
||||
@@ -65,6 +65,7 @@ mod item_particles;
|
||||
mod jukebox;
|
||||
mod lan;
|
||||
mod lan_actions;
|
||||
mod lan_attributes;
|
||||
mod lan_chat;
|
||||
mod lan_crafting;
|
||||
mod lan_entities;
|
||||
@@ -3846,6 +3847,10 @@ impl Game<'_> {
|
||||
}
|
||||
self.audio
|
||||
.play("minecraft:entity.player.death", Some(at), 1.0, 1.0);
|
||||
// LivingEntity.die: the LAN guests see the host's death animation.
|
||||
if let Some(host) = &self.lan {
|
||||
host.hub.entity_event(host.host_entity, 3, feet);
|
||||
}
|
||||
self.screen = Screen::Dead;
|
||||
self.capture(false);
|
||||
}
|
||||
|
||||
@@ -497,10 +497,13 @@ impl Game<'_> {
|
||||
// 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])),
|
||||
// Player.getDisplayName.
|
||||
Some(_) => {
|
||||
let player = self.target_name(super::commands::Target::Player);
|
||||
self.adv
|
||||
.announced
|
||||
.push(Text::translate(key, &[player, name]));
|
||||
}
|
||||
None => self.system_message(Text::translate(
|
||||
key,
|
||||
&[Text::literal(super::chat::PLAYER_NAME), name],
|
||||
@@ -832,18 +835,25 @@ pub(super) fn adv_name(a: &adv::Advancement) -> Text {
|
||||
Frame::Challenge => text::DARK_PURPLE,
|
||||
_ => text::GREEN,
|
||||
};
|
||||
let tooltip = text_of(&d.title)
|
||||
.with_color(color)
|
||||
// Advancement.decorateName: the title in the frame's colour (styles
|
||||
// merged into it), a new line and the description.
|
||||
let coloured = text_of(&d.title).with_color(color);
|
||||
let mut component = coloured.component();
|
||||
if let Some(o) = component.as_object_mut() {
|
||||
o.insert(
|
||||
"extra".into(),
|
||||
serde_json::json!(["\n", text_of(&d.description).component()]),
|
||||
);
|
||||
}
|
||||
let tooltip = coloured
|
||||
.append("\n")
|
||||
.append(text_of(&d.description));
|
||||
.append(text_of(&d.description))
|
||||
.with_component(component);
|
||||
let title = text_of(&d.title).with_style(&Style {
|
||||
hover: Some(Box::new(tooltip)),
|
||||
..Style::default()
|
||||
});
|
||||
Text::literal("[")
|
||||
.append(title)
|
||||
.append("]")
|
||||
.with_color(color)
|
||||
Text::translate("chat.square_brackets", &[title]).with_color(color)
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `AdvancementCommands.Action.GRANT` on one advancement (or one of
|
||||
|
||||
@@ -1546,6 +1546,13 @@ impl Game<'_> {
|
||||
return Err("command TEXT".into());
|
||||
}
|
||||
let command = format!("/{text}");
|
||||
// Single player's console is its server thread's.
|
||||
if let Some(server) = &self.integrated {
|
||||
let chat = server
|
||||
.call(move |g| g.owner_console_command(&command))
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return ok(json!({ "ok": true, "chat": chat }));
|
||||
}
|
||||
if self.remote.is_some() {
|
||||
self.send_chat(&command);
|
||||
return ok(json!({ "ok": true }));
|
||||
|
||||
@@ -9,6 +9,7 @@ pub(super) mod extra;
|
||||
mod items;
|
||||
mod misc;
|
||||
mod place;
|
||||
mod players;
|
||||
mod raid;
|
||||
mod terrain_cmds;
|
||||
mod text_commands;
|
||||
@@ -33,7 +34,11 @@ pub(super) type R<T> = Result<T, CommandError>;
|
||||
/// An entity a selector found.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(super) enum Target {
|
||||
/// The player in place: the host's, or the guest whose turn it is.
|
||||
Player,
|
||||
/// Another player of a hosted world or server: a guest by connection
|
||||
/// (game/commands/players.rs).
|
||||
Guest(u32),
|
||||
Mob(u32),
|
||||
Item(u32),
|
||||
Orb(usize),
|
||||
@@ -232,9 +237,16 @@ impl Game<'_> {
|
||||
}
|
||||
match &self.player {
|
||||
Some(p) => [p.position.x, p.position.y, p.position.z],
|
||||
None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
|
||||
None => self.server_position(),
|
||||
}
|
||||
}
|
||||
/// MinecraftServer.createCommandSourceStack's position: the corner of
|
||||
/// the respawn block (`Vec3.atLowerCornerOf`).
|
||||
pub(super) fn server_position(&self) -> [f64; 3] {
|
||||
self.spawn.map_or([0.0, 64.0, 0.0], |s| {
|
||||
[s.x.floor(), s.y.floor(), s.z.floor()]
|
||||
})
|
||||
}
|
||||
fn source_rotation(&self) -> [f32; 2] {
|
||||
self.command_source
|
||||
.map_or([self.yaw, self.pitch], |s| s.rot)
|
||||
@@ -288,6 +300,7 @@ impl Game<'_> {
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z]),
|
||||
Target::Guest(conn) => self.command_guest(conn).map(|g| g.position),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -347,7 +360,7 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn target_type(&self, t: Target) -> String {
|
||||
match t {
|
||||
Target::Player => "minecraft:player".into(),
|
||||
Target::Player | Target::Guest(_) => "minecraft:player".into(),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -394,12 +407,19 @@ impl Game<'_> {
|
||||
match t {
|
||||
Target::Player => {
|
||||
let name = self.acting_player_name();
|
||||
if let Some(uuid) = self.lan_acting_uuid {
|
||||
return self.player_text(name, uuid);
|
||||
}
|
||||
match self.score.board.players_team(name) {
|
||||
// PlayerTeam.formatNameForTeam.
|
||||
Some(team) => team.formatted_name(Text::literal(name)),
|
||||
None => Text::literal(name),
|
||||
}
|
||||
}
|
||||
Target::Guest(conn) => match self.command_guest(conn) {
|
||||
Some(g) => self.player_text(&g.name, g.uuid),
|
||||
None => Text::empty(),
|
||||
},
|
||||
Target::Item(id) => {
|
||||
let item = self
|
||||
.dropped
|
||||
@@ -446,11 +466,10 @@ impl Game<'_> {
|
||||
/// EntitySelector.findEntities.
|
||||
pub(super) fn select(&mut self, s: &Selector) -> Vec<Target> {
|
||||
if let Some(name) = &s.player_name {
|
||||
return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() {
|
||||
vec![Target::Player]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
return self.player_named(name).into_iter().collect();
|
||||
}
|
||||
if let Some(uuid) = s.uuid {
|
||||
return self.target_by_uuid(uuid).into_iter().collect();
|
||||
}
|
||||
let origin = {
|
||||
let p = self.source_position();
|
||||
@@ -464,10 +483,15 @@ impl Game<'_> {
|
||||
match (s.kind, self.command_source) {
|
||||
// @s: the executing entity (none for a server source).
|
||||
('s', Some(source)) => candidates.extend(source.entity),
|
||||
_ if self.player.is_some() => candidates.push(Target::Player),
|
||||
('s', None) => candidates.extend(self.source_entity()),
|
||||
// A guest in place is among the players, in join order.
|
||||
_ if self.player.is_some() && self.lan_acting.is_none() => {
|
||||
candidates.push(Target::Player);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if s.kind != 's' {
|
||||
candidates.extend(self.player_candidates(s));
|
||||
candidates.extend(
|
||||
self.mobs
|
||||
.iter()
|
||||
@@ -511,7 +535,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
if !s.include_entities
|
||||
&& t != Target::Player
|
||||
&& !t.is_player()
|
||||
&& s.types.iter().all(|(w, n)| *n || w != &ty)
|
||||
&& s.kind != 'e'
|
||||
&& s.kind != 'n'
|
||||
@@ -527,16 +551,20 @@ impl Game<'_> {
|
||||
if !passing.contains(&t) {
|
||||
return None;
|
||||
}
|
||||
let player = match t {
|
||||
Target::Player => Some((level, if creative { "creative" } else { "survival" })),
|
||||
Target::Guest(conn) => self.guest_level_and_mode(conn),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((lo, hi)) = s.level
|
||||
&& (t != Target::Player
|
||||
|| lo.is_some_and(|l| level < l)
|
||||
|| hi.is_some_and(|h| level > h))
|
||||
&& player.is_none_or(|(level, _)| {
|
||||
lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h)
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for (mode, neg) in &s.gamemodes {
|
||||
let current = if creative { "creative" } else { "survival" };
|
||||
if t != Target::Player || (current == mode) == *neg {
|
||||
if player.is_none_or(|(_, current)| (current == mode) == *neg) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -595,12 +623,12 @@ impl Game<'_> {
|
||||
/// EntityArgument.getEntities / getPlayers / getEntity / getPlayer.
|
||||
pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
|
||||
let Some(Arg::Entity(s)) = ctx.get(name).cloned() else {
|
||||
return Ok(vec![Target::Player]);
|
||||
return Ok(vec![self.implied_player()]);
|
||||
};
|
||||
let found: Vec<Target> = self
|
||||
.select(&s)
|
||||
.into_iter()
|
||||
.filter(|t| !players || *t == Target::Player)
|
||||
.filter(|t| !players || t.is_player())
|
||||
.collect();
|
||||
if found.is_empty() {
|
||||
return Err(err(
|
||||
@@ -806,63 +834,63 @@ impl Game<'_> {
|
||||
let targets = if ctx.get("target").is_some() {
|
||||
self.entities(ctx, "target", true)?
|
||||
} else {
|
||||
vec![Target::Player]
|
||||
vec![self.implied_player()]
|
||||
};
|
||||
let mut count = 0;
|
||||
for t in targets {
|
||||
if t != Target::Player || !self.set_game_mode(mode) {
|
||||
let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]);
|
||||
// GameModeCommand.logGamemodeChange: the source's own entity.
|
||||
let own = self.source_entity() == Some(t);
|
||||
let told = !own && self.ui.rules.bool("send_command_feedback");
|
||||
let changed = self.for_player(t, |g| {
|
||||
if !g.set_game_mode(mode) {
|
||||
return false;
|
||||
}
|
||||
if told {
|
||||
g.system_message(Text::translate(
|
||||
"gameMode.changed",
|
||||
std::slice::from_ref(&mode_name),
|
||||
));
|
||||
}
|
||||
true
|
||||
});
|
||||
if changed != Some(true) {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]);
|
||||
// GameModeCommand.logGamemodeChange: the source's own entity.
|
||||
let own = match self.command_source {
|
||||
None => true,
|
||||
Some(s) => s.entity == Some(t),
|
||||
};
|
||||
if own {
|
||||
self.feedback(Text::translate(
|
||||
"commands.gamemode.success.self",
|
||||
&[mode_name],
|
||||
));
|
||||
} else {
|
||||
if self.ui.rules.bool("send_command_feedback") {
|
||||
self.system_message(Text::translate(
|
||||
"gameMode.changed",
|
||||
std::slice::from_ref(&mode_name),
|
||||
));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.gamemode.success.other",
|
||||
&[Text::literal(self.acting_player_name()), mode_name],
|
||||
&[self.target_name(t), mode_name],
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
/// ItemStack.getDisplayName: "[Name]" in the rarity colour.
|
||||
/// ItemStack.getDisplayName of one `item` with no components.
|
||||
pub(super) fn item_display_name(&self, item: &str) -> Text {
|
||||
let rarity = self.item_rarity(item);
|
||||
let color = match rarity.as_str() {
|
||||
"uncommon" => text::YELLOW,
|
||||
"rare" => text::AQUA,
|
||||
"epic" => text::LIGHT_PURPLE,
|
||||
_ => text::WHITE,
|
||||
};
|
||||
Text::literal("[")
|
||||
.append(Text::literal(self.pack.names.item(item)))
|
||||
.append("]")
|
||||
.with_color(color)
|
||||
self.stack_display_name(&ItemStack {
|
||||
item: item.into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
/// `ItemStack.getDisplayName`: the hover name (custom name in italics,
|
||||
/// a written book's title, a potion's effect name...) in brackets, in the
|
||||
/// rarity colour unless the stack is empty.
|
||||
/// a written book's title, a potion's effect name, else the item's
|
||||
/// translated name) in brackets, in the rarity colour and showing the
|
||||
/// stack on hover unless it is empty.
|
||||
pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text {
|
||||
let item = &*s.item;
|
||||
let empty = item == "minecraft:air" || s.count == 0;
|
||||
let custom = s.custom_name();
|
||||
let hover = if let Some(c) = custom {
|
||||
Text::literal(c).italic()
|
||||
Text::literal(c)
|
||||
} else if let Some(title) = s
|
||||
.data()
|
||||
.and_then(|d| d.written.as_ref())
|
||||
@@ -883,9 +911,22 @@ impl Game<'_> {
|
||||
&[],
|
||||
)
|
||||
} else {
|
||||
Text::literal(self.pack.names.item(item))
|
||||
// Item.getDescriptionId: a block item's is the block's.
|
||||
let (namespace, path) = item.split_once(':').unwrap_or(("minecraft", item));
|
||||
let key = format!("item.{namespace}.{path}");
|
||||
let key = if self.pack.names.get(&key).is_some() {
|
||||
key
|
||||
} else {
|
||||
format!("block.{namespace}.{path}")
|
||||
};
|
||||
Text::translate(&key, &[])
|
||||
};
|
||||
let wrapped = Text::translate("chat.square_brackets", &[hover]);
|
||||
// Component.empty().append(getHoverName()), italic for a custom name.
|
||||
let mut name = Text::empty().append(hover);
|
||||
if custom.is_some() {
|
||||
name = name.italic();
|
||||
}
|
||||
let wrapped = Text::translate("chat.square_brackets", &[name]);
|
||||
if empty {
|
||||
return wrapped;
|
||||
}
|
||||
@@ -903,7 +944,14 @@ impl Game<'_> {
|
||||
"epic" => text::LIGHT_PURPLE,
|
||||
_ => text::WHITE,
|
||||
};
|
||||
wrapped.with_color(color)
|
||||
// HoverEvent.ShowItem: the count only when it is not one.
|
||||
let mut shown = serde_json::json!({"action": "show_item", "id": item});
|
||||
if s.count != 1 {
|
||||
shown["count"] = s.count.into();
|
||||
}
|
||||
wrapped
|
||||
.with_color(color)
|
||||
.with_component_fields(vec![("hover_event".into(), shown)])
|
||||
}
|
||||
pub(super) fn item_rarity(&self, item: &str) -> String {
|
||||
static RARITY: std::sync::OnceLock<std::collections::HashMap<String, String>> =
|
||||
@@ -953,33 +1001,38 @@ impl Game<'_> {
|
||||
}
|
||||
// An air stack is empty: nothing is given (but the message still is).
|
||||
let empty = id == "minecraft:air";
|
||||
for _ in targets.iter().filter(|_| !empty) {
|
||||
let mut remaining = count;
|
||||
while remaining > 0 {
|
||||
let size = remaining.min(max_stack);
|
||||
remaining -= size;
|
||||
let left = self.give(ItemStack {
|
||||
item: id.as_str().into(),
|
||||
count: size as u32,
|
||||
damage,
|
||||
extra: extra.clone(),
|
||||
});
|
||||
if let Some(rest) = left {
|
||||
// Inventory full: drop the rest at the player's feet without pickup delay.
|
||||
let p = self.source_position();
|
||||
self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0);
|
||||
} else {
|
||||
let r = &mut self.world.random;
|
||||
let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0;
|
||||
let p = self.source_position();
|
||||
self.audio
|
||||
.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch);
|
||||
for &t in targets.iter().filter(|_| !empty) {
|
||||
self.for_player(t, |g| {
|
||||
let mut remaining = count;
|
||||
while remaining > 0 {
|
||||
let size = remaining.min(max_stack);
|
||||
remaining -= size;
|
||||
let left = g.give(ItemStack {
|
||||
item: id.as_str().into(),
|
||||
count: size as u32,
|
||||
damage,
|
||||
extra: extra.clone(),
|
||||
});
|
||||
// At the player who gets them.
|
||||
let p = g
|
||||
.target_position(Target::Player)
|
||||
.unwrap_or(g.source_position());
|
||||
if let Some(rest) = left {
|
||||
// Inventory full: drop the rest at the player's feet without pickup delay.
|
||||
g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0);
|
||||
} else {
|
||||
let r = &mut g.world.random;
|
||||
let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0;
|
||||
g.audio
|
||||
.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// The prototype stack: one item.
|
||||
let name = self.stack_display_name(&ItemStack {
|
||||
item: id.as_str().into(),
|
||||
count: count.max(1) as u32,
|
||||
count: 1,
|
||||
damage,
|
||||
extra: extra.clone(),
|
||||
});
|
||||
@@ -989,7 +1042,7 @@ impl Game<'_> {
|
||||
&[
|
||||
Text::literal(count.to_string()),
|
||||
name,
|
||||
Text::literal(self.acting_player_name()),
|
||||
self.target_name(targets[0]),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
@@ -1008,6 +1061,9 @@ impl Game<'_> {
|
||||
fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
|
||||
let v = Vec3::new(pos[0], pos[1], pos[2]);
|
||||
match t {
|
||||
Target::Guest(_) => {
|
||||
self.for_player(t, |g| g.teleport_to(Target::Player, pos, rotation));
|
||||
}
|
||||
Target::Player => {
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.position = v;
|
||||
@@ -1088,17 +1144,59 @@ impl Game<'_> {
|
||||
Target::Frame(_) | Target::Painting(_) => {}
|
||||
}
|
||||
}
|
||||
/// A server's player teleported into another level than theirs
|
||||
/// (ServerPlayer.teleport): queued to move after the command. False
|
||||
/// when `t` is not a player in another level.
|
||||
fn teleport_across(
|
||||
&mut self,
|
||||
t: Target,
|
||||
level: super::Dim,
|
||||
pos: [f64; 3],
|
||||
rotation: Option<[f32; 2]>,
|
||||
) -> bool {
|
||||
let (conn, at) = match t {
|
||||
Target::Player => (self.lan_acting, self.dim),
|
||||
Target::Guest(conn) => (
|
||||
Some(conn),
|
||||
self.command_guest(conn)
|
||||
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
|
||||
),
|
||||
_ => (None, self.dim),
|
||||
};
|
||||
let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else {
|
||||
return false;
|
||||
};
|
||||
self.level_teleports
|
||||
.push(super::server_travel::LevelTeleport {
|
||||
conn,
|
||||
dim: level,
|
||||
at: pos,
|
||||
rotation,
|
||||
});
|
||||
true
|
||||
}
|
||||
fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = if id.starts_with("teleport.targets") {
|
||||
self.entities(ctx, "targets", false)?
|
||||
} else {
|
||||
vec![Target::Player]
|
||||
vec![self.implied_player()]
|
||||
};
|
||||
if id.ends_with("destination") {
|
||||
let dest = self.entities(ctx, "destination", false)?[0];
|
||||
let pos = self.target_position(dest).unwrap_or(self.source_position());
|
||||
// Into the destination's level.
|
||||
let level = match dest {
|
||||
Target::Guest(conn) => self
|
||||
.command_guest(conn)
|
||||
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
|
||||
_ => self.dim,
|
||||
};
|
||||
// TeleportCommand.teleportToEntity: the destination's rotation too.
|
||||
let rotation = Some(self.target_rotation(dest));
|
||||
for &t in &targets {
|
||||
self.teleport_to(t, pos, None);
|
||||
if !self.teleport_across(t, level, pos, rotation) {
|
||||
self.teleport_to(t, pos, rotation);
|
||||
}
|
||||
}
|
||||
let message = if targets.len() == 1 {
|
||||
Text::translate(
|
||||
@@ -1156,24 +1254,18 @@ impl Game<'_> {
|
||||
(-(dy.atan2(horizontal).to_degrees())) as f32,
|
||||
]);
|
||||
}
|
||||
// `execute in` another dimension: a server's player moves to that
|
||||
// level (ServerPlayer.teleport into another level), after the command.
|
||||
let level = self
|
||||
.command_source
|
||||
.and_then(|s| s.level)
|
||||
.filter(|d| *d != self.dim && self.options.dedicated.is_some());
|
||||
// A server's player in another level than the source's (`execute
|
||||
// in`, the console's Overworld) moves there (ServerPlayer.teleport
|
||||
// into another level), after the command.
|
||||
let source_level = match self.command_source.and_then(|s| s.level) {
|
||||
Some(level) => level,
|
||||
None if self.source_entity().is_none() => super::Dim::Overworld,
|
||||
None => self.dim,
|
||||
};
|
||||
for &t in &targets {
|
||||
if let (Some(dim), Target::Player, Some(conn)) = (level, t, self.lan_acting) {
|
||||
self.level_teleports
|
||||
.push(super::server_travel::LevelTeleport {
|
||||
conn,
|
||||
dim,
|
||||
at: pos,
|
||||
rotation,
|
||||
});
|
||||
continue;
|
||||
if !self.teleport_across(t, source_level, pos, rotation) {
|
||||
self.teleport_to(t, pos, rotation);
|
||||
}
|
||||
self.teleport_to(t, pos, rotation);
|
||||
}
|
||||
let [x, y, z] = pos.map(|v| Text::literal(format_double(v)));
|
||||
let message = if targets.len() == 1 {
|
||||
@@ -1373,6 +1465,9 @@ impl Game<'_> {
|
||||
}
|
||||
fn kill_target(&mut self, t: Target) {
|
||||
match t {
|
||||
Target::Guest(_) => {
|
||||
self.for_player(t, |g| g.kill_target(Target::Player));
|
||||
}
|
||||
Target::Player => {
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
let _ = p.set_health(0.0, false);
|
||||
@@ -1415,7 +1510,7 @@ impl Game<'_> {
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", false)?
|
||||
} else {
|
||||
vec![Target::Player]
|
||||
vec![self.implied_player()]
|
||||
};
|
||||
let names: Vec<Text> = targets.iter().map(|&t| self.target_name(t)).collect();
|
||||
// Remove indexed entities from the back so earlier indices stay valid.
|
||||
|
||||
@@ -35,6 +35,11 @@ impl Game<'_> {
|
||||
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option<Tag> {
|
||||
let player_uuid = self.level.player_uuid;
|
||||
Some(match t {
|
||||
Target::Guest(_) => {
|
||||
return self
|
||||
.for_player(t, |g| g.entity_nbt(Target::Player))
|
||||
.flatten();
|
||||
}
|
||||
Target::Player => {
|
||||
self.player.as_ref()?;
|
||||
self.sync_level();
|
||||
|
||||
@@ -59,7 +59,7 @@ impl Game<'_> {
|
||||
if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", false)
|
||||
} else {
|
||||
Ok(vec![Target::Player])
|
||||
Ok(vec![self.implied_player()])
|
||||
}
|
||||
}
|
||||
/// `EffectCommands.giveEffect`.
|
||||
@@ -83,10 +83,11 @@ impl Game<'_> {
|
||||
let mut tracker = Tracker::default();
|
||||
for t in self.living_targets(ctx)? {
|
||||
let changed = match t {
|
||||
Target::Player => {
|
||||
Target::Player | Target::Guest(_) => {
|
||||
let mut instance = EffectInstance::new(effect.id, duration, amplifier);
|
||||
instance.visible = particles;
|
||||
self.add_player_effect(instance)
|
||||
self.for_player(t, |g| g.add_player_effect(instance))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
Some(m) => {
|
||||
@@ -131,18 +132,22 @@ impl Game<'_> {
|
||||
let mut tracker = Tracker::default();
|
||||
for t in self.living_targets(ctx)? {
|
||||
let changed = match (t, effect) {
|
||||
(Target::Player, None) => {
|
||||
let any = !self.potions.effects.list.is_empty();
|
||||
self.potions.effects.clear();
|
||||
self.apply_effect_status();
|
||||
any
|
||||
}
|
||||
(Target::Player, Some(e)) => {
|
||||
let before = self.potions.effects.list.len();
|
||||
self.potions.effects.list.retain(|x| x.id != e.id);
|
||||
self.apply_effect_status();
|
||||
self.potions.effects.list.len() != before
|
||||
}
|
||||
(Target::Player | Target::Guest(_), None) => self
|
||||
.for_player(t, |g| {
|
||||
let any = !g.potions.effects.list.is_empty();
|
||||
g.potions.effects.clear();
|
||||
g.apply_effect_status();
|
||||
any
|
||||
})
|
||||
.unwrap_or(false),
|
||||
(Target::Player | Target::Guest(_), Some(e)) => self
|
||||
.for_player(t, |g| {
|
||||
let before = g.potions.effects.list.len();
|
||||
g.potions.effects.list.retain(|x| x.id != e.id);
|
||||
g.apply_effect_status();
|
||||
g.potions.effects.list.len() != before
|
||||
})
|
||||
.unwrap_or(false),
|
||||
(Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
Some(m) => {
|
||||
let before = m.extra.effects.len();
|
||||
|
||||
@@ -73,7 +73,8 @@ impl Game<'_> {
|
||||
/// The source a command typed by the player starts from.
|
||||
pub(in crate::game) fn player_source(&self) -> Source {
|
||||
Source {
|
||||
entity: Some(Target::Player),
|
||||
// The server console has no entity (CommandSourceStack of the server).
|
||||
entity: self.player.is_some().then_some(Target::Player),
|
||||
pos: self.source_position(),
|
||||
rot: self.source_rotation(),
|
||||
eyes: false,
|
||||
@@ -88,7 +89,7 @@ impl Game<'_> {
|
||||
pub(in crate::game) fn server_source(&self) -> Source {
|
||||
Source {
|
||||
entity: None,
|
||||
pos: self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
|
||||
pos: self.server_position(),
|
||||
rot: [0.0, 0.0],
|
||||
eyes: false,
|
||||
silent: true,
|
||||
@@ -101,6 +102,9 @@ impl Game<'_> {
|
||||
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
match t {
|
||||
Target::Player => [self.yaw, self.pitch],
|
||||
Target::Guest(conn) => self
|
||||
.command_guest(conn)
|
||||
.map_or([0.0; 2], |g| [g.yaw, g.pitch]),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -135,6 +139,7 @@ impl Game<'_> {
|
||||
.player
|
||||
.as_ref()
|
||||
.map_or(1.62, |p| f64::from(p.dimensions.eye_height)),
|
||||
Target::Guest(conn) => self.command_guest(conn).map_or(1.62, |g| g.eye_height()),
|
||||
Target::Mob(id) => self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -633,7 +638,7 @@ impl Game<'_> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn target_with_uuid(&self, uuid: [i32; 4]) -> Option<Target> {
|
||||
pub(super) fn target_with_uuid(&self, uuid: [i32; 4]) -> Option<Target> {
|
||||
if Some(uuid) == self.level.player_uuid {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Commands acting on the other players of a hosted world or a server
|
||||
//! (EntitySelector.findPlayers and EntityArgument's player targets). The
|
||||
//! player in place (the host's, or the guest whose turn it is) is
|
||||
//! `Target::Player`; every other guest is `Target::Guest`, found by name,
|
||||
//! UUID or selector, and what a command does to them runs with their state
|
||||
//! swapped in (`for_player`), as their own turn, what it tells them going to
|
||||
//! their chat.
|
||||
use super::{Game, Target};
|
||||
use horizon_client::{command::args::Selector, lan::guest::Guest, text::Text};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
|
||||
impl Target {
|
||||
/// A player, in place or not (`instanceof ServerPlayer`).
|
||||
pub(in crate::game) fn is_player(self) -> bool {
|
||||
matches!(self, Target::Player | Target::Guest(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// GameType.getName for a guest's game mode id.
|
||||
fn mode_name(id: i32) -> &'static str {
|
||||
match id {
|
||||
1 => "creative",
|
||||
2 => "adventure",
|
||||
3 => "spectator",
|
||||
_ => "survival",
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The guest `conn`, while the hub is in `self.lan`.
|
||||
pub(in crate::game) fn command_guest(&self, conn: u32) -> Option<&Guest> {
|
||||
self.lan.as_ref()?.hub.guest(conn)
|
||||
}
|
||||
|
||||
/// `PlayerList.getPlayers` but the player in place: the guests who
|
||||
/// joined the world.
|
||||
fn command_players(&self) -> impl Iterator<Item = &Guest> {
|
||||
let acting = self.lan_acting;
|
||||
self.lan
|
||||
.iter()
|
||||
.flat_map(|h| h.hub.guests.iter())
|
||||
.filter(move |g| g.placed && Some(g.conn) != acting)
|
||||
}
|
||||
|
||||
/// The entity the command runs as (`CommandSourceStack.getEntity`): a
|
||||
/// command typed by the player in place runs as them, the server
|
||||
/// console's as nobody.
|
||||
pub(in crate::game) fn source_entity(&self) -> Option<Target> {
|
||||
match self.command_source {
|
||||
Some(s) => s.entity,
|
||||
None => self.player.is_some().then_some(Target::Player),
|
||||
}
|
||||
}
|
||||
|
||||
/// `CommandSourceStack.getPlayerOrException` for the commands whose
|
||||
/// player argument is optional: the source's player (the player in
|
||||
/// place when it has none, as before).
|
||||
pub(in crate::game) fn implied_player(&self) -> Target {
|
||||
self.source_entity()
|
||||
.filter(|t| t.is_player())
|
||||
.unwrap_or(Target::Player)
|
||||
}
|
||||
|
||||
/// `PlayerList.getPlayerByName`: names are not case sensitive.
|
||||
pub(super) fn player_named(&self, name: &str) -> Option<Target> {
|
||||
if self.player.is_some() && name.eq_ignore_ascii_case(self.acting_player_name()) {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
self.command_players()
|
||||
.find(|g| g.name.eq_ignore_ascii_case(name))
|
||||
.map(|g| Target::Guest(g.conn))
|
||||
}
|
||||
|
||||
/// `EntitySelector.findEntities` with a UUID: the player with it, else
|
||||
/// the entity.
|
||||
pub(super) fn target_by_uuid(&self, uuid: u128) -> Option<Target> {
|
||||
let own = self.lan_acting_uuid.or_else(|| {
|
||||
self.level.player_uuid.map(|[a, b, c, d]| {
|
||||
(u128::from(a as u32) << 96)
|
||||
| (u128::from(b as u32) << 64)
|
||||
| (u128::from(c as u32) << 32)
|
||||
| u128::from(d as u32)
|
||||
})
|
||||
});
|
||||
if self.player.is_some() && own == Some(uuid) {
|
||||
return Some(Target::Player);
|
||||
}
|
||||
if let Some(g) = self.command_players().find(|g| g.uuid == uuid) {
|
||||
return Some(Target::Guest(g.conn));
|
||||
}
|
||||
let words = [96, 64, 32, 0].map(|shift| (uuid >> shift) as u32 as i32);
|
||||
self.target_with_uuid(words)
|
||||
}
|
||||
|
||||
/// The guests a selector looks at, in join order (`PlayerList.getPlayers`),
|
||||
/// the one in place as `Target::Player`: all of them, or those in the
|
||||
/// source's level when it limits the search to a place
|
||||
/// (`isWorldLimited`); `@e` and `@n` skip the dead (`Entity::isAlive`).
|
||||
pub(super) fn player_candidates(&self, s: &Selector) -> Vec<Target> {
|
||||
let limited = s.distance.is_some()
|
||||
|| s.pos.iter().any(Option::is_some)
|
||||
|| s.delta.iter().any(Option::is_some);
|
||||
let alive = matches!(s.kind, 'e' | 'n');
|
||||
let here = self.dim.id();
|
||||
let in_place = self.lan_acting.filter(|_| self.player.is_some());
|
||||
self.lan
|
||||
.iter()
|
||||
.flat_map(|h| h.hub.guests.iter())
|
||||
.filter(|g| g.placed)
|
||||
.filter(|g| !limited || g.dimension == here || Some(g.conn) == in_place)
|
||||
.filter(|g| !alive || (!g.dead && g.health > 0.0))
|
||||
.map(|g| {
|
||||
if Some(g.conn) == in_place {
|
||||
Target::Player
|
||||
} else {
|
||||
Target::Guest(g.conn)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A guest's experience level and game mode, for `level=` and `gamemode=`.
|
||||
pub(super) fn guest_level_and_mode(&self, conn: u32) -> Option<(i32, &'static str)> {
|
||||
self.command_guest(conn)
|
||||
.map(|g| (g.xp_level, mode_name(g.game_mode)))
|
||||
}
|
||||
|
||||
/// `Player.getDisplayName`: the name as its team shows it, suggesting a
|
||||
/// `/tell`, showing the player on hover, inserting the name.
|
||||
pub(in crate::game) fn player_text(&self, name: &str, uuid: u128) -> Text {
|
||||
let shown = match self.score.board.players_team(name) {
|
||||
Some(team) => team.formatted_name(Text::literal(name)),
|
||||
None => Text::literal(name),
|
||||
};
|
||||
shown.with_component_fields(vec![
|
||||
(
|
||||
"click_event".into(),
|
||||
serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}),
|
||||
),
|
||||
(
|
||||
"hover_event".into(),
|
||||
serde_json::json!({"action": "show_entity", "id": "minecraft:player",
|
||||
"uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}),
|
||||
),
|
||||
("insertion".into(), name.into()),
|
||||
])
|
||||
}
|
||||
|
||||
/// Run `f` for the player `t` (None for anything else): in place, or
|
||||
/// with the guest's state swapped in, in their level, as their own turn.
|
||||
/// What `f` tells the player (`system_message`) goes to their chat; the
|
||||
/// command's own feedback is the caller's to send.
|
||||
pub(in crate::game) fn for_player<T>(
|
||||
&mut self,
|
||||
t: Target,
|
||||
f: impl FnOnce(&mut Self) -> T,
|
||||
) -> Option<T> {
|
||||
let conn = match t {
|
||||
Target::Player => return Some(f(self)),
|
||||
Target::Guest(conn) if self.lan_acting == Some(conn) => return Some(f(self)),
|
||||
Target::Guest(conn) => conn,
|
||||
_ => return None,
|
||||
};
|
||||
let mut host = self.lan.take()?;
|
||||
let back = self.dim;
|
||||
let theirs = host
|
||||
.hub
|
||||
.guest(conn)
|
||||
.map(|g| super::super::Dim::from_id(&g.dimension));
|
||||
if let Some(dim) = theirs.filter(|d| *d != back)
|
||||
&& let Err(e) = self.enter_level(Some(&mut host), dim)
|
||||
{
|
||||
log::error!("could not open {}: {e}", dim.id());
|
||||
}
|
||||
let Some(swap) = self.enter_guest(&mut host, conn) else {
|
||||
if self.dim != back
|
||||
&& let Err(e) = self.enter_level(Some(&mut host), back)
|
||||
{
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
self.lan = Some(host);
|
||||
return None;
|
||||
};
|
||||
self.lan = Some(host);
|
||||
let source = self.chat_capture.replace(Vec::new());
|
||||
let out = f(self);
|
||||
let told = std::mem::replace(&mut self.chat_capture, source).unwrap_or_default();
|
||||
let mut host = self
|
||||
.lan
|
||||
.take()
|
||||
.expect("the hub is back after a player's turn");
|
||||
self.leave_guest(&mut host, swap);
|
||||
for line in told {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content: horizon_client::lan::data::component_nbt(&line.component()),
|
||||
overlay: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if self.dim != back
|
||||
&& let Err(e) = self.enter_level(Some(&mut host), back)
|
||||
{
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
self.lan = Some(host);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
@@ -54,12 +54,23 @@ pub struct Flight {
|
||||
/// Reply with every frame time too (`fly ... PITCH raw`).
|
||||
raw: bool,
|
||||
reply: Sender<String>,
|
||||
/// The world's smoothed tick time each frame (the F3 server line): the
|
||||
/// server thread's when single player runs on one.
|
||||
tick_ms: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Move the camera along the running flight; reply when it ends.
|
||||
pub(super) fn advance_flight(&mut self) {
|
||||
let Some(flight) = &self.flight else { return };
|
||||
let tick_ms = self
|
||||
.integrated
|
||||
.as_ref()
|
||||
.map_or(self.debug_charts.smoothed_tick_ms, |s| s.smoothed_tick_ms());
|
||||
let Some(flight) = self.flight.as_mut() else {
|
||||
return;
|
||||
};
|
||||
flight.tick_ms.push(tick_ms);
|
||||
let flight = &*flight;
|
||||
let t = (flight.started.elapsed().as_secs_f64() / flight.seconds).min(1.0);
|
||||
let (a, b) = (flight.from, flight.to);
|
||||
let d = [b.x - a.x, b.y - a.y, b.z - a.z];
|
||||
@@ -79,6 +90,9 @@ impl Game<'_> {
|
||||
&& let Some(flight) = self.flight.take()
|
||||
{
|
||||
let mut summary = self.frame_stats.summary();
|
||||
let n = flight.tick_ms.len().max(1) as f32;
|
||||
summary["tick_ms"] = (flight.tick_ms.iter().sum::<f32>() / n).into();
|
||||
summary["tick_ms_max"] = flight.tick_ms.iter().copied().fold(0.0, f32::max).into();
|
||||
if flight.raw {
|
||||
summary["frame_ms"] = self.frame_stats.frame_millis().into();
|
||||
summary["cpu_ms"] = self.frame_stats.cpu_millis().into();
|
||||
@@ -349,6 +363,14 @@ impl Game<'_> {
|
||||
.get(&item)
|
||||
.ok_or_else(|| format!("unknown item {item}"))?;
|
||||
let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?;
|
||||
// Single player's inventory is its server thread's player's.
|
||||
if let Some(server) = &self.integrated {
|
||||
let command = format!("give @s {item} {count}");
|
||||
server
|
||||
.call(move |g| g.owner_console_command(&command))
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return Ok(Some(json!({ "ok": true, "given": count })));
|
||||
}
|
||||
let max = info.max_stack;
|
||||
let mut given = 0;
|
||||
// Stop once the inventory is full.
|
||||
@@ -379,7 +401,14 @@ impl Game<'_> {
|
||||
ok()
|
||||
}
|
||||
"time" => {
|
||||
self.world.day_time = arg(1)?.parse()?;
|
||||
let time: i64 = arg(1)?.parse()?;
|
||||
self.world.day_time = time;
|
||||
// Single player's clock is its server thread's.
|
||||
if let Some(server) = &self.integrated {
|
||||
server
|
||||
.call(move |g| g.world.day_time = time)
|
||||
.ok_or("the integrated server stopped")?;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"summon" => {
|
||||
@@ -527,6 +556,7 @@ impl Game<'_> {
|
||||
seconds: n(7)?.max(0.1),
|
||||
raw: words.get(9) == Some(&"raw"),
|
||||
reply: reply.clone(),
|
||||
tick_ms: Vec::new(),
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -830,6 +830,7 @@ impl Game<'_> {
|
||||
self.console_command(state, line);
|
||||
self.console_broadcast = None;
|
||||
if let Some(mut host) = self.lan.take() {
|
||||
self.run_level_teleports(&mut host);
|
||||
self.send_admin_feedback(&mut host, None);
|
||||
self.lan = Some(host);
|
||||
}
|
||||
|
||||
@@ -167,7 +167,11 @@ impl Game<'_> {
|
||||
Snapshot {
|
||||
screen: self.screen_label(),
|
||||
dimension: self.dim.id().to_string(),
|
||||
chat: self.ui.chat.received,
|
||||
// A remote client counts the server's lines itself.
|
||||
chat: self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map_or(self.ui.chat.received, |r| r.chat_received),
|
||||
counts: if world.is_some() {
|
||||
self.inventory_counts()
|
||||
} else {
|
||||
@@ -189,8 +193,19 @@ impl Game<'_> {
|
||||
if let Some(before) = &self.events.last
|
||||
&& *before != now
|
||||
{
|
||||
let new_chat = (now.chat - before.chat).min(100) as usize;
|
||||
let lines = self.ui.chat.recent_lines(new_chat);
|
||||
// Joining or leaving a server starts another count.
|
||||
let new_chat = now.chat.saturating_sub(before.chat).min(100) as usize;
|
||||
// Newest first; the remote client keeps its lines oldest first.
|
||||
let lines = match &self.remote {
|
||||
Some(r) => r
|
||||
.chat
|
||||
.iter()
|
||||
.rev()
|
||||
.take(new_chat)
|
||||
.map(|(t, _)| t.clone())
|
||||
.collect(),
|
||||
None => self.ui.chat.recent_lines(new_chat),
|
||||
};
|
||||
for event in diff(before, &now, &lines) {
|
||||
self.events.push(self.ticks, event);
|
||||
}
|
||||
|
||||
@@ -411,6 +411,60 @@ impl Game<'_> {
|
||||
pub(super) fn serving(&self) -> bool {
|
||||
self.serving.is_some()
|
||||
}
|
||||
/// The window's agent runs a command as single player's console does
|
||||
/// (`as_console`, as without a server thread): as the world's owner, in
|
||||
/// the owner's level, at the owner permission level. The feedback goes to
|
||||
/// the owner's chat and is returned.
|
||||
pub(super) fn owner_console_command(&mut self, command: &str) -> Vec<String> {
|
||||
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(mut host) = self.lan.take() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed) {
|
||||
let conn = g.conn;
|
||||
// Commands.performCommand runs in the player's level.
|
||||
let (back, theirs) = (self.dim, super::Dim::from_id(&g.dimension));
|
||||
let entered = theirs == back || self.enter_level(Some(&mut host), theirs).is_ok();
|
||||
if entered {
|
||||
let command = command.trim_start_matches('/').to_owned();
|
||||
let lines = self.as_guest(&mut host, conn, |g| {
|
||||
g.as_console(|g| {
|
||||
g.chat_capture = Some(Vec::new());
|
||||
g.run_command(&command);
|
||||
g.chat_capture.take().unwrap_or_default()
|
||||
})
|
||||
});
|
||||
// A teleport into another level happens before its feedback is sent.
|
||||
self.run_level_teleports(&mut host);
|
||||
for line in lines.unwrap_or_default() {
|
||||
out.push(line.plain());
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&horizon_protocol::packets::play::Clientbound::SystemChat(
|
||||
horizon_protocol::packets::play::SystemChat {
|
||||
content: horizon_client::lan::data::component_nbt(
|
||||
&line.component(),
|
||||
),
|
||||
overlay: false,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
self.send_admin_feedback(&mut host, Some(conn));
|
||||
}
|
||||
if theirs != back
|
||||
&& let Err(e) = self.enter_level(Some(&mut host), back)
|
||||
{
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
}
|
||||
self.lan = Some(host);
|
||||
out
|
||||
}
|
||||
|
||||
/// The window's requests, between two ticks.
|
||||
fn run_tasks(&mut self) {
|
||||
let tasks: Vec<Task> = match &self.serving {
|
||||
|
||||
@@ -61,6 +61,9 @@ pub(super) struct LanHost {
|
||||
/// are dead, whose respawn replaces their waypoint.
|
||||
pub waypoints: lan::waypoints::Waypoints,
|
||||
pub waypoint_dead: std::collections::HashSet<u128>,
|
||||
/// Guests' commands waiting for the hub to be back in `self.lan`, where
|
||||
/// a command can reach every player (game/lan_actions.rs).
|
||||
pub commands: Vec<super::lan_actions::GuestCommand>,
|
||||
}
|
||||
|
||||
/// The player who owns an integrated server's world: a guest whose state is
|
||||
@@ -520,6 +523,7 @@ impl Game<'_> {
|
||||
owner: None,
|
||||
waypoints: Default::default(),
|
||||
waypoint_dead: Default::default(),
|
||||
commands: Vec::new(),
|
||||
});
|
||||
self.audio.capture = Some(Vec::new());
|
||||
Ok(())
|
||||
@@ -722,6 +726,7 @@ impl Game<'_> {
|
||||
sprinting: p.sprinting,
|
||||
equipment,
|
||||
health: p.health.health(),
|
||||
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -732,6 +737,7 @@ impl Game<'_> {
|
||||
let kind = m.kind.id.as_str();
|
||||
let meta = mob_meta(m, hub);
|
||||
let equipment = mob_equipment(m, hub);
|
||||
let attributes = self.mob_attributes(m);
|
||||
let (yaw, pitch) = (m.yaw, m.head_pitch);
|
||||
out.push(EntityState {
|
||||
id: m.id as i32,
|
||||
@@ -746,6 +752,7 @@ impl Game<'_> {
|
||||
data: 0,
|
||||
meta,
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
@@ -764,6 +771,7 @@ impl Game<'_> {
|
||||
data: 0,
|
||||
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
@@ -782,6 +790,7 @@ impl Game<'_> {
|
||||
// ExperienceOrb.DATA_VALUE.
|
||||
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
}
|
||||
@@ -796,7 +805,11 @@ impl Game<'_> {
|
||||
};
|
||||
// What the tick sends a guest goes to its connection at the end.
|
||||
let holding = lan::Holding::start();
|
||||
// The host's own commands' broadcastToAdmins lines.
|
||||
// The host's own commands' (and command blocks') players moving
|
||||
// to another level, and their broadcastToAdmins lines.
|
||||
if !self.level_teleports.is_empty() {
|
||||
self.run_level_teleports(&mut host);
|
||||
}
|
||||
if !self.admin_feedback.is_empty() {
|
||||
self.send_admin_feedback(&mut host, None);
|
||||
}
|
||||
@@ -918,6 +931,11 @@ impl Game<'_> {
|
||||
}
|
||||
HostEvent::Packet(conn, packet) => {
|
||||
self.lan_guest_packet(&mut host, conn, *packet);
|
||||
if !host.commands.is_empty() {
|
||||
self.lan = Some(host);
|
||||
self.run_guest_commands();
|
||||
host = self.lan.take().expect("the hub is back after the commands");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,69 @@ pub(super) struct GuestPlay {
|
||||
pub(super) portal: horizon_client::nether_portal::PortalState,
|
||||
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
|
||||
xp_delay: u32,
|
||||
/// What last killed the guest outright (`/kill`): the death message's key.
|
||||
death_cause: Option<String>,
|
||||
}
|
||||
|
||||
/// A guest's command waiting for the hub (`LanHost::commands`).
|
||||
pub(super) struct GuestCommand {
|
||||
conn: u32,
|
||||
command: String,
|
||||
permission: u8,
|
||||
/// An integrated server's: no admin feedback or level teleports (yet).
|
||||
integrated: bool,
|
||||
}
|
||||
|
||||
/// The game's own state while a guest's is swapped in (`enter_guest`), and
|
||||
/// the guest's records that live outside `Guest`.
|
||||
pub(super) struct GuestSwap {
|
||||
conn: u32,
|
||||
i: usize,
|
||||
play: GuestPlay,
|
||||
player: Option<PlayerMotion>,
|
||||
/// The guest's eye height and the game's.
|
||||
eye: (f32, f32),
|
||||
yaw: f32,
|
||||
pitch: f32,
|
||||
selected: usize,
|
||||
mode: horizon_client::command::args::GameMode,
|
||||
creative: bool,
|
||||
xp: Experience,
|
||||
host_keys: std::collections::HashSet<KeyCode>,
|
||||
screen: Screen,
|
||||
host_sign: Option<super::sign_edit::SignEditor>,
|
||||
host_book: Option<super::books::BookScreen>,
|
||||
host_command_block: Option<super::command_blocks::CommandBlockScreen>,
|
||||
host_mount_menu: super::mount_menu::MountMenu,
|
||||
craft_size: usize,
|
||||
craft_grid: Vec<Option<ItemStack>>,
|
||||
container: Option<(i32, i32, i32)>,
|
||||
mining: Option<Mining>,
|
||||
destroy_delay: u32,
|
||||
using: Option<(usize, u32)>,
|
||||
use_delay: u32,
|
||||
attack_ticks: u32,
|
||||
swing: horizon_client::first_person::SwingState,
|
||||
left: bool,
|
||||
right: bool,
|
||||
riding: Option<u32>,
|
||||
host_station: Option<super::stations::Station>,
|
||||
sleeping: Option<[i32; 3]>,
|
||||
sleep_timer: u32,
|
||||
spawn: Option<Vec3>,
|
||||
respawn: (
|
||||
Option<super::respawn_anchor::RespawnConfig>,
|
||||
Option<[f64; 3]>,
|
||||
),
|
||||
message: Option<(String, std::time::Instant)>,
|
||||
host_ender: Option<(i32, i32, i32)>,
|
||||
adv_loaded: bool,
|
||||
last_inventory: u64,
|
||||
death_cause: Option<String>,
|
||||
/// The guest whose turn this one nests in, if any.
|
||||
acting: (Option<u32>, Option<String>, Option<u128>),
|
||||
/// The packets queued for that guest.
|
||||
packets: Vec<play::Clientbound>,
|
||||
}
|
||||
|
||||
struct ItemRules<'a>(&'a horizon_client::items::Items);
|
||||
@@ -95,6 +158,24 @@ impl Game<'_> {
|
||||
conn: u32,
|
||||
f: impl FnOnce(&mut Self) -> R,
|
||||
) -> Option<R> {
|
||||
let swap = self.enter_guest(host, conn)?;
|
||||
let result = f(self);
|
||||
self.leave_guest(host, swap);
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// The first half of `as_guest`: the guest's state in place of the
|
||||
/// game's, which the returned swap keeps until `leave_guest`. Between the
|
||||
/// two the host may go back into `self.lan`, so that what the guest does
|
||||
/// can reach the other players (their commands, `for_player`), and a
|
||||
/// guest's turn can nest in another's: the acting guest and the packets
|
||||
/// queued for them are kept and restored too.
|
||||
pub(super) fn enter_guest(&mut self, host: &mut LanHost, conn: u32) -> Option<GuestSwap> {
|
||||
// The guest whose turn it is is in place already (their record holds
|
||||
// the game's state until their turn ends).
|
||||
if self.lan_acting == Some(conn) {
|
||||
return None;
|
||||
}
|
||||
let i = host.hub.guests.iter().position(|g| g.conn == conn)?;
|
||||
if host.hub.guests[i].motion.is_none() {
|
||||
let p = Vec3::new(
|
||||
@@ -198,17 +279,109 @@ impl Game<'_> {
|
||||
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);
|
||||
let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take());
|
||||
let acting = (
|
||||
self.lan_acting.replace(conn),
|
||||
self.lan_acting_name.replace(g.name.clone()),
|
||||
self.lan_acting_uuid.replace(g.uuid),
|
||||
);
|
||||
let packets = std::mem::take(&mut self.guest_packets);
|
||||
Some(GuestSwap {
|
||||
conn,
|
||||
i,
|
||||
play,
|
||||
player,
|
||||
eye,
|
||||
yaw,
|
||||
pitch,
|
||||
selected,
|
||||
mode,
|
||||
creative,
|
||||
xp,
|
||||
host_keys,
|
||||
screen,
|
||||
host_sign,
|
||||
host_book,
|
||||
host_command_block,
|
||||
host_mount_menu,
|
||||
craft_size,
|
||||
craft_grid,
|
||||
container,
|
||||
mining,
|
||||
destroy_delay,
|
||||
using,
|
||||
use_delay,
|
||||
attack_ticks,
|
||||
swing,
|
||||
left,
|
||||
right,
|
||||
riding,
|
||||
host_station,
|
||||
sleeping,
|
||||
sleep_timer,
|
||||
spawn,
|
||||
respawn,
|
||||
message,
|
||||
host_ender,
|
||||
adv_loaded,
|
||||
last_inventory,
|
||||
death_cause,
|
||||
acting,
|
||||
packets,
|
||||
})
|
||||
}
|
||||
|
||||
let result = f(self);
|
||||
for packet in std::mem::take(&mut self.guest_packets) {
|
||||
/// The second half of `as_guest`: the guest's state back into their
|
||||
/// record, the game's back in place, and what the turn changed sent.
|
||||
pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) {
|
||||
let GuestSwap {
|
||||
conn,
|
||||
i,
|
||||
mut play,
|
||||
mut player,
|
||||
eye,
|
||||
yaw,
|
||||
pitch,
|
||||
selected,
|
||||
mode,
|
||||
creative,
|
||||
xp,
|
||||
host_keys,
|
||||
screen,
|
||||
host_sign,
|
||||
host_book,
|
||||
host_command_block,
|
||||
host_mount_menu,
|
||||
craft_size,
|
||||
craft_grid,
|
||||
container,
|
||||
mining,
|
||||
destroy_delay,
|
||||
using,
|
||||
use_delay,
|
||||
attack_ticks,
|
||||
swing,
|
||||
left,
|
||||
right,
|
||||
riding,
|
||||
host_station,
|
||||
sleeping,
|
||||
sleep_timer,
|
||||
spawn,
|
||||
respawn,
|
||||
message,
|
||||
host_ender,
|
||||
adv_loaded,
|
||||
last_inventory,
|
||||
death_cause,
|
||||
acting,
|
||||
packets,
|
||||
} = swap;
|
||||
for packet in std::mem::replace(&mut self.guest_packets, packets) {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
self.lan_acting = None;
|
||||
self.lan_acting_name = None;
|
||||
self.lan_acting_uuid = None;
|
||||
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
|
||||
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
|
||||
// An ender chest the guest opened: the menu shows their inventory
|
||||
// itself (lan_open_container), not a stand-in block entity.
|
||||
self.close_ender_chest();
|
||||
@@ -281,6 +454,9 @@ impl Game<'_> {
|
||||
std::mem::swap(&mut self.armor, &mut g.armor);
|
||||
std::mem::swap(&mut self.offhand, &mut g.offhand);
|
||||
std::mem::swap(&mut self.carried, &mut g.carried);
|
||||
// A teleport with a rotation (commands) turns the guest.
|
||||
let turned = [self.yaw, self.pitch] != [g.yaw, g.pitch];
|
||||
[g.yaw, g.pitch] = [self.yaw, self.pitch];
|
||||
self.yaw = yaw;
|
||||
self.pitch = pitch;
|
||||
self.eye = eye.1;
|
||||
@@ -294,7 +470,7 @@ impl Game<'_> {
|
||||
m.sprinting = false;
|
||||
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
|
||||
g.motion = Some(Box::new(m));
|
||||
if moved > 0.0001 {
|
||||
if moved > 0.0001 || turned {
|
||||
host.hub.teleport(i, Some(at));
|
||||
}
|
||||
}
|
||||
@@ -331,7 +507,6 @@ impl Game<'_> {
|
||||
if opened_table {
|
||||
self.lan_open_crafting(host, conn);
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// `ServerLevel.players()` in turn: the host's own player, then each
|
||||
@@ -884,34 +1059,12 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
// An integrated server runs every player's commands at their own
|
||||
// permission level (`CommandSourceStack.permissions`).
|
||||
if host.hub.config.integrated {
|
||||
let Some(level) = host.hub.guest(conn).map(|g| g.permission) else {
|
||||
return;
|
||||
};
|
||||
let command = command.trim_start_matches('/').to_owned();
|
||||
let lines = self.as_guest(host, conn, |g| {
|
||||
let console = std::mem::replace(&mut g.ui.registries.permission, level);
|
||||
g.chat_capture = Some(Vec::new());
|
||||
g.run_command(&command);
|
||||
g.ui.registries.permission = console;
|
||||
g.chat_capture.take().unwrap_or_default()
|
||||
});
|
||||
for line in lines.unwrap_or_default() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content: horizon_client::lan::data::component_nbt(&line.component()),
|
||||
overlay: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A LAN world follows its Allow Commands; a dedicated server leaves
|
||||
// it to the ops list (the guest's permission level).
|
||||
// permission level (`CommandSourceStack.permissions`); a LAN world
|
||||
// follows its Allow Commands, and a dedicated server leaves it to
|
||||
// the ops list (the guest's permission level).
|
||||
let integrated = host.hub.config.integrated;
|
||||
let allowed = self.options.dedicated.is_some() || self.allow_commands();
|
||||
if !host.settings.guest_commands || !allowed {
|
||||
if !integrated && (!host.settings.guest_commands || !allowed) {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
@@ -921,34 +1074,62 @@ impl Game<'_> {
|
||||
);
|
||||
return;
|
||||
}
|
||||
let command = command.trim_start_matches('/').to_owned();
|
||||
// The guest's own level (Commands.performCommand with the player's source): an
|
||||
// operator's on a dedicated server, never the host's.
|
||||
let permission = host.hub.guest(conn).map_or(0, |g| g.permission);
|
||||
let lines = self.as_guest(host, conn, |g| {
|
||||
g.chat_capture = Some(Vec::new());
|
||||
let level = std::mem::replace(&mut g.ui.registries.permission, permission);
|
||||
g.run_command(&command);
|
||||
g.ui.registries.permission = level;
|
||||
g.chat_capture
|
||||
.take()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|t| horizon_client::lan::data::component_nbt(&t.component()))
|
||||
.collect::<Vec<_>>()
|
||||
// The guest's own level (Commands.performCommand with the player's
|
||||
// source): an operator's on a dedicated server, never the host's.
|
||||
let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else {
|
||||
return;
|
||||
};
|
||||
host.commands.push(GuestCommand {
|
||||
conn,
|
||||
command: command.trim_start_matches('/').to_owned(),
|
||||
permission,
|
||||
integrated,
|
||||
});
|
||||
// A teleport into another level happens before its feedback is sent.
|
||||
self.run_level_teleports(host);
|
||||
for content in lines.unwrap_or_default() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content,
|
||||
overlay: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// The guests' queued commands, run with the hub in `self.lan` so that
|
||||
/// they reach the other players too (`/give Bob`, `/tp Bob`, `/kick`).
|
||||
pub(super) fn run_guest_commands(&mut self) {
|
||||
loop {
|
||||
let Some(host) = self.lan.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if host.commands.is_empty() {
|
||||
return;
|
||||
}
|
||||
let c = host.commands.remove(0);
|
||||
let mut host = self.lan.take().expect("checked above");
|
||||
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
|
||||
self.lan = Some(host);
|
||||
continue;
|
||||
};
|
||||
self.lan = Some(host);
|
||||
self.chat_capture = Some(Vec::new());
|
||||
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
|
||||
self.run_command(&c.command);
|
||||
self.ui.registries.permission = level;
|
||||
let lines = self.chat_capture.take().unwrap_or_default();
|
||||
let mut host = self.lan.take().expect("a command puts the hub back");
|
||||
self.leave_guest(&mut host, swap);
|
||||
host.hub.sync_all_effects();
|
||||
if !c.integrated {
|
||||
// A teleport into another level happens before its feedback is sent.
|
||||
self.run_level_teleports(&mut host);
|
||||
}
|
||||
for line in lines {
|
||||
host.hub.send_to(
|
||||
c.conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content: horizon_client::lan::data::component_nbt(&line.component()),
|
||||
overlay: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if !c.integrated {
|
||||
self.send_admin_feedback(&mut host, Some(c.conn));
|
||||
}
|
||||
self.lan = Some(host);
|
||||
}
|
||||
self.send_admin_feedback(host, Some(conn));
|
||||
}
|
||||
|
||||
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
|
||||
@@ -1149,6 +1330,7 @@ impl Game<'_> {
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.count_tick_stats(sleeping);
|
||||
g.tick_advancements();
|
||||
g.update_player_attributes();
|
||||
});
|
||||
host.hub.flush_progress(conn);
|
||||
self.guest_dig_feedback(host, conn);
|
||||
@@ -1165,7 +1347,34 @@ impl Game<'_> {
|
||||
total: g.xp_total,
|
||||
}
|
||||
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
|
||||
let message = literal(&format!("{} died", g.name));
|
||||
let (name, uuid) = (g.name.clone(), g.uuid);
|
||||
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
|
||||
let message = match cause {
|
||||
// ServerPlayer.die: the death message, to everyone unless
|
||||
// the player's team hides it.
|
||||
Some(key) if self.ui.rules.bool("show_death_messages") => {
|
||||
let text = horizon_client::text::Text::translate(
|
||||
&key,
|
||||
&[self.player_text(&name, uuid)],
|
||||
);
|
||||
let message = horizon_client::lan::data::component_nbt(&text.component());
|
||||
let team = self.score.board.players_team(&name);
|
||||
if horizon_client::scoreboard::own_death_message_shown(team) {
|
||||
host.hub.system_message(message.clone());
|
||||
if self.options.dedicated.is_some() {
|
||||
super::dedicated::log(
|
||||
"INFO",
|
||||
&format!("System chat: {}", text.plain()),
|
||||
);
|
||||
} else if self.player.is_some() {
|
||||
self.system_message(text);
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
Some(_) => literal(""),
|
||||
None => literal(&format!("{name} died")),
|
||||
};
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
//! The attribute instances a server syncs for the living entities it tracks
|
||||
//! (`ClientboundUpdateAttributesPacket`, lan/attributes.rs): the ones
|
||||
//! vanilla's `AttributeMap` would have created by then, since only those are
|
||||
//! sent, never the type's other defaults.
|
||||
use super::Game;
|
||||
use super::commands::Target;
|
||||
use horizon_client::{
|
||||
effects,
|
||||
lan::attributes::{add_modifier, generic_syncable, instance, operation_named},
|
||||
mobs::{
|
||||
Mob,
|
||||
finalize::{self, Attr, Op},
|
||||
},
|
||||
};
|
||||
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// `EquipmentSlotGroup.test`: whether a modifier's slot group covers a slot.
|
||||
fn slot_in_group(group: &str, slot: &str) -> bool {
|
||||
group == slot
|
||||
|| group == "any"
|
||||
|| (group == "hand" && matches!(slot, "mainhand" | "offhand"))
|
||||
|| (group == "armor" && matches!(slot, "feet" | "legs" | "chest" | "head" | "body"))
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The registry id of a client-syncable attribute the entity type has
|
||||
/// (`AttributeMap.getInstance` is null for the others), by name.
|
||||
fn synced_attribute(&self, entity: &str, name: &str) -> Option<i32> {
|
||||
let catalog = &self.motion.attributes;
|
||||
let id = catalog.id(name)?;
|
||||
(catalog.attribute(id).syncable && catalog.default_base(entity, id).is_some())
|
||||
.then(|| id.registry_id())
|
||||
}
|
||||
|
||||
/// The type's base value of an attribute, as the instance starts.
|
||||
fn attribute_default(&self, entity: &str, name: &str) -> f64 {
|
||||
let catalog = &self.motion.attributes;
|
||||
catalog
|
||||
.id(name)
|
||||
.and_then(|id| catalog.default_base(entity, id))
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// `LivingEntity.collectEquipmentChanges`: each worn or held item's
|
||||
/// attribute modifiers, slot by slot in `EquipmentSlot` order, create
|
||||
/// their instances (an instance without a modifier keeps its base).
|
||||
fn equipment_attributes<'a>(
|
||||
&self,
|
||||
entity: &str,
|
||||
base: impl Fn(&str) -> Option<f64>,
|
||||
slots: impl IntoIterator<Item = (&'static str, Option<&'a Arc<str>>)>,
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
) {
|
||||
for (slot, item) in slots {
|
||||
let Some(info) = item.and_then(|i| self.res.items().get(i)) else {
|
||||
continue;
|
||||
};
|
||||
for (attribute, id, amount, op, group) in &info.modifiers {
|
||||
if !slot_in_group(group, slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(a) = self.synced_attribute(entity, attribute) else {
|
||||
continue;
|
||||
};
|
||||
let start =
|
||||
base(attribute).unwrap_or_else(|| self.attribute_default(entity, attribute));
|
||||
add_modifier(
|
||||
out,
|
||||
a,
|
||||
start,
|
||||
AttributeModifier {
|
||||
id: id.clone(),
|
||||
amount: *amount,
|
||||
operation: operation_named(op),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mob's synced instances: movement speed (its first `aiStep` reads it,
|
||||
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
|
||||
/// modifier, its effects' modifiers, its equipment's, and what
|
||||
/// `/attribute` changed.
|
||||
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
|
||||
let kind = m.kind.id.as_str();
|
||||
let mut out = Vec::new();
|
||||
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
|
||||
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
|
||||
}
|
||||
if let Some(s) = m.extra.attributes.as_deref() {
|
||||
for (attr, v) in &s.bases {
|
||||
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
|
||||
{
|
||||
instance(&mut out, a, *v).base = *v;
|
||||
}
|
||||
}
|
||||
for x in &s.modifiers {
|
||||
if let Some(a) =
|
||||
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
|
||||
{
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
finalize::base_value(m, x.attr),
|
||||
AttributeModifier {
|
||||
id: x.id.to_owned(),
|
||||
amount: x.amount,
|
||||
operation: match x.op {
|
||||
Op::AddValue => 0,
|
||||
Op::AddMultipliedBase => 1,
|
||||
Op::AddMultipliedTotal => 2,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(a), Some((amount, Op::AddMultipliedBase))) = (
|
||||
self.synced_attribute(kind, "minecraft:movement_speed"),
|
||||
finalize::transient(m, Attr::MovementSpeed),
|
||||
) {
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
finalize::base_value(m, Attr::MovementSpeed),
|
||||
AttributeModifier {
|
||||
id: "minecraft:baby".into(),
|
||||
amount,
|
||||
operation: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
let base = |name: &str| {
|
||||
Attr::ALL
|
||||
.into_iter()
|
||||
.find(|a| name.strip_prefix("minecraft:") == Some(a.name()))
|
||||
.map(|a| finalize::base_value(m, a))
|
||||
};
|
||||
// LivingEntity.onEffectAdded: MobEffect.addAttributeModifiers.
|
||||
for &(effect, _, amplifier) in &m.extra.effects {
|
||||
let Some((attribute, id, amount, op)) =
|
||||
effects::effect_modifier(effect.trim_start_matches("minecraft:"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(a) = self.synced_attribute(kind, attribute) else {
|
||||
continue;
|
||||
};
|
||||
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
|
||||
add_modifier(
|
||||
&mut out,
|
||||
a,
|
||||
start,
|
||||
AttributeModifier {
|
||||
id: id.to_owned(),
|
||||
amount: amount * f64::from(amplifier + 1),
|
||||
operation: operation_named(op),
|
||||
},
|
||||
);
|
||||
}
|
||||
let e = &m.extra;
|
||||
self.equipment_attributes(
|
||||
kind,
|
||||
base,
|
||||
[
|
||||
("mainhand", e.main_hand.as_ref()),
|
||||
("offhand", e.off_hand.as_ref()),
|
||||
("feet", e.feet.as_ref()),
|
||||
("legs", e.legs.as_ref()),
|
||||
("chest", e.chest.as_ref()),
|
||||
("head", e.head.as_ref()),
|
||||
],
|
||||
&mut out,
|
||||
);
|
||||
self.generic_attributes_of(Target::Mob(m.id), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// An armor stand's synced instances: movement speed (its first
|
||||
/// `aiStep`), its equipment's modifiers and what `/attribute` changed.
|
||||
pub(super) fn stand_attributes(
|
||||
&self,
|
||||
id: u32,
|
||||
equipment: &[Option<horizon_client::items::ItemStack>; 6],
|
||||
) -> Vec<AttributeSnapshot> {
|
||||
const KIND: &str = "minecraft:armor_stand";
|
||||
let mut out = Vec::new();
|
||||
if let Some(a) = self.synced_attribute(KIND, "minecraft:movement_speed") {
|
||||
instance(
|
||||
&mut out,
|
||||
a,
|
||||
self.attribute_default(KIND, "minecraft:movement_speed"),
|
||||
);
|
||||
}
|
||||
let slots = horizon_client::entities::ArmorStand::SLOTS
|
||||
.into_iter()
|
||||
.zip(equipment.iter().map(|s| s.as_ref().map(|s| &s.item)));
|
||||
self.equipment_attributes(KIND, |_| None, slots, &mut out);
|
||||
self.generic_attributes_of(Target::Stand(id), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances a server player's tick creates, and
|
||||
/// `ServerPlayer.updatePlayerAttributes`: a creative player reaches 0.5
|
||||
/// further to blocks and 2 to entities. Its client reads the reach from
|
||||
/// these synced modifiers. (The crouching player's waypoint range is
|
||||
/// server-side only: lan_waypoints.rs hides it.)
|
||||
pub(super) fn update_player_attributes(&mut self) {
|
||||
let creative = self.mode_id() == 1;
|
||||
let Some(p) = self.player.as_mut() else {
|
||||
return;
|
||||
};
|
||||
// LivingEntity.aiStep's removeFrost reads the movement speed instance
|
||||
// every tick, which creates it (and its first sync).
|
||||
if let Some(key) = p.attributes.key("minecraft:movement_speed") {
|
||||
let _ = p.attributes.get_instance(Some(key));
|
||||
}
|
||||
for (attribute, id, amount) in [
|
||||
(
|
||||
"minecraft:block_interaction_range",
|
||||
"minecraft:creative_mode_block_range",
|
||||
0.5,
|
||||
),
|
||||
(
|
||||
"minecraft:entity_interaction_range",
|
||||
"minecraft:creative_mode_entity_range",
|
||||
2.0,
|
||||
),
|
||||
] {
|
||||
let Some(key) = p.attributes.key(attribute) else {
|
||||
continue;
|
||||
};
|
||||
// getAttribute creates the instance, a creative player's or not.
|
||||
if !matches!(p.attributes.get_instance(Some(key.clone())), Ok(Some(_))) {
|
||||
continue;
|
||||
}
|
||||
// addOrUpdateTransientModifier with the same modifier and
|
||||
// removeModifier of a missing one leave the instance clean.
|
||||
let has = p.attributes.has_modifier(Some(key), id).unwrap_or(false);
|
||||
if has != creative {
|
||||
let _ = p.set_modifier(attribute, id, amount, "add_value", creative);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The instances `/attribute` created in an entity's generic map
|
||||
/// replace the ones derived from its state.
|
||||
fn generic_attributes_of(&self, t: Target, out: &mut Vec<AttributeSnapshot>) {
|
||||
let Some(map) = self.cmds.attributes.get(&t) else {
|
||||
return;
|
||||
};
|
||||
for s in generic_syncable(map) {
|
||||
let (attribute, base) = (s.attribute, s.base);
|
||||
*instance(out, attribute, base) = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::slot_in_group;
|
||||
|
||||
#[test]
|
||||
fn slot_groups_cover_their_slots() {
|
||||
assert!(slot_in_group("head", "head"));
|
||||
assert!(slot_in_group("armor", "chest"));
|
||||
assert!(!slot_in_group("armor", "mainhand"));
|
||||
assert!(slot_in_group("hand", "offhand"));
|
||||
assert!(slot_in_group("any", "feet"));
|
||||
assert!(!slot_in_group("mainhand", "offhand"));
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -179,6 +180,7 @@ impl Game<'_> {
|
||||
e.equipment.push((slot as u8, hub.stack(item)));
|
||||
}
|
||||
}
|
||||
e.attributes = self.stand_attributes(a.id, &a.equipment);
|
||||
out.push(e);
|
||||
}
|
||||
for f in &self.item_frames {
|
||||
|
||||
@@ -125,6 +125,8 @@ pub(super) struct Remote {
|
||||
health: (f32, i32, f32),
|
||||
game_mode: i32,
|
||||
pub chat: Vec<(String, Instant)>,
|
||||
/// Lines received since joining, for the control socket's events.
|
||||
pub chat_received: u64,
|
||||
/// The server's command tree (ClientboundCommandsPacket).
|
||||
pub commands: Option<horizon_client::command::Dispatcher>,
|
||||
players: HashMap<u128, String>,
|
||||
@@ -321,6 +323,7 @@ impl Game<'_> {
|
||||
health: (20.0, 20, 5.0),
|
||||
game_mode: 0,
|
||||
chat: Vec::new(),
|
||||
chat_received: 0,
|
||||
commands: None,
|
||||
players: HashMap::new(),
|
||||
tab_players: HashMap::new(),
|
||||
@@ -494,6 +497,7 @@ impl Game<'_> {
|
||||
log::info!("[chat] {text}");
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.chat.push((text, Instant::now()));
|
||||
r.chat_received += 1;
|
||||
if r.chat.len() > 100 {
|
||||
r.chat.remove(0);
|
||||
}
|
||||
@@ -1500,6 +1504,20 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Entity.DATA_SHARED_FLAGS_ID's crouching bit: another
|
||||
// player's crouch (their model and Entity.isDiscrete's name tag).
|
||||
if self
|
||||
.remote
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.level_players.contains_key(&p.id))
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
{
|
||||
for (index, _, value) in &p.values {
|
||||
if let (0, Value::Byte(flags)) = (index, value) {
|
||||
m.extra.crouching = flags & 2 != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, _, value) in &p.values {
|
||||
if *index == ITEM_ENTITY_ITEM
|
||||
&& let Value::Item(stack) = value
|
||||
@@ -3770,6 +3788,13 @@ impl Game<'_> {
|
||||
.filter(|t| t.kind == "minecraft:player")
|
||||
.map(|t| t.position)
|
||||
.collect::<Vec<_>>(),
|
||||
// The other players this client draws dead (lying down, after EntityEvent DEATH).
|
||||
"dead_players": self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive())
|
||||
.map(|m| m.id)
|
||||
.collect::<Vec<_>>(),
|
||||
// The player's own model exists (third person and the inventory draw it).
|
||||
"player_model": self.player_model.is_some(),
|
||||
"health": r.health.0,
|
||||
|
||||
@@ -131,6 +131,7 @@ impl Game<'_> {
|
||||
pub(super) fn holder_name(&mut self, t: Target) -> Option<String> {
|
||||
match t {
|
||||
Target::Player => Some(self.acting_player_name().to_owned()),
|
||||
Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()),
|
||||
Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))),
|
||||
_ => None,
|
||||
}
|
||||
@@ -179,7 +180,7 @@ impl Game<'_> {
|
||||
| Target::Cart(id)
|
||||
| Target::Other(id) => self.persist.raw.get(&id),
|
||||
Target::Player => self.level.player_extra.as_ref(),
|
||||
Target::Orb(_) | Target::Arrow(_) => None,
|
||||
Target::Guest(_) | Target::Orb(_) | Target::Arrow(_) => None,
|
||||
};
|
||||
match raw.and_then(|r| r.get("Tags")) {
|
||||
Some(Tag::List(l)) => l
|
||||
|
||||
@@ -288,6 +288,11 @@ impl Game<'_> {
|
||||
if hit == Some(0) && self.remote.is_none() {
|
||||
let keep = self.ui.rules.bool("keep_inventory") || self.spectator();
|
||||
self.experience.respawn(keep);
|
||||
// The guests are sent the respawned host as a new entity, not the dead body.
|
||||
if let Some(host) = self.lan.as_mut() {
|
||||
let id = host.host_entity;
|
||||
host.hub.respawned(id);
|
||||
}
|
||||
// Autosaves keep a login position; death must resolve the respawn point instead.
|
||||
self.level.position = None;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! `ClientboundUpdateAttributesPacket`: the attribute instances a server syncs
|
||||
//! to its clients. `ServerEntity.sendPairingData` sends every client-syncable
|
||||
//! instance an entity has (`AttributeMap.getSyncableAttributes`: the instances
|
||||
//! created so far, not the type's defaults), `sendDirtyEntityData` the ones
|
||||
//! changed since (`getAttributesToSync`), to the trackers and the player itself.
|
||||
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
|
||||
use horizon_world::attributes::{
|
||||
Instance, Operation,
|
||||
entity::{AttributeId, EntityAttributes},
|
||||
live::LiveAttributes,
|
||||
};
|
||||
|
||||
/// `AttributeModifier.Operation.id`.
|
||||
pub fn operation_id(op: Operation) -> i32 {
|
||||
match op {
|
||||
Operation::AddValue => 0,
|
||||
Operation::AddMultipliedBase => 1,
|
||||
Operation::AddMultipliedTotal => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// An `Operation`'s serialized name (`add_value` ...) as its id.
|
||||
pub fn operation_named(name: &str) -> i32 {
|
||||
match name {
|
||||
"add_multiplied_base" => 1,
|
||||
"add_multiplied_total" => 2,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `AttributeSnapshot`: the base and every modifier, in the order they were added.
|
||||
pub fn snapshot(attribute: AttributeId, instance: &Instance) -> AttributeSnapshot {
|
||||
AttributeSnapshot {
|
||||
attribute: attribute.registry_id(),
|
||||
base: instance.base_value(),
|
||||
modifiers: instance
|
||||
.modifiers()
|
||||
.iter()
|
||||
.map(|m| AttributeModifier {
|
||||
id: m.id().to_owned(),
|
||||
amount: m.amount(),
|
||||
operation: operation_id(m.operation()),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `AttributeMap.getSyncableAttributes` of a live map (a player's).
|
||||
pub fn syncable<G: FnMut() -> i32>(map: &LiveAttributes<G>) -> Vec<AttributeSnapshot> {
|
||||
let catalog = map.catalog();
|
||||
map.instances()
|
||||
.filter(|(_, key, _)| catalog.attribute(key.attribute()).syncable)
|
||||
.map(|(_, key, instance)| snapshot(key.attribute(), instance))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `getAttributesToSync`, cleared once read (`ServerEntity.sendDirtyEntityData`).
|
||||
pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<AttributeSnapshot> {
|
||||
if map.sync().is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let handles: Vec<_> = map.sync().values().flatten().cloned().collect();
|
||||
map.sync_mut().clear();
|
||||
handles
|
||||
.iter()
|
||||
.filter_map(|h| {
|
||||
let key = map.attribute(h).ok()?;
|
||||
Some(snapshot(key.attribute(), map.instance(h).ok()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The client-syncable instances of a generic attribute map.
|
||||
pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ {
|
||||
let catalog = map.catalog();
|
||||
catalog
|
||||
.attributes()
|
||||
.filter(|(_, a)| a.syncable)
|
||||
.filter_map(move |(id, _)| map.instance(id).map(|i| snapshot(id, i)))
|
||||
}
|
||||
|
||||
/// Adds a modifier to the snapshot of `attribute`, creating it with `base`.
|
||||
pub fn add_modifier(
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
attribute: i32,
|
||||
base: f64,
|
||||
modifier: AttributeModifier,
|
||||
) {
|
||||
let snapshot = instance(out, attribute, base);
|
||||
match snapshot.modifiers.iter_mut().find(|m| m.id == modifier.id) {
|
||||
Some(m) => *m = modifier,
|
||||
None => snapshot.modifiers.push(modifier),
|
||||
}
|
||||
}
|
||||
|
||||
/// The snapshot of `attribute`, created with `base` if it isn't there yet.
|
||||
pub fn instance(
|
||||
out: &mut Vec<AttributeSnapshot>,
|
||||
attribute: i32,
|
||||
base: f64,
|
||||
) -> &mut AttributeSnapshot {
|
||||
let i = match out.iter().position(|a| a.attribute == attribute) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
out.push(AttributeSnapshot {
|
||||
attribute,
|
||||
base,
|
||||
modifiers: Vec::new(),
|
||||
});
|
||||
out.len() - 1
|
||||
}
|
||||
};
|
||||
&mut out[i]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn modifiers_replace_by_id_and_instances_are_created_once() {
|
||||
let mut out = Vec::new();
|
||||
let m = |id: &str, amount| AttributeModifier {
|
||||
id: id.into(),
|
||||
amount,
|
||||
operation: 0,
|
||||
};
|
||||
add_modifier(&mut out, 1, 0.0, m("minecraft:armor.helmet", 3.0));
|
||||
add_modifier(&mut out, 1, 5.0, m("minecraft:armor.chestplate", 8.0));
|
||||
add_modifier(&mut out, 1, 5.0, m("minecraft:armor.helmet", 2.0));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].base, 0.0);
|
||||
assert_eq!(
|
||||
out[0].modifiers,
|
||||
[
|
||||
m("minecraft:armor.helmet", 2.0),
|
||||
m("minecraft:armor.chestplate", 8.0)
|
||||
]
|
||||
);
|
||||
instance(&mut out, 26, 0.7);
|
||||
assert_eq!(out.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -8,15 +8,31 @@
|
||||
use super::tracking;
|
||||
use horizon_protocol::{
|
||||
buf::pack_degrees,
|
||||
entity_data::Value,
|
||||
entity_data::{Value, serializer},
|
||||
item::Stack,
|
||||
packets::play::{
|
||||
self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot,
|
||||
MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment,
|
||||
SetPassengers, VecDelta,
|
||||
self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos,
|
||||
MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion,
|
||||
SetEquipment, SetPassengers, UpdateAttributes, VecDelta,
|
||||
},
|
||||
};
|
||||
|
||||
/// The attribute instances of `now` that differ from what `sent` held (an
|
||||
/// instance is never removed: one that disappears is left as it was sent).
|
||||
pub fn changed_attributes(
|
||||
now: &[AttributeSnapshot],
|
||||
sent: &[AttributeSnapshot],
|
||||
) -> Vec<AttributeSnapshot> {
|
||||
now.iter()
|
||||
.filter(|a| {
|
||||
sent.iter()
|
||||
.find(|b| b.attribute == a.attribute)
|
||||
.is_none_or(|b| b != *a)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the game says about one entity this tick.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EntityState {
|
||||
@@ -37,6 +53,9 @@ pub struct EntityState {
|
||||
/// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs,
|
||||
/// 4 chest, 5 head, 6 body, 7 saddle) and their stacks.
|
||||
pub equipment: Vec<(u8, Option<Stack>)>,
|
||||
/// A living entity's client-syncable attribute instances
|
||||
/// (`AttributeMap.getSyncableAttributes`), by registry id.
|
||||
pub attributes: Vec<AttributeSnapshot>,
|
||||
/// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks
|
||||
/// touching a block): moves are sent as full position syncs.
|
||||
pub precise: bool,
|
||||
@@ -117,6 +136,8 @@ struct ServerEntity {
|
||||
/// trackedDataValues: the entity data the clients hold.
|
||||
meta: Vec<(u8, i32, Value)>,
|
||||
equipment: Vec<(u8, Option<Stack>)>,
|
||||
/// The attribute instances the clients hold.
|
||||
attributes: Vec<AttributeSnapshot>,
|
||||
was_on_ground: bool,
|
||||
tick: u32,
|
||||
teleport_delay: u32,
|
||||
@@ -153,6 +174,7 @@ impl ServerEntity {
|
||||
velocity: e.velocity,
|
||||
meta: e.meta.clone(),
|
||||
equipment: e.equipment.clone(),
|
||||
attributes: e.attributes.clone(),
|
||||
was_on_ground: e.on_ground,
|
||||
tick: 0,
|
||||
teleport_delay: 0,
|
||||
@@ -190,6 +212,13 @@ impl ServerEntity {
|
||||
values: self.meta.clone(),
|
||||
}));
|
||||
}
|
||||
// getSyncableAttributes: the instances as they are now.
|
||||
if !e.attributes.is_empty() {
|
||||
out.push(play::Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: e.id,
|
||||
values: e.attributes.clone(),
|
||||
}));
|
||||
}
|
||||
if !self.equipment.is_empty() {
|
||||
out.push(play::Clientbound::SetEquipment(SetEquipment {
|
||||
id: e.id,
|
||||
@@ -342,24 +371,48 @@ impl ServerEntity {
|
||||
self.send_equipment(e, out);
|
||||
}
|
||||
|
||||
/// ServerEntity.sendDirtyEntityData.
|
||||
/// ServerEntity.sendDirtyEntityData: the changed entity data, then the
|
||||
/// attribute instances that changed since they were last sent
|
||||
/// (`AttributeMap.getAttributesToSync`).
|
||||
fn send_dirty(&mut self, e: &EntityState, dirty: bool, out: &mut Vec<play::Clientbound>) {
|
||||
if !dirty {
|
||||
return;
|
||||
if dirty {
|
||||
let mut changed: Vec<_> = e
|
||||
.meta
|
||||
.iter()
|
||||
.filter(|m| !self.meta.contains(m))
|
||||
.cloned()
|
||||
.collect();
|
||||
// A value back at its default is left out of the state, but the
|
||||
// clients still hold the old one: Entity's shared flags and pose go
|
||||
// back to 0 (a player standing up again, a mob no longer on fire).
|
||||
for (index, kind, _) in &self.meta {
|
||||
let default = match (*index, *kind) {
|
||||
(0, serializer::BYTE) => Value::Byte(0),
|
||||
(6, serializer::POSE) => Value::Id(0),
|
||||
_ => continue,
|
||||
};
|
||||
if !e.meta.iter().any(|m| m.0 == *index) {
|
||||
changed.push((*index, *kind, default));
|
||||
}
|
||||
}
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::SetEntityData(SetEntityData {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
}
|
||||
self.meta.clone_from(&e.meta);
|
||||
}
|
||||
let changed: Vec<_> = e
|
||||
.meta
|
||||
.iter()
|
||||
.filter(|m| !self.meta.contains(m))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::SetEntityData(SetEntityData {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
if e.attributes != self.attributes {
|
||||
let changed = changed_attributes(&e.attributes, &self.attributes);
|
||||
if !changed.is_empty() {
|
||||
out.push(play::Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: e.id,
|
||||
values: changed,
|
||||
}));
|
||||
}
|
||||
self.attributes.clone_from(&e.attributes);
|
||||
}
|
||||
self.meta.clone_from(&e.meta);
|
||||
}
|
||||
|
||||
fn send_head(&mut self, e: &EntityState, out: &mut Vec<play::Clientbound>) {
|
||||
@@ -416,6 +469,11 @@ impl Tracker {
|
||||
pub fn clear(&mut self) {
|
||||
self.seen.clear();
|
||||
}
|
||||
/// Stop tracking `id` without a packet: the caller removes it from the
|
||||
/// client, and the next tick pairs it again if it is still in range.
|
||||
pub fn forget(&mut self, id: i32) -> bool {
|
||||
self.seen.remove(&id)
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.seen.len()
|
||||
}
|
||||
@@ -645,6 +703,7 @@ mod tests {
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -741,6 +800,71 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_pair_whole_then_send_the_changed_instances_when_due() {
|
||||
let speed = |base| AttributeSnapshot {
|
||||
attribute: 26,
|
||||
base,
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let armor = AttributeSnapshot {
|
||||
attribute: 1,
|
||||
base: 0.0,
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let mut e = state(0.0);
|
||||
e.attributes = vec![speed(0.23), armor];
|
||||
let mut s = added(&e);
|
||||
let mut spawn = Vec::new();
|
||||
s.pairing(&e, 100, &Riding::default(), &mut spawn);
|
||||
let Some(play::Clientbound::UpdateAttributes(p)) = spawn.get(1) else {
|
||||
panic!("expected the attributes after the add");
|
||||
};
|
||||
assert_eq!(p.values, e.attributes);
|
||||
changes(&mut s, &e);
|
||||
e.attributes[0] = speed(0.3);
|
||||
// Not due (a zombie's interval is 3): sendDirtyEntityData waits for the update.
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
let out = changes(&mut s, &e);
|
||||
let Some(play::Clientbound::UpdateAttributes(p)) = out
|
||||
.iter()
|
||||
.find(|p| matches!(p, play::Clientbound::UpdateAttributes(_)))
|
||||
else {
|
||||
panic!("expected the changed attribute");
|
||||
};
|
||||
assert_eq!(p.values, vec![speed(0.3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleared_flags_and_pose_go_back_to_their_default() {
|
||||
let mut e = state(0.0);
|
||||
let mut s = added(&e);
|
||||
changes(&mut s, &e);
|
||||
// A crouching player: the crouch flag and the crouching pose.
|
||||
e.meta = vec![
|
||||
(0, serializer::BYTE, Value::Byte(2)),
|
||||
(6, serializer::POSE, Value::Id(5)),
|
||||
];
|
||||
changes(&mut s, &e);
|
||||
e.meta.clear();
|
||||
let data = changes(&mut s, &e)
|
||||
.into_iter()
|
||||
.find_map(|p| match p {
|
||||
play::Clientbound::SetEntityData(d) => Some(d),
|
||||
_ => None,
|
||||
})
|
||||
.expect("standing up is sent");
|
||||
assert_eq!(
|
||||
data.values,
|
||||
vec![
|
||||
(0, serializer::BYTE, Value::Byte(0)),
|
||||
(6, serializer::POSE, Value::Id(0)),
|
||||
]
|
||||
);
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_and_equipment_send_only_the_changes() {
|
||||
let mut e = state(0.0);
|
||||
@@ -902,4 +1026,28 @@ mod tests {
|
||||
assert!(!t.is_tracking(7) && t.is_tracking(8) && t.is_tracking(9));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forgotten_entity_is_paired_again_at_the_next_tick() {
|
||||
// A respawned player: the hub removes it from the other clients and
|
||||
// forgets it, and the next tick pairs it again as a new entity.
|
||||
let mut level = Entities::default();
|
||||
let mut c = Clients::new();
|
||||
let mut player = state(0.0);
|
||||
player.id = 1;
|
||||
player.kind = "minecraft:player".into();
|
||||
c.tick(&mut level, &[&player]);
|
||||
c.tick(&mut level, &[&player]);
|
||||
assert!(c.trackers[1].forget(1));
|
||||
assert!(!c.trackers[1].forget(1));
|
||||
c.tick(&mut level, &[&player]);
|
||||
assert!(c.trackers[1].is_tracking(1));
|
||||
let paired = c.out[1]
|
||||
.first()
|
||||
.and_then(|p| play::Clientbound::decode(i32::from(p[0]), &p[1..]).ok());
|
||||
assert!(
|
||||
matches!(paired, Some(play::Clientbound::AddEntity(ref a)) if a.id == 1),
|
||||
"{paired:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct HostState {
|
||||
pub sprinting: bool,
|
||||
pub equipment: [Option<ItemStack>; 6],
|
||||
pub health: f32,
|
||||
/// The host player's client-syncable attribute instances.
|
||||
pub attributes: Vec<play::AttributeSnapshot>,
|
||||
}
|
||||
|
||||
/// Everything the hub needs from the game for one tick.
|
||||
@@ -686,6 +688,16 @@ impl Hub {
|
||||
/// onEffectsRemoved, from what changed since the client was told: an
|
||||
/// effect that only counted down is not sent again, except at every
|
||||
/// 600 ticks left (`LivingEntity.tickEffects`).
|
||||
/// `sync_effects` for every player at once: what a command changed
|
||||
/// leaves with its feedback (ServerPlayer.onEffectAdded sends at once),
|
||||
/// not after the tick's countdown.
|
||||
pub fn sync_all_effects(&mut self) {
|
||||
for i in 0..self.guests.len() {
|
||||
if self.guests[i].placed {
|
||||
self.sync_effects(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn sync_effects(&mut self, i: usize) {
|
||||
let g = &self.guests[i];
|
||||
if g.effects.list.is_empty() && g.sent_effects.is_empty() {
|
||||
@@ -1382,6 +1394,7 @@ impl Hub {
|
||||
skin: u8,
|
||||
health: f32,
|
||||
equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>,
|
||||
attributes: Vec<play::AttributeSnapshot>,
|
||||
) -> EntityState {
|
||||
let (sneaking, sprinting, gliding, sleeping) = flags;
|
||||
let mut shared = 0i8;
|
||||
@@ -1429,6 +1442,7 @@ impl Hub {
|
||||
data: 0,
|
||||
meta,
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
}
|
||||
}
|
||||
@@ -1476,6 +1490,7 @@ impl Hub {
|
||||
0x7F,
|
||||
h.health,
|
||||
equipment,
|
||||
h.attributes.clone(),
|
||||
));
|
||||
}
|
||||
let placed: Vec<usize> = (0..self.guests.len())
|
||||
@@ -1505,6 +1520,10 @@ impl Hub {
|
||||
g.info.model_customisation,
|
||||
g.health,
|
||||
equipment,
|
||||
g.motion
|
||||
.as_ref()
|
||||
.map(|m| super::attributes::syncable(&m.attributes))
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -1615,6 +1634,19 @@ impl Hub {
|
||||
self.flush_advancements(i, true);
|
||||
}
|
||||
}
|
||||
// ServerEntity.sendDirtyEntityData: the player's changed attribute
|
||||
// instances go to the player too (its trackers get them from
|
||||
// track_entities).
|
||||
let g = &mut self.guests[i];
|
||||
if let Some(m) = g.motion.as_mut() {
|
||||
let values = super::attributes::take_dirty(&mut m.attributes);
|
||||
if !values.is_empty() {
|
||||
g.send(&C::UpdateAttributes(play::UpdateAttributes {
|
||||
id: g.entity_id,
|
||||
values,
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Sent when the health or the food level changes, or the saturation
|
||||
// reaches or leaves zero; a dead player's health of 0 too.
|
||||
let g = &mut self.guests[i];
|
||||
@@ -2112,6 +2144,18 @@ impl Hub {
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// ServerLevel.removePlayerImmediately, then addRespawnedPlayer: the other players
|
||||
/// lose the dead player's entity (ServerEntity.removePairing) and are sent the
|
||||
/// respawned one as a new entity at the next tick. Their clients would otherwise keep
|
||||
/// the dead body, lying down, wherever the player goes.
|
||||
pub fn respawned(&mut self, id: i32) {
|
||||
for g in &mut self.guests {
|
||||
if g.entity_id != id && g.tracker.forget(id) {
|
||||
g.send(&C::RemoveEntities(play::RemoveEntities { ids: vec![id] }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PlayerList.respawn: back to `at` with a fresh start. The vanilla client waits on its
|
||||
/// level loading screen from the Respawn packet until the level info's "level chunks load
|
||||
/// start" event and the chunk under the player, so the packets follow vanilla's order.
|
||||
@@ -2138,6 +2182,9 @@ impl Hub {
|
||||
g.tracker.clear();
|
||||
g.sent_chunks.clear();
|
||||
g.chunk_queue.clear();
|
||||
let id = g.entity_id;
|
||||
self.respawned(id);
|
||||
let g = &mut self.guests[i];
|
||||
// ServerPlayer.restoreFrom: the game mode again (onUpdateAbilities).
|
||||
g.send(&C::PlayerAbilities(play::PlayerAbilities {
|
||||
flags: g.ability_flags(),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! ever exchanges decoded packets with these threads through channels, so a
|
||||
//! world that is not open to the network pays nothing.
|
||||
mod advancements;
|
||||
pub mod attributes;
|
||||
pub mod chunks;
|
||||
mod command_order;
|
||||
pub mod command_suggestions;
|
||||
|
||||
@@ -47,14 +47,24 @@ pub fn register(m: &mut Mob) {
|
||||
m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI);
|
||||
set_size(m, 1);
|
||||
}
|
||||
/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size.
|
||||
/// AbstractCubeMob.setSize(size, true): the max health (size^2), movement
|
||||
/// speed (0.2 + 0.1 * size, in floats) and attack damage (size) bases, a
|
||||
/// magma cube's armor (size * 3), then the health back to the max.
|
||||
pub fn set_size(m: &mut Mob, size: i32) {
|
||||
use super::finalize::{Attr, set_base};
|
||||
let size = size.clamp(1, 127);
|
||||
m.extra.size = size;
|
||||
m.attrs.max_health = (size * size) as f32;
|
||||
m.attrs.speed = 0.2 + 0.1 * f64::from(size);
|
||||
m.attrs.attack_damage = size as f32;
|
||||
m.health = m.attrs.max_health;
|
||||
set_base(m, Attr::MaxHealth, f64::from(size * size));
|
||||
set_base(
|
||||
m,
|
||||
Attr::MovementSpeed,
|
||||
f64::from(0.2f32 + 0.1f32 * size as f32),
|
||||
);
|
||||
set_base(m, Attr::AttackDamage, f64::from(size));
|
||||
if m.species() == super::Species::MagmaCube {
|
||||
set_base(m, Attr::Armor, f64::from(size * 3));
|
||||
}
|
||||
m.health = super::finalize::max_health(m);
|
||||
}
|
||||
/// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0).
|
||||
pub fn finalize(m: &mut Mob) {
|
||||
|
||||
@@ -483,7 +483,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 {
|
||||
.unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 })
|
||||
}
|
||||
/// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`).
|
||||
fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> {
|
||||
pub fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> {
|
||||
if a != Attr::MovementSpeed || !m.is_baby() {
|
||||
return None;
|
||||
}
|
||||
@@ -1961,19 +1961,7 @@ fn sulfur_size(m: &mut Mob, size: i32) {
|
||||
m.health = max_health(m);
|
||||
}
|
||||
fn cube_size(m: &mut Mob, size: i32) {
|
||||
let size = size.clamp(1, 127);
|
||||
m.extra.size = size;
|
||||
set_base(m, Attr::MaxHealth, f64::from(size * size));
|
||||
set_base(
|
||||
m,
|
||||
Attr::MovementSpeed,
|
||||
f64::from(0.2f32 + 0.1f32 * size as f32),
|
||||
);
|
||||
set_base(m, Attr::AttackDamage, f64::from(size));
|
||||
if m.species() == Species::MagmaCube {
|
||||
set_base(m, Attr::Armor, f64::from(size * 3));
|
||||
}
|
||||
m.health = max_health(m);
|
||||
super::cube::set_size(m, size);
|
||||
}
|
||||
/// The index the game keeps for a variant registry entry.
|
||||
pub fn variant_index(s: Species, name: &str) -> u8 {
|
||||
|
||||
@@ -279,6 +279,12 @@ impl Text {
|
||||
self.source = Some(c.into());
|
||||
self
|
||||
}
|
||||
/// The same spans, sent to vanilla as `component` (a shape the spans'
|
||||
/// own JSON would not take, such as a styled root with siblings).
|
||||
pub fn with_component(mut self, component: Value) -> Self {
|
||||
self.source = Some(component.into());
|
||||
self
|
||||
}
|
||||
pub fn with_color(self, color: u32) -> Self {
|
||||
self.with_style(&Style::color(color))
|
||||
}
|
||||
|
||||
@@ -181,6 +181,7 @@ impl Server {
|
||||
sprinting: false,
|
||||
equipment: Default::default(),
|
||||
health: 20.0,
|
||||
attributes: Vec::new(),
|
||||
};
|
||||
let mut ctx = TickCtx {
|
||||
world: &mut self.world,
|
||||
@@ -422,6 +423,7 @@ fn guests_see_each_other_and_the_world_entities() {
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
};
|
||||
let first = thread::spawn(move || {
|
||||
|
||||
@@ -881,6 +881,24 @@ packet!(
|
||||
UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte }
|
||||
);
|
||||
packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt });
|
||||
packet!(
|
||||
/// AttributeModifier.STREAM_CODEC: id, amount and operation (0 add_value,
|
||||
/// 1 add_multiplied_base, 2 add_multiplied_total).
|
||||
AttributeModifier { id: String => Ident, amount: f64 => Double, operation: i32 => VarInt }
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundUpdateAttributesPacket.AttributeSnapshot: the attribute's
|
||||
/// registry id, its base value and every modifier.
|
||||
AttributeSnapshot {
|
||||
attribute: i32 => VarInt,
|
||||
base: f64 => Double,
|
||||
modifiers: Vec<AttributeModifier> => List<AttributeModifier>,
|
||||
}
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundUpdateAttributesPacket: an entity's synced attribute instances.
|
||||
UpdateAttributes { id: i32 => VarInt, values: Vec<AttributeSnapshot> => List<AttributeSnapshot> }
|
||||
);
|
||||
packet!(
|
||||
/// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing
|
||||
/// type (0 none, 1 whack, 2 stab) with its duration in ticks.
|
||||
@@ -1455,6 +1473,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
TickingState(TickingState) = TICKING_STATE,
|
||||
TickingStep(TickingStep) = TICKING_STEP,
|
||||
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
|
||||
UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES,
|
||||
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
|
||||
UpdateTags(UpdateTags) = UPDATE_TAGS,
|
||||
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
|
||||
@@ -2110,6 +2129,18 @@ mod tests {
|
||||
id: 2,
|
||||
slots: vec![(0, None), (5, Some(Stack::new(1, 1)))],
|
||||
}),
|
||||
Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: 2,
|
||||
values: vec![AttributeSnapshot {
|
||||
attribute: 26,
|
||||
base: 0.23,
|
||||
modifiers: vec![AttributeModifier {
|
||||
id: "minecraft:baby".into(),
|
||||
amount: 0.5,
|
||||
operation: 1,
|
||||
}],
|
||||
}],
|
||||
}),
|
||||
Clientbound::SetHealth(SetHealth {
|
||||
health: 17.5,
|
||||
food: 18,
|
||||
@@ -2347,4 +2378,31 @@ mod tests {
|
||||
);
|
||||
assert_eq!(p.encode()[1..], [1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_attributes_encode_like_vanilla() {
|
||||
let p = Clientbound::UpdateAttributes(UpdateAttributes {
|
||||
id: 5,
|
||||
values: vec![AttributeSnapshot {
|
||||
attribute: 1,
|
||||
base: 0.0,
|
||||
modifiers: vec![AttributeModifier {
|
||||
id: "minecraft:armor.helmet".into(),
|
||||
amount: 3.0,
|
||||
operation: 0,
|
||||
}],
|
||||
}],
|
||||
});
|
||||
let body = p.encode();
|
||||
// The packet id (134) is a two-byte VarInt.
|
||||
let mut expected = vec![134, 1, 5, 1, 1];
|
||||
expected.extend(0.0f64.to_be_bytes());
|
||||
expected.extend([1, 22]);
|
||||
expected.extend(b"minecraft:armor.helmet");
|
||||
expected.extend(3.0f64.to_be_bytes());
|
||||
expected.push(0);
|
||||
assert_eq!(body, expected);
|
||||
assert_eq!(crate::ids::play::clientbound::UPDATE_ATTRIBUTES, 134);
|
||||
assert_eq!(Clientbound::decode(134, &body[2..]).unwrap(), p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,11 @@ impl AttributeId {
|
||||
pub(super) fn index(self) -> usize {
|
||||
self.0
|
||||
}
|
||||
/// The attribute's id in the `minecraft:attribute` registry: the catalog
|
||||
/// export lists `BuiltInRegistries.ATTRIBUTE` in order.
|
||||
pub fn registry_id(self) -> i32 {
|
||||
self.0 as i32
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct RegisteredAttribute {
|
||||
@@ -100,6 +105,10 @@ impl Catalog {
|
||||
defaults,
|
||||
})
|
||||
}
|
||||
/// The entity type's supplier base of an attribute, if the type has it.
|
||||
pub fn default_base(&self, entity: &str, id: AttributeId) -> Option<f64> {
|
||||
self.defaults.get(entity).and_then(|b| b[id.0])
|
||||
}
|
||||
pub fn id(&self, name: &str) -> Option<AttributeId> {
|
||||
self.ids.get(name).copied()
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ import net.minecraft.world.phys.Vec3;
|
||||
* equipment, attributes and passengers, and where the position syncs leave
|
||||
* it (VecDeltaCodec, as handleMoveEntity and handleEntityPositionSync).
|
||||
* Entity ids differ between servers: an entity is named by its type and the
|
||||
* block it was added in, passengers by those names. Players are left out.
|
||||
* block it was added in, passengers by those names. Players are left out, but
|
||||
* for the attributes the player itself is sent from its login on.
|
||||
*/
|
||||
final class EntityTranscript {
|
||||
private static final class Tracked {
|
||||
@@ -67,6 +68,21 @@ final class EntityTranscript {
|
||||
|
||||
private final Map<Integer, Tracked> byId = new HashMap<>();
|
||||
private final List<Tracked> all = new ArrayList<>();
|
||||
private int self = Integer.MIN_VALUE;
|
||||
private final Map<String, String> selfAttributes = new TreeMap<>();
|
||||
|
||||
/** The player's own id (login) and attribute instances; false for any other packet. */
|
||||
boolean acceptSelf(Packet<?> packet) {
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket p) {
|
||||
self = p.playerId();
|
||||
return true;
|
||||
}
|
||||
if (packet instanceof ClientboundUpdateAttributesPacket p && p.getEntityId() == self) {
|
||||
p.getValues().forEach(a -> selfAttributes.put(a.attribute().getRegisteredName(), a.base() + " " + a.modifiers()));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private int unknown;
|
||||
|
||||
/** Applies one packet; false when it isn't about a tracked entity. */
|
||||
@@ -158,6 +174,7 @@ final class EntityTranscript {
|
||||
+ " | attributes " + t.attributes + " | passengers " + riders + " | now " + t.codec.getBase() + " rot " + t.xRot + ","
|
||||
+ t.yRot + " head " + t.headRot + " ground " + t.onGround + " motion " + t.motion + t.power + (t.removed ? " | removed" : ""));
|
||||
}
|
||||
out.add("self attributes " + selfAttributes);
|
||||
out.sort(null);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -82,13 +82,16 @@ import net.minecraft.world.phys.Vec3;
|
||||
* players on|off} (whether each player also records the other players added
|
||||
* to and removed from its level, and its own respawns into a dimension),
|
||||
* {@code chat on|off} (whether the system chat each player receives is
|
||||
* recorded too, as component JSON) and {@code end}, which writes each
|
||||
* recorded too, as component JSON), {@code state on|off} (whether each player
|
||||
* also records what the server changes about it: its game mode, teleports,
|
||||
* inventory slots, effects and death) and {@code end}, which writes each
|
||||
* player's lines to OUT.
|
||||
*/
|
||||
public final class LocatorBarClient {
|
||||
private static volatile String step = "start";
|
||||
private static volatile boolean players;
|
||||
private static volatile boolean chat;
|
||||
private static volatile boolean state;
|
||||
private static final Map<UUID, String> NAMES = new LinkedHashMap<>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
@@ -122,6 +125,7 @@ public final class LocatorBarClient {
|
||||
case "quit" -> players.get(w[1]).close();
|
||||
case "players" -> LocatorBarClient.players = w[1].equals("on");
|
||||
case "chat" -> chat = w[1].equals("on");
|
||||
case "state" -> state = w[1].equals("on");
|
||||
case "end" -> {
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
|
||||
for (Player p : players.values()) {
|
||||
@@ -179,6 +183,8 @@ public final class LocatorBarClient {
|
||||
private ProtocolInfo<?> outbound;
|
||||
private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0);
|
||||
private boolean loaded;
|
||||
/** This player's own entity id (ClientboundLoginPacket). */
|
||||
private volatile int id = -1;
|
||||
/** The other players this one was sent, by entity id. */
|
||||
private final Map<Integer, String> seen = new java.util.HashMap<>();
|
||||
private final Object replyLock = new Object();
|
||||
@@ -287,6 +293,10 @@ public final class LocatorBarClient {
|
||||
while (true) {
|
||||
Received r = read();
|
||||
Packet<?> p = r.packet;
|
||||
if (p instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket l) {
|
||||
id = l.playerId();
|
||||
}
|
||||
if (state) recordState(p);
|
||||
if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a
|
||||
&& a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER) {
|
||||
String who = NAMES.getOrDefault(a.getUUID(), "uuid?");
|
||||
@@ -319,6 +329,10 @@ public final class LocatorBarClient {
|
||||
} else if (p instanceof ClientboundPlayerPositionPacket t) {
|
||||
position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives());
|
||||
Vec3 at = position.position();
|
||||
if (state) {
|
||||
record(String.format(java.util.Locale.ROOT, "teleport %.3f %.3f %.3f %.1f %.1f",
|
||||
at.x, at.y, at.z, position.yRot(), position.xRot()));
|
||||
}
|
||||
send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot()));
|
||||
// Only the spawn teleport is answered with a position too (VanillaProtocolClient).
|
||||
if (!loaded) {
|
||||
@@ -338,6 +352,31 @@ public final class LocatorBarClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** What the server changed about this player ({@code state on}). */
|
||||
private void recordState(Packet<?> p) {
|
||||
if (p instanceof net.minecraft.network.protocol.game.ClientboundGameEventPacket g
|
||||
&& g.getEvent() == net.minecraft.network.protocol.game.ClientboundGameEventPacket.CHANGE_GAME_MODE) {
|
||||
record("gamemode " + (int) g.getParam());
|
||||
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket c) {
|
||||
record("slot " + c.getContainerId() + " " + c.getSlot() + " " + item(c.getItem()));
|
||||
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundSetPlayerInventoryPacket i) {
|
||||
record("inventory " + i.slot() + " " + item(i.contents()));
|
||||
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket e && e.getEntityId() == id) {
|
||||
record("effect " + e.getEffect().getRegisteredName() + " " + e.getEffectAmplifier() + " " + e.getEffectDurationTicks());
|
||||
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket e && e.entityId() == id) {
|
||||
record("effect-removed " + e.effect().getRegisteredName());
|
||||
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket k) {
|
||||
record("killed " + net.minecraft.network.chat.ComponentSerialization.CODEC
|
||||
.encodeStart(ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), k.message())
|
||||
.getOrThrow());
|
||||
}
|
||||
}
|
||||
|
||||
private static String item(net.minecraft.world.item.ItemStack stack) {
|
||||
return stack.isEmpty() ? "empty"
|
||||
: net.minecraft.core.registries.BuiltInRegistries.ITEM.getKey(stack.getItem()) + " x" + stack.getCount();
|
||||
}
|
||||
|
||||
private record Received(Packet<?> packet, byte[] payload) {}
|
||||
|
||||
private Received read() throws Exception {
|
||||
|
||||
@@ -476,7 +476,7 @@ public final class VanillaProtocolClient {
|
||||
if (r != null) {
|
||||
Packet<?> packet = r.packet;
|
||||
counts.merge(r.type, 1, Integer::sum);
|
||||
if (entities != null && step >= ENTITIES) entities.accept(packet);
|
||||
if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet);
|
||||
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
|
||||
if (respawning && !respawned) {
|
||||
String line = respawnLine(r);
|
||||
|
||||
+58
-2
@@ -19,9 +19,14 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
|
||||
drowning and the void (then respawns);
|
||||
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing;
|
||||
- respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the
|
||||
respawned player is a new entity to the others); the host dies, and on the server thread
|
||||
the guest too;
|
||||
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
|
||||
opens as 9x6 with the right half first;
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the
|
||||
server thread the host window's too;
|
||||
- effects: a beacon's power reaches every player in range, the host and the guest;
|
||||
- distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too
|
||||
(IntegratedServer.tickServer), and the guest's chunks follow the server's (#804)
|
||||
@@ -84,7 +89,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -575,6 +580,45 @@ def check_pvp(host, guest, out):
|
||||
return hits
|
||||
|
||||
|
||||
def dead_players(game, want, ticks=60):
|
||||
"""The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`."""
|
||||
for _ in range(ticks // 5):
|
||||
dead = remote(game)['dead_players']
|
||||
if bool(dead) == want:
|
||||
return dead
|
||||
game.wait(5)
|
||||
return dead
|
||||
|
||||
|
||||
def check_respawn(host, guest, out):
|
||||
# ServerLevel.removePlayerImmediately and addRespawnedPlayer: a respawned player is removed
|
||||
# from the other players and paired again as a new entity, so their clients drop the body.
|
||||
# The host window only has a client's view of the guest on the server thread.
|
||||
for g in (host, guest):
|
||||
back_to_game(g)
|
||||
results = {}
|
||||
sides = [('host', host, guest)] + ([('guest', guest, host)] if SERVER_THREAD else [])
|
||||
for name, dying, watching in sides:
|
||||
face_each_other(host, guest)
|
||||
dying('command', command='kill @s')
|
||||
dying.wait(30)
|
||||
dead = dead_players(watching, True)
|
||||
watching.shot(out, f'respawn-{name}-dead')
|
||||
dying.raw('respawn')
|
||||
dying.wait(40)
|
||||
back_to_game(dying)
|
||||
# Back within tracking range of the other player, wherever the respawn point is.
|
||||
x, y, z = pos_of(dying)
|
||||
watching('command', command=f'tp @s {x + 3:.2f} {y:.2f} {z:.2f}')
|
||||
watching.wait(40)
|
||||
alive = dead_players(watching, False)
|
||||
watching.shot(out, f'respawn-{name}-alive')
|
||||
results[name] = {'dead': dead, 'after_respawn': alive}
|
||||
assert dead, f'the {name} was not drawn dead: {results}'
|
||||
assert not alive, f'the {name} still lies dead after respawning: {results}'
|
||||
return results
|
||||
|
||||
|
||||
def container_items(game):
|
||||
"""The open container's stacks by slot (Horizon's container slots are 300 and up) and its size."""
|
||||
slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300]
|
||||
@@ -853,6 +897,17 @@ def check_titles(host, guest, out):
|
||||
return {'shown': shown, 'cleared': cleared}
|
||||
|
||||
|
||||
def check_chat(host, guest, out):
|
||||
# The agent's event log follows a remote client's chat: `wait-for chat` sees the line another
|
||||
# player sends (and on the server thread the host window's own line, back from the server).
|
||||
line = f'chat check {int(time.time())}'
|
||||
host.raw('chat', line)
|
||||
seen = {g.name: g.raw('wait-for', 'chat', line, '--timeout', 10, '--since', 0).get('ok')
|
||||
for g in ((guest, host) if SERVER_THREAD else (guest,))}
|
||||
guest.shot(out, 'chat')
|
||||
return seen
|
||||
|
||||
|
||||
def png_rows(path):
|
||||
"""The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel."""
|
||||
data = Path(path).read_bytes()
|
||||
@@ -1272,7 +1327,8 @@ def check_light(host, guest, out):
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles,
|
||||
'respawn': check_respawn,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat,
|
||||
'commands': check_commands,
|
||||
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
|
||||
'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks,
|
||||
|
||||
@@ -6,13 +6,17 @@ world vanilla generated first, with the same server.properties (offline, view di
|
||||
client (VanillaProtocolClient in its entity mode) joins, and once its chunks are in it asks for the scene: the
|
||||
console freezes the ticks, builds a wall and a rail and summons, around the spawn, every kind of minecart (one
|
||||
set rolling along the rail), boats and a raft (one falling onto the ground), armor stands (posed, small, with
|
||||
arms, wearing a helmet, one falling), a chicken jockey, item frames (one holding a turned diamond), paintings,
|
||||
primed TNT (one falling), a floating falling block, an arrow that lands and an end crystal. The client records
|
||||
for 20 seconds, the ticks running for 200 more after 3, what ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn
|
||||
arms, wearing a helmet, one falling), a chicken jockey, a slime, a pig whose scale `/attribute` sets, item
|
||||
frames (one holding a turned diamond), paintings, primed TNT (one falling), a floating falling block, an arrow
|
||||
that lands and an end crystal. The client records for 20 seconds, the ticks running for 200 more after 3, what
|
||||
ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn
|
||||
packet (position, rotations, data, motion), the entity data it was paired with and all it was sent since, its
|
||||
equipment and passengers, and where its position syncs leave it. Both transcripts must match exactly,
|
||||
entity by entity (named by type and the block it was added in). Attributes are recorded but not compared yet:
|
||||
Horizon sends no ClientboundUpdateAttributesPacket, for mobs either.
|
||||
equipment, its attribute instances (ClientboundUpdateAttributesPacket: the ones its first tick creates, the
|
||||
type's set by finalizeSpawn, the baby speed modifier, effects', equipment's and /attribute's) and passengers, and
|
||||
where its position syncs leave it; and the attribute instances the player itself is sent from its login on. Both
|
||||
transcripts must match exactly, entity by entity (named by type and the block it was added in), once the amounts
|
||||
of vanilla's random spawn modifiers are normalised (only client-syncable attributes are sent, so follow range and
|
||||
knockback resistance never show).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -63,6 +67,10 @@ SCENE = [
|
||||
'Pose:{Head:[10f,20f,0f],RightArm:[-30f,0f,15f]},equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}',
|
||||
# A chicken jockey (passengers).
|
||||
'summon minecraft:chicken -6.5 -60 -2.5 {NoAI:1b,Passengers:[{id:"minecraft:husk",IsBaby:1b,NoAI:1b}]}',
|
||||
# Attributes: a slime's size sets its bases, /attribute a pig's scale.
|
||||
'summon minecraft:slime 2.5 -60 1.5 {Size:1,NoAI:1b}',
|
||||
'summon minecraft:pig -0.5 -60 1.5 {NoAI:1b}',
|
||||
'attribute @e[type=minecraft:pig,limit=1,x=-0.5,y=-60,z=1.5,distance=..1] minecraft:scale base set 1.5',
|
||||
# Frames and paintings on the wall's south face.
|
||||
'summon minecraft:item_frame -3.5 -59 -4.97 {block_pos:[I;-4,-59,-5],Facing:3b,'
|
||||
'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}',
|
||||
@@ -78,14 +86,19 @@ SCENE = [
|
||||
]
|
||||
|
||||
|
||||
# finalizeSpawn's random modifiers on client-syncable attributes (a leader zombie's max health); their amounts
|
||||
# differ from one server to the other.
|
||||
RANDOM_MODIFIERS = re.compile(r'(id=minecraft:(?:random_spawn_bonus|leader_zombie_bonus), amount=)[^,]+')
|
||||
|
||||
|
||||
def scene_lines(lines):
|
||||
"""The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere),
|
||||
without their attributes: ClientboundUpdateAttributesPacket isn't sent by Horizon yet, for mobs either."""
|
||||
"""The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), the
|
||||
amounts of random spawn modifiers normalised."""
|
||||
out = []
|
||||
for line in lines:
|
||||
m = re.match(r'play-entities entity \S+ (-?\d+),-?\d+,(-?\d+)', line)
|
||||
if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10:
|
||||
out.append(re.sub(r' \| attributes \{[^|]*\}', '', line))
|
||||
if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10 or line.startswith('play-entities self '):
|
||||
out.append(RANDOM_MODIFIERS.sub(r'\1~', line))
|
||||
return out
|
||||
|
||||
|
||||
@@ -171,10 +184,10 @@ def main():
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
entities=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, item frames, paintings, primed '
|
||||
'TNT, a falling block, an arrow and an end crystal tracked to a '
|
||||
'vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, passengers and the '
|
||||
'positions the syncs leave them at.'))
|
||||
scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, a slime, a pig with a '
|
||||
'scale, item frames, paintings, primed TNT, a falling block, an arrow and an end crystal '
|
||||
'tracked to a vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, '
|
||||
'attributes, passengers and the positions the syncs leave them at.'))
|
||||
print(f'server entities: {len(vanilla)} entities identical')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Commands acting on other players of a dedicated server, against vanilla's, seen by vanilla clients.
|
||||
|
||||
EntitySelector.findPlayers and EntityArgument's player targets: names, UUIDs, `@a`, `@p`, `@r`, `@s` under
|
||||
`execute as`, from the console and from an operator, with `give`, `gamemode`, `tp` (to a place, to a player, with a
|
||||
rotation, and into another level by `execute in`, the console's own level or the destination's), `effect give` and
|
||||
`effect clear`, and `kill`.
|
||||
|
||||
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world
|
||||
vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made
|
||||
of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes
|
||||
about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other
|
||||
players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly,
|
||||
in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints
|
||||
and what a death does besides its messages are left to their own harnesses.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server
|
||||
from .test_locator_bar_parity import generate_world, server_dir
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server
|
||||
from test_locator_bar_parity import generate_world, server_dir
|
||||
|
||||
NAME = 'server-player-targets-parity'
|
||||
NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld'
|
||||
|
||||
|
||||
def offline_uuid(name):
|
||||
"""UUIDUtil.createOfflinePlayerUUID."""
|
||||
digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest())
|
||||
digest[6] = (digest[6] & 0x0F) | 0x30
|
||||
digest[8] = (digest[8] & 0x3F) | 0x80
|
||||
return str(uuidlib.UUID(bytes=bytes(digest)))
|
||||
|
||||
|
||||
# (label, what the console does, what the players do).
|
||||
SCRIPT = [
|
||||
('console-give', ['give Bob minecraft:diamond 3'], []),
|
||||
('console-give-all', ['give @a minecraft:apple'], []),
|
||||
('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']),
|
||||
('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []),
|
||||
('console-give-nearest', ['give @p minecraft:emerald'], []),
|
||||
('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']),
|
||||
('console-gamemode', ['gamemode survival Bob'], []),
|
||||
('alice-gamemode-bob', [], ['cmd Alice gamemode creative Bob']),
|
||||
('alice-gamemode-all', [], ['cmd Alice gamemode adventure @a']),
|
||||
('console-gamemode-back', ['gamemode creative @a'], []),
|
||||
('console-tp', ['tp Bob 8.5 -60 8.5'], []),
|
||||
('alice-tp-bob-to-alice', [], ['cmd Alice tp Bob Alice']),
|
||||
('console-tp-rotation', ['tp Bob 4.5 -60 0.5 90 10'], []),
|
||||
('bob-tp-self', [], ['cmd Bob tp @s 6.5 -60 0.5']),
|
||||
('console-execute-as', ['execute as Bob run tp @s ~ ~ ~2'], []),
|
||||
('console-execute-at', ['execute at Bob run tp Alice ~1 ~ ~'], []),
|
||||
('alice-execute-as-all', [], ['cmd Alice execute as @a run give @s minecraft:bread']),
|
||||
('console-effect', ['effect give Bob minecraft:speed 30 1'], []),
|
||||
('alice-effect-all', [], ['cmd Alice effect give @a minecraft:haste infinite']),
|
||||
('console-effect-clear', ['effect clear Bob'], []),
|
||||
('alice-effect-clear-all', [], ['cmd Alice effect clear @a minecraft:haste']),
|
||||
('console-nether', [f'execute in {NETHER} run tp Bob 0.5 100 0.5'], []),
|
||||
('console-tp-home', ['tp Bob 4.5 -60 0.5'], []),
|
||||
('alice-nether', [], [f'cmd Alice execute in {NETHER} run tp Bob 0.5 100 0.5']),
|
||||
('console-tp-to-alice', ['tp Bob Alice'], []),
|
||||
('alice-kill-missing', [], ['cmd Alice kill Carol']),
|
||||
('console-kill', ['kill Bob'], []),
|
||||
]
|
||||
# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does
|
||||
# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`.
|
||||
WAYPOINTS = ('track ', 'untrack ', 'update ')
|
||||
DEATH_STEP = 'step=console-kill'
|
||||
STEP_SECONDS = 2.5
|
||||
|
||||
|
||||
def run_side(label, server_command, client_command, build, world):
|
||||
directory = build / label
|
||||
port = server_dir(directory, world)
|
||||
out = build / f'{label}.txt'
|
||||
out.unlink(missing_ok=True)
|
||||
server = Server(server_command, directory, label)
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
with (build / f'{label}-client.log').open('w') as log:
|
||||
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
|
||||
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
|
||||
def tell(line):
|
||||
client.stdin.write(line + '\n')
|
||||
client.stdin.flush()
|
||||
try:
|
||||
for name, x in (('Alice', 0.5), ('Bob', 4.5)):
|
||||
tell(f'join {name}')
|
||||
server.wait_for(rf'{name} joined the game', timeout=120)
|
||||
tell(f'fly {name} on')
|
||||
tell(f'cmd {name} tp @s {x} -60 0.5 0 0')
|
||||
time.sleep(STEP_SECONDS)
|
||||
for flag in ('chat', 'state', 'players'):
|
||||
tell(f'{flag} on')
|
||||
for step, console, actions in SCRIPT:
|
||||
tell(f'step {step}')
|
||||
for command in console:
|
||||
server.console(command)
|
||||
for action in actions:
|
||||
tell(action)
|
||||
time.sleep(STEP_SECONDS)
|
||||
for name in ('Alice', 'Bob'):
|
||||
tell(f'still {name}')
|
||||
tell('end')
|
||||
client.wait(timeout=60)
|
||||
finally:
|
||||
if client.poll() is None:
|
||||
client.kill()
|
||||
finally:
|
||||
server.stop()
|
||||
if not out.exists():
|
||||
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
|
||||
lines = out.read_text(encoding='utf-8').splitlines()
|
||||
errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l]
|
||||
steps = {}
|
||||
for line in lines:
|
||||
who, step, rest = line.split(' ', 2)
|
||||
# At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla.
|
||||
death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed '))
|
||||
or 'chat.type.advancement' in rest)
|
||||
if rest.startswith(WAYPOINTS) or death_side:
|
||||
continue
|
||||
if step != 'step=start':
|
||||
steps.setdefault((who, step), []).append(line)
|
||||
order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)}
|
||||
keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1)))
|
||||
return [l for k in keys for l in sorted(steps[k])], errors
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
|
||||
classes = build / 'classes'
|
||||
shutil.rmtree(classes, ignore_errors=True)
|
||||
classes.mkdir()
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
cwd=lab.ROOT, check=True, capture_output=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
|
||||
|
||||
world = generate_world(vanilla_server, build)
|
||||
vanilla, vanilla_errors = run_side('vanilla', vanilla_server, client, build, world)
|
||||
horizon, horizon_errors = run_side('horizon', horizon_server, client, build, world)
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
errors = vanilla_errors + horizon_errors
|
||||
if errors or vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
|
||||
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
|
||||
+ '\n'.join(errors[:10]) + '\n' + diff[:8000])
|
||||
for needle in ('gamemode 0', 'minecraft:diamond x3', 'effect minecraft:speed', 'respawn ' + NETHER,
|
||||
'death.attack.genericKill'):
|
||||
if not any(needle in l for l in vanilla):
|
||||
raise AssertionError(f'vanilla never sent {needle!r}: the script did not run (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Commands from the console and an operator acting on another player of a dedicated server: names, '
|
||||
'UUIDs, @a, @p, @r and @s under execute as/at, with give, gamemode, tp (place, player, rotation, '
|
||||
'execute in, across levels), effect give and clear and kill, as the players see them.'))
|
||||
print(f'server player targets: {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
Reference in New Issue
Block a user