use crate::items::HotbarState;
use bevy::prelude::*;
mod content;
pub use content::{HotbarContentPlugin, HotbarPickupPulse, ItemIconPalette};
#[derive(Resource, Debug, Clone)]
pub struct HotbarUiConfig {
pub visible: bool,
pub slot_size: f32,
pub slot_gap: f32,
pub slot_color: [f32; 4],
pub selected_color: [f32; 4],
}
impl Default for HotbarUiConfig {
fn default() -> Self {
Self {
visible: true,
slot_size: 50.0,
slot_gap: 4.0,
slot_color: [0.15, 0.15, 0.15, 0.85],
selected_color: [0.45, 0.45, 0.45, 0.95],
}
}
}
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct HotbarSlotStyle {
pub border_width: f32,
pub border_color: [f32; 4],
pub selected_border_width: f32,
pub selected_border_color: [f32; 4],
pub empty_slot_alpha: f32,
}
impl Default for HotbarSlotStyle {
fn default() -> Self {
Self {
border_width: 2.0,
border_color: [0.6, 0.6, 0.6, 0.6],
selected_border_width: 2.0,
selected_border_color: [0.6, 0.6, 0.6, 0.6],
empty_slot_alpha: 1.0,
}
}
}
impl HotbarSlotStyle {
fn width(&self, selected: bool) -> f32 {
let width = if selected {
self.selected_border_width
} else {
self.border_width
};
if width.is_finite() {
width.max(0.0)
} else {
0.0
}
}
fn fade(&self, selected: bool, empty: bool) -> f32 {
if selected || !empty || !self.empty_slot_alpha.is_finite() {
1.0
} else {
self.empty_slot_alpha.clamp(0.0, 1.0)
}
}
fn border_color(&self, selected: bool, empty: bool) -> Color {
let [r, g, b, a] = if selected {
self.selected_border_color
} else {
self.border_color
};
Color::srgba(r, g, b, a * self.fade(selected, empty))
}
}
#[derive(Component)]
struct HotbarUiRoot;
#[derive(Component)]
struct HotbarUiRow;
#[derive(Component)]
struct HotbarSlot(usize);
#[derive(Component)]
struct SlotContent {
empty: bool,
}
fn spawn_hotbar_ui(
mut commands: Commands,
config: Res<HotbarUiConfig>,
hotbar: Res<HotbarState>,
content: Option<Res<content::ContentEnabled>>,
style: Option<Res<HotbarSlotStyle>>,
) {
if !config.visible {
return;
}
let style = style.as_deref().cloned().unwrap_or_default();
let size = if content.is_some() {
config.slot_size.clamp(0.0, 50.0)
} else {
config.slot_size.max(0.0)
};
commands
.spawn((
HotbarUiRoot,
Node {
width: percent(100),
position_type: PositionType::Absolute,
bottom: px(16),
padding: UiRect::horizontal(px(16)),
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
))
.with_children(|root| {
root.spawn((
HotbarUiRow,
Node {
width: percent(100),
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
column_gap: px(config.slot_gap.max(0.0)),
..default()
},
))
.with_children(|row| {
for i in 0..hotbar.slots {
let selected = i == hotbar.selected;
row.spawn((
HotbarSlot(i),
Node {
width: px(size),
min_width: px(0),
aspect_ratio: Some(1.0),
flex_shrink: 1.0,
border: UiRect::all(px(style.width(selected))),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(slot_color(&config, selected, 1.0)),
BorderColor::all(style.border_color(selected, false)),
));
}
});
});
}
fn fit_hotbar(
windows: Query<&Window, With<bevy::window::PrimaryWindow>>,
scale: Option<Res<bevy::ui::UiScale>>,
config: Res<HotbarUiConfig>,
content: Option<Res<content::ContentEnabled>>,
mut slots: Query<&mut Node, With<HotbarSlot>>,
mut rows: Query<&mut Node, (With<HotbarUiRow>, Without<HotbarSlot>)>,
) {
let Ok(window) = windows.single() else {
return;
};
let scale = scale.map_or(1.0, |scale| scale.0).max(f32::EPSILON);
let available = (window.width() / scale - 32.0).max(0.0);
let count = slots.iter().count();
let gaps = count.saturating_sub(1) as f32;
let gap = config.slot_gap.max(0.0).min(available / gaps.max(1.0));
let preferred = if content.is_some() {
config.slot_size.clamp(0.0, 50.0)
} else {
config.slot_size.max(0.0)
};
let size = ((available - gap * gaps) / count.max(1) as f32).clamp(0.0, preferred);
for mut node in &mut slots {
if node.width != px(size) || node.height != px(size) {
node.width = px(size);
node.height = px(size);
node.flex_shrink = 0.0;
}
}
for mut row in &mut rows {
if row.column_gap != px(gap) {
row.column_gap = px(gap);
}
}
}
fn slot_color(config: &HotbarUiConfig, selected: bool, fade: f32) -> Color {
let [r, g, b, a] = if selected {
config.selected_color
} else {
config.slot_color
};
Color::srgba(r, g, b, a * fade)
}
fn update_hotbar_selection(
hotbar: Res<HotbarState>,
config: Res<HotbarUiConfig>,
style: Option<Res<HotbarSlotStyle>>,
mut slots: Query<(
&HotbarSlot,
&mut Node,
&mut BackgroundColor,
&mut BorderColor,
Option<&SlotContent>,
)>,
) {
let style = style.as_deref().cloned().unwrap_or_default();
for (slot, mut node, mut bg, mut border_color, content) in &mut slots {
let selected = slot.0 == hotbar.selected;
let empty = content.is_some_and(|content| content.empty);
let color = slot_color(&config, selected, style.fade(selected, empty));
if bg.0 != color {
bg.0 = color;
}
let color = BorderColor::all(style.border_color(selected, empty));
if *border_color != color {
*border_color = color;
}
let limit = match (node.width, node.height) {
(Val::Px(width), Val::Px(_)) => width / 2.0,
_ => f32::INFINITY,
};
let border = UiRect::all(px(style.width(selected).min(limit)));
if node.border != border {
node.border = border;
}
}
}
pub struct HotbarUiPlugin;
impl Plugin for HotbarUiPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<HotbarUiConfig>();
app.init_resource::<HotbarSlotStyle>();
app.add_systems(Startup, spawn_hotbar_ui);
app.add_systems(
PostUpdate,
(fit_hotbar, update_hotbar_selection)
.chain()
.before(bevy::ui::UiSystems::Prepare),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fourteen_slots_reserve_horizontal_screen_margin() {
let mut app = App::new();
app.insert_resource(HotbarState::new(14))
.add_plugins(HotbarUiPlugin);
app.update();
let world = app.world_mut();
let root = world
.query_filtered::<&Node, With<HotbarUiRoot>>()
.single(world)
.unwrap();
assert_eq!(root.padding.left, Val::Px(16.0));
assert_eq!(root.padding.right, Val::Px(16.0));
assert_eq!(world.query::<&HotbarSlot>().iter(world).count(), 14);
}
#[test]
fn legacy_ui_needs_no_inventory_or_content_plugin() {
let mut app = App::new();
app.insert_resource(HotbarState::new(9))
.add_plugins(HotbarUiPlugin);
app.update();
app.world_mut().resource_mut::<HotbarState>().select(8);
app.update();
let config = app.world().resource::<HotbarUiConfig>().clone();
let world = app.world_mut();
assert_eq!(world.query::<&HotbarSlot>().iter(world).count(), 9);
for (slot, bg) in world.query::<(&HotbarSlot, &BackgroundColor)>().iter(world) {
assert_eq!(bg.0, slot_color(&config, slot.0 == 8, 1.0));
}
assert_eq!(world.query::<&Text>().iter(world).count(), 0);
}
#[test]
fn fourteen_slots_resize_both_dimensions_and_respect_ui_scale() {
let mut app = App::new();
app.insert_resource(HotbarState::new(14))
.insert_resource(bevy::ui::UiScale(1.0))
.add_plugins(HotbarUiPlugin);
let window = app
.world_mut()
.spawn((
Window {
resolution: (600, 600).into(),
..default()
},
bevy::window::PrimaryWindow,
))
.id();
for (width, scale) in [(600, 1.0), (800, 1.0), (1280, 1.0), (1920, 1.0), (800, 2.0)] {
app.world_mut()
.get_mut::<Window>(window)
.unwrap()
.resolution
.set(width as f32, 600.0);
app.world_mut().resource_mut::<bevy::ui::UiScale>().0 = scale;
app.update();
let expected = ((width as f32 / scale - 32.0 - 13.0 * 4.0) / 14.0).min(50.0);
let world = app.world_mut();
for node in world
.query_filtered::<&Node, With<HotbarSlot>>()
.iter(world)
{
assert_eq!(node.width, px(expected));
assert_eq!(node.height, px(expected));
}
}
}
const BORDER: [f32; 4] = [0.1, 0.2, 0.3, 0.4];
const SELECTED_BORDER: [f32; 4] = [0.9, 0.8, 0.7, 1.0];
fn styled_app(style: HotbarSlotStyle) -> App {
let mut app = App::new();
app.insert_resource(HotbarState::new(3))
.insert_resource(style)
.add_plugins(HotbarUiPlugin);
app
}
fn slots(app: &mut App) -> Vec<(UiRect, BorderColor, Color)> {
let world = app.world_mut();
let mut slots: Vec<_> = world
.query::<(&HotbarSlot, &Node, &BorderColor, &BackgroundColor)>()
.iter(world)
.map(|(slot, node, border, bg)| (slot.0, node.border, *border, bg.0))
.collect();
slots.sort_by_key(|slot| slot.0);
slots
.into_iter()
.map(|(_, border, color, bg)| (border, color, bg))
.collect()
}
fn color([r, g, b, a]: [f32; 4]) -> BorderColor {
BorderColor::all(Color::srgba(r, g, b, a))
}
#[test]
fn default_style_keeps_the_historical_borders_and_fills() {
assert_eq!(
HotbarSlotStyle::default(),
HotbarSlotStyle {
border_width: 2.0,
border_color: [0.6, 0.6, 0.6, 0.6],
selected_border_width: 2.0,
selected_border_color: [0.6, 0.6, 0.6, 0.6],
empty_slot_alpha: 1.0,
}
);
let mut app = App::new();
app.insert_resource(HotbarState::new(3))
.add_plugins(HotbarUiPlugin);
assert_eq!(
*app.world().resource::<HotbarSlotStyle>(),
HotbarSlotStyle::default()
);
for _ in 0..2 {
app.update();
let slots = slots(&mut app);
assert_eq!(slots.len(), 3);
for (index, (border, border_color, bg)) in slots.into_iter().enumerate() {
assert_eq!(border, UiRect::all(Val::Px(2.0)));
assert_eq!(
border_color,
BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6))
);
let expected = if index == 0 {
Color::srgba(0.45, 0.45, 0.45, 0.95)
} else {
Color::srgba(0.15, 0.15, 0.15, 0.85)
};
assert_eq!(bg, expected);
}
}
}
#[test]
fn configured_borders_distinguish_the_selected_slot_and_follow_it() {
let mut app = styled_app(HotbarSlotStyle {
border_width: 1.0,
border_color: BORDER,
selected_border_width: 4.0,
selected_border_color: SELECTED_BORDER,
..default()
});
let normal = (UiRect::all(Val::Px(1.0)), color(BORDER));
let selected = (UiRect::all(Val::Px(4.0)), color(SELECTED_BORDER));
let borders = |app: &mut App| -> Vec<(UiRect, BorderColor)> {
slots(app)
.into_iter()
.map(|(border, color, _)| (border, color))
.collect()
};
app.update();
assert_eq!(borders(&mut app), vec![selected, normal, normal]);
app.world_mut().resource_mut::<HotbarState>().select(2);
app.update();
assert_eq!(borders(&mut app), vec![normal, normal, selected]);
app.world_mut()
.resource_mut::<HotbarSlotStyle>()
.border_width = 3.0;
app.update();
assert_eq!(borders(&mut app)[0].0, UiRect::all(Val::Px(3.0)));
assert_eq!(borders(&mut app)[2], selected);
}
#[test]
fn negative_or_non_finite_border_widths_draw_no_border() {
for width in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -3.0] {
let mut app = styled_app(HotbarSlotStyle {
border_width: width,
selected_border_width: width,
..default()
});
for _ in 0..2 {
app.update();
for (border, _, _) in slots(&mut app) {
assert_eq!(border, UiRect::all(Val::Px(0.0)), "width {width}");
}
}
}
}
#[test]
fn borders_never_exceed_half_of_the_fitted_slot() {
let mut app = styled_app(HotbarSlotStyle {
border_width: 30.0,
selected_border_width: 40.0,
..default()
});
let window = app
.world_mut()
.spawn((
Window {
resolution: (132, 600).into(),
..default()
},
bevy::window::PrimaryWindow,
))
.id();
app.update();
let size = (132.0_f32 - 32.0 - 2.0 * 4.0) / 3.0;
let world = app.world_mut();
for node in world
.query_filtered::<&Node, With<HotbarSlot>>()
.iter(world)
{
assert_eq!(node.width, px(size));
assert_eq!(node.border, UiRect::all(px(size / 2.0)));
}
app.world_mut()
.get_mut::<Window>(window)
.unwrap()
.resolution
.set(800.0, 600.0);
app.update();
let slots = slots(&mut app);
assert_eq!(slots[0].0, UiRect::all(Val::Px(25.0)));
assert_eq!(slots[1].0, UiRect::all(Val::Px(25.0)));
}
#[test]
fn slot_style_resource_is_optional() {
let mut app = styled_app(HotbarSlotStyle {
border_width: 7.0,
selected_border_width: 7.0,
border_color: BORDER,
selected_border_color: BORDER,
..default()
});
app.world_mut().remove_resource::<HotbarSlotStyle>();
app.update();
app.update();
for (border, border_color, _) in slots(&mut app) {
assert_eq!(border, UiRect::all(Val::Px(2.0)));
assert_eq!(border_color, color([0.6, 0.6, 0.6, 0.6]));
}
app.insert_resource(HotbarSlotStyle {
border_width: 5.0,
..default()
});
app.update();
assert_eq!(slots(&mut app)[1].0, UiRect::all(Val::Px(5.0)));
}
#[test]
fn slots_without_inventory_content_are_never_faded() {
let mut app = styled_app(HotbarSlotStyle {
empty_slot_alpha: 0.1,
..default()
});
app.update();
app.update();
let slots = slots(&mut app);
assert_eq!(slots[1].1, color([0.6, 0.6, 0.6, 0.6]));
assert_eq!(slots[1].2, Color::srgba(0.15, 0.15, 0.15, 0.85));
}
}