Merge pull request #2060 from kacpherek/fix/1953-creative-menu-fps

🤖 Agent: Gate check by Ludovic's AI agent (Claude). Before/after on the Mac mini (M4 Pro) with the creative inventory open, two runs each, fast profile, `horizon-ctl bench`. Main: CPU frame 0.81 to 0.91 ms on the building/combat tabs and 1.32 to 1.47 ms while searching (664 to 742 fps). This PR: 0.44 to 0.49 ms on building/combat and 0.49 ms while searching (1122 to 1125 fps). The panel pixels match main. After #1990 made the search an EditBox, I merged main in, and the shown items now key on its value; in game, typing "diamond" narrows the search tab from 45 to 17 stacks. `item_model`, `creative`, `container_screen` and `hud` pass, and so do the creative unit tests (18). Fixes #1953 is right. Thanks @kacpherek!
This commit is contained in:
Ludovic Marie
2026-10-26 17:57:51 +01:00
committed by GitHub
8 changed files with 207 additions and 21 deletions
+10 -7
View File
@@ -1031,19 +1031,22 @@ pub struct ItemModels {
}
impl ItemModels {
pub fn components(&self, stack: &StackView) -> Components {
let mut out = self
.prototypes
.get(&stack.item)
.cloned()
.unwrap_or_default();
/// The stack's components: its item's defaults with the stack's patch on top. A stack
/// with no patch (most stacks a screen draws) borrows the defaults instead of copying them.
pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> {
static NONE: Components = BTreeMap::new();
let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE);
if stack.patch.is_empty() {
return std::borrow::Cow::Borrowed(prototype);
}
let mut out = prototype.clone();
for (key, value) in &stack.patch {
match value {
Some(v) => out.insert(key.clone(), v.clone()),
None => out.remove(key),
};
}
out
std::borrow::Cow::Owned(out)
}
/// `ItemModelResolver.updateForTopItem`.
pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem {
+70 -10
View File
@@ -3,7 +3,12 @@
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
use crate::{Result, items::ItemStack, ui::EditBox};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
use std::{
collections::HashMap,
fs,
path::Path,
sync::{Arc, Mutex},
};
#[derive(Clone, Debug)]
pub struct Tab {
@@ -40,6 +45,17 @@ pub struct Creative {
/// The search tab's stacks, in its display order.
search_items: Vec<ItemStack>,
search_index: Vec<SearchEntry>,
/// ItemPickerMenu.items: what the grid shows, filled when the tab or the
/// search changes (selectTab, refreshSearchResults), not on every frame.
shown: Mutex<Option<Shown>>,
}
/// The grid's stacks for one tab, search text and language.
struct Shown {
tab: usize,
search: String,
/// A display name, so a language change refills the search results.
language: String,
items: Arc<[ItemStack]>,
}
/// Display names from the pinned en_us language file.
#[derive(Default)]
@@ -291,6 +307,7 @@ impl Creative {
},
search_items,
search_index,
shown: Mutex::new(None),
}
}
/// Where a stack comes in the creative tabs (the search tab lists them
@@ -303,6 +320,22 @@ impl Creative {
.position(|s| s.same_item_same_components(stack))
.or_else(|| items.iter().position(|s| s.item == stack.item))
}
/// The tabs without their stacks: what the screen draws of them each frame.
pub fn tab_headers(&self) -> Vec<Tab> {
self.tabs
.iter()
.map(|t| Tab {
id: t.id.clone(),
title: t.title.clone(),
icon: t.icon.clone(),
items: Vec::new(),
top: t.top,
column: t.column,
search: t.search,
inventory: t.inventory,
})
.collect()
}
pub fn tab(&self) -> &Tab {
&self.tabs[self.selected.min(self.tabs.len() - 1)]
}
@@ -384,17 +417,44 @@ impl Creative {
})
.collect()
}
/// Items shown by the selected tab (the search tab filters by `search`).
pub fn items(&self, names: &Names) -> Vec<ItemStack> {
let tab = self.tab();
if tab.search {
return self
.search_results(&self.search.value, names)
/// Items shown by the selected tab (the search tab filters by `search`),
/// worked out again only when the tab, the search or the language changed.
pub fn items(&self, names: &Names) -> Arc<[ItemStack]> {
let tab = self.selected.min(self.tabs.len() - 1);
let search = if self.tab().search {
self.search.value.as_str()
} else {
""
};
let language = names.display_get("itemGroup.search").unwrap_or_default();
let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner());
if let Some(s) = shown.as_ref()
&& s.tab == tab
&& s.search == search
&& s.language == language
{
return s.items.clone();
}
let items: Arc<[ItemStack]> = if self.tab().search {
self.search_results(search, names)
.into_iter()
.map(|i| self.search_items[i].clone())
.collect();
}
tab.items.clone()
.collect()
} else {
self.tab().items.as_slice().into()
};
*shown = Some(Shown {
tab,
search: search.to_owned(),
language,
items: items.clone(),
});
items
}
/// Drop the shown items, so the next `items` works them out again: a
/// reload can rename items without changing the Search label.
pub fn forget_items(&self) {
*self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
pub fn rows(&self, names: &Names) -> usize {
self.items(names).len().div_ceil(9)
+11 -2
View File
@@ -1270,6 +1270,13 @@ struct Game<'a> {
/// Controllers (Horizon's own).
pad: pad::Pads,
frames: u64,
/// `item_level` for one frame, game time, day time and dimension.
item_level_cache: std::cell::RefCell<
Option<(
(u64, i64, i64, &'static str),
horizon_assets::item_model::LevelState,
)>,
>,
/// Frames drawn with the player in the world, for `--world-frames`.
world_frames: u64,
fps: f32,
@@ -9816,8 +9823,9 @@ impl Game<'_> {
fn draw_creative(&mut self, batch: &mut HudBatch) {
let (ox, oy) = Self::creative_origin(batch);
let selected = self.creative_screen.selected;
let tabs = self.creative_screen.tabs.clone();
let tab = self.creative_screen.tab().clone();
// Only what is drawn of the tabs: their stacks stay where they are.
let tabs = self.creative_screen.tab_headers();
let tab = tabs[selected.min(tabs.len() - 1)].clone();
let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| {
format!(
"gui/sprites/container/creative_inventory/tab_{}_{}_{}",
@@ -12278,6 +12286,7 @@ impl<'a> Game<'a> {
last_input: now,
pad: Default::default(),
frames: 0,
item_level_cache: Default::default(),
world_frames: 0,
fps: 0.0,
fps_frames: 0,
+19 -1
View File
@@ -196,13 +196,31 @@ impl Game<'_> {
skins: &self.skin_downloads,
}
}
/// The client level as item models read it.
/// The client level as item models read it: worked out once a frame (a
/// screen of items read the same level, its sky sampled once).
pub(super) fn item_level(&self) -> LevelState {
let dimension = match self.dim {
Dim::Overworld => "minecraft:overworld",
Dim::Nether => "minecraft:the_nether",
Dim::End => "minecraft:the_end",
};
let key = (
self.frames,
self.world.game_time,
self.world.day_time,
dimension,
);
let mut cached = self.item_level_cache.borrow_mut();
if let Some((at, level)) = cached.as_ref()
&& *at == key
{
return level.clone();
}
let level = self.level_state_now(dimension);
*cached = Some((key, level.clone()));
level
}
fn level_state_now(&self, dimension: &'static str) -> LevelState {
let sky = self
.dim_environment()
.sample(self.world.day_time, None, None);
@@ -257,6 +257,7 @@ impl Game<'_> {
lang::set(lang::Language::load(&[&root], code));
self.refresh_remote_language();
self.ui.chat.rescale(&self.gui.atlas);
self.creative_screen.forget_items();
}
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
pub(super) fn apply_ui_settings(&mut self) {
+2
View File
@@ -221,6 +221,8 @@ impl Game<'_> {
self.apply_ui_settings();
}
self.ui.chat.rescale(&self.gui.atlas);
// The creative screen survives the reload; item names may not.
self.creative_screen.forget_items();
Ok(())
}
}
+4
View File
@@ -363,6 +363,9 @@ pub struct ItemRenderer {
sprites: FileSprites,
baked: Mutex<HashMap<String, Arc<BakedItemModel>>>,
extents: Mutex<HashMap<String, Arc<Vec<Vec3>>>>,
/// GUI items already drawn: the HUD vertices of a static item at a GUI position
/// (`gui::draw`), which are the same every frame it stays there.
pub(crate) gui_drawn: Mutex<HashMap<gui::DrawnKey, Arc<[crate::hud::HudVertex]>>>,
/// Entity model layers of the special renderers.
parts: HashMap<String, ModelPart>,
/// `colormap/grass.png` as ARGB.
@@ -452,6 +455,7 @@ impl ItemRenderer {
},
baked: Mutex::default(),
extents: Mutex::default(),
gui_drawn: Mutex::default(),
parts,
grass,
})
+90 -1
View File
@@ -8,7 +8,7 @@
use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost};
use crate::hud::{HudBatch, Rect};
use glam::{EulerRot, Mat4, Vec2, Vec3};
use std::{collections::HashMap, f32::consts::PI};
use std::{collections::HashMap, f32::consts::PI, sync::Arc};
mod depth;
@@ -148,6 +148,95 @@ pub fn draw(
if state.is_empty() {
return;
}
// A static item drawn where it was drawn before gives the same vertices:
// take them instead of submitting, sorting and clipping its quads again.
let key = DrawnKey::of(state, renderer, sprites, x, y);
if let Some(key) = &key
&& let Some(drawn) = renderer
.gui_drawn
.lock()
.ok()
.and_then(|d| d.get(key).cloned())
{
batch.vertices.extend_from_slice(&drawn);
return;
}
let start = batch.vertices.len();
draw_now(state, renderer, sprites, host, batch, x, y, time);
if let Some(key) = key
&& let Ok(mut drawn) = renderer.gui_drawn.lock()
{
// GUI positions and items are few; a long scroll through every tab stays bounded.
if drawn.len() >= DRAWN_LIMIT {
drawn.clear();
}
drawn.insert(key, batch.vertices[start..].into());
}
}
/// Entries of `ItemRenderer::gui_drawn` before it starts over.
const DRAWN_LIMIT: usize = 8192;
/// What a GUI item's vertices depend on: its layers' baked models (kept for the
/// renderer's life, so their addresses name them), tints and transforms, the
/// atlas, and the exact position. None for items whose drawing changes with time
/// or the host: a glint, or a special model renderer.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct DrawnKey {
renderer: usize,
sprites: (usize, usize),
at: [u32; 2],
oversized: bool,
layers: Vec<(usize, Vec<i32>, [u32; 16], bool)>,
}
impl DrawnKey {
fn of(
state: &ItemRenderState,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
x: f32,
y: f32,
) -> Option<Self> {
if state.animated {
return None;
}
let layers = state
.layers
.iter()
.map(|layer| match &layer.geometry {
super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => {
Some((
Arc::as_ptr(baked) as usize,
layer.tints.clone(),
layer.matrix.to_cols_array().map(f32::to_bits),
layer.uses_block_light,
))
}
_ => None,
})
.collect::<Option<Vec<_>>>()?;
Some(Self {
renderer: std::ptr::from_ref(renderer) as usize,
sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()),
at: [x.to_bits(), y.to_bits()],
oversized: state.oversized_in_gui,
layers,
})
}
}
/// [`draw`] without the cache.
#[allow(clippy::too_many_arguments)]
fn draw_now(
state: &ItemRenderState,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
batch: &mut HudBatch,
x: f32,
y: f32,
time: f32,
) {
let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0))
* Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0));
let mut quads: Vec<ItemQuad> = Vec::new();