1#![cfg_attr(
16 feature = "items",
17 doc = "| [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |"
18)]
19#![cfg_attr(
20 not(feature = "items"),
21 doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed top-right pop-up text on item pickup |"
22)]
23#![cfg_attr(
28 feature = "items",
29 doc = "Use [`UiPlugin`] when your game uses [`DefaultItem`] and wants all four HUD elements with zero configuration:"
30)]
31#![cfg_attr(
32 not(feature = "items"),
33 doc = "Use [`UiPlugin`] with the default `items` feature when your game uses `DefaultItem` and wants all four HUD elements with zero configuration:"
34)]
35use bevy::prelude::*;
72
73#[cfg(feature = "items")]
74use crate::items::inventory::ItemPickedUp;
75#[cfg(feature = "items")]
76use crate::items::inventory::ItemType;
77use crate::world::loading::{LoadingProgress, WorldLoadingState};
78
79pub mod hud;
81pub use hud::{
82 HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
83 HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
84 HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
85 HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
86 HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
87 MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
88};
89
90#[derive(Resource, Debug, Clone)]
109pub struct CrosshairConfig {
110 pub color: [f32; 4],
113 pub size: f32,
116 pub gap: f32,
119 pub thickness: f32,
122 pub visible: bool,
126}
127
128impl Default for CrosshairConfig {
129 fn default() -> Self {
130 Self {
131 color: [1.0, 1.0, 1.0, 1.0],
132 size: 20.0,
133 gap: 4.0,
134 thickness: 2.0,
135 visible: true,
136 }
137 }
138}
139
140#[derive(Component)]
142struct CrosshairNode;
143
144fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
145 if !config.visible {
146 return;
147 }
148
149 let c = &*config;
150 let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
151
152 commands
154 .spawn((
155 CrosshairNode,
156 Node {
157 width: Val::Percent(100.0),
158 height: Val::Percent(100.0),
159 position_type: PositionType::Absolute,
160 justify_content: JustifyContent::Center,
161 align_items: AlignItems::Center,
162 ..default()
163 },
164 BackgroundColor(Color::NONE),
165 ))
166 .with_children(|root| {
167 root.spawn((
169 CrosshairNode,
170 Node {
171 position_type: PositionType::Absolute,
172 width: Val::Px(c.size),
173 height: Val::Px(c.thickness),
174 right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
175 top: Val::Px(-c.thickness / 2.0),
176 ..default()
177 },
178 BackgroundColor(color),
179 ));
180 root.spawn((
182 CrosshairNode,
183 Node {
184 position_type: PositionType::Absolute,
185 width: Val::Px(c.size),
186 height: Val::Px(c.thickness),
187 left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
188 top: Val::Px(-c.thickness / 2.0),
189 ..default()
190 },
191 BackgroundColor(color),
192 ));
193 root.spawn((
195 CrosshairNode,
196 Node {
197 position_type: PositionType::Absolute,
198 width: Val::Px(c.thickness),
199 height: Val::Px(c.size),
200 left: Val::Px(-c.thickness / 2.0),
201 bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
202 ..default()
203 },
204 BackgroundColor(color),
205 ));
206 root.spawn((
208 CrosshairNode,
209 Node {
210 position_type: PositionType::Absolute,
211 width: Val::Px(c.thickness),
212 height: Val::Px(c.size),
213 left: Val::Px(-c.thickness / 2.0),
214 top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
215 ..default()
216 },
217 BackgroundColor(color),
218 ));
219 });
220}
221
222pub struct CrosshairPlugin;
246
247impl Plugin for CrosshairPlugin {
248 fn build(&self, app: &mut App) {
249 app.init_resource::<CrosshairConfig>();
250 app.add_systems(Startup, spawn_crosshair);
251 }
252}
253
254#[derive(Resource, Debug, Clone)]
270pub struct LoadingScreenConfig {
271 pub background_color: [f32; 4],
275 pub text_color: [f32; 4],
277 pub title: String,
280 pub show_progress_bar: bool,
284}
285
286impl Default for LoadingScreenConfig {
287 fn default() -> Self {
288 Self {
289 background_color: [0.05, 0.05, 0.05, 0.95],
290 text_color: [1.0, 1.0, 1.0, 1.0],
291 title: "Loading...".to_string(),
292 show_progress_bar: true,
293 }
294 }
295}
296
297#[derive(Component)]
299struct LoadingOverlay;
300
301#[derive(Component)]
303struct LoadingText;
304
305#[derive(Component)]
307struct LoadingProgressBar;
308
309fn spawn_loading_overlay(mut commands: Commands, config: Res<LoadingScreenConfig>) {
310 let bg = Color::srgba(
311 config.background_color[0],
312 config.background_color[1],
313 config.background_color[2],
314 config.background_color[3],
315 );
316 let tc = Color::srgba(
317 config.text_color[0],
318 config.text_color[1],
319 config.text_color[2],
320 config.text_color[3],
321 );
322
323 commands
324 .spawn((
325 LoadingOverlay,
326 Node {
327 width: Val::Percent(100.0),
328 height: Val::Percent(100.0),
329 position_type: PositionType::Absolute,
330 flex_direction: FlexDirection::Column,
331 justify_content: JustifyContent::Center,
332 align_items: AlignItems::Center,
333 ..default()
334 },
335 BackgroundColor(bg),
336 ZIndex(100),
337 ))
338 .with_children(|parent| {
339 parent.spawn((
341 LoadingText,
342 Text::new(config.title.clone()),
343 TextFont {
344 font_size: 32.0,
345 ..default()
346 },
347 TextColor(tc),
348 ));
349
350 if config.show_progress_bar {
351 parent
353 .spawn((
354 Node {
355 width: Val::Px(400.0),
356 height: Val::Px(20.0),
357 margin: UiRect::top(Val::Px(20.0)),
358 ..default()
359 },
360 BackgroundColor(Color::srgba(0.2, 0.2, 0.2, 1.0)),
361 ))
362 .with_children(|bar| {
363 bar.spawn((
365 LoadingProgressBar,
366 Node {
367 width: Val::Percent(0.0),
368 height: Val::Percent(100.0),
369 ..default()
370 },
371 BackgroundColor(Color::srgba(0.2, 0.7, 0.3, 1.0)),
372 ));
373 });
374 }
375 });
376}
377
378fn update_loading_overlay(
379 loading_state: Res<WorldLoadingState>,
380 mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
381 mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
382 mut text_query: Query<&mut Text, With<LoadingText>>,
383 mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
384) {
385 if loading_state.ready {
387 if let Ok(mut vis) = overlay_query.single_mut() {
388 *vis = Visibility::Hidden;
389 }
390 return;
391 }
392
393 let mut latest: Option<LoadingProgress> = None;
395 for msg in progress_reader.read() {
396 latest = Some(msg.clone());
397 }
398
399 if let Some(progress) = latest {
400 if let Ok(mut text) = text_query.single_mut() {
402 *text = Text::new(format!(
403 "Loading... {}/{} chunks",
404 progress.loaded, progress.total
405 ));
406 }
407
408 if let Ok(mut node) = bar_query.single_mut() {
410 node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
411 }
412 }
413}
414
415fn despawn_loading_overlay_on_ready(
416 mut commands: Commands,
417 loading_state: Res<WorldLoadingState>,
418 overlay_query: Query<Entity, With<LoadingOverlay>>,
419) {
420 if loading_state.ready {
421 for entity in overlay_query.iter() {
422 commands.entity(entity).despawn();
423 }
424 }
425}
426
427pub struct LoadingScreenPlugin;
451
452impl Plugin for LoadingScreenPlugin {
453 fn build(&self, app: &mut App) {
454 app.init_resource::<LoadingScreenConfig>();
455 app.add_systems(Startup, spawn_loading_overlay);
456 app.add_systems(
457 Update,
458 (update_loading_overlay, despawn_loading_overlay_on_ready),
459 );
460 }
461}
462
463#[cfg(feature = "items")]
465pub mod hotbar;
466#[cfg(feature = "items")]
467pub use hotbar::{HotbarContentPlugin, HotbarUiConfig, HotbarUiPlugin, ItemIconPalette};
468
469#[cfg(feature = "items")]
488#[derive(Resource, Debug, Clone)]
489pub struct PickupNotificationConfig {
490 pub visible: bool,
493 pub duration_secs: f32,
497 pub text_color: [f32; 4],
499 pub max_notifications: usize,
503}
504
505#[cfg(feature = "items")]
506impl Default for PickupNotificationConfig {
507 fn default() -> Self {
508 Self {
509 visible: true,
510 duration_secs: 3.0,
511 text_color: [1.0, 1.0, 1.0, 1.0],
512 max_notifications: 5,
513 }
514 }
515}
516
517#[cfg(feature = "items")]
519#[derive(Component)]
520struct NotificationTimer(Timer);
521
522#[cfg(feature = "items")]
524#[derive(Component)]
525struct NotificationContainer;
526
527#[cfg(feature = "items")]
528fn spawn_notification_container(mut commands: Commands) {
529 commands.spawn((
530 NotificationContainer,
531 Node {
532 position_type: PositionType::Absolute,
533 top: Val::Px(16.0),
534 right: Val::Px(16.0),
535 flex_direction: FlexDirection::Column,
536 row_gap: Val::Px(4.0),
537 align_items: AlignItems::FlexEnd,
538 ..default()
539 },
540 BackgroundColor(Color::NONE),
541 ));
542}
543
544#[cfg(feature = "items")]
545fn on_item_picked_up<I: ItemType>(
546 mut commands: Commands,
547 mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
548 config: Res<PickupNotificationConfig>,
549 container_query: Query<Entity, With<NotificationContainer>>,
550 existing_query: Query<Entity, With<NotificationTimer>>,
551) {
552 if !config.visible {
553 return;
554 }
555
556 let pickups: Vec<(String, u32)> = pickup_reader
558 .read()
559 .map(|p| (p.item.name().to_string(), p.count))
560 .collect();
561
562 if pickups.is_empty() {
563 return;
564 }
565
566 let Ok(container) = container_query.single() else {
567 return;
568 };
569
570 let tc = Color::srgba(
571 config.text_color[0],
572 config.text_color[1],
573 config.text_color[2],
574 config.text_color[3],
575 );
576
577 let existing: Vec<Entity> = existing_query.iter().collect();
579 let available = config.max_notifications.saturating_sub(existing.len());
580 let spawn_count = pickups.len().min(available);
581
582 if existing.len() + pickups.len() > config.max_notifications {
583 let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
584 for entity in existing.iter().take(overflow) {
585 commands.entity(*entity).despawn();
586 }
587 }
588
589 for (name, count) in pickups.iter().take(spawn_count) {
590 let label = format!("+{count} {name}");
591 let notification = commands
592 .spawn((
593 NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
594 Text::new(label),
595 TextFont {
596 font_size: 18.0,
597 ..default()
598 },
599 TextColor(tc),
600 Node { ..default() },
601 ))
602 .id();
603 commands.entity(container).add_child(notification);
604 }
605}
606
607#[cfg(feature = "items")]
608fn tick_notifications(
609 mut commands: Commands,
610 time: Res<Time>,
611 mut query: Query<(Entity, &mut NotificationTimer)>,
612) {
613 for (entity, mut timer) in query.iter_mut() {
614 timer.0.tick(time.delta());
615 if timer.0.just_finished() {
616 commands.entity(entity).despawn();
617 }
618 }
619}
620
621#[cfg(feature = "items")]
651pub struct PickupNotificationPlugin<I: ItemType> {
652 _marker: std::marker::PhantomData<I>,
653}
654
655#[cfg(feature = "items")]
656impl<I: ItemType> PickupNotificationPlugin<I> {
657 pub fn new() -> Self {
658 Self {
659 _marker: std::marker::PhantomData,
660 }
661 }
662}
663
664#[cfg(feature = "items")]
665impl<I: ItemType> Default for PickupNotificationPlugin<I> {
666 fn default() -> Self {
667 Self::new()
668 }
669}
670
671#[cfg(feature = "items")]
672impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
673 fn build(&self, app: &mut App) {
674 app.init_resource::<PickupNotificationConfig>();
675 app.add_message::<ItemPickedUp<I>>();
677 app.add_systems(Startup, spawn_notification_container);
678 app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
679 }
680}
681
682mod pause_menu;
683pub use pause_menu::{PauseMenuConfig, PauseMenuPlugin, PauseMenuState, SaveSettingsRequest};
684
685use crate::chunk::world_to_chunk_coord;
688use crate::player::Player;
689use crate::world::ChunkManager;
690use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
691
692#[derive(Resource, Default)]
694pub struct DebugOverlayState {
695 pub visible: bool,
697}
698
699#[derive(Component)]
701struct DebugOverlay;
702
703#[derive(Component)]
705struct DebugLine(usize);
706
707fn spawn_debug_overlay(mut commands: Commands) {
708 commands
709 .spawn((
710 DebugOverlay,
711 Node {
712 position_type: PositionType::Absolute,
713 top: Val::Px(8.0),
714 left: Val::Px(8.0),
715 flex_direction: FlexDirection::Column,
716 row_gap: Val::Px(2.0),
717 padding: UiRect::all(Val::Px(6.0)),
718 ..default()
719 },
720 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
721 Visibility::Hidden,
722 ZIndex(200),
723 ))
724 .with_children(|root| {
725 let style = TextFont {
726 font_size: 14.0,
727 ..default()
728 };
729 let color = TextColor(Color::WHITE);
730 for i in 0..4 {
731 root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
732 }
733 });
734}
735
736fn update_debug_overlay(
737 keys: Res<ButtonInput<KeyCode>>,
738 mut state: ResMut<DebugOverlayState>,
739 mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
740 mut line_q: Query<(&DebugLine, &mut Text)>,
741 player_q: Query<&Transform, With<Player>>,
742 manager: Res<ChunkManager>,
743 diagnostics: Res<DiagnosticsStore>,
744) {
745 if keys.just_pressed(KeyCode::F3) {
747 state.visible = !state.visible;
748 if let Ok(mut vis) = overlay_q.single_mut() {
749 *vis = if state.visible {
750 Visibility::Visible
751 } else {
752 Visibility::Hidden
753 };
754 }
755 }
756
757 if !state.visible {
758 return;
759 }
760
761 let pos = player_q
762 .single()
763 .map(|t| t.translation)
764 .unwrap_or(Vec3::ZERO);
765
766 let chunk = world_to_chunk_coord(pos);
767 let fps = diagnostics
768 .get(&FrameTimeDiagnosticsPlugin::FPS)
769 .and_then(|d| d.smoothed())
770 .unwrap_or(0.0);
771 let chunk_count = manager.loaded_count();
772
773 let lines = [
774 format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
775 format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
776 format!("FPS: {fps:.0}"),
777 format!("Chunks: {chunk_count}"),
778 ];
779
780 for (line_marker, mut text) in line_q.iter_mut() {
781 if let Some(content) = lines.get(line_marker.0) {
782 *text = Text::new(content.clone());
783 }
784 }
785}
786
787pub struct DebugOverlayPlugin;
803
804impl Plugin for DebugOverlayPlugin {
805 fn build(&self, app: &mut App) {
806 app.add_plugins(FrameTimeDiagnosticsPlugin::default());
807 app.init_resource::<DebugOverlayState>();
808 app.add_systems(Startup, spawn_debug_overlay);
809 app.add_systems(Update, update_debug_overlay);
810 }
811}
812
813#[cfg(feature = "items")]
818use crate::items::inventory::DefaultItem;
819
820#[cfg_attr(
821 feature = "items",
822 doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
823)]
824#[cfg_attr(
825 not(feature = "items"),
826 doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
827)]
828#[cfg_attr(
830 feature = "items",
831 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."
832)]
833#[cfg_attr(
834 not(feature = "items"),
835 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."
836)]
837#[cfg_attr(
839 feature = "items",
840 doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
841)]
842#[cfg_attr(
843 not(feature = "items"),
844 doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
845)]
846pub struct UiPlugin;
858
859impl Plugin for UiPlugin {
860 fn build(&self, app: &mut App) {
861 app.add_plugins(CrosshairPlugin);
862 app.add_plugins(LoadingScreenPlugin);
863 #[cfg(feature = "items")]
864 app.add_plugins(HotbarUiPlugin);
865 #[cfg(feature = "items")]
866 app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
867 }
868}