Skip to main content

voxel_framework/ui/
mod.rs

1//! HUD overlay plugins for voxel game user interfaces.
2//!
3//! This module provides four composable HUD plugins that cover the most common
4//! in-game overlay needs. Each plugin is self-contained and can be added
5//! independently; [`UiPlugin`] is an umbrella that adds all four at once using
6//! [`DefaultItem`] as the item type.
7//!
8//! # Available plugins
9//!
10//! | Plugin | What it provides |
11//! |--------|-----------------|
12//! | [`CrosshairPlugin`] | Center-screen crosshair rendered as four `Node` quads |
13//! | [`LoadingScreenPlugin`] | Full-screen overlay with progress bar while the world loads |
14//! | `HotbarUiPlugin` *(feature `items`)* | Bottom-center row of inventory slots |
15//! | [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |
16//!
17//! # Choosing between [`UiPlugin`] and individual plugins
18//!
19//! Use [`UiPlugin`] when your game uses [`DefaultItem`] and wants all four HUD
20//! elements with zero configuration:
21//!
22//! ```rust,no_run
23//! use bevy::prelude::*;
24//! use voxel_framework::ui::UiPlugin;
25//!
26//! App::new().add_plugins(UiPlugin);
27//! ```
28//!
29//! Use individual plugins when you need a custom item type for pickup
30//! notifications, want to omit specific HUD elements, or need to insert
31//! configuration resources before the plugin initializes them:
32//!
33//! ```rust,no_run
34//! use bevy::prelude::*;
35//! use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
36//!
37//! App::new()
38//!     .insert_resource(CrosshairConfig {
39//!         color: [1.0, 0.3, 0.3, 1.0],
40//!         size: 14.0,
41//!         ..Default::default()
42//!     })
43//!     .add_plugins(CrosshairPlugin);
44//!
45//! // With the default `items` feature enabled, you can also add `HotbarUiPlugin`.
46//! ```
47//!
48//! # Pause menu
49//!
50//! The optional [`PauseMenuPlugin`] lives in the
51//! `pause_menu` submodule and is re-exported from this module. It is **not**
52//! included in [`UiPlugin`] because it manages its own [`PauseMenuState`] and
53//! cursor lifetime, which must be coordinated with your game's state machine.
54
55use bevy::prelude::*;
56
57#[cfg(feature = "items")]
58use crate::items::hotbar::{HotbarSelectionChanged, HotbarState};
59#[cfg(feature = "items")]
60use crate::items::inventory::ItemPickedUp;
61#[cfg(feature = "items")]
62use crate::items::inventory::ItemType;
63use crate::world::loading::{LoadingProgress, WorldLoadingState};
64
65// ─── Crosshair ────────────────────────────────────────────────────────────────
66
67/// Visual configuration for the [`CrosshairPlugin`] overlay.
68///
69/// Insert this resource before adding [`CrosshairPlugin`] to override any
70/// default. The crosshair is spawned once on `Startup`; changes made after
71/// that point have no effect unless you despawn and re-spawn the crosshair
72/// nodes.
73///
74/// # Default values
75///
76/// | Field       | Default              | Notes |
77/// |-------------|----------------------|-------|
78/// | `color`     | `[1,1,1,1]` (white)  | RGBA, linear |
79/// | `size`      | `20.0` px            | Half-length of each arm |
80/// | `gap`       | `4.0` px             | Empty space between center and arm start |
81/// | `thickness` | `2.0` px             | Width of each arm quad |
82/// | `visible`   | `true`               | `false` skips spawning entirely |
83#[derive(Resource, Debug, Clone)]
84pub struct CrosshairConfig {
85    /// RGBA color of the four crosshair arm quads in linear sRGB.
86    /// Alpha controls overall transparency of the overlay.
87    pub color: [f32; 4],
88    /// Half-length of each arm in logical (UI) pixels. The total visual width
89    /// of the crosshair is approximately `2 × (gap + size)`.
90    pub size: f32,
91    /// Empty gap in logical pixels between the screen center and the start of
92    /// each arm. Increase this to leave a clear center dot.
93    pub gap: f32,
94    /// Width of each arm quad in logical pixels. Thicker values (`4.0`–`6.0`)
95    /// are easier to see on busy backgrounds.
96    pub thickness: f32,
97    /// When `false`, [`CrosshairPlugin`] returns early from `spawn_crosshair`
98    /// without creating any entities. Useful for games that manage their own
99    /// reticle or disable the crosshair entirely in certain modes.
100    pub visible: bool,
101}
102
103impl Default for CrosshairConfig {
104    fn default() -> Self {
105        Self {
106            color: [1.0, 1.0, 1.0, 1.0],
107            size: 20.0,
108            gap: 4.0,
109            thickness: 2.0,
110            visible: true,
111        }
112    }
113}
114
115/// Marker component for crosshair quad entities.
116#[derive(Component)]
117struct CrosshairNode;
118
119fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
120    if !config.visible {
121        return;
122    }
123
124    let c = &*config;
125    let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
126
127    // Root container — full screen, no interaction, just a layout anchor.
128    commands
129        .spawn((
130            CrosshairNode,
131            Node {
132                width: Val::Percent(100.0),
133                height: Val::Percent(100.0),
134                position_type: PositionType::Absolute,
135                justify_content: JustifyContent::Center,
136                align_items: AlignItems::Center,
137                ..default()
138            },
139            BackgroundColor(Color::NONE),
140        ))
141        .with_children(|root| {
142            // Left arm
143            root.spawn((
144                CrosshairNode,
145                Node {
146                    position_type: PositionType::Absolute,
147                    width: Val::Px(c.size),
148                    height: Val::Px(c.thickness),
149                    right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
150                    top: Val::Px(-c.thickness / 2.0),
151                    ..default()
152                },
153                BackgroundColor(color),
154            ));
155            // Right arm
156            root.spawn((
157                CrosshairNode,
158                Node {
159                    position_type: PositionType::Absolute,
160                    width: Val::Px(c.size),
161                    height: Val::Px(c.thickness),
162                    left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
163                    top: Val::Px(-c.thickness / 2.0),
164                    ..default()
165                },
166                BackgroundColor(color),
167            ));
168            // Top arm
169            root.spawn((
170                CrosshairNode,
171                Node {
172                    position_type: PositionType::Absolute,
173                    width: Val::Px(c.thickness),
174                    height: Val::Px(c.size),
175                    left: Val::Px(-c.thickness / 2.0),
176                    bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
177                    ..default()
178                },
179                BackgroundColor(color),
180            ));
181            // Bottom arm
182            root.spawn((
183                CrosshairNode,
184                Node {
185                    position_type: PositionType::Absolute,
186                    width: Val::Px(c.thickness),
187                    height: Val::Px(c.size),
188                    left: Val::Px(-c.thickness / 2.0),
189                    top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
190                    ..default()
191                },
192                BackgroundColor(color),
193            ));
194        });
195}
196
197/// Plugin that renders a fixed center-screen crosshair using four UI quads.
198///
199/// The crosshair is built from four [`Node`] rectangles (left, right, top,
200/// bottom arms) positioned with `PositionType::Absolute` relative to a full-
201/// screen container. No images or asset loading are required.
202///
203/// Customize appearance by inserting [`CrosshairConfig`] before adding this
204/// plugin. If [`CrosshairConfig::visible`] is `false`, no entities are spawned.
205///
206/// # Example
207///
208/// ```rust,no_run
209/// use bevy::prelude::*;
210/// use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
211///
212/// App::new()
213///     .insert_resource(CrosshairConfig {
214///         color: [0.0, 1.0, 0.0, 0.9],
215///         gap: 6.0,
216///         ..Default::default()
217///     })
218///     .add_plugins(CrosshairPlugin);
219/// ```
220pub struct CrosshairPlugin;
221
222impl Plugin for CrosshairPlugin {
223    fn build(&self, app: &mut App) {
224        app.init_resource::<CrosshairConfig>();
225        app.add_systems(Startup, spawn_crosshair);
226    }
227}
228
229// ─── Loading Screen ───────────────────────────────────────────────────────────
230
231/// Visual configuration for the [`LoadingScreenPlugin`] overlay.
232///
233/// Insert this resource before adding [`LoadingScreenPlugin`] to override
234/// defaults. Values are read once on `Startup` when the overlay is spawned.
235///
236/// # Default values
237///
238/// | Field              | Default                                   |
239/// |--------------------|-------------------------------------------|
240/// | `background_color` | `[0.05, 0.05, 0.05, 0.95]` (near-black)  |
241/// | `text_color`       | `[1, 1, 1, 1]` (white)                    |
242/// | `title`            | `"Loading..."`                             |
243/// | `show_progress_bar`| `true`                                    |
244#[derive(Resource, Debug, Clone)]
245pub struct LoadingScreenConfig {
246    /// RGBA background color of the full-screen overlay in linear sRGB. The
247    /// default near-black with high alpha (`0.95`) fully obscures the 3D scene
248    /// while the world loads.
249    pub background_color: [f32; 4],
250    /// RGBA color of the loading title text in linear sRGB.
251    pub text_color: [f32; 4],
252    /// Text displayed in the center of the overlay. Updated dynamically with
253    /// `"Loading… X/Y chunks"` as [`LoadingProgress`] messages arrive.
254    pub title: String,
255    /// When `true`, a 400×20 px progress bar is rendered below the title text.
256    /// The bar fill advances from 0 % to 100 % as [`LoadingProgress::progress`]
257    /// increases from `0.0` to `1.0`.
258    pub show_progress_bar: bool,
259}
260
261impl Default for LoadingScreenConfig {
262    fn default() -> Self {
263        Self {
264            background_color: [0.05, 0.05, 0.05, 0.95],
265            text_color: [1.0, 1.0, 1.0, 1.0],
266            title: "Loading...".to_string(),
267            show_progress_bar: true,
268        }
269    }
270}
271
272/// Marker for the loading overlay root.
273#[derive(Component)]
274struct LoadingOverlay;
275
276/// Marker for the loading text entity.
277#[derive(Component)]
278struct LoadingText;
279
280/// Marker for the progress bar fill entity.
281#[derive(Component)]
282struct LoadingProgressBar;
283
284fn spawn_loading_overlay(mut commands: Commands, config: Res<LoadingScreenConfig>) {
285    let bg = Color::srgba(
286        config.background_color[0],
287        config.background_color[1],
288        config.background_color[2],
289        config.background_color[3],
290    );
291    let tc = Color::srgba(
292        config.text_color[0],
293        config.text_color[1],
294        config.text_color[2],
295        config.text_color[3],
296    );
297
298    commands
299        .spawn((
300            LoadingOverlay,
301            Node {
302                width: Val::Percent(100.0),
303                height: Val::Percent(100.0),
304                position_type: PositionType::Absolute,
305                flex_direction: FlexDirection::Column,
306                justify_content: JustifyContent::Center,
307                align_items: AlignItems::Center,
308                ..default()
309            },
310            BackgroundColor(bg),
311            ZIndex(100),
312        ))
313        .with_children(|parent| {
314            // Title + progress text
315            parent.spawn((
316                LoadingText,
317                Text::new(config.title.clone()),
318                TextFont {
319                    font_size: 32.0,
320                    ..default()
321                },
322                TextColor(tc),
323            ));
324
325            if config.show_progress_bar {
326                // Progress bar background
327                parent
328                    .spawn((
329                        Node {
330                            width: Val::Px(400.0),
331                            height: Val::Px(20.0),
332                            margin: UiRect::top(Val::Px(20.0)),
333                            ..default()
334                        },
335                        BackgroundColor(Color::srgba(0.2, 0.2, 0.2, 1.0)),
336                    ))
337                    .with_children(|bar| {
338                        // Fill
339                        bar.spawn((
340                            LoadingProgressBar,
341                            Node {
342                                width: Val::Percent(0.0),
343                                height: Val::Percent(100.0),
344                                ..default()
345                            },
346                            BackgroundColor(Color::srgba(0.2, 0.7, 0.3, 1.0)),
347                        ));
348                    });
349            }
350        });
351}
352
353fn update_loading_overlay(
354    loading_state: Res<WorldLoadingState>,
355    mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
356    mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
357    mut text_query: Query<&mut Text, With<LoadingText>>,
358    mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
359) {
360    // Hide overlay once world is ready
361    if loading_state.ready {
362        if let Ok(mut vis) = overlay_query.single_mut() {
363            *vis = Visibility::Hidden;
364        }
365        return;
366    }
367
368    // Process latest progress message
369    let mut latest: Option<LoadingProgress> = None;
370    for msg in progress_reader.read() {
371        latest = Some(msg.clone());
372    }
373
374    if let Some(progress) = latest {
375        // Update text
376        if let Ok(mut text) = text_query.single_mut() {
377            *text = Text::new(format!(
378                "Loading... {}/{} chunks",
379                progress.loaded, progress.total
380            ));
381        }
382
383        // Update progress bar width
384        if let Ok(mut node) = bar_query.single_mut() {
385            node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
386        }
387    }
388}
389
390fn despawn_loading_overlay_on_ready(
391    mut commands: Commands,
392    loading_state: Res<WorldLoadingState>,
393    overlay_query: Query<Entity, With<LoadingOverlay>>,
394) {
395    if loading_state.ready {
396        for entity in overlay_query.iter() {
397            commands.entity(entity).despawn();
398        }
399    }
400}
401
402/// Plugin that displays a full-screen loading overlay during world generation.
403///
404/// The overlay is spawned on `Startup` and updates every frame by reading
405/// [`LoadingProgress`] messages broadcast by the chunk streaming system. Once
406/// [`WorldLoadingState::ready`] flips to `true`, the overlay is hidden and then
407/// despawned to free the UI node tree.
408///
409/// Customize appearance via [`LoadingScreenConfig`] inserted before this plugin.
410///
411/// # Example
412///
413/// ```rust,no_run
414/// use bevy::prelude::*;
415/// use voxel_framework::ui::{LoadingScreenPlugin, LoadingScreenConfig};
416///
417/// App::new()
418///     .insert_resource(LoadingScreenConfig {
419///         title: "Generating universe…".to_string(),
420///         show_progress_bar: false,
421///         ..Default::default()
422///     })
423///     .add_plugins(LoadingScreenPlugin);
424/// ```
425pub struct LoadingScreenPlugin;
426
427impl Plugin for LoadingScreenPlugin {
428    fn build(&self, app: &mut App) {
429        app.init_resource::<LoadingScreenConfig>();
430        app.add_systems(Startup, spawn_loading_overlay);
431        app.add_systems(
432            Update,
433            (update_loading_overlay, despawn_loading_overlay_on_ready),
434        );
435    }
436}
437
438// ─── Hotbar UI ────────────────────────────────────────────────────────────────
439//
440// Gated on the `items` feature: the hotbar UI reads `HotbarState` and listens
441// for `HotbarSelectionChanged` messages, both defined in `crate::items`.
442
443/// Visual configuration for the [`HotbarUiPlugin`] slot row.
444///
445/// Insert this resource before adding [`HotbarUiPlugin`] to customize the
446/// hotbar. Values are consumed on `Startup`; runtime slot-count changes are not
447/// supported (the hotbar is a static layout).
448///
449/// # Default values
450///
451/// | Field            | Default                             |
452/// |------------------|-------------------------------------|
453/// | `visible`        | `true`                              |
454/// | `slot_size`      | `50.0` px                           |
455/// | `slot_gap`       | `4.0` px                            |
456/// | `slot_color`     | `[0.15, 0.15, 0.15, 0.85]` (dark)  |
457/// | `selected_color` | `[0.45, 0.45, 0.45, 0.95]` (light) |
458#[cfg(feature = "items")]
459#[derive(Resource, Debug, Clone)]
460pub struct HotbarUiConfig {
461    /// When `false`, the hotbar is not spawned. Use this to disable the hotbar
462    /// entirely without removing [`HotbarUiPlugin`] from the app.
463    pub visible: bool,
464    /// Width and height of each square slot node in logical pixels.
465    pub slot_size: f32,
466    /// Horizontal gap between adjacent slot nodes in logical pixels.
467    pub slot_gap: f32,
468    /// RGBA background color applied to unselected hotbar slots in linear sRGB.
469    pub slot_color: [f32; 4],
470    /// RGBA background color applied to the currently selected slot in linear
471    /// sRGB. Updated in real time when a [`HotbarSelectionChanged`] message fires.
472    pub selected_color: [f32; 4],
473}
474
475#[cfg(feature = "items")]
476impl Default for HotbarUiConfig {
477    fn default() -> Self {
478        Self {
479            visible: true,
480            slot_size: 50.0,
481            slot_gap: 4.0,
482            slot_color: [0.15, 0.15, 0.15, 0.85],
483            selected_color: [0.45, 0.45, 0.45, 0.95],
484        }
485    }
486}
487
488/// Marker for the hotbar root container.
489#[cfg(feature = "items")]
490#[derive(Component)]
491struct HotbarUiRoot;
492
493/// Marker for individual hotbar slot nodes. Holds the slot index.
494#[cfg(feature = "items")]
495#[derive(Component)]
496struct HotbarSlot(usize);
497
498#[cfg(feature = "items")]
499fn spawn_hotbar_ui(mut commands: Commands, config: Res<HotbarUiConfig>, hotbar: Res<HotbarState>) {
500    if !config.visible {
501        return;
502    }
503
504    let slot_color = Color::srgba(
505        config.slot_color[0],
506        config.slot_color[1],
507        config.slot_color[2],
508        config.slot_color[3],
509    );
510    let selected_color = Color::srgba(
511        config.selected_color[0],
512        config.selected_color[1],
513        config.selected_color[2],
514        config.selected_color[3],
515    );
516
517    commands
518        .spawn((
519            HotbarUiRoot,
520            Node {
521                width: Val::Percent(100.0),
522                position_type: PositionType::Absolute,
523                bottom: Val::Px(16.0),
524                flex_direction: FlexDirection::Row,
525                justify_content: JustifyContent::Center,
526                align_items: AlignItems::Center,
527                column_gap: Val::Px(config.slot_gap),
528                ..default()
529            },
530            BackgroundColor(Color::NONE),
531        ))
532        .with_children(|row| {
533            for i in 0..hotbar.slots {
534                let bg = if i == hotbar.selected {
535                    selected_color
536                } else {
537                    slot_color
538                };
539                row.spawn((
540                    HotbarSlot(i),
541                    Node {
542                        width: Val::Px(config.slot_size),
543                        height: Val::Px(config.slot_size),
544                        border: UiRect::all(Val::Px(2.0)),
545                        ..default()
546                    },
547                    BackgroundColor(bg),
548                    BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6)),
549                ));
550            }
551        });
552}
553
554#[cfg(feature = "items")]
555fn update_hotbar_selection(
556    mut selection_reader: bevy::ecs::message::MessageReader<HotbarSelectionChanged>,
557    config: Res<HotbarUiConfig>,
558    mut slot_query: Query<(&HotbarSlot, &mut BackgroundColor)>,
559) {
560    let mut new_selected: Option<usize> = None;
561    for msg in selection_reader.read() {
562        new_selected = Some(msg.slot);
563    }
564
565    let Some(selected) = new_selected else {
566        return;
567    };
568
569    let slot_color = Color::srgba(
570        config.slot_color[0],
571        config.slot_color[1],
572        config.slot_color[2],
573        config.slot_color[3],
574    );
575    let selected_color = Color::srgba(
576        config.selected_color[0],
577        config.selected_color[1],
578        config.selected_color[2],
579        config.selected_color[3],
580    );
581
582    for (slot, mut bg) in slot_query.iter_mut() {
583        bg.0 = if slot.0 == selected {
584            selected_color
585        } else {
586            slot_color
587        };
588    }
589}
590
591/// Plugin that renders a horizontal hotbar at the bottom center of the screen.
592///
593/// Reads [`HotbarState`] on startup to determine the number of slots, spawns
594/// one [`Node`] quad per slot, and listens for [`HotbarSelectionChanged`]
595/// messages to update the selected-slot highlight in real time.
596///
597/// Customize via [`HotbarUiConfig`] inserted before this plugin.
598///
599/// # Example
600///
601/// ```rust,no_run
602/// use bevy::prelude::*;
603/// use voxel_framework::ui::{HotbarUiPlugin, HotbarUiConfig};
604///
605/// App::new()
606///     .insert_resource(HotbarUiConfig {
607///         slot_size: 64.0,
608///         slot_gap: 6.0,
609///         ..Default::default()
610///     })
611///     .add_plugins(HotbarUiPlugin);
612/// ```
613#[cfg(feature = "items")]
614pub struct HotbarUiPlugin;
615
616#[cfg(feature = "items")]
617impl Plugin for HotbarUiPlugin {
618    fn build(&self, app: &mut App) {
619        app.init_resource::<HotbarUiConfig>();
620        app.add_systems(Startup, spawn_hotbar_ui);
621        app.add_systems(Update, update_hotbar_selection);
622    }
623}
624
625// ─── Pickup Notification ──────────────────────────────────────────────────────
626//
627// Gated on the `items` feature: the pickup notification system listens for
628// `ItemPickedUp<I>` messages and is meaningless without an item palette.
629
630/// Visual configuration for the [`PickupNotificationPlugin`] pop-up system.
631///
632/// Insert this resource before adding [`PickupNotificationPlugin`] to override
633/// defaults. Configuration is read once per notification spawn.
634///
635/// # Default values
636///
637/// | Field               | Default              |
638/// |---------------------|----------------------|
639/// | `visible`           | `true`               |
640/// | `duration_secs`     | `3.0` s              |
641/// | `text_color`        | `[1, 1, 1, 1]` (white) |
642/// | `max_notifications` | `5`                  |
643#[cfg(feature = "items")]
644#[derive(Resource, Debug, Clone)]
645pub struct PickupNotificationConfig {
646    /// When `false`, no notification entities are spawned even when
647    /// [`ItemPickedUp`] messages fire.
648    pub visible: bool,
649    /// How long each notification text persists on screen in seconds before
650    /// being automatically despawned. Applied per-notification via a
651    /// [`Timer`].
652    pub duration_secs: f32,
653    /// RGBA color of the notification text in linear sRGB.
654    pub text_color: [f32; 4],
655    /// Maximum number of notifications displayed at the same time. When a new
656    /// pickup would exceed this limit, the oldest visible notification is
657    /// despawned first to make room.
658    pub max_notifications: usize,
659}
660
661#[cfg(feature = "items")]
662impl Default for PickupNotificationConfig {
663    fn default() -> Self {
664        Self {
665            visible: true,
666            duration_secs: 3.0,
667            text_color: [1.0, 1.0, 1.0, 1.0],
668            max_notifications: 5,
669        }
670    }
671}
672
673/// Timer component on each notification entity.
674#[cfg(feature = "items")]
675#[derive(Component)]
676struct NotificationTimer(Timer);
677
678/// Marker for the notification container.
679#[cfg(feature = "items")]
680#[derive(Component)]
681struct NotificationContainer;
682
683#[cfg(feature = "items")]
684fn spawn_notification_container(mut commands: Commands) {
685    commands.spawn((
686        NotificationContainer,
687        Node {
688            position_type: PositionType::Absolute,
689            top: Val::Px(16.0),
690            right: Val::Px(16.0),
691            flex_direction: FlexDirection::Column,
692            row_gap: Val::Px(4.0),
693            align_items: AlignItems::FlexEnd,
694            ..default()
695        },
696        BackgroundColor(Color::NONE),
697    ));
698}
699
700#[cfg(feature = "items")]
701fn on_item_picked_up<I: ItemType>(
702    mut commands: Commands,
703    mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
704    config: Res<PickupNotificationConfig>,
705    container_query: Query<Entity, With<NotificationContainer>>,
706    existing_query: Query<Entity, With<NotificationTimer>>,
707) {
708    if !config.visible {
709        return;
710    }
711
712    // Collect all pickups this frame
713    let pickups: Vec<(String, u32)> = pickup_reader
714        .read()
715        .map(|p| (p.item.name().to_string(), p.count))
716        .collect();
717
718    if pickups.is_empty() {
719        return;
720    }
721
722    let Ok(container) = container_query.single() else {
723        return;
724    };
725
726    let tc = Color::srgba(
727        config.text_color[0],
728        config.text_color[1],
729        config.text_color[2],
730        config.text_color[3],
731    );
732
733    // Enforce max_notifications — despawn oldest first
734    let existing: Vec<Entity> = existing_query.iter().collect();
735    let available = config.max_notifications.saturating_sub(existing.len());
736    let spawn_count = pickups.len().min(available);
737
738    if existing.len() + pickups.len() > config.max_notifications {
739        let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
740        for entity in existing.iter().take(overflow) {
741            commands.entity(*entity).despawn();
742        }
743    }
744
745    for (name, count) in pickups.iter().take(spawn_count) {
746        let label = format!("+{count} {name}");
747        let notification = commands
748            .spawn((
749                NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
750                Text::new(label),
751                TextFont {
752                    font_size: 18.0,
753                    ..default()
754                },
755                TextColor(tc),
756                Node { ..default() },
757            ))
758            .id();
759        commands.entity(container).add_child(notification);
760    }
761}
762
763#[cfg(feature = "items")]
764fn tick_notifications(
765    mut commands: Commands,
766    time: Res<Time>,
767    mut query: Query<(Entity, &mut NotificationTimer)>,
768) {
769    for (entity, mut timer) in query.iter_mut() {
770        timer.0.tick(time.delta());
771        if timer.0.just_finished() {
772            commands.entity(entity).despawn();
773        }
774    }
775}
776
777/// Plugin that displays timed item-pickup notifications at the top-right corner.
778///
779/// Listens for [`ItemPickedUp<I>`] messages and spawns a text node formatted as
780/// `"+N ItemName"` for each pickup. Notifications fade out after
781/// [`PickupNotificationConfig::duration_secs`] and are despawned automatically.
782///
783/// When the number of simultaneous notifications would exceed
784/// [`PickupNotificationConfig::max_notifications`], the oldest notifications are
785/// despawned first.
786///
787/// The plugin is **generic over the item type** `I: ItemType`. Use [`UiPlugin`]
788/// for the built-in [`DefaultItem`], or add this plugin manually with a custom
789/// item type:
790///
791/// ```rust,no_run
792/// use bevy::prelude::*;
793/// use voxel_framework::ui::PickupNotificationPlugin;
794/// # use voxel_framework::items::inventory::ItemType;
795/// # #[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
796/// # struct MyItem;
797/// # impl ItemType for MyItem {
798/// #     fn name(&self) -> &'static str { "item" }
799/// #     fn color(&self) -> [f32; 4] { [1.0, 1.0, 1.0, 1.0] }
800/// #     fn to_byte(&self) -> u8 { 0 }
801/// #     fn from_byte(_: u8) -> Self { Self }
802/// # }
803///
804/// App::new().add_plugins(PickupNotificationPlugin::<MyItem>::new());
805/// ```
806#[cfg(feature = "items")]
807pub struct PickupNotificationPlugin<I: ItemType> {
808    _marker: std::marker::PhantomData<I>,
809}
810
811#[cfg(feature = "items")]
812impl<I: ItemType> PickupNotificationPlugin<I> {
813    pub fn new() -> Self {
814        Self {
815            _marker: std::marker::PhantomData,
816        }
817    }
818}
819
820#[cfg(feature = "items")]
821impl<I: ItemType> Default for PickupNotificationPlugin<I> {
822    fn default() -> Self {
823        Self::new()
824    }
825}
826
827#[cfg(feature = "items")]
828impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
829    fn build(&self, app: &mut App) {
830        app.init_resource::<PickupNotificationConfig>();
831        // Ensure the message is registered even if DropsPlugin<I> is not used.
832        app.add_message::<ItemPickedUp<I>>();
833        app.add_systems(Startup, spawn_notification_container);
834        app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
835    }
836}
837
838mod pause_menu;
839pub use pause_menu::{PauseMenuConfig, PauseMenuPlugin, PauseMenuState, SaveSettingsRequest};
840
841// ─── Debug Overlay ────────────────────────────────────────────────────────────
842
843use crate::chunk::world_to_chunk_coord;
844use crate::player::Player;
845use crate::world::ChunkManager;
846use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
847
848/// Tracks whether the debug overlay (F3) is currently visible.
849#[derive(Resource, Default)]
850pub struct DebugOverlayState {
851    /// When `true` the overlay is rendered; toggle with **F3**.
852    pub visible: bool,
853}
854
855/// Marker component for the debug overlay root node.
856#[derive(Component)]
857struct DebugOverlay;
858
859/// Marker for the individual text lines (index 0–3).
860#[derive(Component)]
861struct DebugLine(usize);
862
863fn spawn_debug_overlay(mut commands: Commands) {
864    commands
865        .spawn((
866            DebugOverlay,
867            Node {
868                position_type: PositionType::Absolute,
869                top: Val::Px(8.0),
870                left: Val::Px(8.0),
871                flex_direction: FlexDirection::Column,
872                row_gap: Val::Px(2.0),
873                padding: UiRect::all(Val::Px(6.0)),
874                ..default()
875            },
876            BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
877            Visibility::Hidden,
878            ZIndex(200),
879        ))
880        .with_children(|root| {
881            let style = TextFont {
882                font_size: 14.0,
883                ..default()
884            };
885            let color = TextColor(Color::WHITE);
886            for i in 0..4 {
887                root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
888            }
889        });
890}
891
892fn update_debug_overlay(
893    keys: Res<ButtonInput<KeyCode>>,
894    mut state: ResMut<DebugOverlayState>,
895    mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
896    mut line_q: Query<(&DebugLine, &mut Text)>,
897    player_q: Query<&Transform, With<Player>>,
898    manager: Res<ChunkManager>,
899    diagnostics: Res<DiagnosticsStore>,
900) {
901    // Toggle visibility on F3 press.
902    if keys.just_pressed(KeyCode::F3) {
903        state.visible = !state.visible;
904        if let Ok(mut vis) = overlay_q.single_mut() {
905            *vis = if state.visible {
906                Visibility::Visible
907            } else {
908                Visibility::Hidden
909            };
910        }
911    }
912
913    if !state.visible {
914        return;
915    }
916
917    let pos = player_q
918        .single()
919        .map(|t| t.translation)
920        .unwrap_or(Vec3::ZERO);
921
922    let chunk = world_to_chunk_coord(pos);
923    let fps = diagnostics
924        .get(&FrameTimeDiagnosticsPlugin::FPS)
925        .and_then(|d| d.smoothed())
926        .unwrap_or(0.0);
927    let chunk_count = manager.loaded_count();
928
929    let lines = [
930        format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
931        format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
932        format!("FPS: {fps:.0}"),
933        format!("Chunks: {chunk_count}"),
934    ];
935
936    for (line_marker, mut text) in line_q.iter_mut() {
937        if let Some(content) = lines.get(line_marker.0) {
938            *text = Text::new(content.clone());
939        }
940    }
941}
942
943/// Plugin that renders a debug information overlay toggled with **F3**.
944///
945/// Shows player XYZ position, current chunk coordinate, FPS, and loaded chunk
946/// count. The overlay is hidden by default; press **F3** to show or hide it.
947///
948/// Automatically adds [`FrameTimeDiagnosticsPlugin`] for FPS measurement.
949///
950/// # Example
951///
952/// ```rust,no_run
953/// use bevy::prelude::*;
954/// use voxel_framework::ui::DebugOverlayPlugin;
955///
956/// App::new().add_plugins(DebugOverlayPlugin);
957/// ```
958pub struct DebugOverlayPlugin;
959
960impl Plugin for DebugOverlayPlugin {
961    fn build(&self, app: &mut App) {
962        app.add_plugins(FrameTimeDiagnosticsPlugin::default());
963        app.init_resource::<DebugOverlayState>();
964        app.add_systems(Startup, spawn_debug_overlay);
965        app.add_systems(Update, update_debug_overlay);
966    }
967}
968
969// ─── (InventoryUiPlugin removed — games provide their own inventory UI) ───────
970
971// ─── UiPlugin (umbrella) ──────────────────────────────────────────────────────
972
973#[cfg(feature = "items")]
974use crate::items::inventory::DefaultItem;
975
976/// Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`].
977///
978/// Equivalent to adding [`CrosshairPlugin`], [`LoadingScreenPlugin`],
979/// [`HotbarUiPlugin`], and [`PickupNotificationPlugin::<DefaultItem>`] in one
980/// call. Configuration resources for each sub-plugin can still be inserted
981/// individually before `UiPlugin` is added to override their defaults.
982///
983/// To use a custom item type for pickup notifications, skip `UiPlugin` and add
984/// [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins
985/// individually.
986///
987/// # Example
988///
989/// ```rust,no_run
990/// use bevy::prelude::*;
991/// use voxel_framework::ui::UiPlugin;
992///
993/// App::new()
994///     .add_plugins(DefaultPlugins)
995///     .add_plugins(UiPlugin);
996/// ```
997pub struct UiPlugin;
998
999impl Plugin for UiPlugin {
1000    fn build(&self, app: &mut App) {
1001        app.add_plugins(CrosshairPlugin);
1002        app.add_plugins(LoadingScreenPlugin);
1003        #[cfg(feature = "items")]
1004        app.add_plugins(HotbarUiPlugin);
1005        #[cfg(feature = "items")]
1006        app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
1007    }
1008}