Merge pull request #1570 from ludovic111/feat/server-packs-client
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
//! `ConfirmScreen`: a title, a message wrapped to `width - 50` (15 lines at
|
||||
//! most) and two 150-wide buttons 4 apart and 16 below it, the whole column
|
||||
//! centred; Escape answers no.
|
||||
use crate::{
|
||||
font::Font,
|
||||
hud::{HudAtlas, HudBatch},
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
|
||||
pub struct Confirm {
|
||||
/// Each line and where it is drawn.
|
||||
pub lines: Vec<(Text, f32, f32)>,
|
||||
/// The yes and no buttons' corners.
|
||||
pub buttons: [(f32, f32); 2],
|
||||
}
|
||||
impl Confirm {
|
||||
pub fn new(font: &Font, (w, h): (f32, f32), title: &Text, message: &Text) -> Self {
|
||||
let message: Vec<Text> = font
|
||||
.split_lines(message, w - 50.0)
|
||||
.into_iter()
|
||||
.map(|(line, _)| line)
|
||||
.take(15)
|
||||
.collect();
|
||||
let tw = font.width_text(title);
|
||||
let mw = message
|
||||
.iter()
|
||||
.map(|l| font.width_text(l))
|
||||
.fold(0.0, f32::max);
|
||||
let mh = 9.0 * message.len() as f32;
|
||||
let col = tw.max(mw).max(304.0);
|
||||
let total = 9.0 + 8.0 + mh + 8.0 + 36.0;
|
||||
let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc());
|
||||
let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc();
|
||||
let mid = cell(mw) + (mw / 2.0).trunc();
|
||||
let mut lines = vec![(title.clone(), cell(tw), ly)];
|
||||
for (i, line) in message.into_iter().enumerate() {
|
||||
let x = mid - (font.width_text(&line) / 2.0).trunc();
|
||||
lines.push((line, x, ly + 17.0 + 9.0 * i as f32));
|
||||
}
|
||||
let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0);
|
||||
Self {
|
||||
lines,
|
||||
buttons: [(bx, by), (bx + 154.0, by)],
|
||||
}
|
||||
}
|
||||
/// The answer a click at `cursor` gives: true for yes, false for no.
|
||||
pub fn answer_at(&self, cursor: (f32, f32)) -> Option<bool> {
|
||||
let [yes, no] = self.buttons;
|
||||
let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0);
|
||||
if on(yes) {
|
||||
Some(true)
|
||||
} else if on(no) {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// The lines and the buttons (yes first), over whatever is behind.
|
||||
pub fn draw(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
labels: [&Text; 2],
|
||||
) {
|
||||
for (line, x, y) in &self.lines {
|
||||
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
|
||||
}
|
||||
for ((bx, by), label) in self.buttons.into_iter().zip(labels) {
|
||||
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
|
||||
ui::button(batch, atlas, bx, by, 150.0, 20.0, label, true, hover);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ mod scoreboard;
|
||||
mod screens;
|
||||
mod sculk;
|
||||
mod sculk_fixture;
|
||||
mod server_packs;
|
||||
mod server_travel;
|
||||
mod shield;
|
||||
mod sign_edit;
|
||||
@@ -1126,6 +1127,8 @@ struct Game<'a> {
|
||||
pending_entry: Option<PendingWorldEntry>,
|
||||
world_loader: Option<world_loading::WorldLoader>,
|
||||
pending_pack_reload: bool,
|
||||
/// A server's resource packs (game/server_packs.rs).
|
||||
server_packs: server_packs::ServerPackState,
|
||||
world_renderer_ready: bool,
|
||||
collision: &'a BlockCollisionRegistry<'a>,
|
||||
motion: &'a MotionResources,
|
||||
@@ -4771,7 +4774,14 @@ impl Game<'_> {
|
||||
hud_layout::paint(batch, &self.gui.atlas, &draws);
|
||||
}
|
||||
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
|
||||
let mut batch = self.hud_layers(size);
|
||||
// The pack prompt replaces the connecting screen (setScreen), but
|
||||
// in game it opens over the world.
|
||||
let mut batch = if self.server_packs.prompt.is_some() && self.player.is_none() {
|
||||
HudBatch::new(size)
|
||||
} else {
|
||||
self.hud_layers(size)
|
||||
};
|
||||
self.draw_pack_prompt(&mut batch);
|
||||
// Gui.extractRenderState: the debug overlay comes after the screen
|
||||
// and the toasts, so it is over everything, menus included.
|
||||
self.draw_debug_overlay(&mut batch, size);
|
||||
@@ -10995,6 +11005,13 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.advancements_scroll(scaled(raw_x) as f32, d);
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. }
|
||||
if self.server_packs.prompt.is_some() =>
|
||||
{
|
||||
if state == ElementState::Pressed && button == MouseButton::Left {
|
||||
self.pack_prompt_click()?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
|
||||
if self.options_waiting_for_key() && state == ElementState::Pressed {
|
||||
@@ -11194,6 +11211,14 @@ impl ApplicationHandler for Game<'_> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// ConfirmScreen.keyPressed: Escape answers no.
|
||||
WindowEvent::KeyboardInput { event, .. } if self.server_packs.prompt.is_some() => {
|
||||
if event.state == ElementState::Pressed
|
||||
&& event.physical_key == PhysicalKey::Code(KeyCode::Escape)
|
||||
{
|
||||
self.answer_pack_prompt(false)?;
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::Chat && self.title.is_none() =>
|
||||
{
|
||||
@@ -11572,6 +11597,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
self.tick_server_packs();
|
||||
self.poll_control(event_loop);
|
||||
if self.pending_save.is_some() {
|
||||
return;
|
||||
@@ -11666,6 +11692,7 @@ impl<'a> Game<'a> {
|
||||
pending_entry: None,
|
||||
world_loader: None,
|
||||
pending_pack_reload: false,
|
||||
server_packs: Default::default(),
|
||||
world_renderer_ready: false,
|
||||
collision: res.collision(),
|
||||
motion: res.motion(),
|
||||
@@ -13254,7 +13281,7 @@ pub fn run() -> Result<()> {
|
||||
return run_loading(options, early_settings, vanilla_root, None, started);
|
||||
}
|
||||
let mut pack_error = None;
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs, &[])
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("Horizon: resource packs not applied: {e}");
|
||||
pack_error = Some(e.to_string());
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket).
|
||||
//! Leaving with changes asks first (ConfirmScreen).
|
||||
use horizon_client::{
|
||||
confirm_screen::Confirm,
|
||||
font::Font,
|
||||
gamerules::{self, GameRules, RULES, Rule, Value},
|
||||
hud::{HudAtlas, HudBatch},
|
||||
@@ -66,9 +67,6 @@ fn parse(r: &Rule, s: &str) -> Option<i32> {
|
||||
.flatten()
|
||||
.filter(|v| (r.min..=r.max).contains(v))
|
||||
}
|
||||
fn widest(font: &Font, lines: &[Text]) -> f32 {
|
||||
lines.iter().map(|l| font.width_text(l)).fold(0.0, f32::max)
|
||||
}
|
||||
fn lines(font: &Font, t: &Text, width: f32) -> Vec<Text> {
|
||||
font.split_lines(t, width)
|
||||
.into_iter()
|
||||
@@ -95,38 +93,11 @@ fn yellow() -> u32 {
|
||||
named_color("yellow").unwrap_or(0xFFFF55)
|
||||
}
|
||||
|
||||
/// ConfirmScreen: the title, the message (at most `width - 50` wide), and
|
||||
/// Yes / No 16 below, 4 apart, all centred.
|
||||
struct Confirm {
|
||||
lines: Vec<(Text, f32, f32)>,
|
||||
buttons: [(f32, f32); 2],
|
||||
}
|
||||
impl Confirm {
|
||||
fn new(font: &Font, (w, h): (f32, f32)) -> Self {
|
||||
let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]);
|
||||
let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]);
|
||||
let message: Vec<Text> = lines(font, &message, w - 50.0)
|
||||
.into_iter()
|
||||
.take(15)
|
||||
.collect();
|
||||
let (tw, mw) = (font.width_text(&title), widest(font, &message));
|
||||
let mh = 9.0 * message.len() as f32;
|
||||
let col = tw.max(mw).max(304.0);
|
||||
let total = 9.0 + 8.0 + mh + 8.0 + 36.0;
|
||||
let (lx, ly) = (((w - col) / 2.0).trunc(), ((h - total) / 2.0).trunc());
|
||||
let cell = |cw: f32| lx + ((col - cw) / 2.0).trunc();
|
||||
let mid = cell(mw) + (mw / 2.0).trunc();
|
||||
let mut out = vec![(title, cell(tw), ly)];
|
||||
for (i, line) in message.into_iter().enumerate() {
|
||||
let x = mid - (font.width_text(&line) / 2.0).trunc();
|
||||
out.push((line, x, ly + 17.0 + 9.0 * i as f32));
|
||||
}
|
||||
let (bx, by) = (cell(304.0), ly + 9.0 + 8.0 + mh + 8.0 + 16.0);
|
||||
Self {
|
||||
lines: out,
|
||||
buttons: [(bx, by), (bx + 154.0, by)],
|
||||
}
|
||||
}
|
||||
/// ConfirmScreen "Game Rule Changes".
|
||||
fn confirm(font: &Font, size: (f32, f32)) -> Confirm {
|
||||
let title = Text::translate("editGamerule.inGame.discardChanges.title", &[]);
|
||||
let message = Text::translate("editGamerule.inGame.discardChanges.message", &[]);
|
||||
Confirm::new(font, size, &title, &message)
|
||||
}
|
||||
|
||||
impl RulesScreen {
|
||||
@@ -301,13 +272,10 @@ impl RulesScreen {
|
||||
let (w, h) = size;
|
||||
let on = |x: f32, y: f32, bw: f32, bh: f32| ui::hovered(cursor, x, y, bw, bh);
|
||||
if self.confirm {
|
||||
let c = Confirm::new(&atlas.font, size);
|
||||
let [(yx, yy), (nx, ny)] = c.buttons;
|
||||
if on(yx, yy, 150.0, 20.0) {
|
||||
return Some(Exit::Discard);
|
||||
}
|
||||
if on(nx, ny, 150.0, 20.0) {
|
||||
self.confirm = false;
|
||||
match confirm(&atlas.font, size).answer_at(cursor) {
|
||||
Some(true) => return Some(Exit::Discard),
|
||||
Some(false) => self.confirm = false,
|
||||
None => {}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
@@ -367,7 +335,7 @@ impl RulesScreen {
|
||||
let (w, h) = size;
|
||||
let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0);
|
||||
if self.confirm {
|
||||
return Confirm::new(&atlas.font, size).buttons.into_iter().any(on);
|
||||
return confirm(&atlas.font, size).answer_at(cursor).is_some();
|
||||
}
|
||||
let [done, cancel] = footer(w, h);
|
||||
if (on(done) && !self.invalid()) || on(cancel) {
|
||||
@@ -384,15 +352,11 @@ impl RulesScreen {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
|
||||
if self.confirm {
|
||||
let c = Confirm::new(&atlas.font, (w, h));
|
||||
for (line, x, y) in &c.lines {
|
||||
batch.text_styled(atlas, line, *x, *y, u32::MAX, true);
|
||||
}
|
||||
for ((bx, by), key) in c.buttons.into_iter().zip(["gui.yes", "gui.no"]) {
|
||||
let hover = ui::hovered(cursor, bx, by, 150.0, 20.0);
|
||||
let label = Text::translate(key, &[]);
|
||||
ui::button(batch, atlas, bx, by, 150.0, 20.0, &label, true, hover);
|
||||
}
|
||||
let labels = [
|
||||
Text::translate("gui.yes", &[]),
|
||||
Text::translate("gui.no", &[]),
|
||||
];
|
||||
confirm(&atlas.font, (w, h)).draw(batch, atlas, cursor, [&labels[0], &labels[1]]);
|
||||
return;
|
||||
}
|
||||
let rows = self.rows();
|
||||
|
||||
@@ -34,10 +34,16 @@ pub fn open_folder(dir: &Path) {
|
||||
log::warn!("Horizon: could not open {}: {e}", dir.display());
|
||||
}
|
||||
}
|
||||
/// The resource root to load from, given the vanilla root and the selection.
|
||||
pub fn startup_root(vanilla: &Path, selected: &[String]) -> std::io::Result<PathBuf> {
|
||||
/// The resource root to load from, given the vanilla root, the selection and
|
||||
/// a server's packs, which go on top (`Pack.Position.TOP`, fixed).
|
||||
pub fn startup_root(
|
||||
vanilla: &Path,
|
||||
selected: &[String],
|
||||
server: &[Pack],
|
||||
) -> std::io::Result<PathBuf> {
|
||||
let all = packs::discover(vanilla, &packs_dir());
|
||||
let enabled = packs::enabled(&all, selected);
|
||||
let mut enabled = packs::enabled(&all, selected);
|
||||
enabled.extend_from_slice(server);
|
||||
packs::resource_root(vanilla, &enabled, &cache_dir())
|
||||
}
|
||||
fn info(p: &Pack) -> PackInfo {
|
||||
@@ -117,14 +123,7 @@ impl Game<'_> {
|
||||
self.pending_pack_reload = true;
|
||||
return;
|
||||
}
|
||||
let vanilla = self.vanilla_root();
|
||||
if self.ui.vanilla_root.as_os_str().is_empty() {
|
||||
self.ui.vanilla_root = vanilla.clone();
|
||||
}
|
||||
let result = startup_root(&vanilla, &self.settings.resource_packs)
|
||||
.map_err(Into::into)
|
||||
.and_then(|root| self.reload_resources(&root));
|
||||
if let Err(e) = result {
|
||||
if let Err(e) = self.reload_selected_packs() {
|
||||
log::warn!("Horizon: resource reload failed: {e}");
|
||||
if self.screen != super::Screen::Options {
|
||||
self.open_options_at(
|
||||
@@ -135,6 +134,16 @@ impl Game<'_> {
|
||||
self.ui.options.resource_error = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
/// Reload from the selected packs and the server's.
|
||||
pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> {
|
||||
let vanilla = self.vanilla_root();
|
||||
if self.ui.vanilla_root.as_os_str().is_empty() {
|
||||
self.ui.vanilla_root = vanilla.clone();
|
||||
}
|
||||
let server = &self.server_packs.active;
|
||||
let root = startup_root(&vanilla, &self.settings.resource_packs, server)?;
|
||||
self.reload_resources(&root)
|
||||
}
|
||||
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
|
||||
let render = std::sync::Arc::new(self.pack.assets.reload(root)?);
|
||||
let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?;
|
||||
|
||||
@@ -305,6 +305,16 @@ impl Game<'_> {
|
||||
// A signed-in account always plays under its own name.
|
||||
let auth = horizon_client::auth::current();
|
||||
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
|
||||
let user = auth.as_ref().map_or_else(
|
||||
|| {
|
||||
(
|
||||
name.to_owned(),
|
||||
horizon_protocol::crypto::offline_uuid(name),
|
||||
)
|
||||
},
|
||||
|a| (a.name.clone(), a.uuid),
|
||||
);
|
||||
self.server_packs_connect(local.is_none().then_some(address), user);
|
||||
let session = match local {
|
||||
Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()),
|
||||
None => {
|
||||
@@ -453,6 +463,7 @@ impl Game<'_> {
|
||||
if let Some(mut r) = self.remote.take() {
|
||||
r.session.disconnect();
|
||||
}
|
||||
self.server_packs_disconnect();
|
||||
// Single player's server thread saves the world before the title shows.
|
||||
let single_player = match self.integrated.take() {
|
||||
Some(server) => {
|
||||
@@ -827,6 +838,8 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Event::Reconfigured(registries) => self.set_registries(registries),
|
||||
Event::PackPush(p) => self.handle_pack_push(p),
|
||||
Event::PackPop(id) => self.handle_pack_pop(id),
|
||||
Event::DecodeError(e) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.decode_errors += 1;
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! A server's resource packs bound to the game (`ClientCommonPacketListenerImpl.
|
||||
//! handleResourcePackPush` and `handleResourcePackPop`, its `PackConfirmScreen`,
|
||||
//! and `DownloadedPackSource` as `Minecraft` drives it): the prompt, the
|
||||
//! server list's setting, downloads into `downloads/`, and a resource reload
|
||||
//! with the server's packs on top of the player's own.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
confirm_screen::Confirm,
|
||||
hud::{HudAtlas, HudBatch},
|
||||
multiplayer, packs,
|
||||
scoreboard::{comp_text, tag_to_json},
|
||||
server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url},
|
||||
text::{Text, named_color},
|
||||
ui,
|
||||
};
|
||||
use horizon_protocol::{packets::configuration::ResourcePackPush, servers};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks
|
||||
/// about, whether the last one is required, and the server's message.
|
||||
pub(super) struct PackPrompt {
|
||||
requests: Vec<(u128, String, String)>,
|
||||
required: bool,
|
||||
prompt: Option<Text>,
|
||||
}
|
||||
impl PackPrompt {
|
||||
fn texts(&self) -> (Text, Text, [Text; 2]) {
|
||||
let t = |key: &str| Text::translate(key, &[]);
|
||||
let (title, line2) = if self.required {
|
||||
let yellow = named_color("yellow").unwrap_or(0xFFFF55);
|
||||
(
|
||||
t("multiplayer.requiredTexturePrompt.line1"),
|
||||
t("multiplayer.requiredTexturePrompt.line2")
|
||||
.with_color(yellow)
|
||||
.bold(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
t("multiplayer.texturePrompt.line1"),
|
||||
t("multiplayer.texturePrompt.line2"),
|
||||
)
|
||||
};
|
||||
// preparePackPrompt.
|
||||
let message = match &self.prompt {
|
||||
Some(prompt) => Text::translate(
|
||||
"multiplayer.texturePrompt.serverPrompt",
|
||||
&[line2, prompt.clone()],
|
||||
),
|
||||
None => line2,
|
||||
};
|
||||
let buttons = if self.required {
|
||||
[t("gui.proceed"), t("menu.disconnect")]
|
||||
} else {
|
||||
[t("gui.yes"), t("gui.no")]
|
||||
};
|
||||
(title, message, buttons)
|
||||
}
|
||||
fn layout(&self, atlas: &HudAtlas, size: (f32, f32)) -> Confirm {
|
||||
let (title, message, _) = self.texts();
|
||||
Confirm::new(&atlas.font, size, &title, &message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The game's `DownloadedPackSource`.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ServerPackState {
|
||||
packs: ServerPacks,
|
||||
/// `downloads/` in the game folder, opened at the first download.
|
||||
queue: Option<download::Queue>,
|
||||
pub(super) prompt: Option<PackPrompt>,
|
||||
/// The server list entry the setting is saved to (none: a direct join).
|
||||
address: Option<String>,
|
||||
/// The account the downloads are made for (the download headers).
|
||||
user: (String, u128),
|
||||
/// The packs loaded on top of the player's own, bottom first.
|
||||
pub(super) active: Vec<packs::Pack>,
|
||||
}
|
||||
|
||||
fn saves() -> PathBuf {
|
||||
std::env::current_dir().unwrap_or_default().join("saves")
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `ConnectScreen`: the server's setting decides what its packs do
|
||||
/// (`configureForServerControl`); single player's own server takes them
|
||||
/// all, quietly (`configureForLocalWorld`).
|
||||
pub(super) fn server_packs_connect(&mut self, address: Option<&str>, user: (String, u128)) {
|
||||
let state = &mut self.server_packs;
|
||||
state.user = user;
|
||||
state.prompt = None;
|
||||
let Some(address) = address else {
|
||||
state.address = None;
|
||||
state.packs.local_world();
|
||||
return;
|
||||
};
|
||||
let file = multiplayer::servers_file(&saves());
|
||||
let entry = servers::load(&file).into_iter().find(|s| s.ip == address);
|
||||
let setting = entry.as_ref().and_then(|e| e.accept_textures);
|
||||
state.address = entry.map(|e| e.ip);
|
||||
state.packs.connect(Prompt::for_server(setting));
|
||||
}
|
||||
/// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once.
|
||||
pub(super) fn server_packs_disconnect(&mut self) {
|
||||
self.server_packs.prompt = None;
|
||||
self.server_packs.packs.disconnect();
|
||||
self.tick_server_packs();
|
||||
}
|
||||
|
||||
/// `handleResourcePackPush`.
|
||||
pub(super) fn handle_pack_push(&mut self, p: ResourcePackPush) {
|
||||
if !valid_url(&p.url) {
|
||||
self.send_pack_status(p.id, action::INVALID_URL);
|
||||
return;
|
||||
}
|
||||
let setting = self.server_setting();
|
||||
let prompt = Prompt::for_server(setting);
|
||||
if prompt != Prompt::Pending && (!p.required || prompt != Prompt::Declined) {
|
||||
self.server_packs
|
||||
.packs
|
||||
.push(p.id, &p.url, parse_sha1(&p.hash));
|
||||
return;
|
||||
}
|
||||
// addOrUpdatePackPrompt: one prompt for every pack pushed before it is answered.
|
||||
let text = p.prompt.as_ref().map(|t| comp_text(&tag_to_json(t)));
|
||||
let state = &mut self.server_packs;
|
||||
let open = state.prompt.get_or_insert(PackPrompt {
|
||||
requests: Vec::new(),
|
||||
required: p.required,
|
||||
prompt: None,
|
||||
});
|
||||
open.requests.push((p.id, p.url, p.hash));
|
||||
open.required = p.required;
|
||||
open.prompt = text;
|
||||
self.capture(false);
|
||||
}
|
||||
/// `handleResourcePackPop`: one pack, or all of them.
|
||||
pub(super) fn handle_pack_pop(&mut self, id: Option<u128>) {
|
||||
match id {
|
||||
Some(id) => self.server_packs.packs.pop(id),
|
||||
None => self.server_packs.packs.pop_all(),
|
||||
}
|
||||
}
|
||||
/// The joined server's entry in the server list: its `acceptTextures`.
|
||||
fn server_setting(&self) -> Option<bool> {
|
||||
let address = self.server_packs.address.as_deref()?;
|
||||
servers::load(&multiplayer::servers_file(&saves()))
|
||||
.into_iter()
|
||||
.find(|s| s.ip == address)?
|
||||
.accept_textures
|
||||
}
|
||||
fn send_pack_status(&self, id: u128, status: i32) {
|
||||
if let Some(r) = &self.remote {
|
||||
r.session.send_pack_status(id, status);
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt's answer (`PackConfirmScreen`'s callback): the server's
|
||||
/// setting follows it, declining a required pack disconnects, and every
|
||||
/// pack it asked about is pushed.
|
||||
pub(super) fn answer_pack_prompt(&mut self, yes: bool) -> Result<()> {
|
||||
let Some(prompt) = self.server_packs.prompt.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.player.is_some() && self.screen == super::Screen::Playing {
|
||||
self.capture(true);
|
||||
}
|
||||
let setting = if yes {
|
||||
self.server_packs.packs.allow();
|
||||
Some(true)
|
||||
} else {
|
||||
self.server_packs.packs.reject();
|
||||
if prompt.required {
|
||||
let reason = Text::translate("multiplayer.requiredTexturePrompt.disconnect", &[]);
|
||||
return self.leave_server(Some(reason.plain()));
|
||||
}
|
||||
Some(false)
|
||||
};
|
||||
for (id, url, hash) in prompt.requests {
|
||||
self.server_packs.packs.push(id, &url, parse_sha1(&hash));
|
||||
}
|
||||
// ServerList.saveSingleServer.
|
||||
if let Some(address) = &self.server_packs.address {
|
||||
let file = multiplayer::servers_file(&saves());
|
||||
let mut list = servers::load(&file);
|
||||
for entry in list.iter_mut().filter(|s| &s.ip == address) {
|
||||
entry.accept_textures = setting;
|
||||
}
|
||||
if let Err(e) = servers::save(&file, &list) {
|
||||
log::warn!("Horizon: could not save {}: {e}", file.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs what the packs need (`createUpdateScheduler`): the downloads
|
||||
/// that finished, the ones to start, a resource reload when the active
|
||||
/// packs change, and the statuses for the server.
|
||||
pub(super) fn tick_server_packs(&mut self) {
|
||||
// A reload waits for the world's resources (`reload_packs`).
|
||||
if self.rest_loader.is_some() || self.world_loader.is_some() {
|
||||
return;
|
||||
}
|
||||
let finished = self
|
||||
.server_packs
|
||||
.queue
|
||||
.as_ref()
|
||||
.map(download::Queue::finished)
|
||||
.unwrap_or_default();
|
||||
for batch in finished {
|
||||
self.server_packs.packs.downloaded(batch);
|
||||
}
|
||||
while self.server_packs.packs.wants_tick() {
|
||||
let tick = self.server_packs.packs.tick();
|
||||
if !tick.download.is_empty() {
|
||||
self.start_pack_downloads(tick.download);
|
||||
}
|
||||
if let Some(mut load) = tick.reload {
|
||||
while let Some(recovery) = {
|
||||
let ok = self.reload_server_packs(&load);
|
||||
self.server_packs.packs.reloaded(ok)
|
||||
} {
|
||||
load = recovery;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, status) in self.server_packs.packs.take_replies() {
|
||||
self.send_pack_status(id, status);
|
||||
}
|
||||
}
|
||||
fn start_pack_downloads(&mut self, requests: Vec<horizon_client::server_packs::Request>) {
|
||||
let state = &mut self.server_packs;
|
||||
if state.queue.is_none() {
|
||||
let dir = std::env::current_dir()
|
||||
.unwrap_or_default()
|
||||
.join("downloads");
|
||||
match download::Queue::open(dir) {
|
||||
Ok(queue) => state.queue = Some(queue),
|
||||
Err(e) => {
|
||||
log::error!("Horizon: failed to open the download queue: {e}");
|
||||
let failed = requests.iter().map(|r| r.id).collect();
|
||||
state.packs.downloaded(horizon_client::server_packs::Batch {
|
||||
downloaded: Vec::new(),
|
||||
failed,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let headers = download::headers(&state.user.0, state.user.1);
|
||||
if let Some(queue) = &state.queue {
|
||||
queue.download(requests, headers);
|
||||
}
|
||||
}
|
||||
/// `DownloadedPackSource.startReload`: the packs on top of the player's
|
||||
/// own, then `Minecraft.reloadResourcePacks`. False when a pack has no
|
||||
/// readable `pack.mcmeta` or the reload failed.
|
||||
fn reload_server_packs(&mut self, load: &[(u128, PathBuf)]) -> bool {
|
||||
let packs: Option<Vec<_>> = load
|
||||
.iter()
|
||||
.map(|(id, path)| packs::server_pack(*id, path))
|
||||
.collect();
|
||||
let Some(packs) = packs else {
|
||||
log::warn!("Horizon: invalid pack metadata in a server pack, ignoring all");
|
||||
return false;
|
||||
};
|
||||
self.server_packs.active = packs;
|
||||
match self.reload_selected_packs() {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log::warn!("Horizon: server resource pack reload failed: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn draw_pack_prompt(&self, batch: &mut HudBatch) {
|
||||
let Some(prompt) = &self.server_packs.prompt else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.gui.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
if self.player.is_none() {
|
||||
// In place of the connecting screen, on its background.
|
||||
batch.fill(
|
||||
atlas,
|
||||
0.0,
|
||||
0.0,
|
||||
w,
|
||||
h,
|
||||
horizon_client::hud::rgba(20, 20, 20, 255),
|
||||
);
|
||||
}
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
|
||||
let (_, _, [yes, no]) = prompt.texts();
|
||||
prompt
|
||||
.layout(atlas, (w, h))
|
||||
.draw(batch, atlas, self.cursor, [&yes, &no]);
|
||||
}
|
||||
/// A left click on the prompt: its answer when it hit a button.
|
||||
pub(super) fn pack_prompt_click(&mut self) -> Result<()> {
|
||||
let Some(prompt) = &self.server_packs.prompt else {
|
||||
return Ok(());
|
||||
};
|
||||
let answer = prompt
|
||||
.layout(&self.gui.atlas, self.gui_size())
|
||||
.answer_at(self.cursor);
|
||||
match answer {
|
||||
Some(yes) => {
|
||||
self.audio.play_button_click();
|
||||
self.answer_pack_prompt(yes)
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,12 +219,11 @@ pub(super) fn spawn_loader(
|
||||
.name("resource-loader".into())
|
||||
.spawn(move || {
|
||||
let mut pack_error = None;
|
||||
let root = packs::startup_root(&vanilla_root, &settings.resource_packs).unwrap_or_else(
|
||||
|error| {
|
||||
let root = packs::startup_root(&vanilla_root, &settings.resource_packs, &[])
|
||||
.unwrap_or_else(|error| {
|
||||
pack_error = Some(error.to_string());
|
||||
vanilla_root.clone()
|
||||
},
|
||||
);
|
||||
});
|
||||
let root = mods::content_root(&root, &settings.mods.enabled, &dev_mods);
|
||||
let result = load_resources(
|
||||
root,
|
||||
|
||||
@@ -41,6 +41,7 @@ pub mod command;
|
||||
pub mod command_block;
|
||||
pub mod command_storage;
|
||||
pub mod component;
|
||||
pub mod confirm_screen;
|
||||
pub mod container_screen;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
|
||||
@@ -67,6 +67,9 @@ pub enum Screen {
|
||||
name: String,
|
||||
address: String,
|
||||
focus: u8,
|
||||
/// Server Resource Packs (`acceptTextures`): Enabled, Disabled, or
|
||||
/// none for Prompt.
|
||||
packs: Option<bool>,
|
||||
},
|
||||
Direct {
|
||||
address: String,
|
||||
@@ -224,6 +227,19 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// The Server Resource Packs button's label: `CommonComponents.optionNameValue`.
|
||||
fn pack_setting_label(packs: Option<bool>) -> String {
|
||||
let (key, fallback) = match packs {
|
||||
Some(true) => ("manageServer.resourcePack.enabled", "Enabled"),
|
||||
Some(false) => ("manageServer.resourcePack.disabled", "Disabled"),
|
||||
None => ("manageServer.resourcePack.prompt", "Prompt"),
|
||||
};
|
||||
let name = crate::lang::get_or("manageServer.resourcePack", "Server Resource Packs");
|
||||
crate::lang::get_or("options.generic_value", "%s: %s")
|
||||
.replacen("%s", &name, 1)
|
||||
.replacen("%s", &crate::lang::get_or(key, fallback), 1)
|
||||
}
|
||||
|
||||
/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`.
|
||||
const HEADER: f32 = 33.0;
|
||||
const FOOTER: f32 = 60.0;
|
||||
@@ -461,7 +477,16 @@ impl Screen {
|
||||
),
|
||||
]
|
||||
}
|
||||
Self::Edit { address, .. } => vec![
|
||||
Self::Edit { address, packs, .. } => vec![
|
||||
// ManageServerScreen's CycleButton, above Done.
|
||||
b(
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 72.0,
|
||||
200.0,
|
||||
&pack_setting_label(*packs),
|
||||
true,
|
||||
60,
|
||||
),
|
||||
b(
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 96.0 + 18.0,
|
||||
@@ -847,6 +872,7 @@ impl Screen {
|
||||
name,
|
||||
address,
|
||||
focus,
|
||||
..
|
||||
} => {
|
||||
centered(
|
||||
batch,
|
||||
@@ -996,6 +1022,7 @@ impl Screen {
|
||||
name: "Minecraft Server".into(),
|
||||
address: String::new(),
|
||||
focus: 1,
|
||||
packs: None,
|
||||
}
|
||||
}
|
||||
(
|
||||
@@ -1011,6 +1038,7 @@ impl Screen {
|
||||
name: s.name,
|
||||
address: s.ip,
|
||||
focus: 0,
|
||||
packs: s.accept_textures,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1125,21 +1153,32 @@ impl Screen {
|
||||
*selected = Some(index);
|
||||
}
|
||||
}
|
||||
// CycleButton: Enabled, Disabled, Prompt, and round again.
|
||||
(Self::Edit { packs, .. }, Some(60)) => {
|
||||
*packs = match *packs {
|
||||
Some(true) => Some(false),
|
||||
Some(false) => None,
|
||||
None => Some(true),
|
||||
}
|
||||
}
|
||||
(
|
||||
Self::Edit {
|
||||
index,
|
||||
name,
|
||||
address,
|
||||
packs,
|
||||
..
|
||||
},
|
||||
Some(50),
|
||||
) => {
|
||||
let mut list = servers::load(&servers_file(saves));
|
||||
let entry = ServerEntry::new(name.trim(), address.trim());
|
||||
let mut entry = ServerEntry::new(name.trim(), address.trim());
|
||||
entry.accept_textures = *packs;
|
||||
match index.and_then(|i| list.get_mut(i)) {
|
||||
Some(e) => {
|
||||
e.name = entry.name;
|
||||
e.ip = entry.ip;
|
||||
e.accept_textures = entry.accept_textures;
|
||||
}
|
||||
None => list.push(entry),
|
||||
}
|
||||
@@ -1637,4 +1676,57 @@ mod tests {
|
||||
assert_eq!(names(), ["Keep"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_cycles_and_saves_the_server_resource_pack_setting() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-mp-packs-{}", std::process::id()));
|
||||
let saves = dir.join("saves");
|
||||
std::fs::create_dir_all(&saves).unwrap();
|
||||
let file = servers_file(&saves);
|
||||
let mut entry = ServerEntry::new("Packs", "127.0.0.1:4");
|
||||
entry.accept_textures = Some(false);
|
||||
servers::save(&file, &[entry]).unwrap();
|
||||
let size = (427.0, 240.0);
|
||||
let mut screen = Screen::list(&saves);
|
||||
if let Screen::List { selected, .. } = &mut screen {
|
||||
*selected = Some(0);
|
||||
}
|
||||
screen.click(Some(43), 0.0, 0.0, size, &saves);
|
||||
let cycle = |screen: &Screen| {
|
||||
screen
|
||||
.buttons(size.0, size.1)
|
||||
.into_iter()
|
||||
.find(|b| b.5 == 60)
|
||||
.map(|b| (b.0, b.1, b.2, b.3))
|
||||
};
|
||||
// ManageServerScreen: 200 wide at height / 4 + 72, the saved value first.
|
||||
assert_eq!(
|
||||
cycle(&screen),
|
||||
Some((
|
||||
113.5,
|
||||
132.0,
|
||||
200.0,
|
||||
"Server Resource Packs: Disabled".into()
|
||||
))
|
||||
);
|
||||
// Disabled, Prompt, Enabled: Cancel keeps what was saved.
|
||||
screen.click(Some(60), 0.0, 0.0, size, &saves);
|
||||
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Prompt");
|
||||
screen.click(Some(51), 0.0, 0.0, size, &saves);
|
||||
assert_eq!(servers::load(&file)[0].accept_textures, Some(false));
|
||||
// Done saves it.
|
||||
if let Screen::List { selected, .. } = &mut screen {
|
||||
*selected = Some(0);
|
||||
}
|
||||
screen.click(Some(43), 0.0, 0.0, size, &saves);
|
||||
screen.click(Some(60), 0.0, 0.0, size, &saves);
|
||||
screen.click(Some(60), 0.0, 0.0, size, &saves);
|
||||
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Enabled");
|
||||
screen.click(Some(50), 0.0, 0.0, size, &saves);
|
||||
assert_eq!(servers::load(&file)[0].accept_textures, Some(true));
|
||||
// A new server asks.
|
||||
screen.click(Some(42), 0.0, 0.0, size, &saves);
|
||||
assert_eq!(cycle(&screen).unwrap().3, "Server Resource Packs: Prompt");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ use horizon_protocol::{
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{Receiver, Sender, channel},
|
||||
},
|
||||
thread::JoinHandle,
|
||||
@@ -43,6 +44,10 @@ pub enum Event {
|
||||
DecodeError(String),
|
||||
/// The server sent us back to configuration and finished it again.
|
||||
Reconfigured(Arc<Dynamic>),
|
||||
/// ClientboundResourcePackPushPacket, in configuration or in play.
|
||||
PackPush(cfg::ResourcePackPush),
|
||||
/// ClientboundResourcePackPopPacket: one pack, or every pack.
|
||||
PackPop(Option<u128>),
|
||||
/// The connection ended. `from_server`: the server gave the reason (or
|
||||
/// the connection was refused for good), rather than the connection
|
||||
/// failing (auto-reconnect retries only failures and shutdowns).
|
||||
@@ -55,6 +60,9 @@ pub enum Event {
|
||||
pub struct Session {
|
||||
events: Receiver<Event>,
|
||||
writer: Arc<Mutex<Option<ConnWriter>>>,
|
||||
/// The connection is in configuration (else in play). Changed only
|
||||
/// with `writer` locked, as the packet that switches is sent.
|
||||
configuring: Arc<AtomicBool>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
pub address: String,
|
||||
pub name: String,
|
||||
@@ -92,8 +100,10 @@ impl Session {
|
||||
) -> Self {
|
||||
let (send, events) = channel();
|
||||
let writer = Arc::new(Mutex::new(None));
|
||||
let configuring = Arc::new(AtomicBool::new(true));
|
||||
let counters = Arc::new(Mutex::new(None));
|
||||
let (thread_writer, thread_counters) = (writer.clone(), counters.clone());
|
||||
let thread_configuring = configuring.clone();
|
||||
let (address_owned, name_owned) = (address.to_owned(), name.to_owned());
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("horizon-net".into())
|
||||
@@ -107,6 +117,7 @@ impl Session {
|
||||
&lang,
|
||||
&send,
|
||||
&thread_writer,
|
||||
&thread_configuring,
|
||||
&thread_counters,
|
||||
);
|
||||
let from_server = result.is_ok();
|
||||
@@ -124,6 +135,7 @@ impl Session {
|
||||
Self {
|
||||
events,
|
||||
writer,
|
||||
configuring,
|
||||
thread,
|
||||
address: address.to_owned(),
|
||||
name: name.to_owned(),
|
||||
@@ -153,6 +165,21 @@ impl Session {
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
/// ServerboundResourcePackPacket, in whichever phase the connection is.
|
||||
pub fn send_pack_status(&self, id: u128, action: i32) {
|
||||
let status = cfg::ResourcePackResponse { id, action };
|
||||
let mut writer = self.writer.lock().unwrap();
|
||||
let body = if self.configuring.load(Ordering::Relaxed) {
|
||||
cfg::Serverbound::ResourcePack(status).encode()
|
||||
} else {
|
||||
play::Serverbound::ResourcePack(status).encode()
|
||||
};
|
||||
if let Some(w) = writer.as_mut()
|
||||
&& w.send(&body).is_err()
|
||||
{
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
pub fn disconnect(&mut self) {
|
||||
if let Some(w) = self.writer.lock().unwrap().take() {
|
||||
w.shutdown();
|
||||
@@ -253,6 +280,7 @@ fn run(
|
||||
lang: &Language,
|
||||
send: &Sender<Event>,
|
||||
shared_writer: &Mutex<Option<ConnWriter>>,
|
||||
configuring: &AtomicBool,
|
||||
shared_counters: &Mutex<Option<Arc<Counters>>>,
|
||||
) -> Result<String, String> {
|
||||
let (host, port, mut c) = if let Some(pipe) = local {
|
||||
@@ -377,18 +405,19 @@ fn run(
|
||||
.map_err(e)?;
|
||||
let (mut reader, writer) = c.split();
|
||||
*shared_writer.lock().unwrap() = Some(writer);
|
||||
let registries = configure(&mut reader, shared_writer, lang, send)?;
|
||||
let registries = configure(&mut reader, shared_writer, configuring, lang, send)?;
|
||||
let _ = send.send(Event::Joined {
|
||||
registries: Arc::new(registries),
|
||||
uuid: profile.uuid,
|
||||
name: profile.name,
|
||||
});
|
||||
receive_play(&mut reader, shared_writer, lang, send)
|
||||
receive_play(&mut reader, shared_writer, configuring, lang, send)
|
||||
}
|
||||
|
||||
fn receive_play(
|
||||
reader: &mut ConnReader,
|
||||
shared_writer: &Mutex<Option<ConnWriter>>,
|
||||
configuring: &AtomicBool,
|
||||
lang: &Language,
|
||||
send: &Sender<Event>,
|
||||
) -> Result<String, String> {
|
||||
@@ -416,15 +445,17 @@ fn receive_play(
|
||||
play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)),
|
||||
play::Clientbound::BundleDelimiter(_) => {}
|
||||
play::Clientbound::ResourcePackPush(p) => {
|
||||
// Declined: Horizon has no server resource packs.
|
||||
reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse {
|
||||
id: p.id,
|
||||
action: 1,
|
||||
}));
|
||||
let _ = send.send(Event::PackPush(p));
|
||||
}
|
||||
play::Clientbound::ResourcePackPop(p) => {
|
||||
let _ = send.send(Event::PackPop(p.id));
|
||||
}
|
||||
play::Clientbound::StartConfiguration(_) => {
|
||||
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
|
||||
let registries = configure(reader, shared_writer, lang, send)?;
|
||||
if let Some(w) = shared_writer.lock().unwrap().as_mut() {
|
||||
let _ = w.send(&play::Serverbound::ConfigurationAcknowledged(Empty).encode());
|
||||
configuring.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let registries = configure(reader, shared_writer, configuring, lang, send)?;
|
||||
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
|
||||
}
|
||||
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
|
||||
@@ -445,6 +476,7 @@ fn receive_play(
|
||||
fn configure(
|
||||
reader: &mut ConnReader,
|
||||
writer: &Mutex<Option<ConnWriter>>,
|
||||
configuring: &AtomicBool,
|
||||
lang: &Language,
|
||||
send: &Sender<Event>,
|
||||
) -> Result<Dynamic, String> {
|
||||
@@ -471,11 +503,12 @@ fn configure(
|
||||
cfg::Clientbound::CodeOfConduct(_) => {
|
||||
reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?
|
||||
}
|
||||
// The game answers: it may prompt the player first.
|
||||
cfg::Clientbound::ResourcePackPush(p) => {
|
||||
reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse {
|
||||
id: p.id,
|
||||
action: 1,
|
||||
}))?
|
||||
let _ = send.send(Event::PackPush(p));
|
||||
}
|
||||
cfg::Clientbound::ResourcePackPop(p) => {
|
||||
let _ = send.send(Event::PackPop(p.id));
|
||||
}
|
||||
cfg::Clientbound::CookieRequest(q) => {
|
||||
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
|
||||
@@ -485,7 +518,11 @@ fn configure(
|
||||
}
|
||||
cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)),
|
||||
cfg::Clientbound::FinishConfiguration(_) => {
|
||||
reply(cfg::Serverbound::FinishConfiguration(Empty))?;
|
||||
let mut w = writer.lock().unwrap();
|
||||
let w = w.as_mut().ok_or("Disconnected")?;
|
||||
w.send(&cfg::Serverbound::FinishConfiguration(Empty).encode())
|
||||
.map_err(|e| e.to_string())?;
|
||||
configuring.store(false, Ordering::Relaxed);
|
||||
return Ok(registries);
|
||||
}
|
||||
_ => {}
|
||||
@@ -602,7 +639,13 @@ mod tests {
|
||||
let (send, events) = channel();
|
||||
let thread_writer = writer.clone();
|
||||
let thread = std::thread::spawn(move || {
|
||||
receive_play(&mut reader, &thread_writer, &Language::new(), &send)
|
||||
receive_play(
|
||||
&mut reader,
|
||||
&thread_writer,
|
||||
&AtomicBool::new(false),
|
||||
&Language::new(),
|
||||
&send,
|
||||
)
|
||||
});
|
||||
let mut server = Connection::local(server);
|
||||
let teleport = play::Clientbound::PlayerPosition(play::PlayerPosition {
|
||||
|
||||
@@ -631,6 +631,17 @@ fn merge(kind: Merge, layers: &[Vec<u8>]) -> Option<Vec<u8>> {
|
||||
};
|
||||
serde_json::to_vec(&out).ok()
|
||||
}
|
||||
/// `DownloadedPackSource.loadRequestedPacks`: a server's downloaded pack,
|
||||
/// "World Specific Resources"; None when its `pack.mcmeta` can't be read. Its
|
||||
/// id names the file, which is named after its hash.
|
||||
pub fn server_pack(id: u128, path: &Path) -> Option<Pack> {
|
||||
let file = path.file_name()?.to_string_lossy();
|
||||
pack(
|
||||
format!("server/{id:032x}/{file}"),
|
||||
Text::translate("resourcePack.server.name", &[]),
|
||||
Source::Zip(path.to_path_buf()),
|
||||
)
|
||||
}
|
||||
/// The packs to apply for an options.txt `resourcePacks` list (bottom first).
|
||||
pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
|
||||
ids.iter()
|
||||
|
||||
@@ -13,8 +13,8 @@ use crate::{
|
||||
packets::{
|
||||
Empty,
|
||||
configuration::{
|
||||
ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPush,
|
||||
ResourcePackResponse, UpdateTags,
|
||||
ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop,
|
||||
ResourcePackPush, ResourcePackResponse, UpdateTags,
|
||||
},
|
||||
login::Property,
|
||||
},
|
||||
@@ -1640,6 +1640,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
RemoveEntities(RemoveEntities) = REMOVE_ENTITIES,
|
||||
RemoveMobEffect(RemoveMobEffect) = REMOVE_MOB_EFFECT,
|
||||
ResetScore(ResetScore) = RESET_SCORE,
|
||||
ResourcePackPop(ResourcePackPop) = RESOURCE_PACK_POP,
|
||||
ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH,
|
||||
Respawn(Respawn) = RESPAWN,
|
||||
RotateHead(RotateHead) = ROTATE_HEAD,
|
||||
|
||||
@@ -33,6 +33,7 @@ harness named checks that loader against vanilla).
|
||||
| Overlays per format | `pack.mcmeta` `overlays` | works | `test_resource_pack_parity` (an overlay for 26.3 applied, an older one not) |
|
||||
| Filters | `pack.mcmeta` `filter` | works | `test_resource_pack_parity` (`packs/pattern.rs` regex subset) |
|
||||
| Folder and zip packs, order, built-in packs | `resourcepacks/` | works | `test_resource_pack_parity`, `test_pack_selection_parity` |
|
||||
| Server resource packs: the prompt, the server list's Server Resource Packs setting, download (250 MiB, SHA-1, `downloads/` keeps 20), applied on top of the player's packs, removed on leaving | the server's `resource_pack_push`/`_pop` | works, no download toasts | `tools/server_pack_e2e.py` (against vanilla's server and Horizon's), unit tests in `server_packs.rs`; `test_server_resource_pack_parity` for Horizon's server |
|
||||
| Other namespaces | `assets/<namespace>/` | works | `test_resource_pack_parity` |
|
||||
| Block states: variants, multipart, weights, rotations, uvlock | `blockstates/` | works | `test_blockstate_model_parity`, `test_model_choice_parity`, `test_blockstate_transform_parity` |
|
||||
| Block models: parents, elements, rotations, faces, cullface, tint, shade, light emission, ambient occlusion | `models/block/` | works | `test_model_resolution_parity`, `test_model_baking_parity`, `test_section_mesh_parity` |
|
||||
@@ -74,7 +75,7 @@ harness named checks that loader against vanilla).
|
||||
| Core shaders | `shaders/core/`, `shaders/include/` | **no** | Horizon draws with WGSL; a pack's GLSL core shaders aren't run |
|
||||
| GPU warn list, regional compliance | `gpu_warnlist.json`, `regional_compliancies.json` | n/a | OpenGL driver warnings and play-time notices for some regions; not used |
|
||||
|
||||
Summary: 44 rows; 31 work, 3 partly, 8 don't (interpolated animation, TrueType fonts, credits and end poem,
|
||||
Summary: 45 rows; 32 work, 3 partly, 8 don't (interpolated animation, TrueType fonts, credits and end poem,
|
||||
villager hats, trims on worn armour, locator bar styles, post effects, core shaders), 2 don't apply. Except the
|
||||
shaders, the missing pieces are missing vanilla features too, and each vanilla parity fix covers the pack case as well.
|
||||
|
||||
@@ -83,6 +84,7 @@ shaders, the missing pieces are missing vanilla features too, and each vanilla p
|
||||
| Gap | Size | Where |
|
||||
| --- | --- | --- |
|
||||
| Animation `interpolate` | small | fix PR (`gfx.rs` `animate_sprites`) |
|
||||
| Server pack download toasts (`download.pack.*`) | small | `game/server_packs.rs` |
|
||||
| GUI scaling `width`/`height`, `stretch_inner`, `tile`, `stretch` | small | next fix PR (`ui.rs`) |
|
||||
| Villager hats | small | [#334](https://github.com/ludovic111/horizon/issues/334) |
|
||||
| `blur`/`clamp` from packs | small | [#335](https://github.com/ludovic111/horizon/issues/335) |
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Server resource packs end to end: a real Horizon client joins a real dedicated server (vanilla 26.3's, or
|
||||
Horizon's with --horizon-server BIN) that offers a test pack from a local HTTP server, through tools/net_capture.py,
|
||||
which records the statuses the client sends back.
|
||||
|
||||
The pack is built here: dirt recoloured blue, and three lang strings (dirt's name, the pause menu's "Back to Game",
|
||||
the server list's "Join Server"). Each scenario sets the server list entry's Server Resource Packs setting in
|
||||
servers.dat, joins, answers the prompt the way a player would (horizon-ctl clicks its buttons), and checks the
|
||||
statuses against what vanilla's client sends (ServerPackManager):
|
||||
|
||||
- required, Prompt, Disconnect: no status, the disconnected screen says "This server requires a custom resource
|
||||
pack", the setting stays Prompt;
|
||||
- required, Prompt, Proceed: ACCEPTED, DOWNLOADED, SUCCESSFULLY_LOADED; the setting becomes Enabled, the file is in
|
||||
downloads/ under its SHA-1 with a log.json entry, the HTTP request carries vanilla's X-Minecraft-* headers, the
|
||||
blue dirt is on screen (screenshot) and the pause menu says the pack's "Back to Game"; after leaving, the server
|
||||
list says "Join Server" again (the pack is gone);
|
||||
- required, Enabled: no prompt, the same three statuses, and no second download (the cache);
|
||||
- required with a wrong SHA-1: ACCEPTED, FAILED_DOWNLOAD, and the player still joins;
|
||||
- optional, Prompt, No: DECLINED, joins, the setting becomes Disabled; then joining again sends DECLINED without
|
||||
asking; then Prompt and Yes: the pack (no hash given) is downloaded and loaded;
|
||||
- optional on a dead URL: ACCEPTED, FAILED_DOWNLOAD, joins.
|
||||
|
||||
python3 tools/server_pack_e2e.py # vanilla's server
|
||||
python3 tools/server_pack_e2e.py --horizon-server target/release/horizon-client
|
||||
|
||||
Every game and server here runs in fresh temporary folders (HORIZON_HOME, HORIZON_LAUNCHER_HOME, XDG_*), with no
|
||||
audio and no self-update. Needs .local (the vanilla jars and prepared resources) and a built horizon-client and
|
||||
horizon-ctl (--bin DIR, default target/fast).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import lab # noqa: E402
|
||||
import net_capture # noqa: E402
|
||||
import test_rust_parity as base # noqa: E402
|
||||
from test_dedicated_server_parity import Server, free_port # noqa: E402
|
||||
|
||||
# ServerboundResourcePackPacket.Action, by ordinal.
|
||||
ACTIONS = ['successfully_loaded', 'declined', 'failed_download', 'accepted', 'downloaded', 'invalid_url',
|
||||
'failed_reload', 'discarded']
|
||||
LOADED = ['accepted', 'downloaded', 'successfully_loaded']
|
||||
FAILED = ['accepted', 'failed_download']
|
||||
REQUIRED_REASON = 'This server requires a custom resource pack'
|
||||
PLAYER = 'Steve'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false', 'white-list': 'false', 'level-seed': '12345', 'level-type': 'minecraft\\:flat',
|
||||
'generate-structures': 'false', 'view-distance': '3', 'simulation-distance': '3', 'spawn-protection': '0',
|
||||
'pause-when-empty-seconds': '-1', 'gamemode': 'creative',
|
||||
}
|
||||
|
||||
|
||||
class Failed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def check(condition, what):
|
||||
if not condition:
|
||||
raise Failed(what)
|
||||
print(f' ok: {what}')
|
||||
|
||||
|
||||
# The pack.
|
||||
|
||||
def png(width, height, pixel):
|
||||
rows = b''.join(b'\0' + b''.join(bytes(pixel(x, y)) for x in range(width)) for y in range(height))
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
header = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def build_pack(path):
|
||||
"""The test pack, byte for byte the same every time (fixed dates), and its SHA-1."""
|
||||
def blue(x, y):
|
||||
return (40, 90, 230, 255) if (x // 4 + y // 4) % 2 else (20, 50, 170, 255)
|
||||
files = {
|
||||
'pack.mcmeta': json.dumps({'pack': {'description': 'Horizon server pack test',
|
||||
'min_format': 97, 'max_format': 97}}).encode(),
|
||||
'assets/minecraft/textures/block/dirt.png': png(16, 16, blue),
|
||||
'assets/minecraft/lang/en_us.json': json.dumps({
|
||||
'block.minecraft.dirt': 'Blue Test Dirt',
|
||||
'menu.returnToGame': 'Back to Game (server pack)',
|
||||
'selectServer.select': 'Join Server (server pack)',
|
||||
}).encode(),
|
||||
}
|
||||
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
for name, data in files.items():
|
||||
z.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
|
||||
return hashlib.sha1(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def decode_png(data):
|
||||
"""RGB(A) pixels of an 8-bit PNG: (width, height, rows of (r, g, b))."""
|
||||
pos, idat, width = 8, b'', 0
|
||||
while pos < len(data):
|
||||
length, kind = struct.unpack('>I4s', data[pos:pos + 8])
|
||||
body = data[pos + 8:pos + 8 + length]
|
||||
if kind == b'IHDR':
|
||||
width, height, depth, colour = struct.unpack('>IIBB', body[:10])
|
||||
assert depth == 8 and colour in (2, 6), (depth, colour)
|
||||
channels = 4 if colour == 6 else 3
|
||||
elif kind == b'IDAT':
|
||||
idat += body
|
||||
pos += 12 + length
|
||||
raw, stride, rows, previous = zlib.decompress(idat), width * channels, [], bytearray(width * channels)
|
||||
for y in range(height):
|
||||
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
|
||||
for i in range(stride):
|
||||
left = line[i - channels] if i >= channels else 0
|
||||
up, corner = previous[i], previous[i - channels] if i >= channels else 0
|
||||
if kind == 1:
|
||||
line[i] = (line[i] + left) & 255
|
||||
elif kind == 2:
|
||||
line[i] = (line[i] + up) & 255
|
||||
elif kind == 3:
|
||||
line[i] = (line[i] + (left + up) // 2) & 255
|
||||
elif kind == 4:
|
||||
p = left + up - corner
|
||||
pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner)
|
||||
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else corner)) & 255
|
||||
rows.append([tuple(line[x * channels:x * channels + 3]) for x in range(width)])
|
||||
previous = line
|
||||
return width, height, rows
|
||||
|
||||
|
||||
def blue_share(path):
|
||||
"""How much of the picture's lower middle (the ground under a player looking down) is blue."""
|
||||
width, height, rows = decode_png(path.read_bytes())
|
||||
samples = [rows[y][x] for y in range(height // 2 + height // 8, height - height // 8, 4)
|
||||
for x in range(width // 4, 3 * width // 4, 4)]
|
||||
return sum(b > r + 60 and b > g + 30 for r, g, b in samples) / len(samples)
|
||||
|
||||
|
||||
# The HTTP server the pack comes from.
|
||||
|
||||
class Files(http.server.ThreadingHTTPServer):
|
||||
def __init__(self, files):
|
||||
self.files, self.requests = files, []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(handler):
|
||||
headers = {k: v for k, v in handler.headers.items() if k.lower().startswith(('x-minecraft', 'user-agent'))}
|
||||
self.requests.append((handler.path, headers))
|
||||
data = self.files.get(handler.path)
|
||||
if data is None:
|
||||
handler.send_error(404)
|
||||
return
|
||||
handler.send_response(200)
|
||||
handler.send_header('Content-Type', 'application/zip')
|
||||
handler.send_header('Content-Length', str(len(data)))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
|
||||
def log_message(handler, *args):
|
||||
pass
|
||||
super().__init__(('127.0.0.1', 0), Handler)
|
||||
threading.Thread(target=self.serve_forever, daemon=True).start()
|
||||
|
||||
def url(self, path):
|
||||
return f'http://127.0.0.1:{self.server_address[1]}{path}'
|
||||
|
||||
|
||||
# servers.dat (NbtIo.write: uncompressed, a named root compound).
|
||||
|
||||
def nbt_string(s):
|
||||
data = s.encode()
|
||||
return struct.pack('>H', len(data)) + data
|
||||
|
||||
|
||||
def write_servers(path, ip, setting):
|
||||
"""One entry for ip; setting True (Enabled), False (Disabled) or None (Prompt: no acceptTextures)."""
|
||||
entry = b'\x08' + nbt_string('name') + nbt_string('Pack test') + b'\x08' + nbt_string('ip') + nbt_string(ip)
|
||||
if setting is not None:
|
||||
entry += b'\x01' + nbt_string('acceptTextures') + bytes([int(setting)])
|
||||
root = b'\x09' + nbt_string('servers') + b'\x0a' + struct.pack('>i', 1) + entry + b'\x00'
|
||||
path.write_bytes(b'\x0a' + nbt_string('') + root + b'\x00')
|
||||
|
||||
|
||||
def read_setting(path):
|
||||
data = path.read_bytes()
|
||||
key = b'\x01' + nbt_string('acceptTextures')
|
||||
at = data.find(key)
|
||||
return None if at < 0 else bool(data[at + len(key)])
|
||||
|
||||
|
||||
# The game.
|
||||
|
||||
class Game:
|
||||
def __init__(self, bins, resources, work):
|
||||
self.home = work / 'home'
|
||||
for d in ('home', 'launcher', 'data', 'config'):
|
||||
(work / d).mkdir(parents=True)
|
||||
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
|
||||
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
|
||||
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
|
||||
self.log = work / 'c.log'
|
||||
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
|
||||
self.pid = reply.get('pid')
|
||||
|
||||
def __call__(self, *words, ok=True, timeout=300):
|
||||
result = subprocess.run(self.base + [str(w) for w in words], cwd=self.home, env=self.env,
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
lines = result.stdout.strip().splitlines()
|
||||
reply = json.loads(lines[-1]) if lines else {'error': result.stderr.strip()}
|
||||
print(f' {" ".join(map(str, words))[:80]} -> {json.dumps(reply)[:200]}')
|
||||
if ok and (result.returncode or 'error' in reply):
|
||||
raise Failed(f'{" ".join(map(str, words))}: {reply}')
|
||||
return reply
|
||||
|
||||
def labels(self):
|
||||
return [w.get('label') for w in self('ui').get('widgets', [])]
|
||||
|
||||
def wait_widget(self, widget, timeout=60):
|
||||
return self('wait-for', 'widget', widget, '--timeout', timeout, ok=False)
|
||||
|
||||
def quit(self):
|
||||
try:
|
||||
self('quit', ok=False, timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if self.pid:
|
||||
for _ in range(40):
|
||||
try:
|
||||
os.kill(self.pid, 0)
|
||||
except OSError:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
os.kill(self.pid, 9)
|
||||
|
||||
|
||||
def statuses(capture, conn):
|
||||
"""The resource pack statuses the client sent on one connection: (id, action), in order."""
|
||||
out = []
|
||||
for e in net_capture.load(capture):
|
||||
if e.get('conn') == conn and e.get('dir') == 'c2s' and e.get('name') == 'resource_pack':
|
||||
data = bytes.fromhex(e['data'])
|
||||
out.append((data[:16].hex(), ACTIONS[data[16]]))
|
||||
return out
|
||||
|
||||
|
||||
def connections(capture):
|
||||
return max([e['conn'] for e in net_capture.load(capture) if 'conn' in e], default=0)
|
||||
|
||||
|
||||
class Run:
|
||||
def __init__(self, args, out):
|
||||
self.args, self.out = args, out
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
deps = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
self.vanilla = ['java', '-Xmx2g', '-cp', deps, 'net.minecraft.server.Main', 'nogui']
|
||||
self.resources = lab.LOCAL / 'horizon-client' / lab.VERSION
|
||||
self.files = {}
|
||||
self.http = Files(self.files)
|
||||
self.sha1 = build_pack(out / 'test-pack.zip')
|
||||
self.files['/test-pack.zip'] = (out / 'test-pack.zip').read_bytes()
|
||||
self.files['/optional-pack.zip'] = self.files['/test-pack.zip']
|
||||
dead = free_port() # nothing listens there
|
||||
self.packs = {
|
||||
'required': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': self.sha1,
|
||||
'require-resource-pack': 'true', 'resource-pack-id': '5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a',
|
||||
'resource-pack-prompt': '["Blue dirt for ",{"text":"this test","color":"aqua"}]'},
|
||||
'bad-sha1': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': '0' * 40,
|
||||
'require-resource-pack': 'true'},
|
||||
'optional': {'resource-pack': self.http.url('/optional-pack.zip'), 'require-resource-pack': 'false'},
|
||||
'dead-url': {'resource-pack': f'http://127.0.0.1:{dead}/gone.zip', 'require-resource-pack': 'false'},
|
||||
}
|
||||
self.results = []
|
||||
|
||||
def start_server(self, kind, work):
|
||||
directory = work / f'server-{kind}'
|
||||
directory.mkdir()
|
||||
port = free_port()
|
||||
props = dict(PROPERTIES, **self.packs[kind], **{'server-port': str(port)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
|
||||
encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
if self.args.horizon_server:
|
||||
command = [self.args.horizon_server, '--resources', self.resources, '--dedicated', '--nogui']
|
||||
else:
|
||||
command = self.vanilla
|
||||
server = Server(command, directory, f'server-{kind}')
|
||||
server.wait_for(r'Done \(', timeout=300)
|
||||
return server, port
|
||||
|
||||
def join(self, game, address, scenario):
|
||||
"""Connects; returns the capture's connection number."""
|
||||
game('connect', address, PLAYER)
|
||||
deadline = time.time() + 30
|
||||
while connections(self.capture) <= self.conn and time.time() < deadline:
|
||||
time.sleep(0.2)
|
||||
self.conn = connections(self.capture)
|
||||
print(f' [{scenario}] connection {self.conn}')
|
||||
return self.conn
|
||||
|
||||
def scenario(self, name, fn):
|
||||
print(f'- {name}')
|
||||
try:
|
||||
fn()
|
||||
self.results.append((name, 'pass', ''))
|
||||
except Exception as e: # noqa: BLE001: report every scenario
|
||||
print(f' FAILED: {e}')
|
||||
self.results.append((name, 'FAIL', str(e)[:300]))
|
||||
if self.game('state', ok=False).get('screen') not in (None, 'title'):
|
||||
self.leave(self.game)
|
||||
|
||||
def wait_statuses(self, conn, want, timeout=60):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
got = [a for _, a in statuses(self.capture, conn)]
|
||||
if len(got) >= len(want) and got[:len(want)] == want or got[:1] and got != want[:len(got)]:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
time.sleep(1.5) # nothing more comes after the last one
|
||||
got = [a for _, a in statuses(self.capture, conn)]
|
||||
check(got == want, f'statuses {got} == {want}')
|
||||
|
||||
def leave(self, game):
|
||||
game('disconnect', ok=False)
|
||||
time.sleep(1)
|
||||
|
||||
def run(self):
|
||||
work = Path(tempfile.mkdtemp(prefix='hz-server-packs-'))
|
||||
print(f'scratch: {work}')
|
||||
# The servers too get scratch homes (the game sets its own below).
|
||||
for var, sub in (('HORIZON_HOME', 'home'), ('HORIZON_LAUNCHER_HOME', 'launcher'), ('XDG_DATA_HOME', 'data'),
|
||||
('XDG_CONFIG_HOME', 'config')):
|
||||
(work / 'servers' / sub).mkdir(parents=True)
|
||||
os.environ[var] = str(work / 'servers' / sub)
|
||||
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
|
||||
servers_dat = game.home / 'servers.dat'
|
||||
downloads = game.home / 'downloads'
|
||||
try:
|
||||
for kind, scenarios in self.plan(game, servers_dat, downloads):
|
||||
server, port = self.start_server(kind, work)
|
||||
# One capture per server: its connections are numbered from 1.
|
||||
self.capture, self.conn = self.out / f'capture-{kind}.jsonl', 0
|
||||
self.capture.touch()
|
||||
listen = free_port()
|
||||
stop = net_capture.start_background(listen, f'127.0.0.1:{port}', self.capture)
|
||||
self.address = f'127.0.0.1:{listen}'
|
||||
try:
|
||||
self.server = server
|
||||
for name, fn in scenarios:
|
||||
self.scenario(f'{kind}: {name}', fn)
|
||||
finally:
|
||||
stop.set()
|
||||
server.stop()
|
||||
shutil.copy(server.log_path, self.out / server.log_path.name)
|
||||
finally:
|
||||
game.quit()
|
||||
if game.log.exists():
|
||||
shutil.copy(game.log, self.out / 'client.log')
|
||||
if downloads.exists():
|
||||
shutil.copytree(downloads, self.out / 'downloads')
|
||||
return work
|
||||
|
||||
def plan(self, game, servers_dat, downloads):
|
||||
sha1 = self.sha1
|
||||
|
||||
def required_disconnect():
|
||||
write_servers(servers_dat, self.address, None)
|
||||
conn = self.join(game, self.address, 'decline')
|
||||
check(game.wait_widget('disconnect').get('ok'), 'the required prompt opened')
|
||||
labels = game.labels()
|
||||
check('Proceed' in labels and 'Disconnect' in labels, f'Proceed and Disconnect buttons: {labels}')
|
||||
game('screenshot', self.out / 'prompt-required.png')
|
||||
game('click', 'disconnect')
|
||||
self.wait_statuses(conn, [])
|
||||
screen = json.dumps(game('screen'))
|
||||
check(REQUIRED_REASON in screen, 'the disconnected screen says "This server requires a custom resource pack"')
|
||||
check(read_setting(servers_dat) is None, 'the setting stays Prompt')
|
||||
check(not any(p == '/test-pack.zip' for p, _ in self.http.requests), 'nothing was downloaded')
|
||||
|
||||
def required_proceed():
|
||||
conn = self.join(game, self.address, 'proceed')
|
||||
check(game.wait_widget('proceed').get('ok'), 'the required prompt opened')
|
||||
game('click', 'proceed')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, LOADED)
|
||||
check(read_setting(servers_dat) is True, 'the setting became Enabled (acceptTextures 1)')
|
||||
pack_id = self.packs['required']['resource-pack-id']
|
||||
check((downloads / pack_id / sha1).exists(), f'downloads/{pack_id}/{sha1} is cached')
|
||||
log = json.loads((downloads / 'log.json').read_text().splitlines()[-1])
|
||||
check(log.get('id') == pack_id and log.get('hash') == sha1
|
||||
and log.get('file', {}).get('name') == f'{pack_id}/{sha1}', f'log.json entry {log}')
|
||||
path, headers = [r for r in self.http.requests if r[0] == '/test-pack.zip'][-1]
|
||||
want = {'X-Minecraft-Username': PLAYER, 'X-Minecraft-Version': lab.VERSION,
|
||||
'X-Minecraft-Version-ID': lab.VERSION, 'X-Minecraft-Pack-Format': '97.1',
|
||||
'User-Agent': f'Minecraft Java/{lab.VERSION}'}
|
||||
check(all(headers.get(k) == v for k, v in want.items()) and len(headers.get('X-Minecraft-UUID', '')) == 32,
|
||||
f'download headers {headers}')
|
||||
self.server.console(f'execute at {PLAYER} run fill ~-6 ~-1 ~-6 ~6 ~-1 ~6 minecraft:dirt')
|
||||
game('look', 0, 90)
|
||||
game('wait', 40)
|
||||
shot = self.out / 'applied-blue-dirt.png'
|
||||
game('screenshot', shot)
|
||||
share = blue_share(shot)
|
||||
check(share > 0.5, f'the ground is the pack\'s blue dirt ({share:.0%} of the samples)')
|
||||
game('key', 'esc', 'tap')
|
||||
game('wait', 5)
|
||||
labels = game.labels()
|
||||
check('Back to Game (server pack)' in labels, f'the pause menu uses the pack\'s lang: {labels}')
|
||||
game('key', 'esc', 'tap')
|
||||
self.leave(game)
|
||||
labels = game.labels()
|
||||
check('Join Server' in labels and 'Join Server (server pack)' not in labels,
|
||||
f'after leaving, the pack is gone: {labels}')
|
||||
|
||||
def required_enabled():
|
||||
before = len(self.http.requests)
|
||||
conn = self.join(game, self.address, 'enabled')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, LOADED)
|
||||
check(len(self.http.requests) == before, 'no second download: the cached file is used')
|
||||
game('key', 'esc', 'tap')
|
||||
game('wait', 5)
|
||||
check('Back to Game (server pack)' in game.labels(), 'the pack is applied without a prompt')
|
||||
game('key', 'esc', 'tap')
|
||||
self.leave(game)
|
||||
|
||||
def bad_sha1():
|
||||
write_servers(servers_dat, self.address, True)
|
||||
conn = self.join(game, self.address, 'bad-sha1')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, FAILED)
|
||||
entries = [json.loads(line) for line in (downloads / 'log.json').read_text().splitlines()]
|
||||
failed = [e for e in entries if e.get('hash') == '0' * 40]
|
||||
check(failed and failed[-1].get('error') == 'download_failed' and 'file' not in failed[-1],
|
||||
f'log.json records the failure: {failed[-1:]}')
|
||||
self.leave(game)
|
||||
|
||||
def optional_no():
|
||||
write_servers(servers_dat, self.address, None)
|
||||
conn = self.join(game, self.address, 'optional-no')
|
||||
check(game.wait_widget('no').get('ok'), 'the optional prompt opened')
|
||||
labels = game.labels()
|
||||
check('Yes' in labels and 'No' in labels, f'Yes and No buttons: {labels}')
|
||||
game('screenshot', self.out / 'prompt-optional.png')
|
||||
game('click', 'no')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, ['declined'])
|
||||
check(read_setting(servers_dat) is False, 'the setting became Disabled (acceptTextures 0)')
|
||||
self.leave(game)
|
||||
|
||||
def optional_disabled():
|
||||
conn = self.join(game, self.address, 'optional-disabled')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, ['declined'])
|
||||
self.leave(game)
|
||||
|
||||
def optional_yes():
|
||||
write_servers(servers_dat, self.address, None)
|
||||
conn = self.join(game, self.address, 'optional-yes')
|
||||
check(game.wait_widget('yes').get('ok'), 'the optional prompt opened')
|
||||
game('click', 'yes')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, LOADED)
|
||||
check(any(r[0] == '/optional-pack.zip' for r in self.http.requests), 'downloaded without a hash')
|
||||
self.leave(game)
|
||||
|
||||
def dead_url():
|
||||
write_servers(servers_dat, self.address, True)
|
||||
conn = self.join(game, self.address, 'dead-url')
|
||||
game('wait-for', 'loaded', '--timeout', 180)
|
||||
self.wait_statuses(conn, FAILED)
|
||||
self.leave(game)
|
||||
|
||||
return [
|
||||
('required', [('Disconnect at the prompt', required_disconnect), ('Proceed', required_proceed),
|
||||
('Enabled, cached', required_enabled)]),
|
||||
('bad-sha1', [('wrong SHA-1', bad_sha1)]),
|
||||
('optional', [('No at the prompt', optional_no), ('Disabled', optional_disabled),
|
||||
('Yes at the prompt, no hash', optional_yes)]),
|
||||
('dead-url', [('dead URL', dead_url)]),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--bin', default=str(lab.cargo_target() / 'fast'), help='horizon-client and horizon-ctl')
|
||||
parser.add_argument('--horizon-server', help='a horizon-client binary to run as the dedicated server')
|
||||
parser.add_argument('--out', default=str(lab.LOCAL / 'server-pack-e2e'))
|
||||
args = parser.parse_args()
|
||||
out = Path(args.out) / ('horizon' if args.horizon_server else 'vanilla')
|
||||
shutil.rmtree(out, ignore_errors=True)
|
||||
out.mkdir(parents=True)
|
||||
run = Run(args, out)
|
||||
work = run.run()
|
||||
print(f'\nserver: {"horizon" if args.horizon_server else "vanilla 26.3"}; evidence in {out}')
|
||||
for name, result, detail in run.results:
|
||||
print(f' {result:4} {name}' + (f': {detail}' if detail else ''))
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
if any(r != 'pass' for _, r, _ in run.results):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user