#![cfg_attr(
feature = "items",
doc = "| [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |"
)]
#![cfg_attr(
not(feature = "items"),
doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed top-right pop-up text on item pickup |"
)]
#![cfg_attr(
feature = "items",
doc = "Use [`UiPlugin`] when your game uses [`DefaultItem`] and wants all four HUD elements with zero configuration:"
)]
#![cfg_attr(
not(feature = "items"),
doc = "Use [`UiPlugin`] with the default `items` feature when your game uses `DefaultItem` and wants all four HUD elements with zero configuration:"
)]
use bevy::prelude::*;
#[cfg(feature = "items")]
use crate::items::hotbar::{HotbarSelectionChanged, HotbarState};
#[cfg(feature = "items")]
use crate::items::inventory::ItemPickedUp;
#[cfg(feature = "items")]
use crate::items::inventory::ItemType;
use crate::world::loading::{LoadingProgress, WorldLoadingState};
pub mod hud;
pub use hud::{
HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
};
#[derive(Resource, Debug, Clone)]
pub struct CrosshairConfig {
pub color: [f32; 4],
pub size: f32,
pub gap: f32,
pub thickness: f32,
pub visible: bool,
}
impl Default for CrosshairConfig {
fn default() -> Self {
Self {
color: [1.0, 1.0, 1.0, 1.0],
size: 20.0,
gap: 4.0,
thickness: 2.0,
visible: true,
}
}
}
#[derive(Component)]
struct CrosshairNode;
fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
if !config.visible {
return;
}
let c = &*config;
let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
commands
.spawn((
CrosshairNode,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
position_type: PositionType::Absolute,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::NONE),
))
.with_children(|root| {
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.size),
height: Val::Px(c.thickness),
right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
top: Val::Px(-c.thickness / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.size),
height: Val::Px(c.thickness),
left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
top: Val::Px(-c.thickness / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.thickness),
height: Val::Px(c.size),
left: Val::Px(-c.thickness / 2.0),
bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.thickness),
height: Val::Px(c.size),
left: Val::Px(-c.thickness / 2.0),
top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
..default()
},
BackgroundColor(color),
));
});
}
pub struct CrosshairPlugin;
impl Plugin for CrosshairPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<CrosshairConfig>();
app.add_systems(Startup, spawn_crosshair);
}
}
#[derive(Resource, Debug, Clone)]
pub struct LoadingScreenConfig {
pub background_color: [f32; 4],
pub text_color: [f32; 4],
pub title: String,
pub show_progress_bar: bool,
}
impl Default for LoadingScreenConfig {
fn default() -> Self {
Self {
background_color: [0.05, 0.05, 0.05, 0.95],
text_color: [1.0, 1.0, 1.0, 1.0],
title: "Loading...".to_string(),
show_progress_bar: true,
}
}
}
#[derive(Component)]
struct LoadingOverlay;
#[derive(Component)]
struct LoadingText;
#[derive(Component)]
struct LoadingProgressBar;
fn spawn_loading_overlay(mut commands: Commands, config: Res<LoadingScreenConfig>) {
let bg = Color::srgba(
config.background_color[0],
config.background_color[1],
config.background_color[2],
config.background_color[3],
);
let tc = Color::srgba(
config.text_color[0],
config.text_color[1],
config.text_color[2],
config.text_color[3],
);
commands
.spawn((
LoadingOverlay,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
position_type: PositionType::Absolute,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(bg),
ZIndex(100),
))
.with_children(|parent| {
parent.spawn((
LoadingText,
Text::new(config.title.clone()),
TextFont {
font_size: 32.0,
..default()
},
TextColor(tc),
));
if config.show_progress_bar {
parent
.spawn((
Node {
width: Val::Px(400.0),
height: Val::Px(20.0),
margin: UiRect::top(Val::Px(20.0)),
..default()
},
BackgroundColor(Color::srgba(0.2, 0.2, 0.2, 1.0)),
))
.with_children(|bar| {
bar.spawn((
LoadingProgressBar,
Node {
width: Val::Percent(0.0),
height: Val::Percent(100.0),
..default()
},
BackgroundColor(Color::srgba(0.2, 0.7, 0.3, 1.0)),
));
});
}
});
}
fn update_loading_overlay(
loading_state: Res<WorldLoadingState>,
mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
mut text_query: Query<&mut Text, With<LoadingText>>,
mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
) {
if loading_state.ready {
if let Ok(mut vis) = overlay_query.single_mut() {
*vis = Visibility::Hidden;
}
return;
}
let mut latest: Option<LoadingProgress> = None;
for msg in progress_reader.read() {
latest = Some(msg.clone());
}
if let Some(progress) = latest {
if let Ok(mut text) = text_query.single_mut() {
*text = Text::new(format!(
"Loading... {}/{} chunks",
progress.loaded, progress.total
));
}
if let Ok(mut node) = bar_query.single_mut() {
node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
}
}
}
fn despawn_loading_overlay_on_ready(
mut commands: Commands,
loading_state: Res<WorldLoadingState>,
overlay_query: Query<Entity, With<LoadingOverlay>>,
) {
if loading_state.ready {
for entity in overlay_query.iter() {
commands.entity(entity).despawn();
}
}
}
pub struct LoadingScreenPlugin;
impl Plugin for LoadingScreenPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<LoadingScreenConfig>();
app.add_systems(Startup, spawn_loading_overlay);
app.add_systems(
Update,
(update_loading_overlay, despawn_loading_overlay_on_ready),
);
}
}
#[cfg(feature = "items")]
#[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],
}
#[cfg(feature = "items")]
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],
}
}
}
#[cfg(feature = "items")]
#[derive(Component)]
struct HotbarUiRoot;
#[cfg(feature = "items")]
#[derive(Component)]
struct HotbarSlot(usize);
#[cfg(feature = "items")]
fn spawn_hotbar_ui(mut commands: Commands, config: Res<HotbarUiConfig>, hotbar: Res<HotbarState>) {
if !config.visible {
return;
}
let slot_color = Color::srgba(
config.slot_color[0],
config.slot_color[1],
config.slot_color[2],
config.slot_color[3],
);
let selected_color = Color::srgba(
config.selected_color[0],
config.selected_color[1],
config.selected_color[2],
config.selected_color[3],
);
commands
.spawn((
HotbarUiRoot,
Node {
width: Val::Percent(100.0),
position_type: PositionType::Absolute,
bottom: Val::Px(16.0),
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
column_gap: Val::Px(config.slot_gap),
..default()
},
BackgroundColor(Color::NONE),
))
.with_children(|row| {
for i in 0..hotbar.slots {
let bg = if i == hotbar.selected {
selected_color
} else {
slot_color
};
row.spawn((
HotbarSlot(i),
Node {
width: Val::Px(config.slot_size),
height: Val::Px(config.slot_size),
border: UiRect::all(Val::Px(2.0)),
..default()
},
BackgroundColor(bg),
BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6)),
));
}
});
}
#[cfg(feature = "items")]
fn update_hotbar_selection(
mut selection_reader: bevy::ecs::message::MessageReader<HotbarSelectionChanged>,
config: Res<HotbarUiConfig>,
mut slot_query: Query<(&HotbarSlot, &mut BackgroundColor)>,
) {
let mut new_selected: Option<usize> = None;
for msg in selection_reader.read() {
new_selected = Some(msg.slot);
}
let Some(selected) = new_selected else {
return;
};
let slot_color = Color::srgba(
config.slot_color[0],
config.slot_color[1],
config.slot_color[2],
config.slot_color[3],
);
let selected_color = Color::srgba(
config.selected_color[0],
config.selected_color[1],
config.selected_color[2],
config.selected_color[3],
);
for (slot, mut bg) in slot_query.iter_mut() {
bg.0 = if slot.0 == selected {
selected_color
} else {
slot_color
};
}
}
#[cfg(feature = "items")]
pub struct HotbarUiPlugin;
#[cfg(feature = "items")]
impl Plugin for HotbarUiPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<HotbarUiConfig>();
app.add_systems(Startup, spawn_hotbar_ui);
app.add_systems(Update, update_hotbar_selection);
}
}
#[cfg(feature = "items")]
#[derive(Resource, Debug, Clone)]
pub struct PickupNotificationConfig {
pub visible: bool,
pub duration_secs: f32,
pub text_color: [f32; 4],
pub max_notifications: usize,
}
#[cfg(feature = "items")]
impl Default for PickupNotificationConfig {
fn default() -> Self {
Self {
visible: true,
duration_secs: 3.0,
text_color: [1.0, 1.0, 1.0, 1.0],
max_notifications: 5,
}
}
}
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationTimer(Timer);
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationContainer;
#[cfg(feature = "items")]
fn spawn_notification_container(mut commands: Commands) {
commands.spawn((
NotificationContainer,
Node {
position_type: PositionType::Absolute,
top: Val::Px(16.0),
right: Val::Px(16.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
align_items: AlignItems::FlexEnd,
..default()
},
BackgroundColor(Color::NONE),
));
}
#[cfg(feature = "items")]
fn on_item_picked_up<I: ItemType>(
mut commands: Commands,
mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
config: Res<PickupNotificationConfig>,
container_query: Query<Entity, With<NotificationContainer>>,
existing_query: Query<Entity, With<NotificationTimer>>,
) {
if !config.visible {
return;
}
let pickups: Vec<(String, u32)> = pickup_reader
.read()
.map(|p| (p.item.name().to_string(), p.count))
.collect();
if pickups.is_empty() {
return;
}
let Ok(container) = container_query.single() else {
return;
};
let tc = Color::srgba(
config.text_color[0],
config.text_color[1],
config.text_color[2],
config.text_color[3],
);
let existing: Vec<Entity> = existing_query.iter().collect();
let available = config.max_notifications.saturating_sub(existing.len());
let spawn_count = pickups.len().min(available);
if existing.len() + pickups.len() > config.max_notifications {
let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
for entity in existing.iter().take(overflow) {
commands.entity(*entity).despawn();
}
}
for (name, count) in pickups.iter().take(spawn_count) {
let label = format!("+{count} {name}");
let notification = commands
.spawn((
NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
Text::new(label),
TextFont {
font_size: 18.0,
..default()
},
TextColor(tc),
Node { ..default() },
))
.id();
commands.entity(container).add_child(notification);
}
}
#[cfg(feature = "items")]
fn tick_notifications(
mut commands: Commands,
time: Res<Time>,
mut query: Query<(Entity, &mut NotificationTimer)>,
) {
for (entity, mut timer) in query.iter_mut() {
timer.0.tick(time.delta());
if timer.0.just_finished() {
commands.entity(entity).despawn();
}
}
}
#[cfg(feature = "items")]
pub struct PickupNotificationPlugin<I: ItemType> {
_marker: std::marker::PhantomData<I>,
}
#[cfg(feature = "items")]
impl<I: ItemType> PickupNotificationPlugin<I> {
pub fn new() -> Self {
Self {
_marker: std::marker::PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for PickupNotificationPlugin<I> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
fn build(&self, app: &mut App) {
app.init_resource::<PickupNotificationConfig>();
app.add_message::<ItemPickedUp<I>>();
app.add_systems(Startup, spawn_notification_container);
app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
}
}
mod pause_menu;
pub use pause_menu::{PauseMenuConfig, PauseMenuPlugin, PauseMenuState, SaveSettingsRequest};
use crate::chunk::world_to_chunk_coord;
use crate::player::Player;
use crate::world::ChunkManager;
use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
#[derive(Resource, Default)]
pub struct DebugOverlayState {
pub visible: bool,
}
#[derive(Component)]
struct DebugOverlay;
#[derive(Component)]
struct DebugLine(usize);
fn spawn_debug_overlay(mut commands: Commands) {
commands
.spawn((
DebugOverlay,
Node {
position_type: PositionType::Absolute,
top: Val::Px(8.0),
left: Val::Px(8.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(2.0),
padding: UiRect::all(Val::Px(6.0)),
..default()
},
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
Visibility::Hidden,
ZIndex(200),
))
.with_children(|root| {
let style = TextFont {
font_size: 14.0,
..default()
};
let color = TextColor(Color::WHITE);
for i in 0..4 {
root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
}
});
}
fn update_debug_overlay(
keys: Res<ButtonInput<KeyCode>>,
mut state: ResMut<DebugOverlayState>,
mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
mut line_q: Query<(&DebugLine, &mut Text)>,
player_q: Query<&Transform, With<Player>>,
manager: Res<ChunkManager>,
diagnostics: Res<DiagnosticsStore>,
) {
if keys.just_pressed(KeyCode::F3) {
state.visible = !state.visible;
if let Ok(mut vis) = overlay_q.single_mut() {
*vis = if state.visible {
Visibility::Visible
} else {
Visibility::Hidden
};
}
}
if !state.visible {
return;
}
let pos = player_q
.single()
.map(|t| t.translation)
.unwrap_or(Vec3::ZERO);
let chunk = world_to_chunk_coord(pos);
let fps = diagnostics
.get(&FrameTimeDiagnosticsPlugin::FPS)
.and_then(|d| d.smoothed())
.unwrap_or(0.0);
let chunk_count = manager.loaded_count();
let lines = [
format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
format!("FPS: {fps:.0}"),
format!("Chunks: {chunk_count}"),
];
for (line_marker, mut text) in line_q.iter_mut() {
if let Some(content) = lines.get(line_marker.0) {
*text = Text::new(content.clone());
}
}
}
pub struct DebugOverlayPlugin;
impl Plugin for DebugOverlayPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(FrameTimeDiagnosticsPlugin::default());
app.init_resource::<DebugOverlayState>();
app.add_systems(Startup, spawn_debug_overlay);
app.add_systems(Update, update_debug_overlay);
}
}
#[cfg(feature = "items")]
use crate::items::inventory::DefaultItem;
#[cfg_attr(
feature = "items",
doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
)]
#[cfg_attr(
not(feature = "items"),
doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
)]
#[cfg_attr(
feature = "items",
doc = "Equivalent to adding [`CrosshairPlugin`], [`LoadingScreenPlugin`], [`HotbarUiPlugin`], and [`PickupNotificationPlugin::<DefaultItem>`] in one call. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
)]
#[cfg_attr(
not(feature = "items"),
doc = "Without the `items` feature, this adds [`CrosshairPlugin`] and [`LoadingScreenPlugin`]. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
)]
#[cfg_attr(
feature = "items",
doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
)]
#[cfg_attr(
not(feature = "items"),
doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
)]
pub struct UiPlugin;
impl Plugin for UiPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(CrosshairPlugin);
app.add_plugins(LoadingScreenPlugin);
#[cfg(feature = "items")]
app.add_plugins(HotbarUiPlugin);
#[cfg(feature = "items")]
app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
}
}