feat(server): commands act on other players (names, UUIDs, @a/@p/@r/@s)
EntitySelector.findPlayers and EntityArgument's player targets on a hosted world or dedicated server: every guest other than the one in place is Target::Guest, found by name, UUID or selector, and what a command does to them (give, gamemode, tp, kill, effect give/clear, data) runs with their state swapped in, their own messages going to their chat. The console, operators and command blocks can all target them; execute as/at reads their position, rotation and eye height; a teleport into another level (execute in, the console's Overworld, a destination in another level) moves them there. as_guest splits into enter_guest/leave_guest so that guest turns nest, and a guest's commands run with the hub back in self.lan (queued per packet), so they reach the other players (and /kick works for ops). Item and advancement names and player names in feedback take vanilla's component shape; /kill on a guest sends vanilla's death message. Harness: tools/test_server_player_targets_parity.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -829,6 +829,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);
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
@@ -796,7 +800,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 +926,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
|
||||
@@ -1165,7 +1346,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 }),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -670,6 +670,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() {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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