diff --git a/crates/horizon-client/examples/creative_search_fixture.rs b/crates/horizon-client/examples/creative_search_fixture.rs new file mode 100644 index 000000000..628e0486d --- /dev/null +++ b/crates/horizon-client/examples/creative_search_fixture.rs @@ -0,0 +1,53 @@ +//! The creative inventory, for tools/test_creative_parity.py: loads an +//! exported `creative-inventory.json` into `horizon_client::creative::Creative` +//! and prints the tabs it shows (canonical stacks) and the search tab's +//! results for every query of the vanilla oracle's output. +//! +//! usage: creative_search_fixture RESOURCES CREATIVE_JSON VANILLA_JSON OUTPUT +use horizon_client::{ + creative::{Creative, Names}, + item_data::canon_stack, +}; +use serde_json::{Value, json}; +use std::{fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: creative_search_fixture RESOURCES CREATIVE_JSON VANILLA_JSON OUTPUT"; + let names = Names::load(Path::new(args.get(1).ok_or(usage)?)); + let creative = Creative::from_json(&serde_json::from_slice(&fs::read( + args.get(2).ok_or(usage)?, + )?)?)?; + let vanilla: Value = serde_json::from_slice(&fs::read(args.get(3).ok_or(usage)?)?)?; + let tabs: Vec = creative + .tabs + .iter() + .map(|t| { + json!({ + "id": t.id, + "title": t.title, + "icon": t.icon, + "row": if t.top { "TOP" } else { "BOTTOM" }, + "column": t.column, + "items": t.items.iter().map(|s| canon_stack(Some(s))).collect::>(), + }) + }) + .collect(); + let searches: Vec = vanilla["searches"] + .as_array() + .ok_or("searches")? + .iter() + .map(|s| { + let query = s["query"].as_str().unwrap_or_default(); + json!({"query": query, "results": creative.search_results(query, &names)}) + }) + .collect(); + let search: Vec = creative + .search_items() + .iter() + .map(|s| canon_stack(Some(s))) + .collect(); + let out = json!({"tabs": tabs, "search": search, "searches": searches}); + fs::write(args.get(4).ok_or(usage)?, out.to_string())?; + Ok(()) +} diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 6be74498c..b696348f2 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -1,7 +1,7 @@ //! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their //! contents as built by the game's own display generators -//! (`creative-tabs.json`), a 9x5 scrolling grid and the search tab. -use crate::Result; +//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab. +use crate::{Result, items::ItemStack}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -10,19 +10,35 @@ pub struct Tab { pub id: String, pub title: String, pub icon: String, - pub items: Vec, + pub items: Vec, pub top: bool, pub column: u32, pub search: bool, pub inventory: bool, } +/// What the client's creative search trees (SessionSearchTrees) index for one +/// stack of the search tab: its creative tooltip lines and its item tags. +#[derive(Clone, Debug, Default)] +struct SearchEntry { + /// The item id's namespace and path, lower-cased. + namespace: String, + path: String, + /// Tooltip lines, lower-cased; empty when the resources predate them. + lines: Vec, + /// Item tags as (namespace, path), lower-cased. + tags: Vec<(String, String)>, +} pub struct Creative { pub tabs: Vec, pub selected: usize, - /// Scroll position 0..1. + /// Scroll position 0..1 (scrollOffs). pub scroll: f32, + /// The scrollbar is held (scrolling): dragging moves it. + pub scrolling: bool, pub search: String, - all_items: Vec, + /// The search tab's stacks, in its display order. + search_items: Vec, + search_index: Vec, } /// Display names from the pinned en_us language file. pub struct Names { @@ -51,26 +67,94 @@ impl Names { impl Creative { pub const WIDTH: f32 = 195.0; pub const HEIGHT: f32 = 136.0; + /// The scrollbar track (insideScrollbar), relative to the screen origin. + pub const SCROLL_X: f32 = 175.0; + pub const SCROLL_Y: f32 = 18.0; + pub const SCROLL_WIDTH: f32 = 14.0; + pub const SCROLL_HEIGHT: f32 = 112.0; + /// `creative-inventory.json` (VanillaCreativeTabsExporter); resources + /// prepared before it fall back to `creative-tabs.json`'s item ids. pub fn load(root: &Path) -> Result { - let raw: Value = serde_json::from_slice(&fs::read(root.join("creative-tabs.json"))?)?; + let path = root.join("creative-inventory.json"); + if path.exists() { + Self::from_json(&serde_json::from_slice(&fs::read(path)?)?) + } else { + Self::from_legacy(&serde_json::from_slice(&fs::read( + root.join("creative-tabs.json"), + )?)?) + } + } + pub fn from_json(raw: &Value) -> Result { let mut tabs = Vec::new(); - let mut all_items: Vec = Vec::new(); - for t in raw.as_array().into_iter().flatten() { - let items: Vec = t["items"] - .as_array() - .into_iter() - .flatten() - .filter_map(|v| v.as_str().map(str::to_owned)) - .collect(); - for i in &items { - if !all_items.contains(i) { - all_items.push(i.clone()); + let mut search_items = Vec::new(); + let mut search_index = Vec::new(); + for t in raw["tabs"].as_array().into_iter().flatten() { + let mut items = Vec::new(); + for v in t["items"].as_array().into_iter().flatten() { + let snbt = v.as_str().unwrap_or("-"); + if let Some(stack) = crate::item_data::parse_stack(snbt)? { + items.push(stack); } } let kind = t["type"].as_str().unwrap_or(""); + if kind == "SEARCH" { + let strings = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(java_lower)) + .collect() + }; + for (i, stack) in items.iter().enumerate() { + let (namespace, path) = split_id(&java_lower(&stack.item)); + search_index.push(SearchEntry { + namespace, + path, + lines: strings(&t["lines"][i]), + tags: strings(&t["tags"][i]).iter().map(|t| split_id(t)).collect(), + }); + } + search_items = items.clone(); + } + if kind == "HOTBAR" || t["visible"] == false { + continue; + } + let icon = t["icon"] + .as_str() + .and_then(|s| crate::item_data::parse_stack(s).ok().flatten()); + tabs.push(Tab { + id: t["id"].as_str().unwrap_or("").to_owned(), + title: t["title"].as_str().unwrap_or("").to_owned(), + icon: icon.map_or_else(|| "minecraft:stone".to_owned(), |s| s.item.to_string()), + items, + top: t["row"] == "TOP", + column: t["column"].as_u64().unwrap_or(0) as u32, + search: kind == "SEARCH", + inventory: kind == "INVENTORY", + }); + } + Ok(Self::new(tabs, search_items, search_index)) + } + /// The old export: item ids per tab, no components, tooltips or tags. + fn from_legacy(raw: &Value) -> Result { + let mut tabs = Vec::new(); + let mut search_items: Vec = Vec::new(); + for t in raw.as_array().into_iter().flatten() { + let items: Vec = t["items"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(|id| ItemStack::new(id, 1))) + .collect(); if t["id"] == "minecraft:hotbar" || t["id"] == "minecraft:op_blocks" { continue; } + for i in &items { + if !search_items.iter().any(|s| s.item == i.item) { + search_items.push(i.clone()); + } + } + let kind = t["type"].as_str().unwrap_or(""); tabs.push(Tab { id: t["id"].as_str().unwrap_or("").to_owned(), title: t["title"].as_str().unwrap_or("").to_owned(), @@ -82,31 +166,101 @@ impl Creative { inventory: kind == "INVENTORY", }); } - Ok(Self { + let search_index = search_items + .iter() + .map(|s| { + let (namespace, path) = split_id(&java_lower(&s.item)); + SearchEntry { + namespace, + path, + ..Default::default() + } + }) + .collect(); + Ok(Self::new(tabs, search_items, search_index)) + } + fn new(tabs: Vec, search_items: Vec, search_index: Vec) -> Self { + Self { tabs, selected: 0, scroll: 0.0, + scrolling: false, search: String::new(), - all_items, - }) + search_items, + search_index, + } } pub fn tab(&self) -> &Tab { &self.tabs[self.selected.min(self.tabs.len() - 1)] } - /// Items shown by the selected tab (the search tab filters by name). - pub fn items(&self, names: &Names) -> Vec { + /// selectTab: a different tab empties the search box; the scrollbar goes to the top. + pub fn select(&mut self, tab: usize) { + if tab != self.selected { + self.search.clear(); + } + self.selected = tab; + self.scroll = 0.0; + } + /// The search tab's stacks. + pub fn search_items(&self) -> &[ItemStack] { + &self.search_items + } + /// Indices into `search_items` that CreativeModeInventoryScreen.refreshSearchResults + /// shows for `term`: the whole tab when empty, the tag tree after `#`, else + /// the name tree, both over vanilla's suffix arrays (substring matches, + /// results in the tab's order). + pub fn search_results(&self, term: &str, names: &Names) -> Vec { + let all = 0..self.search_index.len(); + if term.is_empty() { + return all.collect(); + } + if let Some(tag) = term.strip_prefix('#') { + // IdSearchTree over the stacks' tags. + let text = java_lower(tag); + return all + .filter(|&i| { + let tags = &self.search_index[i].tags; + match text.split_once(':') { + None => any(tags.iter().map(|t| t.1.as_str()), &text), + Some((ns, path)) => { + let (ns, path) = (java_trim(ns), java_trim(path)); + any(tags.iter().map(|t| t.0.as_str()), ns) + && any(tags.iter().map(|t| t.1.as_str()), path) + } + } + }) + .collect(); + } + // FullTextSearchTree: tooltip lines, and the item id after a colon. + let text = java_lower(term); + all.filter(|&i| { + let e = &self.search_index[i]; + let fallback; + let lines: &[String] = if e.lines.is_empty() { + fallback = [java_lower(&names.item(&self.search_items[i].item))]; + &fallback + } else { + &e.lines + }; + match text.split_once(':') { + None => any(lines.iter().map(String::as_str), &text), + Some((ns, path)) => { + let (ns, path) = (java_trim(ns), java_trim(path)); + e.namespace.contains(ns) + && (e.path.contains(path) || any(lines.iter().map(String::as_str), path)) + } + } + }) + .collect() + } + /// Items shown by the selected tab (the search tab filters by `search`). + pub fn items(&self, names: &Names) -> Vec { let tab = self.tab(); if tab.search { - let query = self.search.to_lowercase(); return self - .all_items - .iter() - .filter(|i| { - query.is_empty() - || names.item(i).to_lowercase().contains(&query) - || i.contains(&query) - }) - .cloned() + .search_results(&self.search, names) + .into_iter() + .map(|i| self.search_items[i].clone()) .collect(); } tab.items.clone() @@ -114,10 +268,60 @@ impl Creative { pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) } - /// First visible grid row for the scroll position. + /// ItemPickerMenu.calculateRowCount: rows beyond the five shown. + fn hidden_rows(&self, names: &Names) -> i32 { + self.rows(names) as i32 - 5 + } + /// First visible grid row for the scroll position (getRowIndexForScroll). pub fn first_row(&self, names: &Names) -> usize { - let hidden = self.rows(names).saturating_sub(5); - (self.scroll * hidden as f32 + 0.5) as usize + ((self.scroll * self.hidden_rows(names) as f32 + 0.5) as i32).max(0) as usize + } + /// CreativeModeInventoryScreen.canScroll: more than five rows, on a tab with a scrollbar. + pub fn can_scroll(&self, names: &Names) -> bool { + !self.tab().inventory && self.items(names).len() > 45 + } + /// insideScrollbar, for a point relative to the screen origin. + pub fn inside_scrollbar(&self, x: f32, y: f32) -> bool { + x >= Self::SCROLL_X + && y >= Self::SCROLL_Y + && x < Self::SCROLL_X + Self::SCROLL_WIDTH + && y < Self::SCROLL_Y + Self::SCROLL_HEIGHT + && !self.tab().inventory + } + /// mouseClicked on the scrollbar: it is held only if the tab can scroll + /// (the thumb doesn't move until the mouse does). + pub fn press_scrollbar(&mut self, x: f32, y: f32, names: &Names) -> bool { + if !self.inside_scrollbar(x, y) { + return false; + } + self.scrolling = self.can_scroll(names); + true + } + /// mouseDragged while the scrollbar is held, at a cursor height relative to + /// the screen origin, wherever the cursor is (even off the track or the window). + pub fn drag_scrollbar(&mut self, y: f32) -> bool { + if !self.scrolling { + return false; + } + let (top, bottom) = (Self::SCROLL_Y, Self::SCROLL_Y + Self::SCROLL_HEIGHT); + self.scroll = ((y - top - 7.5) / (bottom - top - 15.0)).clamp(0.0, 1.0); + true + } + /// mouseReleased. + pub fn release(&mut self) { + self.scrolling = false; + } + /// mouseScrolled: ItemPickerMenu.subtractInputFromScroll. + pub fn wheel(&mut self, amount: f64, names: &Names) { + if !self.can_scroll(names) { + return; + } + let rows = self.hidden_rows(names) as f64; + self.scroll = (self.scroll - (amount / rows) as f32).clamp(0.0, 1.0); + } + /// The scroller sprite's offset from the top of the track. + pub fn scroller_offset(&self) -> f32 { + ((Self::SCROLL_HEIGHT - 17.0) * self.scroll) as i32 as f32 } /// Tab button position relative to the screen origin (CreativeModeInventoryScreen.getTabX/Y). pub fn tab_position(tab: &Tab) -> (f32, f32) { @@ -130,3 +334,163 @@ impl Creative { (x, y) } } +/// Whether a suffix array of `strings` has a suffix starting with `text`: +/// some string contains it (none for no strings, even when `text` is empty). +fn any<'a>(strings: impl IntoIterator, text: &str) -> bool { + strings.into_iter().any(|s| s.contains(text)) +} +/// String.toLowerCase(Locale.ROOT). +fn java_lower(s: &str) -> String { + s.to_lowercase() +} +/// String.trim: strips code points up to U+0020. +fn java_trim(s: &str) -> &str { + s.trim_matches(|c: char| c <= ' ') +} +/// Identifier.parse's namespace and path (default namespace `minecraft`). +fn split_id(id: &str) -> (String, String) { + match id.split_once(':') { + Some((ns, path)) => (ns.to_owned(), path.to_owned()), + None => ("minecraft".to_owned(), id.to_owned()), + } +} +#[cfg(test)] +mod tests { + use super::*; + + fn creative(items: usize) -> Creative { + let mut stacks: Vec = ["anvil", "crafting_table", "wooden_hoe"] + .iter() + .map(|i| format!("{{count:1,id:\"minecraft:{i}\"}}")) + .collect(); + stacks.extend((0..items).map(|i| format!("{{count:1,id:\"minecraft:item_{i}\"}}"))); + let mut lines = vec![ + vec!["Anvil"], + vec!["Crafting Table"], + vec!["Wooden Hoe", "When in Main Hand:", "-3 Attack Speed"], + ]; + lines.extend(vec![vec!["Thing"]; items]); + let mut tags = vec![ + vec!["minecraft:anvil"], + vec![], + vec!["minecraft:hoes", "minecraft:enchantable/mining"], + ]; + tags.extend(vec![vec![]; items]); + let raw = serde_json::json!({"schema": 2, "tabs": [ + {"id": "minecraft:functional_blocks", "type": "CATEGORY", "row": "TOP", "column": 3, "title": "Functional Blocks", + "icon": "{count:1,id:\"minecraft:oak_sign\"}", "visible": true, + "items": ["{count:1,id:\"minecraft:anvil\"}", "{count:1,id:\"minecraft:crafting_table\"}"]}, + {"id": "minecraft:op_blocks", "type": "CATEGORY", "row": "BOTTOM", "column": 5, "title": "Operator Utilities", + "icon": "{count:1,id:\"minecraft:command_block\"}", "visible": false, "items": []}, + {"id": "minecraft:search", "type": "SEARCH", "row": "TOP", "column": 6, "title": "Search Items", + "icon": "{count:1,id:\"minecraft:compass\"}", "visible": true, + "items": stacks, "lines": lines, "tags": tags}, + {"id": "minecraft:inventory", "type": "INVENTORY", "row": "BOTTOM", "column": 6, "title": "Survival Inventory", + "icon": "{count:1,id:\"minecraft:chest\"}", "visible": true, "items": []} + ]}); + Creative::from_json(&raw).unwrap() + } + + #[test] + fn hidden_tabs_are_skipped() { + let c = creative(0); + let ids: Vec<&str> = c.tabs.iter().map(|t| t.id.as_str()).collect(); + assert_eq!( + ids, + [ + "minecraft:functional_blocks", + "minecraft:search", + "minecraft:inventory" + ] + ); + assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil"); + let mut c = c; + c.select(1); + c.search = "anvil".into(); + c.scroll = 0.5; + c.select(1); + assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0)); + c.select(0); + assert_eq!(c.search, ""); + } + + #[test] + fn search_matches_vanilla_trees() { + let c = creative(0); + let names = Names { + map: HashMap::new(), + }; + let q = |s: &str| c.search_results(s, &names); + assert_eq!(q(""), [0, 1, 2]); + assert_eq!(q("ANVIL"), [0]); + assert_eq!(q("table"), [1]); + assert_eq!(q("a"), [0, 1, 2]); + // Tooltip lines, not just names; no trimming without a colon. + assert_eq!(q("attack speed"), [2]); + assert_eq!(q(" anvil"), Vec::::new()); + // A colon searches the id: namespace, then the path or a tooltip line. + assert_eq!(q("minecraft:crafting_t"), [1]); + assert_eq!(q(" minecraft : hoe "), [2]); + assert_eq!(q("mine:anvil"), [0]); + assert_eq!(q("other:anvil"), Vec::::new()); + assert_eq!(q(":"), [0, 1, 2]); + // Tags after "#": only stacks with tags. + assert_eq!(q("#"), [0, 2]); + assert_eq!(q("#hoe"), [2]); + assert_eq!(q("#minecraft:enchantable/"), [2]); + assert_eq!(q("#craft"), Vec::::new()); + } + + #[test] + fn scrollbar_drag_follows_the_mouse_while_held() { + let mut c = creative(90); + let names = Names { + map: HashMap::new(), + }; + c.selected = 1; + // Pressing the track holds the scrollbar without moving it. + assert!(c.press_scrollbar(180.0, 60.0, &names)); + assert!(c.scrolling); + assert_eq!(c.scroll, 0.0); + // Dragging maps the cursor height onto the track (minus half the thumb). + assert!(c.drag_scrollbar(18.0 + 7.5 + 48.5)); + assert!((c.scroll - 0.5).abs() < 1e-6); + // The cursor may leave the track, the panel or the window: it keeps scrolling. + c.drag_scrollbar(400.0); + assert_eq!(c.scroll, 1.0); + c.drag_scrollbar(-50.0); + assert_eq!(c.scroll, 0.0); + c.drag_scrollbar(18.0 + 7.5 + 97.0 * 0.25); + assert!((c.scroll - 0.25).abs() < 1e-6); + let rows = (93usize.div_ceil(9) - 5) as f32; + assert_eq!(c.first_row(&names), (0.25 * rows + 0.5) as usize); + // Releasing stops it. + c.release(); + assert!(!c.drag_scrollbar(400.0)); + assert!((c.scroll - 0.25).abs() < 1e-6); + // Off the track, or with too few items, it isn't held. + assert!(!c.press_scrollbar(170.0, 60.0, &names)); + assert!(!c.press_scrollbar(180.0, 130.0, &names)); + c.selected = 0; + assert!(c.press_scrollbar(180.0, 60.0, &names)); + assert!(!c.scrolling); + } + + #[test] + fn wheel_moves_one_row_per_notch() { + let mut c = creative(90); + let names = Names { + map: HashMap::new(), + }; + c.selected = 1; + let rows = (93usize.div_ceil(9) - 5) as f32; + c.wheel(-1.0, &names); + assert!((c.scroll - 1.0 / rows).abs() < 1e-6); + assert_eq!(c.first_row(&names), 1); + c.wheel(5.0, &names); + assert_eq!(c.scroll, 0.0); + assert_eq!(c.scroller_offset(), 0.0); + c.scroll = 1.0; + assert_eq!(c.scroller_offset(), 95.0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7f02bf53b..de855dd31 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6959,24 +6959,18 @@ impl Game<'_> { let mut hovered: Option = None; for r in 0..5 { for c in 0..9 { - let Some(item) = items.get((first + r) * 9 + c) else { + let Some(stack) = items.get((first + r) * 9 + c) else { continue; }; let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - let stack = ItemStack { - item: Arc::from(item.as_str()), - count: 1, - damage: 0, - extra: None, - }; - self.draw_item(batch, &stack, x, y); + self.draw_item(batch, stack, x, y); if self.cursor.0 >= x && self.cursor.0 < x + 16.0 && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); - hovered = Some(item.clone()); + hovered = Some(stack.item.to_string()); } } } @@ -7002,8 +6996,8 @@ impl Game<'_> { batch.sprite( &self.res.atlas, scroller, - ox + 175.0, - oy + 18.0 + self.creative_screen.scroll * (112.0 - 15.0), + ox + Creative::SCROLL_X, + oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), ); for t in &tabs { let (tx, ty) = Creative::tab_position(t); @@ -7041,13 +7035,16 @@ impl Game<'_> { self.screen = Screen::Inventory; return; } - self.creative_screen.selected = i; - self.creative_screen.scroll = 0.0; + self.creative_screen.select(i); return; } } - if cx >= ox + 175.0 && cx < ox + 187.0 && cy >= oy + 18.0 && cy < oy + 130.0 { - self.creative_screen.scroll = ((cy - oy - 18.0 - 7.5) / (112.0 - 15.0)).clamp(0.0, 1.0); + // Holding the scrollbar scrolls as the mouse moves (mouseDragged). + if !right + && self + .creative_screen + .press_scrollbar(cx - ox, cy - oy, &self.res.names) + { return; } let shift = self.keys.contains(&KeyCode::ShiftLeft); @@ -7063,15 +7060,13 @@ impl Game<'_> { if self.carried.take().is_some() { return; } - let Some(item) = items.get((first + r) * 9 + c) else { + let Some(stack) = items.get((first + r) * 9 + c) else { return; }; - let max = self.res.items.get(item).map_or(64, |i| i.max_stack); + let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); let stack = ItemStack { - item: Arc::from(item.as_str()), count: if right { 1 } else { max }, - damage: 0, - extra: None, + ..stack.clone() }; if shift { let _ = self.give(stack); @@ -7829,6 +7824,10 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Advancements { self.advancements_drag(); } + if self.screen == Screen::Creative { + let (_, oy) = Self::creative_origin(&b); + self.creative_screen.drag_scrollbar(self.cursor.1 - oy); + } if self.screen == Screen::Inventory { self.loom_drag(); self.inventory_drag_move(); @@ -7874,13 +7873,7 @@ impl ApplicationHandler for Game<'_> { self.options_scroll(d); } if self.screen == Screen::Creative && d != 0.0 { - let rows = self - .creative_screen - .rows(&self.res.names) - .saturating_sub(5) - .max(1) as f32; - self.creative_screen.scroll = - (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); + self.creative_screen.wheel(f64::from(d), &self.res.names); } if self.screen == Screen::Inventory && d != 0.0 { self.station_scroll(d); @@ -7992,6 +7985,9 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); } + Screen::Creative if button == MouseButton::Left => { + self.creative_screen.release(); + } Screen::Paused if pressed => self.pause_click()?, Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index e64942da7..0c35a5a8c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -339,9 +339,13 @@ impl Game<'_> { Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } + Screen::Creative if self.creative_screen.tab().search => { + self.creative_screen.search.push_str(text); + self.creative_screen.scroll = 0.0; + } _ => { return Err( - "type needs the chat screen (key t tap) or the language search".into(), + "type needs the chat screen (key t tap), the language search or the creative search".into(), ); } } diff --git a/docs/rust-parity.md b/docs/rust-parity.md index d03417bfa..fee801463 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1523,6 +1523,21 @@ suggestions the server's dispatcher answers as input's state and every call. Not compared: the mouse wheel over the suggestion list and clipboard keys. +`horizon_client::creative` is the creative inventory. Its tabs come from +`creative-inventory.json`, which `VanillaCreativeTabsExporter` writes from +vanilla's own `CreativeModeTabs.tryRebuildTabContents` over the vanilla data +pack's registries: every stack with its components, and for each stack of the +search tab the creative tooltip lines and item tags that the client's search +trees index. The search ports `refreshSearchResults` and `SessionSearchTrees` +(substring matches over tooltip lines; after a colon the item id's namespace, +then its path or a line; tags after `#`), and the scrollbar follows +`mouseClicked`/`mouseDragged`/`mouseScrolled`. `tools/test_creative_parity.py` +compares every shown tab's stacks, the search tab and 6,793 searches (fixed +queries, then every stack's item path and tooltip lines and every tag, whole +and halved) with the vanilla client's own search trees +(`VanillaCreativeSearchOracle`). Not compared: the operator tab (off by +default, `operatorItemsTab`) and the saved hotbars tab. + ## Pillager patrols and raids `horizon_client::patrol` ports `PatrolSpawner` and `horizon_client::raid` ports diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeSearchOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeSearchOracle.java new file mode 100644 index 000000000..7ec8edf3d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeSearchOracle.java @@ -0,0 +1,100 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.multiplayer.SessionSearchTrees; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.CreativeModeTabs; +import net.minecraft.world.item.ItemStack; + +/** + * Original oracle for the creative inventory (test_creative_parity.py): writes + * the exported creative-inventory.json Horizon loads, then what the vanilla + * client shows: every tab's display items (canonical stacks) and, for each + * query, CreativeModeInventoryScreen.refreshSearchResults' items as indices + * into the search tab, searched through the client's own SessionSearchTrees + * (FullTextSearchTree over creative tooltip lines and item ids, IdSearchTree + * over item tags after "#"). + * + * VanillaCreativeSearchOracle QUERIES.json EXPORT.json OUT.json + * + * The queries are the file's list, then every search stack's item path and + * tooltip lines and every item tag, each also as a prefix and with "#". + */ +public final class VanillaCreativeSearchOracle { + public static void main(String[] args) throws Exception { + ParityData.init(); + var lookup = ParityData.lookup; + Files.writeString(Path.of(args[1]), + VanillaCreativeTabsExporter.export(FeatureFlags.DEFAULT_FLAGS, VanillaCreativeTabsExporter.HAS_PERMISSIONS, lookup).toString(), + StandardCharsets.UTF_8); + // CreativeModeInventoryScreen.tryRebuildTabContents, as the screen calls it. + CreativeModeTabs.tryRebuildTabContents(FeatureFlags.DEFAULT_FLAGS, VanillaCreativeTabsExporter.HAS_PERMISSIONS, lookup); + List searchItems = List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); + var trees = new SessionSearchTrees(); + trees.updateCreativeTooltips(lookup, searchItems); + trees.updateCreativeTags(searchItems); + + var out = new JsonObject(); + var tabs = new JsonArray(); + for (CreativeModeTab tab : BuiltInRegistries.CREATIVE_MODE_TAB) { + var o = new JsonObject(); + o.addProperty("id", BuiltInRegistries.CREATIVE_MODE_TAB.getKey(tab).toString()); + o.addProperty("type", tab.getType().name()); + o.addProperty("shown", tab.getType() != CreativeModeTab.Type.HOTBAR && tab.shouldDisplay()); + o.addProperty("title", tab.getDisplayName().getString()); + o.addProperty("icon", BuiltInRegistries.ITEM.getKey(tab.getIconItem().getItem()).toString()); + o.addProperty("row", tab.row().name()); + o.addProperty("column", tab.column()); + var items = new JsonArray(); + for (ItemStack stack : tab.getDisplayItems()) items.add(ParityData.canon(stack)); + o.add("items", items); + tabs.add(o); + } + out.add("tabs", tabs); + + var queries = new LinkedHashSet(); + for (var q : JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonArray()) queries.add(q.getAsString()); + var context = net.minecraft.world.item.Item.TooltipContext.of(lookup); + var flag = net.minecraft.world.item.TooltipFlag.Default.NORMAL.asCreative(); + var tags = new TreeSet(); + for (ItemStack stack : searchItems) { + String path = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath(); + queries.add(path); + queries.add(path.substring(0, (path.length() + 1) / 2)); + for (String line : VanillaCreativeTabsExporter.tooltipLines(stack, context, flag)) { + queries.add(line); + queries.add(line.substring(0, (line.length() + 1) / 2)); + } + stack.tags().forEach(t -> tags.add(t.location().toString())); + } + for (String tag : tags) { + queries.add("#" + tag); + queries.add("#" + tag.substring(tag.indexOf(':') + 1)); + } + var index = new IdentityHashMap(); + for (int i = 0; i < searchItems.size(); i++) index.put(searchItems.get(i), i); + var results = new JsonArray(); + for (String query : queries) { + var r = new JsonObject(); + r.addProperty("query", query); + var found = new JsonArray(); + for (ItemStack stack : refreshSearchResults(trees, query)) found.add(index.get(stack)); + r.add("results", found); + results.add(r); + } + out.add("searches", results); + Files.writeString(Path.of(args[2]), out.toString(), StandardCharsets.UTF_8); + } + + /** CreativeModeInventoryScreen.refreshSearchResults' items for the search box's value. */ + static List refreshSearchResults(SessionSearchTrees trees, String searchTerm) { + if (searchTerm.isEmpty()) return List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); + if (searchTerm.startsWith("#")) return trees.creativeTagSearch().search(searchTerm.substring(1).toLowerCase(Locale.ROOT)); + return trees.creativeNameSearch().search(searchTerm.toLowerCase(Locale.ROOT)); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeTabsExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeTabsExporter.java index 407bcf0f0..ea0b00686 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeTabsExporter.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeTabsExporter.java @@ -3,33 +3,42 @@ package dev.horizonlab.parity; import com.google.gson.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; -import net.minecraft.SharedConstants; -import net.minecraft.core.RegistryAccess; +import java.util.List; +import net.minecraft.ChatFormatting; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.server.Bootstrap; +import net.minecraft.network.chat.Component; +import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.CreativeModeTabs; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; /** - * Original exporter of the creative inventory tab contents built by vanilla's own - * CreativeModeTab display generators (built-in registries; tabs needing dynamic - * registries keep whatever they produced before failing). + * Original exporter of the creative inventory: every tab's contents as vanilla's + * own CreativeModeTabs.tryRebuildTabContents builds them over the vanilla data + * pack's registries (category tabs first, then the search tab from their + * search-tab items), each stack as SNBT with its components, and for every stack + * of the search tab the inputs of the client's creative search trees + * (SessionSearchTrees): its creative tooltip lines and its item tags. + * + * VanillaCreativeTabsExporter OUT.json */ public final class VanillaCreativeTabsExporter { + /** The operator tab and its items need permissions and the operatorItemsTab option (off by default). */ + public static final boolean HAS_PERMISSIONS = false; + public static void main(String[] args) throws Exception { - SharedConstants.tryDetectVersion(); - Bootstrap.bootStrap(); - // Display generators only need ItemStacks to exist: bind minimal components. - for (var item : BuiltInRegistries.ITEM) { - item.builtInRegistryHolder().bindComponents( - net.minecraft.core.component.DataComponentMap.builder() - .set(net.minecraft.core.component.DataComponents.MAX_STACK_SIZE, 64) - .build()); - } - var lookup = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); - var parameters = new CreativeModeTab.ItemDisplayParameters(FeatureFlags.DEFAULT_FLAGS, true, lookup); - var out = new JsonArray(); + ParityData.init(); + Files.writeString(Path.of(args[0]), export(FeatureFlags.DEFAULT_FLAGS, HAS_PERMISSIONS, ParityData.lookup).toString(), + StandardCharsets.UTF_8); + } + + public static JsonObject export(FeatureFlagSet features, boolean hasPermissions, HolderLookup.Provider lookup) { + CreativeModeTabs.tryRebuildTabContents(features, hasPermissions, lookup); + var tabs = new JsonArray(); for (CreativeModeTab tab : BuiltInRegistries.CREATIVE_MODE_TAB) { var o = new JsonObject(); var key = BuiltInRegistries.CREATIVE_MODE_TAB.getKey(tab); @@ -38,22 +47,50 @@ public final class VanillaCreativeTabsExporter { o.addProperty("row", tab.row().name()); o.addProperty("column", tab.column()); o.addProperty("title", tab.getDisplayName().getString()); + o.addProperty("icon", snbt(tab.getIconItem())); + o.addProperty("visible", tab.shouldDisplay()); var items = new JsonArray(); - try { - tab.buildContents(parameters); - for (var stack : tab.getDisplayItems()) { - items.add(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()); - } - } catch (RuntimeException error) { - o.addProperty("error", error.toString()); - } - try { - o.addProperty("icon", BuiltInRegistries.ITEM.getKey(tab.getIconItem().getItem()).toString()); - } catch (RuntimeException ignored) { - } + for (ItemStack stack : tab.getDisplayItems()) items.add(snbt(stack)); o.add("items", items); - out.add(o); + if (tab.getType() == CreativeModeTab.Type.SEARCH) { + var context = Item.TooltipContext.of(lookup); + var flag = TooltipFlag.Default.NORMAL.asCreative(); + var lines = new JsonArray(); + var tags = new JsonArray(); + for (ItemStack stack : tab.getDisplayItems()) { + lines.add(strings(tooltipLines(stack, context, flag))); + tags.add(strings(stack.tags().map(t -> t.location().toString()).toList())); + } + o.add("lines", lines); + o.add("tags", tags); + } + tabs.add(o); } - Files.writeString(Path.of(args[0]), new Gson().toJson(out), StandardCharsets.UTF_8); + var out = new JsonObject(); + out.addProperty("schema", 2); + out.addProperty("permissions", hasPermissions); + out.add("tabs", tabs); + return out; + } + + /** SessionSearchTrees.getTooltipLines for one stack. */ + public static List tooltipLines(ItemStack stack, Item.TooltipContext context, TooltipFlag flag) { + return stack.getTooltipLines(context, null, flag).stream() + .map(Component::getString) + .map(l -> ChatFormatting.stripFormatting(l).trim()) + .filter(s -> !s.isEmpty()) + .toList(); + } + + /** ItemStack.CODEC as SNBT (the form horizon_client::item_data::parse_stack reads). */ + public static String snbt(ItemStack stack) { + if (stack.isEmpty()) return "-"; + return ItemStack.CODEC.encodeStart(ParityData.ops, stack).getOrThrow().toString(); + } + + private static JsonArray strings(List values) { + var a = new JsonArray(); + values.forEach(a::add); + return a; } } diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 5d74b5294..22c621b70 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -413,21 +413,23 @@ def main(): 'dev.horizonlab.parity.VanillaCommandParseOracle', 'registries', str(export)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) command_registries.write_bytes((export / 'registries.json').read_bytes()) - creative = root / 'creative-tabs.json' - creative_oracle = oracle.with_name('VanillaCreativeTabsExporter.java') - creative_sources = base.source_hashes([creative_oracle]) + # The creative inventory (creative-inventory.json): every tab built by vanilla's + # CreativeModeTabs over the vanilla data pack's registries, with the search + # tab's tooltip lines and tags. + creative = root / 'creative-inventory.json' + creative_oracles = [oracle.with_name('VanillaCreativeTabsExporter.java'), oracle.with_name('ParityData.java')] + creative_sources = base.source_hashes(creative_oracles) if not (previous.get('creative_exporters_sha256') == creative_sources and creative.exists() and previous.get('server_sha256') == origin['server_sha256']): - classes = lab.LOCAL / 'creative-tabs' / 'classes'; classes.mkdir(parents=True, exist_ok=True) + classes = lab.LOCAL / 'creative-inventory' / 'classes'; classes.mkdir(parents=True, exist_ok=True) dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) with (root / 'creative-export.log').open('w') as log: subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', - '-cp', dependencies, '-d', str(classes), str(creative_oracle)], + '-cp', dependencies, '-d', str(classes), *map(str, creative_oracles)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaCreativeTabsExporter', str(creative)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) - recover_creative_tabs(creative, root) lab.write_json(manifest, {'schema': 7, **origin, 'health_exporters_sha256': health_sources, 'health_files_sha256': {name: lab.digest(root/name, 'sha256') for name in health_files}, @@ -451,31 +453,5 @@ def main(): print(f'Prepared Horizon native-client resources: {root}') -def recover_creative_tabs(path, root): - """Tabs whose generators need dynamic registries (banner patterns) fail in - the bare bootstrap; recover their item order from the decompiled source.""" - import re - tabs = json.loads(path.read_text()) - source = lab.LOCAL / 'decompiled/net/minecraft/world/item/CreativeModeTabs.java' - if not source.exists(): - return - items = json.loads((root / 'items.json').read_text()) - text = source.read_text() - for tab in tabs: - if tab['items'] or tab['type'] != 'CATEGORY': - continue - name = tab['id'].split(':')[1].upper() - start = text.find(f'{name},') - end = text.find('Registry.register(', start + 1) - found = [] - for m in re.finditer(r'\b(Items|Blocks)\.([A-Z0-9_]+)(?:\.(\w+)\(\))?', text[start:end]): - base, colour = m.group(2).lower(), m.group(3) - item = 'minecraft:' + (f'{colour}_{base}' if colour and colour not in ('asItem', 'defaultBlockState', 'get') else base) - if item in items and item not in found: - found.append(item) - tab['items'] = found - path.write_text(json.dumps(tabs)) - - if __name__ == '__main__': main() diff --git a/tools/test_creative_parity.py b/tools/test_creative_parity.py new file mode 100644 index 000000000..79b50f32a --- /dev/null +++ b/tools/test_creative_parity.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Compare the creative inventory's tabs and search with the vanilla client's. + +The Java oracle (VanillaCreativeSearchOracle) writes the creative-inventory.json +that tools/prepare_native_client.py exports (VanillaCreativeTabsExporter: every +tab built by vanilla's CreativeModeTabs over the vanilla data pack's +registries), then what the vanilla client shows: every tab's display items +and, for each search query, CreativeModeInventoryScreen.refreshSearchResults' +items, searched through the client's own SessionSearchTrees. +examples/creative_search_fixture loads the export into +horizon_client::creative::Creative. The tabs it shows (id, title, icon, +position, every stack with its components), the search tab's stacks and the +results of every query must agree. The queries are QUERIES below, then every +search stack's item path and tooltip lines, every item tag with and without +"#", and half of each as a prefix. + + test_creative_parity.py [--detail N] +""" +import argparse +import json +import os +import subprocess +import sys + +try: + from . import interaction_lab as lib, lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import interaction_lab as lib + import lab + import test_rust_parity as base + import test_model_baking_parity as baking + +PARITY_RUST_SCOPE = ['crates/horizon-client/src/creative.rs', 'crates/horizon-client/examples/creative_search_fixture.rs'] +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +# Players' reports (anvil, crafting table, smithing table), other blocks of the +# functional tab, case, spaces, colons and tag searches. +QUERIES = ['', 'anvil', 'Anvil', 'ANVIL', 'crafting', 'crafting table', 'smithing', 'smithing table', 'table', 'chest', + 'furnace', 'bed', 'sign', 'banner', 'ominous', 'painting', 'loom', 'grindstone', 'lectern', 'stone', 'oak', + 'a', 'e', ' ', ' ', 'xyz', 'potion', 'healing', 'splash', 'sharpness', 'enchanted', 'book', 'mending', + 'goat horn', 'ponder', 'firework', 'flight', 'music disc', 'disc', 'spawn egg', 'egg', 'stew', 'arrow', + 'tipped', 'light gray', 'red ', ' red', 'minecraft:', 'minecraft:anvil', 'minecraft:table', 'mine:craft', + ':anvil', ':', 'anvil:', 'minecraft: anvil', ' minecraft : anvil ', 'diamond_sword', 'diamond sword', + 'attack', 'when in main hand', '+', '-3', 'command', 'barrier', 'debug', 'light', 'structure', 'jigsaw', + '#', '#logs', '#minecraft:logs', '#minecraft:', '#:planks', '#wool', '#LOGS', '#swords', '#anvil', '#xyz', + '#minecraft', '#enchantable/', 'é', 'İ', 'Σ'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--detail', type=int, default=5) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'creative-parity'; build.mkdir(parents=True, exist_ok=True) + queries = build / 'queries.json'; queries.write_text(json.dumps(QUERIES)) + classes = build / 'classes'; classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaCreativeTabsExporter', 'VanillaCreativeSearchOracle'))], + 'compile-java') + run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaCreativeSearchOracle', + queries, build / 'creative-inventory.json', build / 'vanilla.json'], 'vanilla') + lib.cargo_example('horizon-client', 'creative_search_fixture', lib.RESOURCES, build / 'creative-inventory.json', + build / 'vanilla.json', build / 'rust.json') + vanilla = json.loads((build / 'vanilla.json').read_text()) + rust = json.loads((build / 'rust.json').read_text()) + bad = 0 + shown = [{k: t[k] for k in ('id', 'title', 'icon', 'row', 'column', 'items')} for t in vanilla['tabs'] if t['shown']] + if [t['id'] for t in shown] != [t['id'] for t in rust['tabs']]: + bad += 1 + print('TABS vanilla', [t['id'] for t in shown], '\n horizon', [t['id'] for t in rust['tabs']]) + for v, r in zip(shown, rust['tabs']): + for k in ('title', 'icon', 'row', 'column'): + if v[k] != r[k]: + bad += 1; print(f'TAB {v["id"]} {k}: vanilla {v[k]!r} | horizon {r[k]!r}') + if v['items'] != r['items']: + bad += 1 + i = next((i for i, (a, b) in enumerate(zip(v['items'], r['items'])) if a != b), min(len(v['items']), len(r['items']))) + print(f'TAB {v["id"]}: {len(v["items"])} vanilla stacks, {len(r["items"])} horizon; first difference at {i}:') + print(' vanilla', v['items'][i] if i < len(v['items']) else None) + print(' horizon', r['items'][i] if i < len(r['items']) else None) + print(f' {v["id"]}: {len(v["items"])} stacks') + search = next(t['items'] for t in vanilla['tabs'] if t['type'] == 'SEARCH') + if search != rust['search']: + bad += 1; print(f'SEARCH TAB: {len(search)} vanilla stacks, {len(rust["search"])} horizon') + wrong = [(v, r) for v, r in zip(vanilla['searches'], rust['searches']) if v != r] + for v, r in wrong[:args.detail]: + missing = [search[i] for i in v['results'] if i not in r['results']][:3] + extra = [search[i] for i in r['results'] if i not in v['results']][:3] + print(f'SEARCH {v["query"]!r}: vanilla {len(v["results"])} results, horizon {len(r["results"])}; ' + f'missing {missing} extra {extra}') + bad += len(wrong) + abs(len(vanilla['searches']) - len(rust['searches'])) + for q in ('anvil', 'crafting', 'smithing'): + hits = next(v['results'] for v in vanilla['searches'] if v['query'] == q) + print(f' search {q!r}: {len(hits)} results, ' + ', '.join(json.loads('"' + search[i].split('id:"')[1].split('"')[0] + '"') + for i in hits[:6])) + print(f'{len(vanilla["searches"]) - len(wrong)}/{len(vanilla["searches"])} searches match; {len(shown)} tabs, ' + f'{len(search)} search stacks') + if bad: + sys.exit(1) + print('creative parity ok') + + +if __name__ == '__main__': + main()