Merge remote-tracking branch 'upstream/main' into fix/piston-entity-push
This commit is contained in:
@@ -103,6 +103,8 @@ mod minecarts;
|
||||
mod mob_blocks;
|
||||
mod mob_gear;
|
||||
mod mod_input;
|
||||
#[cfg(feature = "mods")]
|
||||
mod mod_recipes;
|
||||
mod mod_render;
|
||||
mod mods;
|
||||
mod mount_menu;
|
||||
|
||||
@@ -126,28 +126,7 @@ impl Game<'_> {
|
||||
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
|
||||
let mut finder = match self.player_spawn {
|
||||
Some(finder) => finder,
|
||||
None if self.level.game_mode == 2 => {
|
||||
// Adventure mode: the suggestion itself.
|
||||
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
|
||||
finder.next_candidate();
|
||||
finder
|
||||
}
|
||||
None => {
|
||||
let mut radius = self.ui.rules.int("respawn_radius").max(0);
|
||||
let to_border = self
|
||||
.border
|
||||
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
|
||||
.floor() as i32;
|
||||
if to_border < radius {
|
||||
radius = to_border;
|
||||
}
|
||||
if to_border <= 1 {
|
||||
radius = 1;
|
||||
}
|
||||
PlayerSpawnFinder::new(suggestion, radius, |n| {
|
||||
entity_random().next_int_bound(n).unwrap_or(0)
|
||||
})
|
||||
}
|
||||
None => self.spawn_finder(suggestion),
|
||||
};
|
||||
let found = loop {
|
||||
let Some(candidate) = finder.next_candidate() else {
|
||||
@@ -176,6 +155,58 @@ impl Game<'_> {
|
||||
self.player_spawn = found.is_none().then_some(finder);
|
||||
Ok(found)
|
||||
}
|
||||
/// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
|
||||
/// by the world border; the suggestion itself in adventure mode.
|
||||
fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder {
|
||||
if self.level.game_mode == 2 {
|
||||
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
|
||||
finder.next_candidate();
|
||||
return finder;
|
||||
}
|
||||
let mut radius = self.ui.rules.int("respawn_radius").max(0);
|
||||
let to_border = self
|
||||
.border
|
||||
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
|
||||
.floor() as i32;
|
||||
if to_border < radius {
|
||||
radius = to_border;
|
||||
}
|
||||
if to_border <= 1 {
|
||||
radius = 1;
|
||||
}
|
||||
PlayerSpawnFinder::new(suggestion, radius, |n| {
|
||||
entity_random().next_int_bound(n).unwrap_or(0)
|
||||
})
|
||||
}
|
||||
/// ServerPlayer.adjustSpawnLocation for a server's new player: where
|
||||
/// PlayerSpawnFinder.findSpawn puts their feet around the world spawn
|
||||
/// (`spawn`, the feet there), so that players new to a world don't all
|
||||
/// stand in one spot. Vanilla waits for each candidate's chunk; a server
|
||||
/// tick can't, so a candidate in a chunk not loaded yet is passed over,
|
||||
/// and `spawn` stays when the search never reaches a loaded column.
|
||||
pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] {
|
||||
let suggestion = spawn.map(|v| v.floor() as i32);
|
||||
let mut finder = self.spawn_finder(suggestion);
|
||||
while let Some(candidate) = finder.next_candidate() {
|
||||
let (x, z) = match candidate {
|
||||
SpawnCandidate::Column(x, z) => (x, z),
|
||||
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
|
||||
};
|
||||
if !self.streaming.is_lit(x >> 4, z >> 4) {
|
||||
continue;
|
||||
}
|
||||
let feet = match candidate {
|
||||
SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z)
|
||||
.filter(|&pos| self.player_fits(pos))
|
||||
.map(bottom_center),
|
||||
SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)),
|
||||
};
|
||||
if let Some(feet) = feet {
|
||||
return [feet.x, feet.y, feet.z];
|
||||
}
|
||||
}
|
||||
spawn
|
||||
}
|
||||
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
|
||||
/// block's bottom centre touches no block or liquid.
|
||||
fn player_fits(&self, pos: [i32; 3]) -> bool {
|
||||
|
||||
@@ -1128,8 +1128,17 @@ impl Game<'_> {
|
||||
g.game_mode = default_mode;
|
||||
}
|
||||
if !known {
|
||||
g.position = spawn;
|
||||
g.previous_position = spawn;
|
||||
// ServerPlayer.adjustSpawnLocation: a player new to the world
|
||||
// stands where PlayerSpawnFinder puts them, not all on one spot
|
||||
// (it reads the loaded level, which holds the spawn when it is
|
||||
// the overworld).
|
||||
let feet = if self.dim == super::Dim::Overworld {
|
||||
self.server_player_spawn(spawn)
|
||||
} else {
|
||||
spawn
|
||||
};
|
||||
g.position = feet;
|
||||
g.previous_position = feet;
|
||||
g.health = 20.0;
|
||||
g.food = 20;
|
||||
g.dimension = super::Dim::Overworld.id().to_owned();
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
//! Capability `recipes` (docs/mods.md): every item and recipe the game
|
||||
//! knows, made once for the mods that read them, and the recipe book's
|
||||
//! known displays. The recipes are the window's own data: the world's in
|
||||
//! single player, vanilla's on a server (a client is sent no others), while
|
||||
//! the known displays follow the server's book as the recipe book does.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
crafting::Ingredient,
|
||||
items::ItemStack,
|
||||
recipe_book::{Category, Display},
|
||||
stations::Smithing,
|
||||
};
|
||||
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
/// Item id -> its index in [`Recipes::items`].
|
||||
struct Index(HashMap<Arc<str>, u32>);
|
||||
impl Index {
|
||||
fn stack(&self, item: &str, count: u32, components: String) -> Option<RecipeStack> {
|
||||
Some(RecipeStack {
|
||||
item: *self.0.get(item)?,
|
||||
count,
|
||||
components,
|
||||
})
|
||||
}
|
||||
fn of(&self, s: &ItemStack) -> Option<RecipeStack> {
|
||||
self.stack(&s.item, s.count, components(s))
|
||||
}
|
||||
fn any(&self, i: &Ingredient) -> Vec<RecipeStack> {
|
||||
i.1.iter()
|
||||
.filter_map(|id| self.stack(id, 1, String::new()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stack's components beyond its item's, as vanilla's item syntax writes
|
||||
/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "".
|
||||
fn components(s: &ItemStack) -> String {
|
||||
use horizon_world::nbt::Tag;
|
||||
let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else {
|
||||
return String::new();
|
||||
};
|
||||
let parts: Vec<String> = entries
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
format!(
|
||||
"{}={}",
|
||||
k.to_string_lossy(),
|
||||
horizon_client::snbt::to_snbt(v)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
format!("[{}]", parts.join(","))
|
||||
}
|
||||
|
||||
fn recipe(id: String, kind: RecipeKind) -> Recipe {
|
||||
Recipe {
|
||||
id,
|
||||
kind,
|
||||
category: String::new(),
|
||||
group: String::new(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
slots: Vec::new(),
|
||||
results: Vec::new(),
|
||||
cooking_time: 0,
|
||||
experience: 0.0,
|
||||
book_id: -1,
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Capability `recipes`'s tables and known displays for this tick's
|
||||
/// snapshot; nothing while no running mod reads them.
|
||||
pub(super) fn mod_recipes(&mut self) -> (Option<Arc<Recipes>>, Arc<[i32]>) {
|
||||
if !self.mods.mods.wants_recipes() {
|
||||
return (None, Arc::from([]));
|
||||
}
|
||||
if self.mods.recipes.is_none() {
|
||||
self.mods.recipes = Some(Arc::new(self.make_mod_recipes()));
|
||||
}
|
||||
let (version, known) = self.recipe_book_displays();
|
||||
if self.mods.known_recipes.0 != Some(version) {
|
||||
self.mods.known_recipes = (Some(version), known.into());
|
||||
}
|
||||
(self.mods.recipes.clone(), self.mods.known_recipes.1.clone())
|
||||
}
|
||||
|
||||
fn make_mod_recipes(&mut self) -> Recipes {
|
||||
let names = &self.pack.names;
|
||||
let items = self.res.items();
|
||||
let mut tags: HashMap<&str, Vec<String>> = HashMap::new();
|
||||
for (tag, members) in &items.item_tags {
|
||||
for m in members {
|
||||
tags.entry(m).or_default().push(tag.clone());
|
||||
}
|
||||
}
|
||||
let table: Vec<RecipeItem> = items
|
||||
.registry_order
|
||||
.iter()
|
||||
.map(|id| RecipeItem {
|
||||
id: id.to_string(),
|
||||
name: names.display_item(id),
|
||||
tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| {
|
||||
t.sort();
|
||||
t
|
||||
}),
|
||||
})
|
||||
.collect();
|
||||
let index = Index(
|
||||
items
|
||||
.registry_order
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| (id.clone(), i as u32))
|
||||
.collect(),
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
let cooking: HashMap<String, (u32, f32)> = self
|
||||
.res
|
||||
.recipes()
|
||||
.cooking
|
||||
.iter()
|
||||
.map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience)))
|
||||
.collect();
|
||||
for e in self.recipe_book_entries() {
|
||||
let furnace = |c: Category| match c.name().split('_').next() {
|
||||
Some("blast") => RecipeKind::Blasting,
|
||||
Some("smoker") => RecipeKind::Smoking,
|
||||
_ => RecipeKind::Smelting,
|
||||
};
|
||||
let kind = match &e.display {
|
||||
Display::Shaped { .. } => RecipeKind::CraftingShaped,
|
||||
Display::Shapeless(_) => RecipeKind::CraftingShapeless,
|
||||
Display::Furnace(_) => furnace(e.category),
|
||||
};
|
||||
let mut r = recipe(e.id.clone(), kind);
|
||||
r.category = e.category.name().to_owned();
|
||||
r.group = e.group.clone().unwrap_or_default();
|
||||
r.book_id = e.display_id;
|
||||
r.slots = match &e.display {
|
||||
Display::Shaped {
|
||||
width,
|
||||
height,
|
||||
cells,
|
||||
} => {
|
||||
(r.width, r.height) = (*width as u32, *height as u32);
|
||||
cells
|
||||
.iter()
|
||||
.map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i)))
|
||||
.collect()
|
||||
}
|
||||
Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(),
|
||||
Display::Furnace(i) => vec![index.any(i)],
|
||||
};
|
||||
// Requirements shown as other stacks (an arrow's potions): the
|
||||
// requirement's index counts the filled slots only.
|
||||
let filled: Vec<usize> = (0..r.slots.len())
|
||||
.filter(
|
||||
|&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()),
|
||||
)
|
||||
.collect();
|
||||
for (req, stacks) in &e.stacks {
|
||||
if let Some(&k) = filled.get(*req) {
|
||||
r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect();
|
||||
}
|
||||
}
|
||||
r.results = e.results().iter().filter_map(|s| index.of(s)).collect();
|
||||
if let Some(&(time, xp)) = cooking.get(&e.id) {
|
||||
(r.cooking_time, r.experience) = (time, xp);
|
||||
}
|
||||
out.push(r);
|
||||
}
|
||||
for c in &self.res.recipes().cooking {
|
||||
if c.kind == "minecraft:campfire_cooking" {
|
||||
let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire);
|
||||
r.group = c.group.clone();
|
||||
r.slots = vec![index.any(&c.ingredient)];
|
||||
r.results = index.of(&c.result).into_iter().collect();
|
||||
(r.cooking_time, r.experience) = (c.time, c.experience);
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
let stations = self.res.stations();
|
||||
for s in &stations.recipes.stonecutting {
|
||||
let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting);
|
||||
r.slots = vec![index.any(&s.input)];
|
||||
r.results = index.of(&s.result).into_iter().collect();
|
||||
out.push(r);
|
||||
}
|
||||
for s in &stations.recipes.smithing {
|
||||
let (id, template, base, addition, results) = match s {
|
||||
Smithing::Transform {
|
||||
id,
|
||||
template,
|
||||
base,
|
||||
addition,
|
||||
result,
|
||||
} => (
|
||||
id,
|
||||
template,
|
||||
base,
|
||||
addition,
|
||||
index.stack(result, 1, String::new()).into_iter().collect(),
|
||||
),
|
||||
Smithing::Trim {
|
||||
id,
|
||||
template,
|
||||
base,
|
||||
addition,
|
||||
..
|
||||
} => (id, template, base, addition, index.any(base)),
|
||||
};
|
||||
let mut r = recipe(id.clone(), RecipeKind::Smithing);
|
||||
r.slots = vec![index.any(template), index.any(base), index.any(addition)];
|
||||
r.results = results;
|
||||
out.push(r);
|
||||
}
|
||||
for b in &stations.brewing.recipes {
|
||||
let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec<RecipeStack> {
|
||||
let mut item_ids: Vec<&String> = p.items.iter().collect();
|
||||
item_ids.sort();
|
||||
let mut potions: Vec<&String> = p.potions.iter().flatten().collect();
|
||||
potions.sort();
|
||||
item_ids
|
||||
.into_iter()
|
||||
.flat_map(|item| {
|
||||
let one = |c: String| index.stack(item, 1, c);
|
||||
if potions.is_empty() {
|
||||
one(String::new()).into_iter().collect::<Vec<_>>()
|
||||
} else {
|
||||
potions
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut r = recipe(b.id.clone(), RecipeKind::Brewing);
|
||||
r.slots = vec![potion(&b.input), potion(&b.reagent)];
|
||||
r.results = index.of(&b.output).into_iter().collect();
|
||||
out.push(r);
|
||||
}
|
||||
Recipes {
|
||||
items: table,
|
||||
recipes: out,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,12 @@ pub(super) struct ModsState {
|
||||
/// The HUD font's advances for `render.text-width`, made once.
|
||||
#[cfg(feature = "mods")]
|
||||
font_widths: std::sync::Arc<[f32]>,
|
||||
/// Capability `recipes`'s tables, made once a mod reads them.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) recipes: Option<std::sync::Arc<horizon_mods::Recipes>>,
|
||||
/// The recipe book's known displays, and the book's version they are of.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) known_recipes: (Option<u64>, std::sync::Arc<[i32]>),
|
||||
/// Extras that are official mods now, being installed.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) moved: super::moved_extras::MovedState,
|
||||
@@ -301,6 +307,8 @@ impl Game<'_> {
|
||||
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
|
||||
// Entries were replaced wholesale: a screen's owner index is stale.
|
||||
self.mods.screen = None;
|
||||
// Content mods may have changed the items: remade on the next read.
|
||||
self.mods.recipes = None;
|
||||
self.list_mods();
|
||||
self.sync_mod_commands();
|
||||
self.show_mod_output();
|
||||
@@ -449,6 +457,7 @@ impl Game<'_> {
|
||||
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
|
||||
.collect();
|
||||
}
|
||||
let (recipes, known_recipes) = self.mod_recipes();
|
||||
Snapshot {
|
||||
player,
|
||||
clock,
|
||||
@@ -460,6 +469,8 @@ impl Game<'_> {
|
||||
font_widths: self.mods.font_widths.clone(),
|
||||
players,
|
||||
view_hit: self.mod_view_hit(),
|
||||
recipes,
|
||||
known_recipes,
|
||||
}
|
||||
}
|
||||
/// The first block along the player's view within
|
||||
|
||||
@@ -338,6 +338,25 @@ impl Game<'_> {
|
||||
ui.client_known = Some(known.clone());
|
||||
ui.client_version += 1;
|
||||
}
|
||||
/// Every entry of the book, in its order (capability `recipes`).
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn recipe_book_entries(&mut self) -> Vec<Entry> {
|
||||
self.ensure_book();
|
||||
self.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map_or_else(Vec::new, |b| b.entries.clone())
|
||||
}
|
||||
/// The display ids the player's book holds, and a number that changes
|
||||
/// whenever they do (capability `recipes`).
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec<i32>) {
|
||||
self.sync_client_book();
|
||||
(
|
||||
self.recipe_ui.client_version,
|
||||
self.recipe_ui.client.displays(),
|
||||
)
|
||||
}
|
||||
fn ensure_book(&mut self) {
|
||||
if self.recipe_ui.book.is_none() {
|
||||
let mut book = Book::build(self.res.recipes(), self.res.items());
|
||||
|
||||
@@ -448,6 +448,7 @@ pub fn grindstone_experience(
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Smithing {
|
||||
Transform {
|
||||
id: String,
|
||||
template: Ingredient,
|
||||
base: Ingredient,
|
||||
addition: Ingredient,
|
||||
@@ -527,6 +528,7 @@ impl StationRecipes {
|
||||
);
|
||||
match v["type"].as_str().unwrap_or("") {
|
||||
"minecraft:smithing_transform" => smithing.push(Smithing::Transform {
|
||||
id,
|
||||
template: ingredient(&v["template"], items),
|
||||
base: ingredient(&v["base"], items),
|
||||
addition: ingredient(&v["addition"], items),
|
||||
@@ -630,6 +632,7 @@ impl StationRecipes {
|
||||
base: b,
|
||||
addition: a,
|
||||
result,
|
||||
..
|
||||
} => {
|
||||
if t.test(template) && b.test(base) && a.test(addition) {
|
||||
// SmithingTransformRecipe: transmute the base keeping its components.
|
||||
|
||||
@@ -175,6 +175,11 @@ pub enum Done {
|
||||
}
|
||||
struct Queued {
|
||||
priority: i64,
|
||||
/// The column the job is for and what it adds to the column's distance
|
||||
/// (`Streaming::submit`): the priority is computed again from them when
|
||||
/// the centre moves (`Streaming::requeue`). None for saves, which go first.
|
||||
at: Option<(i32, i32)>,
|
||||
bias: i64,
|
||||
order: u64,
|
||||
job: Job,
|
||||
}
|
||||
@@ -222,6 +227,9 @@ pub struct Streaming {
|
||||
/// radius it was last ranked for.
|
||||
decoration_order: DecorationOrder,
|
||||
order_area: Option<((i32, i32), i32)>,
|
||||
/// What the queued jobs' priorities were computed from (`requeue`): the
|
||||
/// centre, the loading screen, the band, and the extra areas.
|
||||
queue_basis: (((i32, i32), bool, Option<Band>), Vec<((i32, i32), i32)>),
|
||||
finishing: FxHashSet<(i32, i32)>,
|
||||
decorates: bool,
|
||||
lighting: FxHashMap<(i32, i32), u64>,
|
||||
@@ -544,6 +552,7 @@ impl Streaming {
|
||||
saving: 0,
|
||||
decoration_order: DecorationOrder::default(),
|
||||
order_area: None,
|
||||
queue_basis: Default::default(),
|
||||
finishing: Default::default(),
|
||||
decorates: generator.decorates(),
|
||||
lighting: Default::default(),
|
||||
@@ -648,15 +657,39 @@ impl Streaming {
|
||||
world.dirty_sections.take_column(x, z);
|
||||
world.chunks.remove(&(x, z))
|
||||
}
|
||||
fn submit(&mut self, priority: i64, job: Job) {
|
||||
/// Queue a job for the column `at`, nearest first: its distance (`distance`)
|
||||
/// times four plus `bias`, which orders a column's jobs. A job without a
|
||||
/// column (a save) goes ahead of every other.
|
||||
fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) {
|
||||
self.order += 1;
|
||||
let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias);
|
||||
self.shared.queue.lock().unwrap().push(Queued {
|
||||
priority,
|
||||
at,
|
||||
bias,
|
||||
order: self.order,
|
||||
job,
|
||||
});
|
||||
self.shared.ready.notify_one();
|
||||
}
|
||||
/// Rank the queued jobs again when what their priorities were computed
|
||||
/// from changed: the centre, the extra areas, the band, or the loading
|
||||
/// screen (ring order, `Ranges::rings`, whose values are far above the
|
||||
/// distances used after it). Vanilla's chunk task queue follows the
|
||||
/// current ticket levels in the same way. Without it, generation queued
|
||||
/// while the loading screen was up waited behind every job queued after
|
||||
/// it, and with it the decoration of the chunks around the player: at
|
||||
/// render distance 32 nothing was decorated until every proto chunk had
|
||||
/// been generated.
|
||||
fn requeue(&mut self) {
|
||||
let basis = (self.center, self.loading, self.band);
|
||||
if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra {
|
||||
return;
|
||||
}
|
||||
self.queue_basis = (basis, self.extra.clone());
|
||||
let mut queue = self.shared.queue.lock().unwrap();
|
||||
rank_again(&mut queue, |x, z| self.distance(x, z));
|
||||
}
|
||||
fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) {
|
||||
self.generation_scan.exhausted = false;
|
||||
self.decorating -= 1;
|
||||
@@ -686,7 +719,7 @@ impl Streaming {
|
||||
self.saving += 1;
|
||||
// Ahead of every other job: a column generated again meanwhile
|
||||
// would not find them saved.
|
||||
self.submit(i64::MIN, Job::Save(protos));
|
||||
self.submit(None, 0, Job::Save(protos));
|
||||
}
|
||||
}
|
||||
fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) {
|
||||
@@ -829,6 +862,7 @@ impl Streaming {
|
||||
return (uploads, Vec::new());
|
||||
}
|
||||
ExtraCover::refresh(&mut self.cover, &self.extra);
|
||||
self.requeue();
|
||||
self.relight_edits(world);
|
||||
let deferred = std::mem::take(&mut self.deferred);
|
||||
let received = std::iter::from_fn(|| self.results.try_recv().ok());
|
||||
@@ -984,7 +1018,7 @@ impl Streaming {
|
||||
.expect("present proto");
|
||||
self.finishing.insert((x, z));
|
||||
self.written.remove(&(x, z));
|
||||
self.submit(self.distance(x, z) * 4, Job::Finish(proto));
|
||||
self.submit(Some((x, z)), 0, Job::Finish(proto));
|
||||
}
|
||||
}
|
||||
// Decorate chunks whose 3x3 proto neighbourhood is available, in
|
||||
@@ -1052,7 +1086,7 @@ impl Streaming {
|
||||
w.0 = self.decoration_order.rank_or_append(w.2, w.3);
|
||||
}
|
||||
wanted.sort_unstable();
|
||||
for (_, d, x, z) in wanted {
|
||||
for (_, _, x, z) in wanted {
|
||||
if self.decorating >= workers * 2 {
|
||||
break;
|
||||
}
|
||||
@@ -1091,7 +1125,7 @@ impl Streaming {
|
||||
Err(_) => continue,
|
||||
};
|
||||
self.decorating += 1;
|
||||
self.submit(d * 4 + 1, Job::Decorate(x, z, region));
|
||||
self.submit(Some((x, z)), 1, Job::Decorate(x, z, region));
|
||||
}
|
||||
}
|
||||
self.schedule_generation(world, workers);
|
||||
@@ -1111,7 +1145,8 @@ impl Streaming {
|
||||
self.light_snapshots
|
||||
.insert((x, z), self.light_edit_sequence);
|
||||
self.submit(
|
||||
self.distance(x, z) * 4 + 1,
|
||||
Some((x, z)),
|
||||
1,
|
||||
Job::Light(x, z, region, self.sequence, self.sky_light),
|
||||
);
|
||||
}
|
||||
@@ -1183,7 +1218,8 @@ impl Streaming {
|
||||
self.sequence += 1;
|
||||
self.meshing.insert((x, sy, z), self.sequence);
|
||||
self.submit(
|
||||
self.distance(x, z) * 4 + if first { 2 } else { 0 },
|
||||
Some((x, z)),
|
||||
if first { 2 } else { 0 },
|
||||
Job::Mesh(
|
||||
x,
|
||||
sy,
|
||||
@@ -1222,9 +1258,9 @@ impl Streaming {
|
||||
loading: self.loading,
|
||||
};
|
||||
if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) {
|
||||
for (d, x, z) in wanted {
|
||||
for (_, x, z) in wanted {
|
||||
self.generating.insert((x, z));
|
||||
self.submit(d * 4, Job::Generate(x, z));
|
||||
self.submit(Some((x, z)), 0, Job::Generate(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> {
|
||||
})
|
||||
})
|
||||
}
|
||||
/// The queued jobs' priorities computed again from each one's column
|
||||
/// `distance` (`Streaming::submit`).
|
||||
fn rank_again(queue: &mut BinaryHeap<Queued>, distance: impl Fn(i32, i32) -> i64) {
|
||||
if queue.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut jobs = std::mem::take(queue).into_vec();
|
||||
for job in &mut jobs {
|
||||
if let Some((x, z)) = job.at {
|
||||
job.priority = distance(x, z) * 4 + job.bias;
|
||||
}
|
||||
}
|
||||
*queue = BinaryHeap::from(jobs);
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn queued_jobs_follow_the_centre_and_the_loading_screen() {
|
||||
let forced = HashSet::new();
|
||||
let ranges = |center| Ranges {
|
||||
center,
|
||||
radius: 32,
|
||||
extra: &[],
|
||||
forced: &forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
};
|
||||
let generate = |x, z, priority, order| Queued {
|
||||
priority,
|
||||
at: Some((x, z)),
|
||||
bias: 0,
|
||||
order,
|
||||
job: Job::Generate(x, z),
|
||||
};
|
||||
let loading = ranges((0, 0));
|
||||
let queued = || {
|
||||
BinaryHeap::from(vec![
|
||||
// Queued while the loading screen was up: ring order.
|
||||
generate(3, 1, loading.priority(3, 1, true) * 4, 1),
|
||||
// Queued after it closed: plain distances, far below any ring past the first.
|
||||
generate(20, 0, loading.priority(20, 0, false) * 4, 2),
|
||||
Queued {
|
||||
priority: i64::MIN,
|
||||
at: None,
|
||||
bias: 0,
|
||||
order: 3,
|
||||
job: Job::Save(Vec::new()),
|
||||
},
|
||||
])
|
||||
};
|
||||
let pops = |mut queue: BinaryHeap<Queued>| {
|
||||
std::iter::from_fn(move || queue.pop())
|
||||
.map(|q| q.at)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
pops(queued()),
|
||||
[None, Some((20, 0)), Some((3, 1))],
|
||||
"the stale order"
|
||||
);
|
||||
let mut queue = queued();
|
||||
rank_again(&mut queue, |x, z| loading.priority(x, z, false));
|
||||
assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]);
|
||||
// The player moved: the job near the new centre goes first.
|
||||
let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]);
|
||||
let moved = ranges((19, 0));
|
||||
rank_again(&mut queue, |x, z| moved.priority(x, z, false));
|
||||
assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_distance_is_vanillas_shape() {
|
||||
// ChunkTrackingView.isInViewDistance at render distance 12: a column
|
||||
|
||||
@@ -39,7 +39,7 @@ wit_bindgen::generate!({
|
||||
|
||||
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
|
||||
pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest;
|
||||
pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui};
|
||||
pub use horizon::mods::{chat, command, game, hud, input, log, recipes, render, storage, ui};
|
||||
|
||||
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
|
||||
/// are called; the others may stay as their defaults.
|
||||
|
||||
@@ -439,6 +439,76 @@ interface events {
|
||||
chat: func(text: string);
|
||||
}
|
||||
|
||||
/// Capability `recipes` (experimental): the recipes and items the game
|
||||
/// knows, for recipe viewers. In single player and on Horizon's servers
|
||||
/// they are the world's; on any other server they are vanilla 26.3's (a
|
||||
/// client is sent no others), while `known` follows that server's book.
|
||||
interface recipes {
|
||||
/// An item of `items`, by its index there, with a count and the
|
||||
/// components it has beyond the item's own, in vanilla's item syntax
|
||||
/// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "".
|
||||
record stack {
|
||||
item: u32,
|
||||
count: u32,
|
||||
components: string,
|
||||
}
|
||||
/// The station a recipe is made at.
|
||||
enum kind {
|
||||
crafting-shaped,
|
||||
crafting-shapeless,
|
||||
smelting,
|
||||
blasting,
|
||||
smoking,
|
||||
campfire,
|
||||
stonecutting,
|
||||
smithing,
|
||||
brewing,
|
||||
}
|
||||
record recipe {
|
||||
/// `minecraft:oak_planks`.
|
||||
id: string,
|
||||
kind: kind,
|
||||
/// The recipe book's tab (`crafting_building_blocks`,
|
||||
/// `furnace_food`), or "".
|
||||
category: string,
|
||||
/// Recipes the book shows on one button share a group, or "".
|
||||
group: string,
|
||||
/// A shaped recipe's grid: `slots` holds its cells row by row.
|
||||
/// 0 for the other kinds.
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Each slot's stacks, any one of which fits; an empty list is an
|
||||
/// empty cell. Cooking and stonecutting: the input. Smithing: the
|
||||
/// template, the base, the addition. Brewing: the bottle, the
|
||||
/// reagent.
|
||||
slots: list<list<stack>>,
|
||||
/// What it makes; several when that varies (a trim on any armour).
|
||||
results: list<stack>,
|
||||
/// Cooking: game ticks and experience; 0 for the other kinds.
|
||||
cooking-time: u32,
|
||||
experience: f32,
|
||||
/// The recipe book's id for it (one per way the book shows it), as
|
||||
/// `known` lists them; -1 for the kinds the book doesn't show
|
||||
/// (campfire, stonecutting, smithing, brewing).
|
||||
book-id: s32,
|
||||
}
|
||||
record item {
|
||||
/// `minecraft:diamond`, `<mod>:<path>`.
|
||||
id: string,
|
||||
/// In the player's language.
|
||||
name: string,
|
||||
/// Its item tags, without the `#`.
|
||||
tags: list<string>,
|
||||
}
|
||||
/// Every item, in the registry's order: `stack.item` indexes this list.
|
||||
items: func() -> list<item>;
|
||||
/// Every recipe: the book's in its order, then campfire, stonecutting,
|
||||
/// smithing and brewing. They don't change while a world is open.
|
||||
all: func() -> list<recipe>;
|
||||
/// The `book-id`s of the recipes the player's recipe book holds now.
|
||||
known: func() -> list<s32>;
|
||||
}
|
||||
|
||||
/// Capability `players`, server mods only (manifest `api = "0.3"`,
|
||||
/// experimental): the players on the server, and messages to them.
|
||||
interface players {
|
||||
@@ -573,6 +643,7 @@ world horizon-ui-mod {
|
||||
import ui;
|
||||
import render;
|
||||
import input;
|
||||
import recipes;
|
||||
export ui-events;
|
||||
}
|
||||
|
||||
@@ -587,3 +658,8 @@ world render-host {
|
||||
import render;
|
||||
import input;
|
||||
}
|
||||
|
||||
/// The game's side of capability `recipes` (imports only).
|
||||
world recipes-host {
|
||||
import recipes;
|
||||
}
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
//! version's level so the launcher can tell before it installs.
|
||||
|
||||
/// The newest level this Horizon serves.
|
||||
pub const LEVEL: u32 = 4;
|
||||
pub const LEVEL: u32 = 5;
|
||||
|
||||
/// Every function the game offers mods, as `interface.function`, with its
|
||||
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
|
||||
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
|
||||
/// test fails until it is listed here).
|
||||
pub const FUNCTIONS: [(&str, u32); 37] = [
|
||||
pub const FUNCTIONS: [(&str, u32); 40] = [
|
||||
("log.write", 0),
|
||||
("game.get-player", 0),
|
||||
("game.get-clock", 0),
|
||||
@@ -51,6 +51,9 @@ pub const FUNCTIONS: [(&str, u32); 37] = [
|
||||
("world.get-block", 4),
|
||||
("world.get-biome", 4),
|
||||
("world.set-blocks", 4),
|
||||
("recipes.items", 5),
|
||||
("recipes.all", 5),
|
||||
("recipes.known", 5),
|
||||
];
|
||||
|
||||
/// What the game's program carries so the launcher can read its level
|
||||
|
||||
@@ -100,9 +100,12 @@ pub enum Capability {
|
||||
/// Blocks in the server's loaded chunks, and changes to them (server
|
||||
/// mods; client mods later, where the game runs the world).
|
||||
World,
|
||||
/// The recipes and items the game knows, for recipe viewers
|
||||
/// (interface `recipes`).
|
||||
Recipes,
|
||||
}
|
||||
impl Capability {
|
||||
pub const ALL: [Capability; 11] = [
|
||||
pub const ALL: [Capability; 12] = [
|
||||
Capability::GameRead,
|
||||
Capability::Chat,
|
||||
Capability::Hud,
|
||||
@@ -114,6 +117,7 @@ impl Capability {
|
||||
Capability::Input,
|
||||
Capability::Players,
|
||||
Capability::World,
|
||||
Capability::Recipes,
|
||||
];
|
||||
/// Whether a server mod may have it: the others act on a local player.
|
||||
pub fn on_server(self) -> bool {
|
||||
@@ -136,6 +140,7 @@ impl Capability {
|
||||
Capability::Input => "input",
|
||||
Capability::Players => "players",
|
||||
Capability::World => "world",
|
||||
Capability::Recipes => "recipes",
|
||||
}
|
||||
}
|
||||
/// May change in any release: a mod uses it only with
|
||||
@@ -143,7 +148,7 @@ impl Capability {
|
||||
pub fn is_experimental(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Capability::Ui | Capability::Render | Capability::Input
|
||||
Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes
|
||||
)
|
||||
}
|
||||
/// What the player reads before turning the mod on: "May <this>".
|
||||
@@ -162,6 +167,7 @@ impl Capability {
|
||||
}
|
||||
Capability::Players => "see who is on the server and message them",
|
||||
Capability::World => "read and change the world's blocks",
|
||||
Capability::Recipes => "read the game's recipes and items, and which recipes you know",
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
@@ -198,6 +204,7 @@ impl fmt::Display for Capability {
|
||||
Capability::Input => "input",
|
||||
Capability::Players => "players",
|
||||
Capability::World => "world",
|
||||
Capability::Recipes => "recipes",
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
|
||||
@@ -81,6 +81,18 @@ pub use render_bindings::horizon::mods::render::{
|
||||
Zoom as ModZoom,
|
||||
};
|
||||
use render_bindings::{RenderHost, horizon::mods::render};
|
||||
/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items.
|
||||
mod recipes_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
path: "../horizon-mod-sdk/wit",
|
||||
world: "recipes-host",
|
||||
});
|
||||
}
|
||||
/// What capability `recipes` reads (WIT `interface recipes`).
|
||||
pub use recipes_bindings::horizon::mods::recipes::{
|
||||
Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack,
|
||||
};
|
||||
use recipes_bindings::{RecipesHost, horizon::mods::recipes};
|
||||
|
||||
/// A mod's linear memory cap.
|
||||
const MEMORY: usize = 64 << 20;
|
||||
@@ -138,6 +150,19 @@ pub struct Snapshot {
|
||||
/// its distance from the eye, for `game.raycast`; the game works it out
|
||||
/// only while a mod calls it ([`Mods::wants_raycast`]).
|
||||
pub view_hit: Option<(f32, Hit)>,
|
||||
/// Every item and recipe, for capability `recipes`; the game makes them
|
||||
/// once, and only while a mod reads them ([`Mods::wants_recipes`]).
|
||||
pub recipes: Option<Arc<Recipes>>,
|
||||
/// The `book-id`s of the recipes the player's book holds.
|
||||
pub known_recipes: Arc<[i32]>,
|
||||
}
|
||||
|
||||
/// Capability `recipes`'s tables: `items` in the registry's order, which
|
||||
/// each [`RecipeStack::item`] indexes.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Recipes {
|
||||
pub items: Vec<RecipeItem>,
|
||||
pub recipes: Vec<Recipe>,
|
||||
}
|
||||
|
||||
/// Which mods a game starts: the window's game the client mods, the game
|
||||
@@ -270,6 +295,8 @@ struct Running {
|
||||
hooks: Hooks,
|
||||
/// It imports `game.raycast`.
|
||||
raycasts: bool,
|
||||
/// It imports capability `recipes`.
|
||||
reads_recipes: bool,
|
||||
}
|
||||
|
||||
/// A running mod's exports and the hooks its `init` asked for.
|
||||
@@ -448,6 +475,8 @@ impl Mods {
|
||||
.map_err(|e| e.to_string())?;
|
||||
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
RecipesHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.engine = Some((engine, linker));
|
||||
}
|
||||
Ok(self.engine.as_ref().expect("made above"))
|
||||
@@ -567,6 +596,7 @@ impl Mods {
|
||||
ui,
|
||||
hooks,
|
||||
raycasts: functions.iter().any(|f| f == "game.raycast"),
|
||||
reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -827,6 +857,13 @@ impl Mods {
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.raycasts))
|
||||
}
|
||||
/// Some running mod reads capability `recipes`: the snapshot needs
|
||||
/// [`Snapshot::recipes`] and [`Snapshot::known_recipes`].
|
||||
pub fn wants_recipes(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes))
|
||||
}
|
||||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||||
/// every frame for it.
|
||||
pub fn wants_frames(&self) -> bool {
|
||||
@@ -1183,6 +1220,23 @@ impl game::Host for State {
|
||||
(*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone())
|
||||
}
|
||||
}
|
||||
impl recipes::Host for State {
|
||||
fn items(&mut self) -> Vec<RecipeItem> {
|
||||
self.snapshot
|
||||
.recipes
|
||||
.as_ref()
|
||||
.map_or_else(Vec::new, |r| r.items.clone())
|
||||
}
|
||||
fn all(&mut self) -> Vec<Recipe> {
|
||||
self.snapshot
|
||||
.recipes
|
||||
.as_ref()
|
||||
.map_or_else(Vec::new, |r| r.recipes.clone())
|
||||
}
|
||||
fn known(&mut self) -> Vec<i32> {
|
||||
self.snapshot.known_recipes.to_vec()
|
||||
}
|
||||
}
|
||||
impl State {
|
||||
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
|
||||
fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool {
|
||||
|
||||
@@ -26,8 +26,8 @@ id = "test_ui_guest"
|
||||
name = "Test UI Guest"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
capabilities = ["game-read", "chat", "command", "ui", "render", "input"]
|
||||
experimental = ["ui", "render", "input"]
|
||||
capabilities = ["game-read", "chat", "command", "ui", "render", "input", "recipes"]
|
||||
experimental = ["ui", "render", "input", "recipes"]
|
||||
"#;
|
||||
|
||||
/// Builds the mods once and writes their `.hmod` files; returns the folder.
|
||||
@@ -241,8 +241,8 @@ id = "too_new"
|
||||
name = "Too New"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"]
|
||||
experimental = ["ui", "render", "input"]
|
||||
capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input", "recipes"]
|
||||
experimental = ["ui", "render", "input", "recipes"]
|
||||
"#;
|
||||
std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap();
|
||||
std::fs::write(dir.join("mod.wasm"), wasm).unwrap();
|
||||
@@ -255,8 +255,8 @@ experimental = ["ui", "render", "input"]
|
||||
needed(imports(&wasm).unwrap().iter().map(String::as_str)).0
|
||||
};
|
||||
assert_eq!(level("coords_hud.hmod"), 0);
|
||||
// The UI guest runs quiet commands (`command.run-quiet`, level 3).
|
||||
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 3);
|
||||
// The UI guest reads the recipes (`recipes`, level 5).
|
||||
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1041,3 +1041,85 @@ fn a_server_mod_runs_only_where_the_world_does() {
|
||||
"a server command isn't the window's"
|
||||
);
|
||||
}
|
||||
|
||||
/// Capability `recipes`: the guest reads tables as big as vanilla's (1,500
|
||||
/// items, 1,600 recipes of nine five-item slots) within one command's fuel.
|
||||
#[test]
|
||||
fn recipes_reads_the_tables() {
|
||||
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
let stack = |item| RecipeStack {
|
||||
item,
|
||||
count: 1,
|
||||
components: String::new(),
|
||||
};
|
||||
let items = (0..1500)
|
||||
.map(|i| RecipeItem {
|
||||
id: format!("minecraft:item_{i}"),
|
||||
name: format!("Item {i}"),
|
||||
tags: vec!["planks".into(), "logs".into()],
|
||||
})
|
||||
.collect();
|
||||
let mut recipes: Vec<Recipe> = (0..1600)
|
||||
.map(|i| Recipe {
|
||||
id: format!("minecraft:recipe_{i}"),
|
||||
kind: RecipeKind::CraftingShaped,
|
||||
category: "crafting_misc".into(),
|
||||
group: String::new(),
|
||||
width: 3,
|
||||
height: 3,
|
||||
slots: (0..9)
|
||||
.map(|k| (0..5).map(|j| stack((i + k + j) % 1500)).collect())
|
||||
.collect(),
|
||||
results: vec![RecipeStack {
|
||||
item: 7,
|
||||
count: 4,
|
||||
components: String::new(),
|
||||
}],
|
||||
cooking_time: 0,
|
||||
experience: 0.0,
|
||||
book_id: i as i32,
|
||||
})
|
||||
.collect();
|
||||
recipes[1].kind = RecipeKind::Brewing;
|
||||
recipes[1].results[0].components =
|
||||
"[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into();
|
||||
mods.set_snapshot(Snapshot {
|
||||
recipes: Some(std::sync::Arc::new(Recipes { items, recipes })),
|
||||
known_recipes: vec![1, 5, 9].into(),
|
||||
..Snapshot::default()
|
||||
});
|
||||
let said = |mods: &mut Mods, command: &str| {
|
||||
assert!(mods.command(command));
|
||||
mods.drain()
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Output::Chat { text, .. } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
said(&mut mods, "recipes"),
|
||||
["1500 items, 1600 recipes, 3 known, 1 brewing"]
|
||||
);
|
||||
assert_eq!(
|
||||
said(&mut mods, "recipes minecraft:recipe_1"),
|
||||
[
|
||||
"minecraft:recipe_1 Kind::Brewing 3x3 0t slots 9, the first 1 minecraft:item_1 -> \
|
||||
4 minecraft:item_7[minecraft:potion_contents={potion:\"minecraft:swiftness\"}] known true"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
mods.entries()
|
||||
.iter()
|
||||
.all(|e| e.status == horizon_mods::Status::Running),
|
||||
"it ran out of fuel"
|
||||
);
|
||||
// Without the game's tables (no mod read them yet): empty, not a trap.
|
||||
mods.set_snapshot(Snapshot::default());
|
||||
assert_eq!(
|
||||
said(&mut mods, "recipes"),
|
||||
["0 items, 0 recipes, 0 known, 0 brewing"]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@
|
||||
//! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`;
|
||||
//! `/corner` and `/readings` the calls the official extras mods use;
|
||||
//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs
|
||||
//! lines with `command.run-quiet` (`/quiet_many N`: N of them).
|
||||
//! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes`
|
||||
//! counts what `recipes` reads; `/recipes ID` describes that recipe.
|
||||
use horizon_mod_sdk::{
|
||||
Mod, Registration, chat, command, game,
|
||||
input::{self, Event},
|
||||
recipes,
|
||||
render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape},
|
||||
ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget},
|
||||
};
|
||||
@@ -102,6 +104,7 @@ impl Mod for Guest {
|
||||
"raycast",
|
||||
"quiet",
|
||||
"quiet_many",
|
||||
"recipes",
|
||||
"corner",
|
||||
"readings",
|
||||
]
|
||||
@@ -241,6 +244,41 @@ impl Mod for Guest {
|
||||
None => "no hit".into(),
|
||||
});
|
||||
}
|
||||
"recipes" => {
|
||||
let items = recipes::items();
|
||||
let all = recipes::all();
|
||||
let known = recipes::known();
|
||||
let name = |s: &recipes::Stack| {
|
||||
let id = items.get(s.item as usize).map_or("?", |i| i.id.as_str());
|
||||
format!("{} {id}{}", s.count, s.components)
|
||||
};
|
||||
chat::show(&match all.iter().find(|r| r.id == args) {
|
||||
Some(r) => format!(
|
||||
"{} {:?} {}x{} {}t slots {}, the first {} -> {} known {}",
|
||||
r.id,
|
||||
r.kind,
|
||||
r.width,
|
||||
r.height,
|
||||
r.cooking_time,
|
||||
r.slots.len(),
|
||||
r.slots
|
||||
.first()
|
||||
.and_then(|s| s.first())
|
||||
.map_or("-".into(), name),
|
||||
r.results.first().map_or("-".into(), name),
|
||||
known.contains(&r.book_id)
|
||||
),
|
||||
None => format!(
|
||||
"{} items, {} recipes, {} known, {} brewing",
|
||||
items.len(),
|
||||
all.len(),
|
||||
known.len(),
|
||||
all.iter()
|
||||
.filter(|r| r.kind == recipes::Kind::Brewing)
|
||||
.count()
|
||||
),
|
||||
});
|
||||
}
|
||||
// Clamped to (1, 10); the two after it shake nothing.
|
||||
"render_shake" => {
|
||||
render::shake(2.0, 99.0);
|
||||
|
||||
@@ -18,6 +18,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys |
|
||||
| `players` | [`players`](#players) | see who is on the server and message them |
|
||||
| `world` | [`world`](#world) | read and change the world's blocks |
|
||||
| `recipes` | [`recipes`](#recipes) | read the game's recipes and items, and which recipes you know |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
@@ -37,7 +38,7 @@ A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs whe
|
||||
|
||||
A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets.
|
||||
|
||||
- Imports (what the game offers): `ui`, `render`, `input`, `log`, `game`, `chat`, `hud`, `storage`, `command`
|
||||
- Imports (what the game offers): `ui`, `render`, `input`, `recipes`, `log`, `game`, `chat`, `hud`, `storage`, `command`
|
||||
- Exports (what the mod provides): `ui-events`, `events`
|
||||
|
||||
## World `ui-host`
|
||||
@@ -54,6 +55,13 @@ The game's side of capability `render` (imports only).
|
||||
- Imports (what the game offers): `render`, `input`
|
||||
- Exports (what the mod provides):
|
||||
|
||||
## World `recipes-host`
|
||||
|
||||
The game's side of capability `recipes` (imports only).
|
||||
|
||||
- Imports (what the game offers): `recipes`
|
||||
- Exports (what the mod provides):
|
||||
|
||||
## `log`
|
||||
|
||||
Access: always granted.
|
||||
@@ -462,6 +470,68 @@ What the game calls. Only the hooks `init` asks for are ever called.
|
||||
| `command` | `func(name: string, args: string) -> result<option<string>, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. |
|
||||
| `chat` | `func(text: string)` | Each chat line the player receives, as plain text. |
|
||||
|
||||
## `recipes`
|
||||
|
||||
Access: capability `recipes`.
|
||||
|
||||
Capability `recipes` (experimental): the recipes and items the game knows, for recipe viewers. In single player and on Horizon's servers they are the world's; on any other server they are vanilla 26.3's (a client is sent no others), while `known` follows that server's book.
|
||||
|
||||
### record `stack`
|
||||
|
||||
An item of `items`, by its index there, with a count and the components it has beyond the item's own, in vanilla's item syntax (`[potion_contents={potion:"minecraft:swiftness"}]`), or "".
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `item` | `u32` | |
|
||||
| `count` | `u32` | |
|
||||
| `components` | `string` | |
|
||||
|
||||
### enum `kind`
|
||||
|
||||
The station a recipe is made at.
|
||||
|
||||
| Case | |
|
||||
| --- | --- |
|
||||
| `crafting-shaped` | |
|
||||
| `crafting-shapeless` | |
|
||||
| `smelting` | |
|
||||
| `blasting` | |
|
||||
| `smoking` | |
|
||||
| `campfire` | |
|
||||
| `stonecutting` | |
|
||||
| `smithing` | |
|
||||
| `brewing` | |
|
||||
|
||||
### record `recipe`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `string` | `minecraft:oak_planks`. |
|
||||
| `kind` | `kind` | |
|
||||
| `category` | `string` | The recipe book's tab (`crafting_building_blocks`, `furnace_food`), or "". |
|
||||
| `group` | `string` | Recipes the book shows on one button share a group, or "". |
|
||||
| `width` | `u32` | A shaped recipe's grid: `slots` holds its cells row by row. 0 for the other kinds. |
|
||||
| `height` | `u32` | |
|
||||
| `slots` | `list<list<stack>>` | Each slot's stacks, any one of which fits; an empty list is an empty cell. Cooking and stonecutting: the input. Smithing: the template, the base, the addition. Brewing: the bottle, the reagent. |
|
||||
| `results` | `list<stack>` | What it makes; several when that varies (a trim on any armour). |
|
||||
| `cooking-time` | `u32` | Cooking: game ticks and experience; 0 for the other kinds. |
|
||||
| `experience` | `f32` | |
|
||||
| `book-id` | `s32` | The recipe book's id for it (one per way the book shows it), as `known` lists them; -1 for the kinds the book doesn't show (campfire, stonecutting, smithing, brewing). |
|
||||
|
||||
### record `item`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `string` | `minecraft:diamond`, `<mod>:<path>`. |
|
||||
| `name` | `string` | In the player's language. |
|
||||
| `tags` | `list<string>` | Its item tags, without the `#`. |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `items` | `func() -> list<item>` | Every item, in the registry's order: `stack.item` indexes this list. |
|
||||
| `all` | `func() -> list<recipe>` | Every recipe: the book's in its order, then campfire, stonecutting, smithing and brewing. They don't change while a world is open. |
|
||||
| `known` | `func() -> list<s32>` | The `book-id`s of the recipes the player's recipe book holds now. |
|
||||
|
||||
## `players`
|
||||
|
||||
Access: capability `players`.
|
||||
|
||||
@@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says
|
||||
|
||||
A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every
|
||||
function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`):
|
||||
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`. A mod needs the level of
|
||||
level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 server mods' `world`, level 5 `recipes` (`items`, `all`, `known`). A mod needs the level of
|
||||
the newest function it imports (a component imports only the functions it calls). The level is read from the file,
|
||||
never declared:
|
||||
|
||||
|
||||
+1
-1
@@ -91,6 +91,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|
||||
| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` |
|
||||
| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` |
|
||||
| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key.<mod>.<name>:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |
|
||||
| `recipes` | `recipes` | `items()`: every item in the registry's order, with its name in the player's language and its tags; `all()`: every recipe (crafting, smelting, blasting, smoking, campfire, stonecutting, smithing, brewing), its slots as the stacks that fit each, its results, cooking time and experience, and the recipe book's id for it; `known()`: the book ids the player's recipe book holds. The recipes are the world's in single player and on Horizon's servers, vanilla 26.3's on any other server (a client is sent no others), while `known` follows that server's book. The game makes the tables once, when a mod first reads them. **Experimental:** `experimental = ["recipes"]` |
|
||||
|
||||
| Hook (export) | When |
|
||||
|---|---|
|
||||
@@ -116,7 +117,6 @@ loading. Ordered by what the first native ports need:
|
||||
| `keys` | keybinds | registered binds appear in Controls; press/release events |
|
||||
| `target` | the crosshair's block or entity, with its state and NBT summary | Jade/WTHIT-style tooltips |
|
||||
| `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers |
|
||||
| `recipes` | the recipe registry and lookups | JEI/EMI-style viewers |
|
||||
| `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics |
|
||||
| `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints |
|
||||
| `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) |
|
||||
|
||||
@@ -44,6 +44,17 @@ Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/pari
|
||||
|
||||
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on.
|
||||
|
||||
### Any command on playhorizon: `tools/remote.sh`
|
||||
|
||||
For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh <worktree> <command...>` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/<name>` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 4-7 (`--cpus`; 0-3 stay free for benchmarks), with scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Logs stay in `~/remote-work/<name>.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones.
|
||||
|
||||
```sh
|
||||
tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib # 33 s, warm
|
||||
tools/remote.sh . python3 tools/parity.py food # 19 s warm (4 min the first time); here: 188 s, 229 CPU-seconds
|
||||
```
|
||||
|
||||
The host is lent by a partner who keeps hypervisor access: send it no secret, token or credential, and never take a result from it as a CI result.
|
||||
|
||||
### Shards and Rust scopes
|
||||
|
||||
A harness can declare, at the top level of its script:
|
||||
|
||||
@@ -487,6 +487,17 @@ public final class VanillaProtocolClient {
|
||||
long deadCommandAt = 0;
|
||||
// When the client last sent where it is.
|
||||
long positionAt = 0;
|
||||
// Chat lines and furnace slot changes received, and how many there were when the current step sent
|
||||
// its command or click: a step goes on once the server answered, not after a fixed time (a busy
|
||||
// server answers seconds late, and a click sent before the last one's reply carries a stale state id).
|
||||
int replies = 0;
|
||||
int repliesBefore = 0;
|
||||
// A shift-click changes two slots, each its own packet, which a busy server can send ticks apart: a furnace
|
||||
// step waits for both. A full resend of the menu counts as both.
|
||||
int furnaceReplies = 0;
|
||||
int furnaceBefore = 0;
|
||||
// The furnace's lit and cooking totals received: the server sends them a tick after what changed them.
|
||||
int furnaceData = 0;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Received r;
|
||||
try {
|
||||
@@ -501,7 +512,7 @@ public final class VanillaProtocolClient {
|
||||
if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet);
|
||||
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
|
||||
if (respawning && !respawned) {
|
||||
String line = respawnLine(r);
|
||||
String line = respawnLine(r, playerId);
|
||||
// PlayerList.respawn ends with initInventoryMenu: what follows is the
|
||||
// next ticks' (health, entity data, chunks), in each server's own order.
|
||||
respawned = r.type.equals("minecraft:container_set_content") && respawnAt != null;
|
||||
@@ -558,15 +569,18 @@ public final class VanillaProtocolClient {
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket p
|
||||
&& furnaceWindow > 0 && p.containerId() == furnaceWindow) {
|
||||
furnaceState = p.stateId();
|
||||
furnaceReplies += 2;
|
||||
record("play-furnace", "content " + p.items() + " carried " + p.carriedItem());
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket p
|
||||
&& furnaceWindow > 0 && p.getContainerId() == furnaceWindow) {
|
||||
furnaceState = p.getStateId();
|
||||
furnaceReplies++;
|
||||
record("play-furnace", "slot " + p.getSlot() + " " + p.getItem());
|
||||
if (p.getSlot() == 2 && !p.getItem().isEmpty() && smeltedAt == 0) smeltedAt = now;
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket p
|
||||
&& furnaceWindow > 0 && p.getContainerId() == furnaceWindow && (p.getId() == 1 || p.getId() == 3)) {
|
||||
// Lit total and cooking total; the time left and the cooking timer follow the ticks.
|
||||
furnaceData++;
|
||||
record("play-furnace", "data " + p.getId() + " " + p.getValue());
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p
|
||||
&& step == 5 + REPLIES.length && (int) (byte) field(p, "eventId") == 28) {
|
||||
@@ -583,13 +597,16 @@ public final class VanillaProtocolClient {
|
||||
record("play-death", "command reply " + json(p.content()));
|
||||
respawning = respawn();
|
||||
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0 && step < 5 + REPLIES.length) {
|
||||
replies++;
|
||||
record("play-chat", "system " + p.overlay() + " " + json(p.content()));
|
||||
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0 && step < 5 + REPLIES.length) {
|
||||
replies++;
|
||||
record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent()
|
||||
+ " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " "
|
||||
+ p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " "
|
||||
+ p.chatType().targetName().map(VanillaProtocolClient::json));
|
||||
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0 && step < 5 + REPLIES.length) {
|
||||
replies++;
|
||||
record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName());
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p
|
||||
&& p.getType() == net.minecraft.world.entity.EntityTypes.SNOWBALL) {
|
||||
@@ -679,20 +696,24 @@ public final class VanillaProtocolClient {
|
||||
record("play-light-layers", inner.size() + " " + inner);
|
||||
step = 1;
|
||||
stepAt = now;
|
||||
repliesBefore = replies;
|
||||
send(new ServerboundChatPacket("hello from the parity client", Instant.now(), 0L, Optional.empty(),
|
||||
new LastSeenMessages.Update(0, new BitSet(), (byte) 0)));
|
||||
} else if (step == 1 && now - stepAt > 1500) {
|
||||
} else if (step == 1 && answered(replies, repliesBefore, stepAt, now)) {
|
||||
step = 2;
|
||||
stepAt = now;
|
||||
repliesBefore = replies;
|
||||
send(new ServerboundChatCommandPacket("list"));
|
||||
} else if (step >= 2 && step < 2 + REPLIES.length && now - stepAt > 1500) {
|
||||
} else if (step >= 2 && step < 2 + REPLIES.length && answered(replies, repliesBefore, stepAt, now)) {
|
||||
// Commands a player without operator rights may run, whose
|
||||
// replies (a failure, a syntax error with its context, a
|
||||
// failure with an argument) are compared component by component.
|
||||
send(new ServerboundChatCommandPacket(REPLIES[step - 2]));
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 2 + REPLIES.length && now - stepAt > 1500 && (villager >= 0 || now - stepAt > PATIENCE)) {
|
||||
repliesBefore = replies;
|
||||
} else if (step == 2 + REPLIES.length && answered(replies, repliesBefore, stepAt, now)
|
||||
&& (villager >= 0 || now - stepAt > PATIENCE)) {
|
||||
// Right-click the villager (once the server sent it): the trading screen and its offers.
|
||||
record("play-trade", "villager " + (villager >= 0));
|
||||
if (villager >= 0) {
|
||||
@@ -739,9 +760,13 @@ public final class VanillaProtocolClient {
|
||||
send(new net.minecraft.network.protocol.game.ServerboundUseItemOnPacket(net.minecraft.world.InteractionHand.MAIN_HAND,
|
||||
new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(furnace),
|
||||
net.minecraft.core.Direction.NORTH, furnace, false), 1));
|
||||
furnaceBefore = furnaceReplies;
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0 && now - stepAt > 1500
|
||||
} else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0
|
||||
&& answered(furnaceReplies, furnaceBefore + 1, stepAt, now)
|
||||
// Both totals with the window, then the cooking total the ore set, then the lit total the coal set.
|
||||
&& (furnaceData >= step - 6 - REPLIES.length || now - stepAt > PATIENCE)
|
||||
// The ingot out once the furnace made it (200 ticks), and its tick's other changes came.
|
||||
&& (step < 10 + REPLIES.length || smeltedAt > 0 && now - smeltedAt > 1000 || now - stepAt > 10_000 + PATIENCE)) {
|
||||
// Shift-click the ore (hotbar 0) into the input, the coal (hotbar 1) into the
|
||||
@@ -752,9 +777,10 @@ public final class VanillaProtocolClient {
|
||||
send(new net.minecraft.network.protocol.game.ServerboundContainerClickPacket(furnaceWindow, furnaceState, (short) slot,
|
||||
(byte) 0, net.minecraft.world.inventory.ContainerInput.QUICK_MOVE,
|
||||
new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(), net.minecraft.network.HashedStack.EMPTY));
|
||||
furnaceBefore = furnaceReplies;
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 11 + REPLIES.length && now - stepAt > 1500) {
|
||||
} else if (step == 11 + REPLIES.length && answered(furnaceReplies, furnaceBefore + 1, stepAt, now)) {
|
||||
send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(furnaceWindow));
|
||||
record("play-furnace", "closed");
|
||||
step++;
|
||||
@@ -816,6 +842,11 @@ public final class VanillaProtocolClient {
|
||||
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
|
||||
}
|
||||
|
||||
/** The server answered the step's command or click (at least 1.5 s after it, as before), or had all the time. */
|
||||
private static boolean answered(int count, int before, long sent, long now) {
|
||||
return now - sent > 1500 && (count > before || now - sent > PATIENCE);
|
||||
}
|
||||
|
||||
/**
|
||||
* A right click's snowballs are counted: once the first came and a second could have come with it
|
||||
* (the server spawns each in the tick it handles the click), or once the server had all the time.
|
||||
@@ -857,8 +888,12 @@ public final class VanillaProtocolClient {
|
||||
* packets (time, keep-alive, chunk data and light, whose batching follows each server's
|
||||
* timing) left out; null to skip it.
|
||||
*/
|
||||
private String respawnLine(Received r) {
|
||||
private String respawnLine(Received r, int playerId) {
|
||||
String t = r.type;
|
||||
// Other entities (a squid's swim event, a mob coming into view) land in the window as each server's
|
||||
// ticks fall: only the player's own are PlayerList.respawn's.
|
||||
Integer entity = entityOf(r.packet);
|
||||
if (entity != null && entity != playerId) return null;
|
||||
// Entities moving, blocks the world's ticks change (a lava fall flows again once the game
|
||||
// runs) and the dead player's health land in the window between the death and the respawn
|
||||
// as each server's ticks fall: left out.
|
||||
@@ -891,6 +926,21 @@ public final class VanillaProtocolClient {
|
||||
return t;
|
||||
}
|
||||
|
||||
/** The entity a packet is about, for the packets that name one; null for the rest. */
|
||||
private static Integer entityOf(Packet<?> packet) {
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p) return p.getId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket p) return p.getEntityId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p) return (int) field(p, "entityId");
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket p) return p.getEntity();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundAnimatePacket p) return p.getId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundHurtAnimationPacket p) return p.id();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundDamageEventPacket p) return p.entityId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket p) return p.getEntityId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket p) return p.entityId();
|
||||
if (packet instanceof net.minecraft.network.protocol.game.ClientboundSoundEntityPacket p) return p.getId();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A chunk's blocks, biomes, heightmaps and block entities (its
|
||||
* ClientboundLevelChunkPacketData bytes). The light is left out: both servers relight around chunks
|
||||
|
||||
+29
-12
@@ -9,7 +9,8 @@ PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/hor
|
||||
"horizon-theme": "crates/horizon-theme", "xtask": "xtask"}
|
||||
LIBRARIES = set(PACKAGES) - {"xtask"}
|
||||
DEPENDENCIES = {"horizon-client": {"horizon-core"}}
|
||||
MODS = " --features horizon-mods/runtime,horizon-mods/pack,horizon-client/mods"
|
||||
MODS = " --features horizon-client/mods,horizon-mods/pack"
|
||||
CLIPPY = pr_ready.CI_CLIPPY + " && " + pr_ready.CI_CLIPPY_SERVER
|
||||
|
||||
|
||||
def args(host="local", quick=False):
|
||||
@@ -35,6 +36,9 @@ class PrReadyTests(unittest.TestCase):
|
||||
self.assertFalse(pr_ready.workspace_rust("crates/horizon-client/README.md"))
|
||||
self.assertFalse(pr_ready.workspace_rust("launcher/src/main.rs"))
|
||||
self.assertTrue(pr_ready.launcher_rust("launcher/src/main.rs"))
|
||||
# CI's launcher job also runs for the root workspace's manifests and for its own check.
|
||||
self.assertTrue(pr_ready.launcher_rust("Cargo.lock"))
|
||||
self.assertTrue(pr_ready.launcher_rust("tools/ci/rust_changes.py"))
|
||||
self.assertTrue(pr_ready.launcher_rust("crates/horizon-prepare/src/lib.rs"))
|
||||
self.assertTrue(pr_ready.launcher_rust("crates/horizon-theme/src/lib.rs"))
|
||||
self.assertTrue(pr_ready.launcher_rust("crates/horizon-telemetry/src/lib.rs"))
|
||||
@@ -46,10 +50,9 @@ class PrReadyTests(unittest.TestCase):
|
||||
with mock.patch.object(pr_ready, "affected_here", return_value=[]):
|
||||
steps = pr_ready.plan(args(quick=True), "origin/main", {"crates/horizon-client/src/game.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES)
|
||||
by_name = {step.name: step for step in steps}
|
||||
self.assertEqual(by_name["clippy"].command,
|
||||
"cargo clippy -p horizon-client --all-targets --locked -- -D warnings")
|
||||
self.assertEqual(by_name["clippy"].command, CLIPPY)
|
||||
self.assertEqual(by_name["tests: horizon-client"].command,
|
||||
"cargo test --locked -p horizon-client --tests")
|
||||
"cargo test --locked -p horizon-client --features horizon-client/mods --tests")
|
||||
self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-client --doc")
|
||||
self.assertIsNone(by_name["doc tests"].status)
|
||||
|
||||
@@ -58,12 +61,24 @@ class PrReadyTests(unittest.TestCase):
|
||||
with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]):
|
||||
steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES)
|
||||
by_name = {step.name: step for step in steps}
|
||||
self.assertEqual(by_name["clippy"].command,
|
||||
"cargo clippy --workspace" + MODS + " --all-targets --locked -- -D warnings")
|
||||
self.assertEqual(by_name["clippy"].command, CLIPPY)
|
||||
self.assertEqual(by_name["tests: workspace"].command,
|
||||
"cargo test --locked --workspace" + MODS + " --tests")
|
||||
self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc")
|
||||
|
||||
def test_tests_get_the_features_ci_s_workspace_run_gives_them(self):
|
||||
self.assertEqual(pr_ready.mod_features(["horizon-world"]), "")
|
||||
self.assertEqual(pr_ready.mod_features(["horizon-client"]), " --features horizon-client/mods")
|
||||
self.assertEqual(pr_ready.mod_features(["horizon-mods"]),
|
||||
" --features horizon-mods/runtime,horizon-mods/pack,horizon-mods/index")
|
||||
self.assertEqual(pr_ready.mod_features(None), MODS)
|
||||
|
||||
def test_python_tests_always_run(self):
|
||||
with mock.patch.object(pr_ready, "affected_here", return_value=[]):
|
||||
steps = pr_ready.plan(args(quick=True), "origin/main", {"crates/horizon-core/src/lib.rs"},
|
||||
PACKAGES, LIBRARIES, DEPENDENCIES)
|
||||
self.assertIsNone({step.name: step for step in steps}["Python tests"].status)
|
||||
|
||||
def test_non_rust_changes_skip_workspace_checks(self):
|
||||
for path in ("README.md", "tools/pr_ready.py", "launcher/src/main.rs"):
|
||||
with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]):
|
||||
@@ -77,7 +92,7 @@ class PrReadyTests(unittest.TestCase):
|
||||
steps = pr_ready.plan(args(), "origin/main",
|
||||
{"crates/horizon-core/src/lib.rs", "crates/horizon-client/examples/probe.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES)
|
||||
for step in steps:
|
||||
if step.name in ("clippy", "tests: horizon-client, horizon-core", "doc tests"):
|
||||
if step.name in ("tests: horizon-client, horizon-core", "doc tests"):
|
||||
self.assertIn("-p horizon-client -p horizon-core", step.command)
|
||||
self.assertIsNone(step.status)
|
||||
|
||||
@@ -94,15 +109,17 @@ class PrReadyTests(unittest.TestCase):
|
||||
by_name = {step.name: step for step in steps}
|
||||
self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-core --doc")
|
||||
|
||||
def test_clippy_checks_transitive_consumers_but_tests_only_touched_crates(self):
|
||||
packages = {name: f"crates/{name}" for name in ("core", "world", "client", "unrelated")}
|
||||
dependencies = {"world": {"core"}, "client": {"world"}, "unrelated": set()}
|
||||
def test_clippy_is_ci_s_and_the_server_build_when_the_game_is_affected(self):
|
||||
packages = {name: f"crates/{name}" for name in ("core", "world", "horizon-client", "unrelated")}
|
||||
dependencies = {"world": {"core"}, "horizon-client": {"world"}, "unrelated": set()}
|
||||
with mock.patch.object(pr_ready, "affected_here", return_value=[]):
|
||||
steps = pr_ready.plan(args(), "origin/main", {"crates/core/src/lib.rs"},
|
||||
packages, set(packages), dependencies)
|
||||
unrelated = pr_ready.plan(args(), "origin/main", {"crates/unrelated/src/lib.rs"},
|
||||
packages, set(packages), dependencies)
|
||||
self.assertEqual({step.name: step for step in unrelated}["clippy"].command, pr_ready.CI_CLIPPY)
|
||||
by_name = {step.name: step for step in steps}
|
||||
self.assertEqual(by_name["clippy"].command,
|
||||
"cargo clippy -p client -p core -p world --all-targets --locked -- -D warnings")
|
||||
self.assertEqual(by_name["clippy"].command, CLIPPY)
|
||||
self.assertEqual(by_name["tests: core"].command, "cargo test --locked -p core --tests")
|
||||
self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p core --doc")
|
||||
|
||||
|
||||
+39
-1
@@ -14,6 +14,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
closes on both when the guest closes it; the host keeps playing with its mouse look (#687);
|
||||
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which
|
||||
leaves the host's screen and mouse look alone;
|
||||
- spawned: the host and a guest new to the world join on different spots (PlayerSpawnFinder), and the
|
||||
guest opens a crafting table, a chest, a furnace and a stonecutter where it joined;
|
||||
- sign: a sign the guest places doesn't open a sign editor on the host;
|
||||
- damage: a guest in survival takes fall damage;
|
||||
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
|
||||
@@ -292,7 +294,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# Match normal single player; --in-frame is the comparison path.
|
||||
SERVER_THREAD = True
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp',
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'spawned', 'sign', 'damage', 'mobs', 'hazards', 'pvp',
|
||||
'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles',
|
||||
'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing',
|
||||
'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push',
|
||||
@@ -554,6 +556,39 @@ def check_crafting(host, guest, out):
|
||||
return {'planks': planks, 'table': counts}
|
||||
|
||||
|
||||
def check_spawned(host, guest, out):
|
||||
"""Players new to a world don't share one spot: ServerPlayer.adjustSpawnLocation spreads them over the
|
||||
respawn radius (PlayerSpawnFinder). Two players standing in each other target each other, so a guest
|
||||
left in the host could open nothing it clicked. At its own spot, the guest opens a crafting table, a
|
||||
chest, a furnace and a stonecutter."""
|
||||
joined = {'host': [round(v, 2) for v in host.joined_at], 'guest': [round(v, 2) for v in guest.joined_at]}
|
||||
apart = abs(joined['host'][0] - joined['guest'][0]) + abs(joined['host'][2] - joined['guest'][2]) >= 0.6
|
||||
guest('command', command='gamemode survival')
|
||||
for game in (host, guest):
|
||||
x, y, z = game.joined_at
|
||||
game('command', command=f'tp @s {x} {y} {z}')
|
||||
guest.wait(20)
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
grab(host)
|
||||
opened = {}
|
||||
for block in ('crafting_table', 'chest', 'furnace', 'stonecutter'):
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.wait(10)
|
||||
opened[block] = guest('state').get('screen')
|
||||
guest.shot(out, f'spawned-{block}')
|
||||
back_to_game(guest)
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
host_unaffected(host, "the guest's stations")
|
||||
face_each_other(host, guest)
|
||||
assert apart, f'the host and the guest joined on one spot: {joined}'
|
||||
want = {'crafting_table': 'inventory', 'chest': 'container', 'furnace': 'container', 'stonecutter': 'station'}
|
||||
assert opened == want, f'where it joined, the guest opened {opened}'
|
||||
return {'joined': joined, 'opened': opened}
|
||||
|
||||
|
||||
def check_sign(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
spot = (x + 2, y, z)
|
||||
@@ -4722,6 +4757,7 @@ def check_worn(host, guest, out):
|
||||
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour,
|
||||
'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting,
|
||||
'spawned': check_spawned,
|
||||
'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs,
|
||||
'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles,
|
||||
@@ -4780,6 +4816,8 @@ def run(ctl, out, resources, checks):
|
||||
guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
|
||||
guest.raw('wait-for', 'loaded', '--timeout', 300)
|
||||
guest.wait(40)
|
||||
# Where each joined, before anything moves them (check_spawned).
|
||||
host.joined_at, guest.joined_at = pos_of(host), pos_of(guest)
|
||||
face_each_other(host, guest)
|
||||
host.shot(out, 'joined')
|
||||
guest.shot(out, 'joined')
|
||||
|
||||
@@ -44,7 +44,6 @@
|
||||
"lan_integration": "the whole lan_e2e suite: ~40 min a run on a loaded runner, and single checks flake under load; run it by name, or tools/lan_e2e.py"
|
||||
},
|
||||
"known_flaky": {
|
||||
"dedicated_server": "its Java client moves to the next step on a 1.5 s timer, not on the server's reply: under load a respawn's add_entity/update_attributes or entity_event 19 lands in the wrong step (failed, then passed at the same head, 10-26)",
|
||||
"remote_fireball": "samples the fireball on the wall clock, so a slow host sees it in too few samples (desktop runner, 3 times on 10-26)",
|
||||
"world_reopen": "counted 4 minecarts instead of 3 once on a loaded Mac mini runner, then passed at the same head (10-26)"
|
||||
}
|
||||
|
||||
+37
-24
@@ -7,12 +7,13 @@
|
||||
python3 tools/pr_ready.py --quick # without running the vanilla harnesses
|
||||
|
||||
From the files the branch changes since its merge base with --base (committed or not) it decides what to run:
|
||||
rustfmt, clippy with warnings denied and the tests of the touched crates; the launcher (its own workspace) the
|
||||
same way when it, horizon-prepare or horizon-theme changed; crates/horizon-theme/tokens.css against horizon-theme;
|
||||
Cargo.lock changing only with a Cargo.toml; the Python tests and the public-tree check; and the vanilla
|
||||
harnesses the changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run
|
||||
where the vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI.
|
||||
Clippy checks all targets of touched crates and their transitive workspace dependents, including examples.
|
||||
rustfmt, and clippy with warnings denied exactly as CI's verify job runs it (the whole workspace with the game's code
|
||||
mods, plus the server build when horizon-client is affected); the tests of the touched crates, with the features
|
||||
CI's workspace-wide run gives them; the launcher (its own workspace) the same way when CI's launcher job would run
|
||||
(tools/ci/rust_changes.py --launcher); crates/horizon-theme/tokens.css against horizon-theme; Cargo.lock changing
|
||||
only with a Cargo.toml; the Python tests (always, as in CI) and the public-tree check; and the vanilla harnesses the
|
||||
changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run where the
|
||||
vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI.
|
||||
Tests select library, binary and integration targets explicitly, followed by doc tests, so unrelated example
|
||||
executables are not built and linked again.
|
||||
|
||||
@@ -43,6 +44,7 @@ if "PARITY_SHARED" not in os.environ and not (ROOT / ".local" / "minecraft").exi
|
||||
# A fleet worktree without vanilla data still knows each harness's dependencies.
|
||||
os.environ["PARITY_SHARED"] = str(FLEET_SHARED)
|
||||
from tools import parity, release_train # noqa: E402
|
||||
from tools.ci import rust_changes # noqa: E402
|
||||
|
||||
RBUILD = Path.home() / "fleet" / "rbuild"
|
||||
LINE_LIMIT = 500
|
||||
@@ -82,9 +84,8 @@ def workspace_rust(path):
|
||||
|
||||
|
||||
def launcher_rust(path):
|
||||
"""Whether a change to path is built into the launcher (its own workspace)."""
|
||||
return not is_doc(path) and any(path.startswith(p) for p in release_train.LAUNCHER_PATHS) and \
|
||||
path != "launcher/links.json" and not path.startswith("launcher/docs/")
|
||||
"""Whether a change to path is built into the launcher (its own workspace): CI's launcher job's own rule."""
|
||||
return rust_changes.needs_launcher([path])
|
||||
|
||||
|
||||
def touched_crates(paths, packages):
|
||||
@@ -268,14 +269,25 @@ def parity_summary(output):
|
||||
return text
|
||||
|
||||
|
||||
# CI's verify job (.github/workflows/ci.yml): clippy over the whole workspace with the game's code mods, and over the
|
||||
# server build (the game without sound or controllers); tests with code mods and mod packaging.
|
||||
CI_CLIPPY = "cargo clippy --workspace --all-targets --locked --features horizon-client/mods -- -D warnings"
|
||||
CI_CLIPPY_SERVER = "cargo clippy -p horizon-client --all-targets --locked --no-default-features -- -D warnings"
|
||||
CI_TEST_FEATURES = "horizon-client/mods,horizon-mods/pack"
|
||||
|
||||
|
||||
def mod_features(crates):
|
||||
"""Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI."""
|
||||
if crates is not None and "horizon-mods" not in crates:
|
||||
return ""
|
||||
features = ["horizon-mods/runtime", "horizon-mods/pack"]
|
||||
if crates is None or "horizon-client" in crates:
|
||||
"""The features CI's workspace-wide test run gives these crates (code mods are off by default: docs/mods.md).
|
||||
Cargo unifies features over the packages it builds, so a crate tested alone needs the ones the workspace would
|
||||
have turned on for it: horizon-client's code mods, and horizon-mods' runtime, packaging and index."""
|
||||
if crates is None:
|
||||
return f" --features {CI_TEST_FEATURES}"
|
||||
features = []
|
||||
if "horizon-mods" in crates:
|
||||
features += ["horizon-mods/runtime", "horizon-mods/pack", "horizon-mods/index"]
|
||||
if "horizon-client" in crates:
|
||||
features.append("horizon-client/mods")
|
||||
return f" --features {','.join(features)}"
|
||||
return f" --features {','.join(features)}" if features else ""
|
||||
|
||||
|
||||
def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
@@ -283,16 +295,18 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
rust = any(workspace_rust(path) for path in changed)
|
||||
launcher = any(launcher_rust(path) for path in changed)
|
||||
# The Python tests also hold ROADMAP.md to roadmap/roadmap.toml (tests/test_roadmap.py).
|
||||
python = any(path.endswith(".py") or path.startswith(("tests/", "tools/", "roadmap/")) or path == "ROADMAP.md"
|
||||
for path in changed)
|
||||
crates = touched_crates(changed, crates_of) if rust else []
|
||||
# An unrecognised Rust path must not silently skip validation.
|
||||
if rust and crates == []:
|
||||
crates = None
|
||||
selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in crates)
|
||||
# CI's own clippy commands: a crate checked alone gets other features than in CI's workspace-wide run, and an
|
||||
# unused import behind a feature passed here and failed in CI (#1895). Warm, the workspace run costs about what
|
||||
# the touched crates and their dependents did (14-32 s against 14-17 s on the Mac mini, 2026-10-26).
|
||||
clippy_crates = dependent_crates(crates, dependencies)
|
||||
clippy_selection = "--workspace" if clippy_crates is None else " ".join(
|
||||
f"-p {shlex.quote(c)}" for c in clippy_crates)
|
||||
clippy = CI_CLIPPY
|
||||
if clippy_crates is None or "horizon-client" in clippy_crates:
|
||||
clippy += f" && {CI_CLIPPY_SERVER}"
|
||||
test_skip = None if crates is None or crates else "no crate touched"
|
||||
doc_crates = sorted(libraries if crates is None else libraries.intersection(crates))
|
||||
doc_selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in doc_crates)
|
||||
@@ -300,11 +314,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
steps = [
|
||||
Step("Cargo.lock", where="git"),
|
||||
Step("Public tree", "python3 tools/check_public_tree.py", where="here"),
|
||||
Step("Python tests", "python3 -m unittest discover -s tests", where="here",
|
||||
skip=None if python else "no Python change", summary=unittest_passed),
|
||||
# Always, as in CI: some read the crates, the roadmap or the workflows.
|
||||
Step("Python tests", "python3 -m unittest discover -s tests", where="here", summary=unittest_passed),
|
||||
Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust),
|
||||
Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings",
|
||||
skip=None if rust else no_rust),
|
||||
Step("clippy", clippy, skip=None if rust else no_rust),
|
||||
Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""),
|
||||
f"cargo test --locked {selection}{mod_features(crates)} --tests",
|
||||
skip=test_skip, summary=tests_passed),
|
||||
@@ -404,7 +417,7 @@ def run_windows(steps, verbose):
|
||||
elif step.name == "rustfmt":
|
||||
command = ["cargo", "fmt", "--all", "--", "--check"]
|
||||
elif step.name == "clippy":
|
||||
command = ["cargo", "clippy", "--workspace", "--all-targets", "--locked", "--", "-D", "warnings"]
|
||||
command = shlex.split(CI_CLIPPY) # the server build's clippy runs in CI (Linux)
|
||||
elif step.name.startswith("tests"):
|
||||
command = shlex.split(step.command)
|
||||
elif step.name == "tokens.css up to date":
|
||||
|
||||
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run a command on a Linux build host (default playhorizon) at a worktree's commit, and get its output back.
|
||||
#
|
||||
# tools/remote.sh [--host H] [--name N] [--cpus LIST] [--jobs J] <worktree> <command...>
|
||||
# tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib
|
||||
# tools/remote.sh . python3 tools/parity.py food light
|
||||
# tools/remote.sh --list # checkouts on the host, their size and last use
|
||||
# tools/remote.sh --gc [DAYS] # remove checkouts unused for DAYS (default 2)
|
||||
#
|
||||
# The host fetches the commit from GitHub itself: commit and push first (uncommitted changes are not sent, and
|
||||
# nothing else leaves this machine: no files, no credentials, no environment). Each name (default: the worktree's
|
||||
# folder) keeps one checkout there, ~/remote-work/<name>, with its own target/: the next run checks out the new
|
||||
# commit over it, so only what changed rebuilds (sccache shares the registry crates between names). One run per
|
||||
# name at a time. The command runs in bash at the checkout's root, niced in the host's CI slice, with the host's
|
||||
# toolchains, a virtual screen and scratch homes for the game and launcher. .local/ links to the host's vanilla
|
||||
# data; a command that runs harnesses (it names parity, lan_e2e or horizon-prepare) also gets .local/horizon-client,
|
||||
# prepared as CI prepares it (tools/ci/vanilla-data.sh). Output streams back and is kept in ~/remote-work/<name>.logs/.
|
||||
# The exit status is the command's.
|
||||
#
|
||||
# The host is lent by a partner who keeps hypervisor access: never send secrets, tokens or credentials there,
|
||||
# and never treat a result from it as a CI result.
|
||||
set -euo pipefail
|
||||
|
||||
# CPUs 0-3 stay free for benchmarks (perf-world-entry measures on playhorizon pinned to them); --cpus all for every one.
|
||||
host=playhorizon name="" jobs="" cpus=4-7
|
||||
usage() { sed -n '2,8s/^# \{0,1\}//p' "$0" >&2; exit 2; }
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--host) host=$2; shift 2;;
|
||||
--name) name=$2; shift 2;;
|
||||
--jobs) jobs=$2; shift 2;;
|
||||
--cpus) cpus=$2; shift 2;;
|
||||
--list) exec ssh "ludovic@$host" 'cd ~/remote-work 2>/dev/null && for d in */; do d=${d%/};
|
||||
printf "%-32s %8s last used %s\n" "$d" "$(du -sh "$d" 2>/dev/null | cut -f1)" "$(stat -c %y "$d.logs" 2>/dev/null | cut -c1-16)"; done';;
|
||||
--gc) days=${2:-2}; exec ssh "ludovic@$host" "cd ~/remote-work 2>/dev/null || exit 0
|
||||
find . -maxdepth 1 -name '*.logs' -mtime +$days | while read -r logs; do d=\${logs%.logs};
|
||||
flock -n \"\$d.lock\" rm -rf \"\$d\" \"\$logs\" \"\$d.lock\" && echo \"removed \${d#./}\"; done";;
|
||||
-h|--help) usage;;
|
||||
*) break;;
|
||||
esac
|
||||
done
|
||||
[ $# -ge 2 ] || usage
|
||||
tree=$(cd "$1" && git rev-parse --show-toplevel); shift
|
||||
sha=$(git -C "$tree" rev-parse HEAD)
|
||||
name=${name:-$(basename "$tree")}
|
||||
[[ $name =~ ^[A-Za-z0-9._-]+$ ]] || { echo "remote.sh: name '$name' must be letters, digits, . _ -" >&2; exit 2; }
|
||||
if ! git -C "$tree" diff --quiet HEAD -- 2>/dev/null; then
|
||||
echo "remote.sh: uncommitted changes in $tree are not sent: the host runs ${sha:0:9}" >&2
|
||||
fi
|
||||
if [ -z "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ]; then
|
||||
git -C "$tree" fetch -q origin 2>/dev/null || true
|
||||
[ -n "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ] ||
|
||||
{ echo "remote.sh: ${sha:0:9} is not on GitHub yet: push it first (the host fetches from GitHub)" >&2; exit 2; }
|
||||
fi
|
||||
command=$(printf '%q ' "$@")
|
||||
|
||||
# The host side reads its script and these four values on stdin (nothing is re-split by a remote shell); its
|
||||
# own environment comes from the runner's files there.
|
||||
{
|
||||
printf 'name=%q sha=%q jobs=%q cpus=%q command=%q\n' "$name" "$sha" "$jobs" "$cpus" "$command"
|
||||
cat <<'REMOTE'
|
||||
set -euo pipefail
|
||||
if [ "$cpus" = all ]; then pin=(); jobs=${jobs:-$(nproc)}; else pin=(taskset -c "$cpus"); jobs=${jobs:-$(taskset -c "$cpus" nproc)}; fi
|
||||
runner=~/.actions-runners/horizon
|
||||
if [ -e "$runner/paused" ]; then echo "remote.sh: this host is paused ($runner/paused)" >&2; exit 75; fi
|
||||
set -a; . "$runner/.env"; set +a
|
||||
export PATH="$(cat "$runner/.path")" DISPLAY=":$(cat "$runner/display")" RUSTC_WRAPPER="$(command -v sccache || true)"
|
||||
export CARGO_BUILD_JOBS=$jobs FLEET_LOAD_JOBS=$jobs PARITY_LOCAL_JOBS=$(( jobs > 1 ? jobs / 2 : 1 ))
|
||||
unset WAYLAND_DISPLAY
|
||||
mkdir -p ~/remote-work && cd ~/remote-work
|
||||
exec 9> "$name.lock"
|
||||
flock -n 9 || { echo "remote.sh: $name is busy with another run" >&2; exit 75; }
|
||||
if [ ! -d "$name/.git" ]; then
|
||||
git clone -q --filter=blob:none --no-checkout https://github.com/ludovic111/horizon "$name" 9>&-
|
||||
fi
|
||||
cd "$name"
|
||||
# The lock's descriptor stays out of everything started here (9>&-): a daemon one of them starts (sccache's server,
|
||||
# from the preparer's build or the command's) would hold the lock after the run.
|
||||
git fetch -q --no-tags origin "$sha" 9>&-
|
||||
git checkout -q --force --detach "$sha"
|
||||
git clean -qfd -e /target -e /.local
|
||||
# The host's vanilla data, linked as CI's runner links it; for harnesses also .local/horizon-client, prepared by
|
||||
# this commit's own preparer (once per preparer version, kept beside the data and shared by every name).
|
||||
if [[ $command =~ parity|lan_e2e|horizon-prepare ]]; then
|
||||
RUNNER_WORKSPACE=$(dirname "$HORIZON_SHARED_SOURCE") RUNNER_TEMP=$(mktemp -d) bash tools/ci/vanilla-data.sh >&2 9>&-
|
||||
else
|
||||
mkdir -p .local
|
||||
for d in minecraft tools datagen; do
|
||||
if [ -e "$HORIZON_SHARED_SOURCE/$d" ]; then ln -sfn "$HORIZON_SHARED_SOURCE/$d" ".local/$d"; fi
|
||||
done
|
||||
fi
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
export HORIZON_HOME=$scratch/game HORIZON_LAUNCHER_HOME=$scratch/launcher XDG_DATA_HOME=$scratch/data \
|
||||
XDG_CONFIG_HOME=$scratch/config HORIZON_NO_AUDIO=1 HORIZON_LAUNCHER_NO_SELF_UPDATE=1 HORIZON_TELEMETRY_URL=off
|
||||
mkdir -p "$HORIZON_HOME" "$HORIZON_LAUNCHER_HOME" "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" ../"$name.logs"
|
||||
log=../"$name.logs/$(date -u +%Y%m%dT%H%M%SZ)-${sha:0:9}.log"
|
||||
echo "remote.sh: $(hostname) at ${sha:0:9} in ~/remote-work/$name, CPUs $cpus, -j $jobs; log ~/remote-work/${log#../}" >&2
|
||||
status=0
|
||||
systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit="remote-$name-$$" \
|
||||
"${pin[@]}" nice -n 10 bash -c "$command" 2>&1 < /dev/null 9>&- | tee "$log" || status=${PIPESTATUS[0]}
|
||||
exit "$status"
|
||||
REMOTE
|
||||
} | ssh -o BatchMode=yes "ludovic@$host" bash -s
|
||||
Reference in New Issue
Block a user