From fb954f7d7f80b107b4b3dfa76dd02c738bb40dc4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:29:51 +0200 Subject: [PATCH 01/19] Load saved light and test it against vanilla Chunks saved with isLightOn now read their SkyLight and BlockLight arrays back like vanilla instead of being relit: a missing sky layer repeats the bottom layer of the section above it, and a missing block layer is dark. Such chunks skip the light job, mesh as soon as their neighbours are lit, and only relight when a freshly generated neighbour arrives. tools/test_light_parity.py builds a scene of slabs, stairs, snow, trapdoors, lanterns, leaves and lava in a vanilla world, edits it, and requires every saved light value and every incremental relight to match Horizon's engine. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/chunk.rs | 3 + crates/horizon-client/src/save.rs | 104 ++++++++++++++++++++++++- crates/horizon-client/src/streaming.rs | 15 +++- tools/test_light_parity.py | 100 ++++++++++++++++++++++++ 4 files changed, 220 insertions(+), 2 deletions(-) create mode 100755 tools/test_light_parity.py diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index e1332b159..d5e65655c 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -94,6 +94,8 @@ pub struct Chunk { /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. pub heights: Arc<[i16; 256]>, pub lit: bool, + /// Light read from a save with `isLightOn`: no light job is needed. + pub light_loaded: bool, /// Newly generated (not loaded from a save): eligible for generation-time spawns. pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. @@ -120,6 +122,7 @@ impl Chunk { biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, + light_loaded: false, fresh: false, block_entities: Vec::new(), structure_refs: Vec::new(), diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index bcca25e8a..83e93e8e1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -901,6 +901,60 @@ pub fn decode_with( Some(chunk) } +/// Read the stored `SkyLight`/`BlockLight` layers of a chunk saved with +/// `isLightOn` (`SerializableChunkData.read` + `ThreadedLevelLightEngine`), +/// so it needs no relighting. A missing sky layer repeats the bottom layer of +/// the section above it (15 above the highest stored one); a missing block +/// layer is dark. +pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { + if tag.get("isLightOn") != Some(&Tag::Byte(1)) { + return; + } + let Some(Tag::List(sections)) = tag.get("sections") else { + return; + }; + let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS]; + for section in sections { + let Some(y) = number(section.get("Y")) else { + continue; + }; + let si = y as i32 - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + let layer = |name: &str| match section.get(name) { + Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]), + _ => None, + }; + layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); + } + let sky_default = if sky_light { 15u8 } else { 0 }; + // Sky nibbles of the section above's bottom layer, going down. + let mut above: [u8; 256] = [sky_default; 256]; + for si in (0..SECTIONS).rev() { + let (sky, block) = layers[si]; + let mut data = Box::new([0u8; 4096]); + let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; + for (i, packed) in data.iter_mut().enumerate() { + let s = match sky { + Some(a) if sky_light => nibble(a, i), + _ => above[i & 255], + }; + let b = block.map_or(0, |a| nibble(a, i)); + *packed = s << 4 | b; + } + for (i, a) in above.iter_mut().enumerate() { + *a = data[i] >> 4; + } + let mut section = (*chunk.sections[si]).clone(); + section.light = Light::Full(data); + section.compact(); + chunk.sections[si] = Arc::new(section); + } + chunk.lit = true; + chunk.light_loaded = true; +} + type RegionCache = Mutex>>>>; /// One dimension folder (`dimensions/minecraft/`). Region files are /// read lazily by worker threads. @@ -951,7 +1005,9 @@ impl SaveDir { pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { let root = self.read_record("region", x, z)?; let tables = self.tables.get().map(|t| &**t); - decode_with(&root, registry, biomes, tables) + let mut chunk = decode_with(&root, registry, biomes, tables)?; + load_light(&root.tag, &mut chunk, self.sky_light); + Some(chunk) } /// Entities saved for a chunk (`entities/`; older chunks may still keep /// them in the chunk's own `entities` list). @@ -2016,6 +2072,52 @@ mod tests { assert_eq!(nibbles(&light, true)[0], 0x5F); } #[test] + fn stored_light_loads_with_vanilla_defaults() { + let mut sky = vec![0u8; 2048]; + sky[0] = 0x5A; // x=0 -> 10, x=1 -> 5 + let section = |y: i8, entries: Vec<(&str, Tag)>| { + let mut all = vec![("Y", Tag::Byte(y))]; + all.extend(entries); + Tag::compound(all) + }; + let tag = Tag::compound([ + ("isLightOn", Tag::Byte(1)), + ( + "sections", + Tag::List(vec![ + section( + -4, + vec![ + ("SkyLight", Tag::ByteArray(sky)), + ("BlockLight", Tag::ByteArray(vec![0x21; 2048])), + ], + ), + // No sky layer: repeats the bottom layer of the section above. + section(-3, vec![]), + ]), + ), + ]); + let mut chunk = Chunk::empty(0, 0); + load_light(&tag, &mut chunk, true); + assert!(chunk.lit && chunk.light_loaded); + let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i); + assert_eq!(at(&chunk, 0, 0), 0xA1, "stored sky 10, block 1"); + assert_eq!(at(&chunk, 0, 1), 0x52, "stored sky 5, block 2"); + // Section -3 has no layers; above it (-2..) sky defaults to 15. + assert_eq!(at(&chunk, 1, 0), 0xF0); + assert_eq!(at(&chunk, SECTIONS - 1, 5), 0xF0); + let mut dark = Chunk::empty(0, 0); + load_light(&tag, &mut dark, false); + assert_eq!(at(&dark, 1, 0), 0x00, "no skylight dimension"); + let mut unlit = Chunk::empty(0, 0); + load_light( + &Tag::compound([("isLightOn", Tag::Byte(0))]), + &mut unlit, + true, + ); + assert!(!unlit.lit && !unlit.light_loaded); + } + #[test] fn level_round_trips_through_the_vanilla_files() { let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 6fd8a64bd..c43e82e69 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -329,10 +329,23 @@ impl Streaming { self.decorated.insert(key); if self.in_range(key.0, key.1, 2) { self.generated_total += 1; + // A chunk saved with its light needs no light job; its + // unlit neighbours still light themselves from it. + let loaded = chunk.light_loaded; world.chunks.insert(key, Arc::new(chunk)); + if loaded { + self.lit.insert(key); + for sy in 0..SECTIONS as i32 { + world.dirty_sections.insert((key.0, sy, key.1)); + } + } for dz in -1..=1 { for dx in -1..=1 { - world.dirty_light.insert((key.0 + dx, key.1 + dz)); + let n = (key.0 + dx, key.1 + dz); + if !loaded || world.chunks.get(&n).is_some_and(|c| !c.light_loaded) + { + world.dirty_light.insert(n); + } } } } diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py new file mode 100755 index 000000000..3e42acd5c --- /dev/null +++ b/tools/test_light_parity.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Compare Horizon's light engine with the vanilla 26.3 server. + +Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, +leaves, water and glowstone in a fresh vanilla world, lets the vanilla light +engine settle, stops the server so the SkyLight/BlockLight arrays are saved, +then relights every saved chunk with `examples/light_parity` and requires every +value to agree. The example also replays block edits through the incremental +`light::relight` and checks them against a full relight. + + test_light_parity.py [--seed N] [--keep] +""" +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LOCAL = ROOT / '.local' +RESOURCES = LOCAL / 'horizon-client' / '26.3' +SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar' + +# Absolute coordinates well above the terrain, inside force-loaded chunks. +SCENE = [ + 'forceload add 0 0 63 63', + 'sleep 6', + # Closed room with a bottom-slab roof and a glowstone lamp. + 'fill 2 170 2 20 175 20 stone hollow', + 'fill 2 176 2 20 176 20 stone_slab[type=bottom]', + 'setblock 10 171 10 glowstone', + # Stairs, top and bottom; snow layers; trapdoors; lanterns; water. + 'fill 4 171 4 4 171 18 oak_stairs[facing=east,half=top]', + 'fill 6 171 4 6 171 18 stone_brick_stairs[facing=north,half=bottom,shape=inner_left]', + 'fill 12 171 4 18 171 6 snow[layers=3]', + 'fill 12 172 8 18 172 8 oak_trapdoor[half=bottom,open=false]', + 'fill 12 173 12 18 173 12 oak_trapdoor[half=top,open=true,facing=north]', + 'setblock 14 171 14 lantern', + 'setblock 15 175 15 soul_lantern[hanging=true]', + 'fill 8 171 16 9 172 17 water', + # Open-air structures: sky light through slabs, stairs and leaves. + 'fill 24 170 24 46 170 46 stone', + 'fill 26 171 26 44 171 26 stone_slab[type=top]', + 'fill 26 171 28 44 171 28 stone_slab[type=bottom]', + 'fill 26 172 30 44 172 30 oak_leaves[persistent=true]', + 'fill 26 171 32 30 171 40 glass', + 'fill 32 171 32 36 171 40 oak_stairs[facing=south,half=bottom]', + 'fill 38 171 32 38 175 40 stone_brick_wall', + 'fill 40 171 32 44 171 40 dirt_path', + 'fill 40 172 34 44 172 34 daylight_detector', + 'fill 24 180 50 46 180 50 stone_slab[type=double]', + 'fill 24 178 52 46 178 52 oak_stairs[facing=west,half=top]', + 'setblock 30 171 44 torch', + 'setblock 34 171 44 campfire', + 'setblock 38 171 44 sea_lantern', + 'setblock 42 171 44 lava', + 'sleep 10', + # Edits after the first lighting pass, so vanilla updates incrementally. + 'setblock 10 171 10 air', + 'setblock 10 176 10 air', + 'setblock 30 171 26 air', + 'fill 26 172 30 30 172 30 air', + # Vanilla saves a chunk only when its blocks changed, so light that + # reached an untouched chunk later is stale on disk: mark every compared + # chunk (0..2, 0..3) as edited so it is written at shutdown. + *[f'setblock {x * 16 + 8} 169 {z * 16 + 8} stone' for x in range(3) for z in range(4)], + 'sleep 8', +] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', default='4242') + parser.add_argument('--keep', action='store_true') + args = parser.parse_args() + run = LOCAL / 'rust-light-parity' + shutil.rmtree(run, ignore_errors=True) + run.mkdir(parents=True) + command = [sys.executable, str(ROOT / 'tools' / 'vanilla_world_check.py'), '--jar', str(SERVER), + '--dir', str(run), '--world', 'world', '--seed', args.seed, '--wait-after', '8'] + for step in SCENE: + command += ['--command', step] + if subprocess.run(command).returncode: + sys.exit('vanilla server reported problems') + dimension = run / 'world' / 'dimensions' / 'minecraft' / 'overworld' + if not (dimension / 'region').is_dir(): + dimension = run / 'world' + for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): + status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', + '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + cwd=ROOT).returncode + if status: + sys.exit('light mismatch against vanilla') + print('light parity ok') + if not args.keep: + shutil.rmtree(run, ignore_errors=True) + + +if __name__ == '__main__': + main() From 19336564d2bd782186b62674d55c04d343835cf0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:40:31 +0200 Subject: [PATCH 02/19] Add the loom and banner patterns The loom now opens its menu: a banner, a dye and an optional pattern item go in, the 32 plain patterns (or the one the pattern item provides) show in a scrolling 4x4 grid with hover names, picking one previews the result banner and the result slot gives a banner with one more layer, using up one banner and one dye. Banners with six layers show the error state and give nothing. Shift-click routes banners, dyes and pattern items to the right slots. Banner layers are stored in the banner_patterns item component, in a new banner block entity (saved to chunks), and carry over when a banner is placed or dropped. Placed banners draw all their pattern layers, banner and shield icons are drawn as the vanilla 3D models with their patterns, a held banner is shown in the first-person hand, and tooltips list the layers. Banner duplication and shield decoration crafting recipes work, and crafting now returns item remainders such as buckets. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/banner.rs | 313 +++++++++++++ .../horizon-client/src/block_entity_render.rs | 17 +- crates/horizon-client/src/containers.rs | 24 +- crates/horizon-client/src/crafting.rs | 197 +++++++++ crates/horizon-client/src/game.rs | 54 ++- crates/horizon-client/src/game/banners.rs | 222 ++++++++++ crates/horizon-client/src/game/loom.rs | 415 ++++++++++++++++++ crates/horizon-client/src/game/minecarts.rs | 1 + crates/horizon-client/src/game/shield.rs | 76 +++- crates/horizon-client/src/game/stations.rs | 50 ++- crates/horizon-client/src/game/storage.rs | 4 + crates/horizon-client/src/item_data.rs | 33 ++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 41 +- crates/horizon-client/src/stations.rs | 2 + 15 files changed, 1411 insertions(+), 39 deletions(-) create mode 100644 crates/horizon-client/src/banner.rs create mode 100644 crates/horizon-client/src/game/banners.rs create mode 100644 crates/horizon-client/src/game/loom.rs diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs new file mode 100644 index 000000000..d2bc33fba --- /dev/null +++ b/crates/horizon-client/src/banner.rs @@ -0,0 +1,313 @@ +//! Banner patterns: the `banner_pattern` registry and its tags, the +//! `banner_patterns` layers carried by banner items, shields and placed +//! banners, and the loom rules of `LoomMenu` (selectable patterns, the +//! six-layer limit and the result stack). +use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path, sync::Arc}; + +/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BannerLayer { + pub pattern: Arc, + pub color: Arc, +} +impl BannerLayer { + pub fn new(pattern: &str, color: &str) -> Self { + Self { + pattern: Arc::from(pattern), + color: Arc::from(color), + } + } +} + +/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`). +pub const MAX_LAYERS: usize = 6; + +/// One `banner_pattern` registry entry. +#[derive(Clone, Debug)] +pub struct Pattern { + pub id: Arc, + /// `asset_id` path, the texture under `entity/banner` and `entity/shield`. + pub asset: String, + pub translation_key: String, +} + +/// The pattern registry, its tags and the item components the loom reads. +#[derive(Default)] +pub struct Banners { + patterns: Vec, + /// `#minecraft:no_item_required`, in tag order. + no_item_required: Vec>, + /// Item -> `dye` component. + dyes: HashMap, Arc>, + /// Item -> `provides_banner_patterns`, in tag order. + provided: HashMap, Vec>>, +} + +fn read_tag(root: &Path, name: &str, depth: u32) -> Vec> { + if depth > 8 { + return Vec::new(); + } + let path = root.join(format!( + "data/minecraft/tags/banner_pattern/{}.json", + name.trim_start_matches("minecraft:") + )); + let Some(v) = fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for value in v["values"].as_array().into_iter().flatten() { + let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else { + continue; + }; + match s.strip_prefix('#') { + Some(tag) => out.extend(read_tag(root, tag, depth + 1)), + None => out.push(Arc::from(s)), + } + } + out +} + +impl Banners { + pub fn load(root: &Path) -> Self { + let mut banners = Self::default(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + for path in files { + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Some(v) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + let asset = v["asset_id"] + .as_str() + .unwrap_or(stem) + .trim_start_matches("minecraft:") + .to_owned(); + banners.patterns.push(Pattern { + id: Arc::from(format!("minecraft:{stem}").as_str()), + asset, + translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(), + }); + } + banners.no_item_required = read_tag(root, "no_item_required", 0); + if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| { + serde_json::from_slice::>(&b).ok() + }) { + for (item, c) in raw { + let id: Arc = Arc::from(item.as_str()); + if let Some(dye) = c["minecraft:dye"].as_str() { + banners.dyes.insert(id.clone(), Arc::from(dye)); + } + match &c["minecraft:provides_banner_patterns"] { + Value::String(tag) if tag.starts_with('#') => { + banners.provided.insert(id, read_tag(root, &tag[1..], 0)); + } + Value::String(single) => { + banners + .provided + .insert(id, vec![Arc::from(single.as_str())]); + } + _ => {} + } + } + } + banners + } + pub fn pattern(&self, id: &str) -> Option<&Pattern> { + self.patterns.iter().find(|p| &*p.id == id) + } + /// `Sheets.getBannerSprite` texture name of a pattern. + pub fn banner_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/banner/{}", p.asset), + None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")), + } + } + /// `Sheets.getShieldSprite` texture name of a pattern. + pub fn shield_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/shield/{}", p.asset), + None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")), + } + } + /// `BannerPatternLayers.Layer.description` translation key. + pub fn layer_key(&self, layer: &BannerLayer) -> String { + let base = self.pattern(&layer.pattern).map_or_else( + || { + format!( + "block.minecraft.banner.{}", + layer.pattern.trim_start_matches("minecraft:") + ) + }, + |p| p.translation_key.clone(), + ); + format!("{base}.{}", layer.color) + } + /// `LoomMenu.isDyeItem`: the dye colour of a loom dye. + pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option> { + let tagged = items + .item_tags + .get("minecraft:loom_dyes") + .is_some_and(|t| t.contains(&*stack.item)); + tagged + .then(|| self.dyes.get(&stack.item).cloned()) + .flatten() + } + /// `LoomMenu.isPatternItem`. + pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool { + items + .item_tags + .get("minecraft:loom_patterns") + .is_some_and(|t| t.contains(&*stack.item)) + && self.provided.contains_key(&stack.item) + } + /// `LoomMenu.getSelectablePatterns`. + pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec> { + match pattern_item { + None => self.no_item_required.clone(), + Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(), + } + } +} + +/// `BannerItem`: a banner's dye colour from its item id. +pub fn banner_color(item: &str) -> Option<&'static str> { + let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?; + DYES.iter().map(|d| d.0).find(|d| *d == name) +} +/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name. +pub fn dye_rgb(name: &str) -> u32 { + DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1) +} +/// The layers of a banner or shield stack. +pub fn layers(stack: &ItemStack) -> &[BannerLayer] { + stack.data().map_or(&[], |d| &d.banner_patterns) +} +/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour. +pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack { + let mut result = ItemStack { + count: 1, + ..banner.clone() + }; + result + .data_mut() + .banner_patterns + .push(BannerLayer::new(pattern, dye)); + result +} +/// Whether the banner already carries the loom's limit. +pub fn has_max_layers(banner: &ItemStack) -> bool { + layers(banner).len() >= MAX_LAYERS +} + +/// The `banner_patterns` NBT list of layers. +pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { + Tag::List( + layers + .iter() + .map(|l| { + Tag::compound([ + ("pattern", Tag::String((&*l.pattern).into())), + ("color", Tag::String((&*l.color).into())), + ]) + }) + .collect(), + ) +} +pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + list.iter() + .filter_map(|e| { + let text = |k: &str| match e.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let pattern = text("pattern")?; + let color = text("color")?; + Some(BannerLayer::new( + &if pattern.contains(':') { + pattern + } else { + format!("minecraft:{pattern}") + }, + &color, + )) + }) + .collect() +} +/// Keeps `item_data` linked: the `StackData` fields the banner code reads. +pub fn set_layers(stack: &mut ItemStack, layers: Vec) { + let data: &mut item_data::StackData = stack.data_mut(); + data.banner_patterns = layers; + stack.tidy(); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn banners() -> Banners { + let mut b = Banners { + no_item_required: vec![Arc::from("minecraft:stripe_top")], + ..Default::default() + }; + b.provided.insert( + Arc::from("minecraft:flower_banner_pattern"), + vec![Arc::from("minecraft:flower")], + ); + b + } + #[test] + fn selectable_follow_the_pattern_item() { + let b = banners(); + assert_eq!(b.selectable(None).len(), 1); + let item = ItemStack::new("minecraft:flower_banner_pattern", 1); + assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower"); + } + #[test] + fn banner_colour_comes_from_the_item() { + assert_eq!( + banner_color("minecraft:light_gray_banner"), + Some("light_gray") + ); + assert_eq!(banner_color("minecraft:white_banner"), Some("white")); + assert_eq!(banner_color("minecraft:white_wool"), None); + } + #[test] + fn loom_adds_a_layer_up_to_the_limit() { + let mut banner = ItemStack::new("minecraft:white_banner", 3); + for i in 0..MAX_LAYERS { + assert!(!has_max_layers(&banner)); + banner = loom_result(&banner, "red", "minecraft:cross"); + assert_eq!(banner.count, 1); + assert_eq!(layers(&banner).len(), i + 1); + } + assert!(has_max_layers(&banner)); + } + #[test] + fn layers_round_trip_through_nbt() { + let l = vec![ + BannerLayer::new("minecraft:flower", "red"), + BannerLayer::new("minecraft:border", "black"), + ]; + assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 5869f6de0..8114542b0 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -700,6 +700,8 @@ pub struct Scene<'a> { pub lid: &'a dyn Fn([i32; 3]) -> f32, /// Sign block-entity data at a position. pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Banner layers at a position: pattern texture and RGB tint, bottom first. + pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, /// Font glyph cell and advance. pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, } @@ -773,6 +775,13 @@ impl BlockEntityRenderer { random: LegacyRandom::new(0x5EED_B00C), } } + /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). + pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { + Some(( + self.models.get("standing_banner")?, + self.models.get("standing_banner_flag")?, + )) + } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } @@ -993,10 +1002,16 @@ impl BlockEntityRenderer { draw_part(main, "root", m, &none, paint, out); draw_part(flag, "root", m, &wave, paint, out); } - // BannerRenderer.submitPatterns: the base pattern layer in the dye colour. + // BannerRenderer.submitPatterns: the base pattern layer in the dye colour, + // then up to 16 pattern layers in order. if let Some(paint) = paint("entity/banner/base", *color, packed) { draw_part(flag, "root", m, &wave, paint, out); } + for (texture, tint) in (scene.banner)(pos).iter().take(16) { + if let Some(paint) = paint(texture, *tint, packed) { + draw_part(flag, "root", m, &wave, paint, out); + } + } } Kind::Skull { kind, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..431eac25f 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,13 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// `BannerBlockEntity`: the pattern layers. + Banner(Banner), +} +#[derive(Clone, Debug, Default)] +pub struct Banner { + pub layers: Vec, + pub name: Option, } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -104,6 +111,9 @@ impl BlockEntity { if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if name.ends_with("_banner") { + return Some(Self::Banner(Banner::default())); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -155,6 +165,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::Banner(_) => "minecraft:banner", } } pub fn contents(&self) -> Vec { @@ -166,6 +177,7 @@ impl BlockEntity { Self::Jukebox(j) => j.record.iter().cloned().collect(), Self::Beacon(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), + Self::Banner(_) => Vec::new(), } } pub fn slots(&self) -> &[Option] { @@ -173,7 +185,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +197,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &mut [], } } } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index ecf8f9bd6..7994d0bd7 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -53,6 +53,96 @@ pub enum Recipe { ingredients: Vec, result: ItemStack, }, + /// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`. + Special(Special), +} +/// The banner-copying custom recipes. +#[derive(Clone, Debug)] +pub enum Special { + /// A patterned banner and a blank one of the same colour copy the patterns. + BannerDuplicate { banner: Ingredient, result: String }, + /// A banner decorates an undecorated shield. + ShieldDecoration { + banner: Ingredient, + target: Ingredient, + result: String, + }, +} +impl Special { + /// `matches` + `assemble` over the non-empty stacks of the grid. + fn assemble(&self, stacks: &[&ItemStack]) -> Option { + use crate::banner; + if stacks.len() != 2 { + return None; + } + match self { + Self::BannerDuplicate { + banner: ing, + result, + } => { + let color = banner::banner_color(&stacks[0].item)?; + let mut source = None; + let mut target = false; + for s in stacks { + if !ing.test(s) || banner::banner_color(&s.item)? != color { + return None; + } + let layers = banner::layers(s).len(); + if layers > banner::MAX_LAYERS { + return None; + } + if layers > 0 { + if source.is_some() { + return None; + } + source = Some(*s); + } else { + if target { + return None; + } + target = true; + } + } + let source = source.filter(|_| target)?; + // TransmuteRecipe.createWithOriginalComponents: the source's components. + Some(ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..(*source).clone() + }) + } + Self::ShieldDecoration { + banner: ing, + target: tgt, + result, + } => { + let (mut patterned, mut clear) = (None, None); + for s in stacks { + if ing.test(s) && banner::banner_color(&s.item).is_some() { + if patterned.is_some() { + return None; + } + patterned = Some(*s); + } else { + if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() { + return None; + } + clear = Some(*s); + } + } + let (banner_stack, shield) = (patterned?, clear?); + let mut out = ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..shield.clone() + }; + let data = out.data_mut(); + data.banner_patterns = banner::layers(banner_stack).to_vec(); + data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from); + Some(out) + } + } + } } #[derive(Clone, Debug)] pub struct Cooking { @@ -145,6 +235,36 @@ impl Recipes { )); } } + "minecraft:crafting_special_bannerduplicate" => { + if let (Some(banner), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::BannerDuplicate { + banner, + result: id.to_owned(), + }), + )); + } + } + "minecraft:crafting_special_shielddecoration" => { + if let (Some(banner), Some(target), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + Ingredient::parse(&v["target"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::ShieldDecoration { + banner, + target, + result: id.to_owned(), + }), + )); + } + } kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" @@ -189,6 +309,12 @@ impl Recipes { let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); for (_, recipe) in &self.crafting { match recipe { + Recipe::Special(special) => { + let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); + if let Some(result) = special.assemble(&stacks) { + return Some(result); + } + } Recipe::Shaped { width, height, @@ -242,9 +368,80 @@ impl Recipes { } None } + /// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder + /// (buckets, bottles), and the patterned banner a duplicate keeps. + pub fn remainders( + &self, + items: &Items, + grid: &[Option], + result: &ItemStack, + ) -> Vec> { + grid.iter() + .map(|cell| { + let s = cell.as_ref()?; + if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) { + return Some(ItemStack::new(rem, 1)); + } + (result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then( + || ItemStack { + count: 1, + ..s.clone() + }, + ) + }) + .collect() + } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::banner::BannerLayer; + + fn ingredient(items: &[&str]) -> Ingredient { + Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + } + fn patterned(item: &str) -> ItemStack { + let mut s = ItemStack::new(item, 1); + s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; + s + } + #[test] + fn banner_duplicate_copies_the_patterns_of_the_same_colour() { + let recipe = Special::BannerDuplicate { + banner: ingredient(&["minecraft:white_banner"]), + result: "minecraft:white_banner".into(), + }; + let source = patterned("minecraft:white_banner"); + let blank = ItemStack::new("minecraft:white_banner", 1); + let out = recipe.assemble(&[&source, &blank]).expect("copy"); + assert_eq!(out.data().unwrap().banner_patterns.len(), 1); + // Two blanks, or two patterned banners, do not match. + assert!(recipe.assemble(&[&blank, &blank]).is_none()); + assert!(recipe.assemble(&[&source, &source]).is_none()); + // Another colour is not in the recipe's ingredient. + let other = ItemStack::new("minecraft:red_banner", 1); + assert!(recipe.assemble(&[&source, &other]).is_none()); + } + #[test] + fn shield_decoration_needs_a_bare_shield() { + let recipe = Special::ShieldDecoration { + banner: ingredient(&["minecraft:red_banner"]), + target: ingredient(&["minecraft:shield"]), + result: "minecraft:shield".into(), + }; + let banner = patterned("minecraft:red_banner"); + let shield = ItemStack::new("minecraft:shield", 1); + let out = recipe.assemble(&[&banner, &shield]).expect("decorated"); + let data = out.data().unwrap(); + assert_eq!(data.base_color.as_deref(), Some("red")); + assert_eq!(data.banner_patterns.len(), 1); + // A shield that already has patterns cannot be decorated again. + assert!(recipe.assemble(&[&banner, &out]).is_none()); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..d5e5a8de4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4,6 +4,7 @@ mod advancements; mod advancements_screen; mod allays; mod armor_stands; +mod banners; mod beacon; mod blockctl; mod boats; @@ -28,6 +29,7 @@ mod game_mode; mod growth; mod jukebox; mod lightning; +mod loom; mod machines; mod maps; mod minecarts; @@ -607,6 +609,8 @@ struct Game<'a> { ender_open: Option<(i32, i32, i32)>, /// Contents of broken shulker boxes waiting for their dropped item. pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, + /// Layers of broken banners waiting for their dropped item. + pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, /// The player's fishing hook. hook: Option, tridents: Vec, @@ -977,6 +981,7 @@ impl Game<'_> { /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); + self.attach_banner_layers(pos, &mut stack); let r = &mut self.world.random; let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; let p = [ @@ -1808,6 +1813,7 @@ impl Game<'_> { .block_entities .insert((target[0], target[1], target[2]), entity); self.fill_placed_box(target, &stack); + self.fill_placed_banner(target, &stack); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); } @@ -2653,13 +2659,18 @@ impl Game<'_> { .map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned())) } fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - if &*stack.item == "minecraft:shield" { - shield::draw_shield_icon(batch, &self.res.atlas, x, y); - return; - } - let icon = self.icon(&stack.item); + // Special-model items: the shield and banners draw their own 3D icon. + let banner = if &*stack.item == "minecraft:shield" { + let passes = shield::shield_passes(&self.res.stations.banners, stack); + shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes); + true + } else { + self.draw_banner_icon(batch, stack, x, y) + }; + let icon = if banner { None } else { self.icon(&stack.item) }; let atlas = &self.res.atlas; match icon { + None if banner => {} Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), Some(Icon::Cube { top, @@ -3040,7 +3051,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3265,7 +3277,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -3453,6 +3466,12 @@ impl Game<'_> { let mut crafted = 0; while let Some(result) = self.craft_result() { let made = (result.item.clone(), result.count); + let cells = self.craft_size * self.craft_size; + let remainders = self.res.recipes.remainders( + &self.res.items, + &self.craft_grid[..cells], + &result, + ); if shift { if self.give(result).is_some() { break; @@ -3477,6 +3496,14 @@ impl Game<'_> { } } } + for (i, rest) in remainders.into_iter().enumerate() { + let Some(rest) = rest else { continue }; + match &mut self.craft_grid[i] { + cell @ None => *cell = Some(rest), + Some(c) if c.same_item_same_components(&rest) => c.count += rest.count, + _ => self.give_or_drop(rest), + } + } crafted += 1; self.stats.add("crafted", &made.0, made.1 as i32); if !shift || crafted >= 64 { @@ -3867,6 +3894,7 @@ impl Game<'_> { Some(BlockEntity::Sign(sign)) => Some(sign), _ => None, }, + banner: &|p| self.banner_layers_at(p), glyph: &|c| self.res.atlas.glyph(c), }; self.res @@ -5760,6 +5788,10 @@ impl Game<'_> { } first(&d["model"]) }); + if item.ends_with("_banner") { + // The banner item model is a special renderer over this base model. + current = Some("minecraft:item/template_banner".to_owned()); + } for _ in 0..16 { let Some(m) = current.take() else { break }; let path = m.trim_start_matches("minecraft:").to_owned(); @@ -5906,6 +5938,9 @@ impl Game<'_> { * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2]))) * glam::Mat4::from_scale(glam::Vec3::from(scale)) * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); + if self.held_banner_geometry(m, &stack, packed, &mut out) { + return out; + } let atlas = &self.res.atlas; let quad = |corners: [glam::Vec3; 4], name: &str, @@ -7033,6 +7068,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Advancements { self.advancements_drag(); } + if self.screen == Screen::Inventory { + self.loom_drag(); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -7164,6 +7202,7 @@ impl ApplicationHandler for Game<'_> { self.container_changed(key); } } + Screen::Inventory => self.loom_release(), Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -7665,6 +7704,7 @@ pub fn run() -> Result<()> { ender_items: vec![None; 27], ender_open: None, pending_shulker: HashMap::new(), + pending_banner: HashMap::new(), hook: None, tridents: Vec::new(), rockets: Vec::new(), diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs new file mode 100644 index 000000000..b9f701a0c --- /dev/null +++ b/crates/horizon-client/src/game/banners.rs @@ -0,0 +1,222 @@ +//! Placed banners (`BannerBlockEntity`): the pattern layers move from the +//! banner item to the block when placed and back to the dropped item when +//! broken (`copy_components` in the banner loot tables). +use super::Game; +use glam::{EulerRot, Mat4, Quat, Vec3}; +use horizon_client::{ + banner::{self, BannerLayer}, + block_entity_render::{Paint, draw_part}, + containers::{Banner, BlockEntity}, + hud::{HudBatch, rgba}, + items::ItemStack, + mesher::Vertex, +}; + +impl Game<'_> { + /// The pattern textures and tints of the banner at `pos`, bottom first. + pub(super) fn banner_layers_at(&self, pos: [i32; 3]) -> Vec<(String, u32)> { + let Some(BlockEntity::Banner(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return Vec::new(); + }; + layer_textures(&self.res.stations.banners, &b.layers) + } + /// A placed banner takes the item's layers and name. + pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) { + self.pending_banner.remove(&pos); + if !stack.item.ends_with("_banner") { + return; + } + if let Some(BlockEntity::Banner(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.layers = banner::layers(stack).to_vec(); + b.name = stack.custom_name().map(str::to_owned); + } + } + /// A banner in a slot: `item/template_banner`'s `gui` transform on the + /// banner model (pole, bar and flag with every layer), flat-lit and + /// depth-sorted. False when the stack is not a banner. + pub(super) fn draw_banner_icon( + &self, + batch: &mut HudBatch, + stack: &ItemStack, + x: f32, + y: f32, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let banners = &self.res.stations.banners; + let sprites = &self.res.atlas.sprites; + // display.gui, then the item's special transformation (a banner is + // modelled upside down and 2/3 size around the block centre). + let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0)) + * Mat4::from_quat(Quat::from_euler( + EulerRot::XYZ, + 30f32.to_radians(), + 20f32.to_radians(), + 0.0, + )) + * Mat4::from_scale(Vec3::splat(0.5325)) + * Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let mut passes: Vec<(&str, u32, bool, String)> = vec![ + ("entity/banner/banner_base", 0xFFFFFF, true, String::new()), + ( + "entity/banner/base", + banner::dye_rgb(base), + false, + String::new(), + ), + ]; + for layer in banner::layers(stack).iter().take(16) { + passes.push(( + "", + banner::dye_rgb(&layer.color), + false, + banners.banner_texture(&layer.pattern), + )); + } + // (depth, pass, screen corners, uv, colour) + let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() { + let name = if fixed.is_empty() { + dynamic.as_str() + } else { + fixed + }; + let Some(sprite) = sprites.get(name).copied() else { + continue; + }; + let paint = Paint { + sprite, + tint: 0xFFFFFF, + light: 0, + lights: (Vec3::ZERO, Vec3::ZERO), + }; + let mut verts: Vec = Vec::new(); + if *with_pole { + draw_part(main, "root", m, &none, paint, &mut verts); + } + draw_part(flag, "root", m, &wave, paint, &mut verts); + for quad in verts.as_chunks::<4>().0 { + let p = |i: usize| Vec3::from(quad[i].pos); + let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero(); + // Faces turned away from the viewer are culled. + if normal.z <= 0.0 { + continue; + } + let depth = (0..4).map(|i| p(i).z).sum::() / 4.0; + let shade = (0.6 + 0.4 * normal.z).min(1.0); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + faces.push(( + depth, + index, + std::array::from_fn(|i| { + [ + x + 8.0 + quad[i].pos[0] * 16.0, + y + 8.0 - quad[i].pos[1] * 16.0, + ] + }), + std::array::from_fn(|i| quad[i].uv), + rgba(c(16), c(8), c(0), 255), + )); + } + } + faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, corners, uv, color) in faces { + batch.quad(corners, uv, color); + } + true + } + /// A banner in the first-person hand: the standing banner model under the + /// item's `firstperson_righthand` transform (`m`) and its special + /// transformation. False when the stack is not a banner. + pub(super) fn held_banner_geometry( + &self, + m: Mat4, + stack: &ItemStack, + packed: u32, + out: &mut Vec, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let m = m + * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let lights = horizon_client::block_entity_render::diffuse_lights(false); + let sprites = &self.res.atlas.sprites; + let paint = |name: &str, tint: u32| { + sprites.get(name).map(|&sprite| Paint { + sprite, + tint, + light: packed, + lights, + }) + }; + if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) { + draw_part(main, "root", m, &none, p, out); + draw_part(flag, "root", m, &wave, p, out); + } + if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) { + draw_part(flag, "root", m, &wave, p, out); + } + for layer in banner::layers(stack).iter().take(16) { + let texture = self.res.stations.banners.banner_texture(&layer.pattern); + if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) { + draw_part(flag, "root", m, &wave, p, out); + } + } + true + } + /// The layers a banner dropped at `pos` carries. + pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if !stack.item.ends_with("_banner") { + return; + } + if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) { + let data = stack.data_mut(); + data.banner_patterns = layers; + if name.is_some() { + data.custom_name = name; + } + stack.tidy(); + } + } +} + +/// Texture names and tints of banner layers (`Sheets.getBannerSprite`). +pub(super) fn layer_textures( + banners: &banner::Banners, + layers: &[BannerLayer], +) -> Vec<(String, u32)> { + layers + .iter() + .map(|l| { + ( + banners.banner_texture(&l.pattern), + banner::dye_rgb(&l.color), + ) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs new file mode 100644 index 000000000..39663c298 --- /dev/null +++ b/crates/horizon-client/src/game/loom.rs @@ -0,0 +1,415 @@ +//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a +//! banner with a dye (and a pattern item for the special patterns), the +//! six-layer limit, the scrolling pattern list and the banner preview. +use super::{ + Game, + stations::{INPUT, Station}, +}; +use horizon_client::{ + banner::{self, BannerLayer}, + hud::{HudBatch, Rect, rgba}, + items::ItemStack, +}; +use std::sync::Arc; + +/// Per-menu loom state: `selectablePatterns`, the selected index and the +/// screen's scroller. +#[derive(Default)] +pub(super) struct LoomState { + pub(super) patterns: Vec>, + pub(super) selected: Option, + /// `displayPatterns`: the pattern buttons are shown. + pub(super) display: bool, + pub(super) has_max: bool, + pub(super) scroll: f32, + pub(super) start_row: usize, + pub(super) scrolling: bool, +} +impl LoomState { + fn total_rows(&self) -> usize { + self.patterns.len().div_ceil(4) + } + fn offscreen_rows(&self) -> i32 { + self.total_rows() as i32 - 4 + } + fn scroll_active(&self) -> bool { + self.display && self.patterns.len() > 16 + } + /// `startRow` for a scroller position. + fn row_for(&self, offs: f32) -> usize { + ((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize + } +} + +const BUTTON: f32 = 14.0; + +fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} +/// A sub-rectangle of a sprite given in texels. +fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + Rect { + u0: r.u0 + x * du, + v0: r.v0 + y * dv, + u1: r.u0 + (x + w) * du, + v1: r.v0 + (y + h) * dv, + w: w as u32, + h: h as u32, + } +} +/// A dye's tint as a HUD vertex colour. +pub(super) fn dye_color(name: &str) -> u32 { + let c = banner::dye_rgb(name); + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255) +} + +impl Game<'_> { + /// `LoomMenu.slotsChanged` and the screen's `containerChanged`. + pub(super) fn loom_changed(&self, s: &mut Station) { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref()); + let l = &mut s.loom; + let mut result = None; + if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) { + let valid = l.selected.is_some_and(|i| i < l.patterns.len()); + let previous = std::mem::take(&mut l.patterns); + l.patterns = banners.selectable(s.inputs[2].as_ref()); + let shown = if l.patterns.len() == 1 { + l.selected = Some(0); + Some(l.patterns[0].clone()) + } else if !valid { + l.selected = None; + None + } else { + let value = previous[l.selected.unwrap_or(0)].clone(); + match l.patterns.iter().position(|p| *p == value) { + Some(i) => { + l.selected = Some(i); + Some(value) + } + None => { + l.selected = None; + None + } + } + }; + l.has_max = banner::has_max_layers(banner_stack); + if let Some(pattern) = shown { + if l.has_max { + l.selected = None; + } else if let Some(dye) = banners.loom_dye(items, dye_stack) { + result = Some(banner::loom_result(banner_stack, &dye, &pattern)); + } + } + l.display = !l.has_max && !l.patterns.is_empty(); + } else { + l.patterns.clear(); + l.selected = None; + l.has_max = banner_in.is_some_and(banner::has_max_layers); + l.display = false; + } + if l.start_row >= l.total_rows() { + l.start_row = 0; + l.scroll = 0.0; + } + s.result = result; + } + /// The loom slots' `mayPlace`. + pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) { + let banners = &self.res.stations.banners; + let ok = match input { + 0 => stack.item.ends_with("_banner"), + 1 => banners.loom_dye(&self.res.items, stack).is_some(), + _ => banners.is_pattern_item(&self.res.items, stack), + }; + (ok, 64) + } + /// The result slot's `onTake`: one banner and one dye are used up. + pub(super) fn loom_taken(&mut self, s: &mut Station) { + for slot in &mut s.inputs[..2] { + if let Some(x) = slot.as_mut() { + x.count -= 1; + if x.count == 0 { + *slot = None; + } + } + } + if s.inputs[0].is_none() || s.inputs[1].is_none() { + s.loom.selected = None; + } + if s.last_sound != self.ticks { + s.last_sound = self.ticks; + let pos = s.pos; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0); + } + } + /// `LoomMenu.quickMoveStack` from an inventory slot. + pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let target = if stack.item.ends_with("_banner") { + Some(INPUT) + } else if banners.loom_dye(items, stack).is_some() { + Some(INPUT + 1) + } else if banners.is_pattern_item(items, stack) { + Some(INPUT + 2) + } else { + None + }; + match target { + Some(t) => self.move_to(stack, &[t], false), + None if (9..36).contains(&slot) => { + let hotbar: Vec = (0..9).collect(); + self.move_to(stack, &hotbar, false) + } + None if slot < 9 => { + let main: Vec = (9..36).collect(); + self.move_to(stack, &main, false) + } + None => false, + } + } + /// A left click inside the loom's pattern grid or scroller. + pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool { + let Some(s) = self.station.as_ref() else { + return false; + }; + let l = &s.loom; + if !l.display { + return false; + } + for row in 0..4 { + for column in 0..4 { + let index = (row + l.start_row) * 4 + column; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) { + if let Some(s) = self.station.as_mut() { + s.loom.selected = Some(index); + } + self.audio + .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.station_changed(); + return true; + } + } + } + if inside(local, 119.0, 9.0, 12.0, 56.0) + && let Some(s) = self.station.as_mut() + { + s.loom.scrolling = true; + return true; + } + false + } + /// `LoomScreen.mouseDragged` on the scroller. + pub(super) fn loom_drag(&mut self) { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; + let (_, oy) = self.inventory_origin(&HudBatch::new(size)); + let cursor_y = self.cursor.1; + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + if l.scrolling && l.display && l.offscreen_rows() > 0 { + let top = oy + 13.0; + l.scroll = ((cursor_y - top - 7.5) / (56.0 - 15.0)).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + pub(super) fn loom_release(&mut self) { + if let Some(s) = self.station.as_mut() { + s.loom.scrolling = false; + } + } + /// `LoomScreen.mouseScrolled`. + pub(super) fn loom_scroll(&mut self, d: f32) { + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + let offscreen = l.offscreen_rows(); + if l.display && offscreen > 0 { + l.scroll = (l.scroll - d / offscreen as f32).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + /// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1)) + /// drawn flat: the cloth, the base colour and every layer. + pub(super) fn draw_flag( + &self, + batch: &mut HudBatch, + rect: [f32; 4], + base: &str, + layers: &[BannerLayer], + ) { + let banners = &self.res.stations.banners; + let mut paint = |name: &str, color: u32| { + if let Some(r) = self.res.atlas.sprites.get(name).copied() { + let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]); + batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color); + } + }; + paint("entity/banner/banner_base", u32::MAX); + paint("entity/banner/base", dye_color(base)); + for layer in layers.iter().take(16) { + paint( + &banners.banner_texture(&layer.pattern), + dye_color(&layer.color), + ); + } + } + /// `LoomScreen.extractBackground` after the background; returns the + /// pattern name tooltip of the hovered button. + pub(super) fn draw_loom( + &mut self, + batch: &mut HudBatch, + ox: f32, + oy: f32, + local: (f32, f32), + ) -> Option> { + let s = self.station.as_ref()?; + let l = &s.loom; + let atlas = &self.res.atlas; + for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() { + if s.inputs[i].is_none() { + let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i]; + batch.sprite( + atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + pos.0, + oy + pos.1, + ); + } + } + let scroller = if l.scroll_active() { + "scroller" + } else { + "scroller_disabled" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{scroller}"), + ox + 119.0, + oy + 13.0 + (41.0 * l.scroll).floor(), + ); + let result = s.result.clone(); + let (display, has_max, start_row, selected) = + (l.display, l.has_max, l.start_row, l.selected); + let patterns = l.patterns.clone(); + let dye = s.inputs[1] + .as_ref() + .and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d)) + .unwrap_or_else(|| Arc::from("white")); + if let Some(result) = result.filter(|_| !has_max) + && let Some(base) = banner::banner_color(&result.item) + { + self.draw_flag( + batch, + [ox + 141.0, oy + 8.0, 20.0, 40.0], + base, + banner::layers(&result), + ); + } else if has_max { + batch.sprite( + &self.res.atlas, + "gui/sprites/container/loom/error", + ox + 138.0, + oy + 52.0, + ); + } + let mut tooltip = None; + if display { + let atlas = &self.res.atlas; + for row in 0..4 { + for column in 0..4 { + let index = (row + start_row) * 4 + column; + let Some(pattern) = patterns.get(index) else { + return tooltip; + }; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + let hover = inside(local, x, y, BUTTON, BUTTON); + let sprite = if selected == Some(index) { + "pattern_selected" + } else if hover { + let key = self + .res + .stations + .banners + .layer_key(&BannerLayer::new(pattern, &dye)); + tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]); + "pattern_highlighted" + } else { + "pattern" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{sprite}"), + ox + x, + oy + y, + ); + // extractBannerOnButton: a 5x10 grey cloth with the pattern. + batch.fill( + atlas, + ox + x + 4.0, + oy + y + 2.0, + 5.0, + 10.0, + dye_color("gray"), + ); + let texture = self.res.stations.banners.banner_texture(pattern); + if let Some(r) = atlas.sprites.get(&texture).copied() { + let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]); + batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX); + } + } + } + } + tooltip + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scroller_rows_follow_the_offset() { + let l = LoomState { + patterns: (0..40) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + // 40 patterns = 10 rows, 6 off screen. + assert_eq!(l.offscreen_rows(), 6); + assert!(l.scroll_active()); + assert_eq!(l.row_for(0.0), 0); + assert_eq!(l.row_for(1.0), 6); + assert_eq!(l.row_for(0.5), 3); + } + #[test] + fn few_patterns_do_not_scroll() { + let l = LoomState { + patterns: (0..16) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + assert!(!l.scroll_active()); + assert_eq!(l.offscreen_rows(), 0); + } +} diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 259758994..9f201dc8a 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1238,6 +1238,7 @@ impl Game<'_> { nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, + banner: &|_| Vec::new(), glyph: &|c| self.res.atlas.glyph(c), }; self.res diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index eade37109..7857c047e 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -252,14 +252,8 @@ pub(super) fn draw_shield_icon( atlas: &horizon_client::hud::HudAtlas, x: f32, y: f32, + passes: &[(String, u32)], ) { - let Some(r) = atlas - .sprites - .get("entity/shield/shield_base_nopattern") - .copied() - else { - return; - }; // display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65. let (sx, cx) = 15f32.to_radians().sin_cos(); let (sy, cy) = (-25f32).to_radians().sin_cos(); @@ -282,15 +276,9 @@ pub(super) fn draw_shield_icon( qz, ] }; - let tex = |u: f32, v: f32| { - [ - r.u0 + (r.u1 - r.u0) * u / 64.0, - r.v0 + (r.v1 - r.v0) * v / 64.0, - ] - }; // ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and // handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6). - let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new(); for (tu, tv, from, size) in [ (0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]), (26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]), @@ -324,16 +312,64 @@ pub(super) fn draw_shield_icon( } let p = verts.map(place); let depth = p.iter().map(|q| q[2]).sum::() / 4.0; - let uv = [tex(c, b), tex(a, b), tex(a, e), tex(c, e)]; + let texels = [[c, b], [a, b], [a, e], [c, e]]; // Flat item lighting: faces toward the viewer are brightest. let shade = (0.6 + 0.4 * normal[2]).min(1.0); - let s = (shade * 255.0) as u8; - let color = horizon_client::hud::rgba(s, s, s, 255); - faces.push((depth, p.map(|q| [q[0], q[1]]), uv, color)); + faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade)); } } - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, p, uv, color) in faces { + // Every pass redraws the same boxes; equal depths keep the pass order. + let mut quads = Vec::new(); + for (index, (name, tint)) in passes.iter().enumerate() { + let Some(r) = atlas.sprites.get(name).copied() else { + continue; + }; + for (depth, p, texels, shade) in &faces { + let uv = texels.map(|[u, v]| { + [ + r.u0 + (r.u1 - r.u0) * u / 64.0, + r.v0 + (r.v1 - r.v0) * v / 64.0, + ] + }); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + quads.push(( + *depth, + index, + *p, + uv, + horizon_client::hud::rgba(c(16), c(8), c(0), 255), + )); + } + } + quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, p, uv, color) in quads { batch.quad(p, uv, color); } } +/// The textures a shield draws: the plain or patterned base, then the +/// banner layers (`ShieldSpecialRenderer.submit`). +pub(super) fn shield_passes( + banners: &horizon_client::banner::Banners, + stack: &ItemStack, +) -> Vec<(String, u32)> { + let data = stack.data(); + let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]); + let base = data.and_then(|d| d.base_color.as_deref()); + if layers.is_empty() && base.is_none() { + return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)]; + } + let mut passes = vec![ + ("entity/shield/shield_base".into(), 0xFFFFFF), + ( + "entity/shield/base".into(), + horizon_client::banner::dye_rgb(base.unwrap_or("white")), + ), + ]; + for layer in layers.iter().take(16) { + passes.push(( + banners.shield_texture(&layer.pattern), + horizon_client::banner::dye_rgb(&layer.color), + )); + } + passes +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index eb6f8c24d..e2771daba 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -32,6 +32,8 @@ pub(super) enum Kind { Beacon, /// The cartography table (game/cartography.rs). Cartography, + /// The loom (game/loom.rs). + Loom, } impl Kind { fn from_block(name: &str) -> Option { @@ -45,12 +47,13 @@ impl Kind { "minecraft:stonecutter" => Self::Stonecutter, "minecraft:beacon" => Self::Beacon, "minecraft:cartography_table" => Self::Cartography, + "minecraft:loom" => Self::Loom, _ => return None, }) } fn inputs(self) -> usize { match self { - Self::Smithing => 3, + Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, _ => 2, } @@ -65,6 +68,7 @@ impl Kind { Self::Merchant => "gui/container/villager", Self::Beacon => "gui/container/beacon", Self::Cartography => "gui/container/cartography_table", + Self::Loom => "gui/container/loom", } } fn title_key(self) -> &'static str { @@ -77,6 +81,7 @@ impl Kind { Self::Merchant => "merchant.trades", Self::Beacon => "container.beacon", Self::Cartography => "container.cartography_table", + Self::Loom => "container.loom", } } /// (titleLabelX, titleLabelY). @@ -85,7 +90,7 @@ impl Kind { Self::Anvil => (60.0, 6.0), Self::Smithing => (44.0, 15.0), Self::Stonecutter => (8.0, 5.0), - Self::Cartography => (8.0, 4.0), + Self::Cartography | Self::Loom => (8.0, 4.0), _ => (8.0, 6.0), } } @@ -99,6 +104,7 @@ impl Kind { Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)], Self::Beacon => &[(109.0, 110.0)], Self::Cartography => &[(15.0, 15.0), (15.0, 52.0)], + Self::Loom => &[(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)], }; table[i.min(table.len() - 1)] } @@ -112,6 +118,7 @@ impl Kind { Self::Merchant => Some((170.0, 37.0)), Self::Beacon => None, Self::Cartography => Some((145.0, 39.0)), + Self::Loom => Some((143.0, 57.0)), } } } @@ -133,11 +140,13 @@ pub(super) struct Station { input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, - last_sound: u64, + pub(super) last_sound: u64, /// Villager trading state. pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// The loom's patterns, selection and scroller (game/loom.rs). + pub(super) loom: super::loom::LoomState, } impl Station { fn new(kind: Kind, pos: [i32; 3]) -> Self { @@ -158,6 +167,7 @@ impl Station { last_sound: 0, merchant: None, beacon: [None; 2], + loom: Default::default(), } } pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { @@ -437,6 +447,7 @@ impl Game<'_> { Kind::Merchant => super::trading::update(&mut s, items), Kind::Beacon => {} Kind::Cartography => s.result = self.cartography_result(&s), + Kind::Loom => self.loom_changed(&mut s), Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -498,6 +509,7 @@ impl Game<'_> { match s.kind { Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), + Kind::Loom => self.loom_slot_rules(i, stack), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( matches!( @@ -565,7 +577,12 @@ impl Game<'_> { self.carried = new_carried; } /// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots. - fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool { + pub(super) fn move_to( + &mut self, + stack: &mut ItemStack, + targets: &[usize], + reverse: bool, + ) -> bool { let order: Vec = if reverse { targets.iter().rev().copied().collect() } else { @@ -614,8 +631,12 @@ impl Game<'_> { return false; }; let player = Self::player_slots(); + let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom); let moved = if (300..305).contains(&slot) || slot >= INPUT { - self.move_to(&mut stack, &player, true) + // LoomMenu moves into the inventory front to back, the others back to front. + self.move_to(&mut stack, &player, !loom) + } else if loom { + self.loom_quick_move(slot, &mut stack) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); @@ -673,7 +694,7 @@ impl Game<'_> { moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); } } - Some(Kind::Merchant) => {} + Some(Kind::Merchant | Kind::Loom) => {} Some(Kind::Beacon) => { // BeaconMenu.quickMoveStack: one payment item into the empty slot. if super::beacon::is_payment(&stack.item) { @@ -713,7 +734,7 @@ impl Game<'_> { ]; self.audio.play(sound, Some(at), volume, pitch); } - fn give_or_drop(&mut self, stack: ItemStack) { + pub(super) fn give_or_drop(&mut self, stack: ItemStack) { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { @@ -860,6 +881,7 @@ impl Game<'_> { self.cartography_taken(pos); } } + Kind::Loom => self.loom_taken(&mut s), Kind::Enchanting => {} } self.station = Some(s); @@ -991,6 +1013,9 @@ impl Game<'_> { if kind == Kind::Merchant && !right && self.merchant_click(local) { return true; } + if kind == Kind::Loom && !right && self.loom_click(local) { + return true; + } if kind == Kind::Beacon && !right && self.beacon_click(local) { return true; } @@ -1065,6 +1090,7 @@ impl Game<'_> { } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); + self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; @@ -1308,6 +1334,9 @@ impl Game<'_> { if kind == Kind::Cartography { self.draw_cartography(batch, ox, oy); } + if kind == Kind::Loom { + tooltip = self.draw_loom(batch, ox, oy, local); + } let atlas = &self.res.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); @@ -1598,7 +1627,7 @@ impl Game<'_> { } } } - Kind::Merchant | Kind::Beacon | Kind::Cartography => {} + Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { let display = s.inputs[0].is_some() && !s.recipes.is_empty(); let active = display && s.recipes.len() > 12; @@ -1799,6 +1828,11 @@ impl Game<'_> { }, )); } + // BannerPatternLayers.addToTooltip: up to six layer names. + for layer in horizon_client::banner::layers(stack).iter().take(6) { + let key = self.res.stations.banners.layer_key(layer); + lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + } if let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 4d161514f..78c002d1a 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -11,6 +11,10 @@ impl Game<'_> { /// Block-entity contents on removal: shulker boxes keep theirs for the /// dropped box (`copy_components`), other containers spill them. pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { + if let BlockEntity::Banner(banner) = entity { + self.pending_banner.insert(pos, banner); + return; + } if is_shulker_box(block) { if let BlockEntity::Chest(items) = entity { let kept = items diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d7643d3dd..792373e7a 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -35,6 +35,10 @@ pub struct StackData { pub writable_pages: Vec, /// `minecraft:written_book_content`. pub written: Option, + /// `minecraft:banner_patterns` (banners and shields). + pub banner_patterns: Vec, + /// `minecraft:base_color` (a shield's dye). + pub base_color: Option>, } /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] @@ -267,6 +271,15 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { if let Some(id) = d.map_id { entries.push(("minecraft:map_id", Tag::Int(id))); } + if !d.banner_patterns.is_empty() { + entries.push(( + "minecraft:banner_patterns", + crate::banner::layers_to_nbt(&d.banner_patterns), + )); + } + if let Some(color) = &d.base_color { + entries.push(("minecraft:base_color", Tag::String((&**color).into()))); + } // Filterable values are saved as {raw: ..}. let raw = |t: Tag| Tag::compound([("raw", t)]); if !d.writable_pages.is_empty() { @@ -371,6 +384,11 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option { + if !b.layers.is_empty() { + entries.push(("patterns", crate::banner::layers_to_nbt(&b.layers))); + } + if let Some(name) = &b.name { + entries.push(("CustomName", string(name))); + } + } } Tag::compound(entries) } @@ -428,6 +436,15 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; return Some((pos, BlockEntity::Lectern(lectern))); } + if id == "minecraft:banner" { + return Some(( + pos, + BlockEntity::Banner(crate::containers::Banner { + layers: crate::banner::layers_from_nbt(tag.get("patterns")), + name: text(tag.get("CustomName")), + }), + )); + } if id == "minecraft:beacon" { let beacon = crate::containers::Beacon { levels: int("Levels").unwrap_or(0), @@ -474,7 +491,10 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), - BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} + BlockEntity::Jukebox(_) + | BlockEntity::Beacon(_) + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_) => {} } Some((pos, entity)) } @@ -1993,6 +2013,25 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn banner_block_entity_round_trips() { + let banner = crate::containers::Banner { + layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")], + name: Some("Flag".into()), + }; + let tag = encode_block_entity( + (1, 2, 3), + &crate::containers::BlockEntity::Banner(banner.clone()), + "minecraft:red_banner", + ); + let (pos, back) = decode_block_entity(&tag).expect("banner"); + assert_eq!(pos, (1, 2, 3)); + let crate::containers::BlockEntity::Banner(back) = back else { + panic!("not a banner"); + }; + assert_eq!(back.layers, banner.layers); + assert_eq!(back.name, banner.name); + } use super::*; #[test] diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 8fd6f85d7..eee0a7442 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -18,6 +18,7 @@ pub struct StationData { pub recipes: StationRecipes, pub brewing: crate::brewing::Brewing, pub trades: crate::merchant::Trades, + pub banners: crate::banner::Banners, } impl StationData { pub fn load(root: &Path, items: &Items) -> Self { @@ -26,6 +27,7 @@ impl StationData { recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items), trades: crate::merchant::Trades::load(root), + banners: crate::banner::Banners::load(root), } } } From ef6f41b12c34e5cec584360ac3ccb8283664b930 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:42:27 +0200 Subject: [PATCH 03/19] Add scoreboards and teams Scoreboards now work like vanilla: objectives with every criteria kind (dummy, trigger, health, food, xp, level, armor, deathCount, kill counts, per-colour team kills and any statistic such as minecraft.mined:minecraft.stone), the full /scoreboard command (objectives add, remove, list, modify and setdisplay; players set, add, remove, reset, get, list, enable, operation and display name or number format), /trigger, and /team with colour, prefix, suffix, friendly fire, invisibility, nametag, death message and collision options. Scores, teams and display slots are saved as vanilla NBT in data/minecraft/scoreboard.dat. The sidebar draws with the objective title, team colour slots, number formats and the vanilla layout, and target selectors accept scores={...}, team= and tag=. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/command/args.rs | 272 +++- crates/horizon-client/src/command/mod.rs | 1 + .../src/command/tree_scoreboard.rs | 214 ++++ crates/horizon-client/src/command/vanilla.rs | 1 + crates/horizon-client/src/game.rs | 8 + crates/horizon-client/src/game/commands.rs | 21 +- crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/game/persist.rs | 6 +- crates/horizon-client/src/game/scoreboard.rs | 510 ++++++++ crates/horizon-client/src/game/stats.rs | 7 + crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/save.rs | 4 +- crates/horizon-client/src/scoreboard.rs | 1115 ++++++++++++++++ crates/horizon-client/src/scoreboard_cmd.rs | 1124 +++++++++++++++++ .../src/scoreboard_cmd_tests.rs | 295 +++++ 15 files changed, 3568 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/command/tree_scoreboard.rs create mode 100644 crates/horizon-client/src/game/scoreboard.rs create mode 100644 crates/horizon-client/src/scoreboard.rs create mode 100644 crates/horizon-client/src/scoreboard_cmd.rs create mode 100644 crates/horizon-client/src/scoreboard_cmd_tests.rs diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index bfe79244d..a98c30816 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -29,6 +29,13 @@ pub struct Registries { /// Game rule name -> integer-valued. pub game_rules: Vec<(String, bool)>, pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + pub function_tags: Vec, /// The block the source is looking at (relevant coordinates). pub target_block: Option<[i32; 3]>, } @@ -116,6 +123,24 @@ pub enum ArgType { Component, /// CompoundTagArgument (kept as SNBT text). Nbt, + /// ScoreHolderArgument. + ScoreHolder { + multiple: bool, + }, + /// ObjectiveArgument (checked when the command runs). + Objective, + /// TeamArgument (checked when the command runs). + Team, + /// ObjectiveCriteriaArgument. + Criteria, + /// ScoreboardSlotArgument. + ScoreboardSlot, + /// OperationArgument. + Operation, + /// TeamColorArgument. + TeamColor, + /// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`). + IntRange, } pub fn integer(min: i32) -> ArgType { ArgType::Integer { min, max: i32::MAX } @@ -227,6 +252,29 @@ pub struct Selector { pub y_rotation: Option, pub pos: [Option; 3], pub delta: [Option; 3], + /// `scores={objective=range,...}`. + pub scores: Vec<(String, IntRange)>, + /// `team=` (an empty name matches entities without a team). + pub teams: Vec<(String, bool)>, + /// `nbt=` compounds (SNBT text). + pub nbt: Vec<(String, bool)>, + /// `advancements={id=true|{criterion=true}}`. + pub advancements: Vec<(String, AdvCondition)>, + /// `predicate=` ids. + pub predicates: Vec<(String, bool)>, +} +/// An `advancements=` entry: all done or not, or per-criterion states. +#[derive(Clone, Debug, PartialEq)] +pub enum AdvCondition { + Done(bool), + Criteria(Vec<(String, bool)>), +} +/// A `ScoreHolderArgument` value. +#[derive(Clone, Debug, PartialEq)] +pub enum ScoreHolderArg { + Wildcard, + Name(String), + Selector(Selector), } impl Selector { pub fn is_self(&self) -> bool { @@ -293,6 +341,8 @@ pub enum Arg { GameMode(GameMode), /// `eyes` (true) or `feet`. Anchor(bool), + ScoreHolder(ScoreHolderArg), + IntRange(IntRange), } fn is_id_char(c: char) -> bool { @@ -563,6 +613,7 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries) { } } +pub const OPERATIONS: [&str; 9] = ["=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"]; const SELECTORS: [(&str, &str); 6] = [ ("@a", "argument.entity.selector.allPlayers"), ("@e", "argument.entity.selector.allEntities"), @@ -571,7 +622,7 @@ const SELECTORS: [(&str, &str); 6] = [ ("@r", "argument.entity.selector.randomPlayer"), ("@s", "argument.entity.selector.self"), ]; -const OPTIONS: [&str; 16] = [ +const OPTIONS: [&str; 21] = [ "name", "distance", "level", @@ -588,7 +639,22 @@ const OPTIONS: [&str; 16] = [ "gamemode", "tag", "type", + "scores", + "team", + "nbt", + "advancements", + "predicate", ]; +/// StringReader.expect. +fn expect_symbol(reader: &mut Reader, c: char) -> CmdResult<()> { + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == c { + reader.skip(); + Ok(()) + } else { + Err(CommandError::tr_at("parsing.expected", &[&c], reader)) + } +} fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult { let start = reader.cursor; if !(reader.can_read() && reader.peek() == '@') { @@ -791,6 +857,81 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let v = reader.read_unquoted_string().to_owned(); s.tags.push((v, neg)); } + "team" => { + let neg = negated(reader); + let v = reader.read_unquoted_string().to_owned(); + s.teams.push((v, neg)); + } + "nbt" => { + let neg = negated(reader); + if !reader.can_read() || reader.peek() != '{' { + return Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )); + } + s.nbt.push((read_braced(reader, '{', '}')?, neg)); + } + "predicate" => { + let neg = negated(reader); + s.predicates.push((read_id(reader)?, neg)); + } + "scores" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let name = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + let range = range_int(reader)?; + s.scores.push((name, range)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + } + "advancements" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let id = read_id(reader)?; + expect_symbol(reader, '=')?; + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == '{' { + reader.skip(); + reader.skip_whitespace(); + let mut criteria = Vec::new(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let c = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + criteria.push((c, reader.read_boolean()?)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.advancements.push((id, AdvCondition::Criteria(criteria))); + } else { + s.advancements + .push((id, AdvCondition::Done(reader.read_boolean()?))); + } + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.include_entities = false; + } "type" => { let neg = negated(reader); let at = reader.cursor; @@ -1436,6 +1577,91 @@ impl ArgType { } Arg::Str(axes) } + ArgType::ScoreHolder { multiple } => { + if reader.can_read() && reader.peek() == '@' { + let sel = parse_selector(reader, reg)?; + if !*multiple && sel.limit > 1 { + reader.cursor = start; + return Err(CommandError::tr_at("argument.entity.toomany", &[], reader)); + } + Arg::ScoreHolder(ScoreHolderArg::Selector(sel)) + } else { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let text = &reader.string[start..reader.cursor]; + if text == "*" { + Arg::ScoreHolder(ScoreHolderArg::Wildcard) + } else { + Arg::ScoreHolder(ScoreHolderArg::Name(text.to_owned())) + } + } + } + ArgType::Objective | ArgType::Team => { + Arg::Str(reader.read_unquoted_string().to_owned()) + } + ArgType::Criteria => { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let id = &reader.string[start..reader.cursor]; + if !crate::scoreboard::criteria_exists(id, reg) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.criteria.invalid", + &[&id], + reader, + )); + } + Arg::Str(id.to_owned()) + } + ArgType::ScoreboardSlot => { + let name = reader.read_unquoted_string(); + if !crate::scoreboard::display_slot_valid(name) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.scoreboardDisplaySlot.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::Operation => { + if !reader.can_read() { + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let op = &reader.string[start..reader.cursor]; + if !OPERATIONS.contains(&op) { + reader.cursor = start; + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + Arg::Str(op.to_owned()) + } + ArgType::TeamColor => { + let name = reader.read_unquoted_string(); + if crate::scoreboard::team_color_rgb(name).is_none() { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.color.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::IntRange => Arg::IntRange(range_int(reader)?), ArgType::Anchor => { let name = reader.read_unquoted_string(); match name { @@ -1511,6 +1737,50 @@ impl ArgType { } } ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)), + ArgType::ScoreHolder { .. } => { + suggest_selector(builder, reg); + let names: Vec = reg + .players + .iter() + .chain(reg.tracked.iter()) + .cloned() + .collect(); + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::Objective => { + builder.suggest_matching(reg.objectives.iter().map(String::as_str)) + } + ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), + ArgType::Criteria => { + let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + .iter() + .map(|s| (*s).to_owned()) + .collect(); + for c in crate::scoreboard::team_colors() { + ids.push(format!("teamkill.{c}")); + ids.push(format!("killedByTeam.{c}")); + } + let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); + for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { + ids.extend(reg.items.iter().map(|i| stat(ty, i))); + } + for ty in ["killed", "killed_by"] { + ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); + } + ids.extend( + crate::scoreboard::CUSTOM_STATS + .iter() + .map(|c| stat("custom", &format!("minecraft:{c}"))), + ); + builder.suggest_matching(ids.iter().map(String::as_str)); + } + ArgType::ScoreboardSlot => { + let slots = crate::scoreboard::display_slots(); + builder.suggest_matching(slots.iter().map(String::as_str)); + } + ArgType::Operation => builder.suggest_matching(OPERATIONS), + ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Swizzle | ArgType::Component => {} ArgType::Message => { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 7e8090d6b..d1ca22799 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -4,6 +4,7 @@ //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. pub mod args; +pub mod tree_scoreboard; pub mod vanilla; use crate::text::Text; diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-client/src/command/tree_scoreboard.rs new file mode 100644 index 000000000..4493ca8f1 --- /dev/null +++ b/crates/horizon-client/src/command/tree_scoreboard.rs @@ -0,0 +1,214 @@ +//! The `/scoreboard`, `/team` and `/trigger` command trees +//! (ScoreboardCommand, TeamCommand, TriggerCommand). +use super::{Dispatcher, args::ArgType, vanilla::GAMEMASTERS}; + +const HOLDERS: ArgType = ArgType::ScoreHolder { multiple: true }; +const HOLDER: ArgType = ArgType::ScoreHolder { multiple: false }; + +/// `addNumberFormats`: blank | fixed | styled