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::*;
70
71#[cfg(feature = "items")]
72use crate::items::hotbar::{HotbarSelectionChanged, HotbarState};
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")]
484#[derive(Resource, Debug, Clone)]
485pub struct HotbarUiConfig {
486 pub visible: bool,
489 pub slot_size: f32,
491 pub slot_gap: f32,
493 pub slot_color: [f32; 4],
495 pub selected_color: [f32; 4],
498}
499
500#[cfg(feature = "items")]
501impl Default for HotbarUiConfig {
502 fn default() -> Self {
503 Self {
504 visible: true,
505 slot_size: 50.0,
506 slot_gap: 4.0,
507 slot_color: [0.15, 0.15, 0.15, 0.85],
508 selected_color: [0.45, 0.45, 0.45, 0.95],
509 }
510 }
511}
512
513#[cfg(feature = "items")]
515#[derive(Component)]
516struct HotbarUiRoot;
517
518#[cfg(feature = "items")]
520#[derive(Component)]
521struct HotbarSlot(usize);
522
523#[cfg(feature = "items")]
524fn spawn_hotbar_ui(mut commands: Commands, config: Res<HotbarUiConfig>, hotbar: Res<HotbarState>) {
525 if !config.visible {
526 return;
527 }
528
529 let slot_color = Color::srgba(
530 config.slot_color[0],
531 config.slot_color[1],
532 config.slot_color[2],
533 config.slot_color[3],
534 );
535 let selected_color = Color::srgba(
536 config.selected_color[0],
537 config.selected_color[1],
538 config.selected_color[2],
539 config.selected_color[3],
540 );
541
542 commands
543 .spawn((
544 HotbarUiRoot,
545 Node {
546 width: Val::Percent(100.0),
547 position_type: PositionType::Absolute,
548 bottom: Val::Px(16.0),
549 flex_direction: FlexDirection::Row,
550 justify_content: JustifyContent::Center,
551 align_items: AlignItems::Center,
552 column_gap: Val::Px(config.slot_gap),
553 ..default()
554 },
555 BackgroundColor(Color::NONE),
556 ))
557 .with_children(|row| {
558 for i in 0..hotbar.slots {
559 let bg = if i == hotbar.selected {
560 selected_color
561 } else {
562 slot_color
563 };
564 row.spawn((
565 HotbarSlot(i),
566 Node {
567 width: Val::Px(config.slot_size),
568 height: Val::Px(config.slot_size),
569 border: UiRect::all(Val::Px(2.0)),
570 ..default()
571 },
572 BackgroundColor(bg),
573 BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6)),
574 ));
575 }
576 });
577}
578
579#[cfg(feature = "items")]
580fn update_hotbar_selection(
581 mut selection_reader: bevy::ecs::message::MessageReader<HotbarSelectionChanged>,
582 config: Res<HotbarUiConfig>,
583 mut slot_query: Query<(&HotbarSlot, &mut BackgroundColor)>,
584) {
585 let mut new_selected: Option<usize> = None;
586 for msg in selection_reader.read() {
587 new_selected = Some(msg.slot);
588 }
589
590 let Some(selected) = new_selected else {
591 return;
592 };
593
594 let slot_color = Color::srgba(
595 config.slot_color[0],
596 config.slot_color[1],
597 config.slot_color[2],
598 config.slot_color[3],
599 );
600 let selected_color = Color::srgba(
601 config.selected_color[0],
602 config.selected_color[1],
603 config.selected_color[2],
604 config.selected_color[3],
605 );
606
607 for (slot, mut bg) in slot_query.iter_mut() {
608 bg.0 = if slot.0 == selected {
609 selected_color
610 } else {
611 slot_color
612 };
613 }
614}
615
616#[cfg(feature = "items")]
639pub struct HotbarUiPlugin;
640
641#[cfg(feature = "items")]
642impl Plugin for HotbarUiPlugin {
643 fn build(&self, app: &mut App) {
644 app.init_resource::<HotbarUiConfig>();
645 app.add_systems(Startup, spawn_hotbar_ui);
646 app.add_systems(Update, update_hotbar_selection);
647 }
648}
649
650#[cfg(feature = "items")]
669#[derive(Resource, Debug, Clone)]
670pub struct PickupNotificationConfig {
671 pub visible: bool,
674 pub duration_secs: f32,
678 pub text_color: [f32; 4],
680 pub max_notifications: usize,
684}
685
686#[cfg(feature = "items")]
687impl Default for PickupNotificationConfig {
688 fn default() -> Self {
689 Self {
690 visible: true,
691 duration_secs: 3.0,
692 text_color: [1.0, 1.0, 1.0, 1.0],
693 max_notifications: 5,
694 }
695 }
696}
697
698#[cfg(feature = "items")]
700#[derive(Component)]
701struct NotificationTimer(Timer);
702
703#[cfg(feature = "items")]
705#[derive(Component)]
706struct NotificationContainer;
707
708#[cfg(feature = "items")]
709fn spawn_notification_container(mut commands: Commands) {
710 commands.spawn((
711 NotificationContainer,
712 Node {
713 position_type: PositionType::Absolute,
714 top: Val::Px(16.0),
715 right: Val::Px(16.0),
716 flex_direction: FlexDirection::Column,
717 row_gap: Val::Px(4.0),
718 align_items: AlignItems::FlexEnd,
719 ..default()
720 },
721 BackgroundColor(Color::NONE),
722 ));
723}
724
725#[cfg(feature = "items")]
726fn on_item_picked_up<I: ItemType>(
727 mut commands: Commands,
728 mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
729 config: Res<PickupNotificationConfig>,
730 container_query: Query<Entity, With<NotificationContainer>>,
731 existing_query: Query<Entity, With<NotificationTimer>>,
732) {
733 if !config.visible {
734 return;
735 }
736
737 let pickups: Vec<(String, u32)> = pickup_reader
739 .read()
740 .map(|p| (p.item.name().to_string(), p.count))
741 .collect();
742
743 if pickups.is_empty() {
744 return;
745 }
746
747 let Ok(container) = container_query.single() else {
748 return;
749 };
750
751 let tc = Color::srgba(
752 config.text_color[0],
753 config.text_color[1],
754 config.text_color[2],
755 config.text_color[3],
756 );
757
758 let existing: Vec<Entity> = existing_query.iter().collect();
760 let available = config.max_notifications.saturating_sub(existing.len());
761 let spawn_count = pickups.len().min(available);
762
763 if existing.len() + pickups.len() > config.max_notifications {
764 let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
765 for entity in existing.iter().take(overflow) {
766 commands.entity(*entity).despawn();
767 }
768 }
769
770 for (name, count) in pickups.iter().take(spawn_count) {
771 let label = format!("+{count} {name}");
772 let notification = commands
773 .spawn((
774 NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
775 Text::new(label),
776 TextFont {
777 font_size: 18.0,
778 ..default()
779 },
780 TextColor(tc),
781 Node { ..default() },
782 ))
783 .id();
784 commands.entity(container).add_child(notification);
785 }
786}
787
788#[cfg(feature = "items")]
789fn tick_notifications(
790 mut commands: Commands,
791 time: Res<Time>,
792 mut query: Query<(Entity, &mut NotificationTimer)>,
793) {
794 for (entity, mut timer) in query.iter_mut() {
795 timer.0.tick(time.delta());
796 if timer.0.just_finished() {
797 commands.entity(entity).despawn();
798 }
799 }
800}
801
802#[cfg(feature = "items")]
832pub struct PickupNotificationPlugin<I: ItemType> {
833 _marker: std::marker::PhantomData<I>,
834}
835
836#[cfg(feature = "items")]
837impl<I: ItemType> PickupNotificationPlugin<I> {
838 pub fn new() -> Self {
839 Self {
840 _marker: std::marker::PhantomData,
841 }
842 }
843}
844
845#[cfg(feature = "items")]
846impl<I: ItemType> Default for PickupNotificationPlugin<I> {
847 fn default() -> Self {
848 Self::new()
849 }
850}
851
852#[cfg(feature = "items")]
853impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
854 fn build(&self, app: &mut App) {
855 app.init_resource::<PickupNotificationConfig>();
856 app.add_message::<ItemPickedUp<I>>();
858 app.add_systems(Startup, spawn_notification_container);
859 app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
860 }
861}
862
863mod pause_menu;
864pub use pause_menu::{PauseMenuConfig, PauseMenuPlugin, PauseMenuState, SaveSettingsRequest};
865
866use crate::chunk::world_to_chunk_coord;
869use crate::player::Player;
870use crate::world::ChunkManager;
871use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
872
873#[derive(Resource, Default)]
875pub struct DebugOverlayState {
876 pub visible: bool,
878}
879
880#[derive(Component)]
882struct DebugOverlay;
883
884#[derive(Component)]
886struct DebugLine(usize);
887
888fn spawn_debug_overlay(mut commands: Commands) {
889 commands
890 .spawn((
891 DebugOverlay,
892 Node {
893 position_type: PositionType::Absolute,
894 top: Val::Px(8.0),
895 left: Val::Px(8.0),
896 flex_direction: FlexDirection::Column,
897 row_gap: Val::Px(2.0),
898 padding: UiRect::all(Val::Px(6.0)),
899 ..default()
900 },
901 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
902 Visibility::Hidden,
903 ZIndex(200),
904 ))
905 .with_children(|root| {
906 let style = TextFont {
907 font_size: 14.0,
908 ..default()
909 };
910 let color = TextColor(Color::WHITE);
911 for i in 0..4 {
912 root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
913 }
914 });
915}
916
917fn update_debug_overlay(
918 keys: Res<ButtonInput<KeyCode>>,
919 mut state: ResMut<DebugOverlayState>,
920 mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
921 mut line_q: Query<(&DebugLine, &mut Text)>,
922 player_q: Query<&Transform, With<Player>>,
923 manager: Res<ChunkManager>,
924 diagnostics: Res<DiagnosticsStore>,
925) {
926 if keys.just_pressed(KeyCode::F3) {
928 state.visible = !state.visible;
929 if let Ok(mut vis) = overlay_q.single_mut() {
930 *vis = if state.visible {
931 Visibility::Visible
932 } else {
933 Visibility::Hidden
934 };
935 }
936 }
937
938 if !state.visible {
939 return;
940 }
941
942 let pos = player_q
943 .single()
944 .map(|t| t.translation)
945 .unwrap_or(Vec3::ZERO);
946
947 let chunk = world_to_chunk_coord(pos);
948 let fps = diagnostics
949 .get(&FrameTimeDiagnosticsPlugin::FPS)
950 .and_then(|d| d.smoothed())
951 .unwrap_or(0.0);
952 let chunk_count = manager.loaded_count();
953
954 let lines = [
955 format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
956 format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
957 format!("FPS: {fps:.0}"),
958 format!("Chunks: {chunk_count}"),
959 ];
960
961 for (line_marker, mut text) in line_q.iter_mut() {
962 if let Some(content) = lines.get(line_marker.0) {
963 *text = Text::new(content.clone());
964 }
965 }
966}
967
968pub struct DebugOverlayPlugin;
984
985impl Plugin for DebugOverlayPlugin {
986 fn build(&self, app: &mut App) {
987 app.add_plugins(FrameTimeDiagnosticsPlugin::default());
988 app.init_resource::<DebugOverlayState>();
989 app.add_systems(Startup, spawn_debug_overlay);
990 app.add_systems(Update, update_debug_overlay);
991 }
992}
993
994#[cfg(feature = "items")]
999use crate::items::inventory::DefaultItem;
1000
1001#[cfg_attr(
1002 feature = "items",
1003 doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
1004)]
1005#[cfg_attr(
1006 not(feature = "items"),
1007 doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
1008)]
1009#[cfg_attr(
1011 feature = "items",
1012 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."
1013)]
1014#[cfg_attr(
1015 not(feature = "items"),
1016 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."
1017)]
1018#[cfg_attr(
1020 feature = "items",
1021 doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
1022)]
1023#[cfg_attr(
1024 not(feature = "items"),
1025 doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
1026)]
1027pub struct UiPlugin;
1039
1040impl Plugin for UiPlugin {
1041 fn build(&self, app: &mut App) {
1042 app.add_plugins(CrosshairPlugin);
1043 app.add_plugins(LoadingScreenPlugin);
1044 #[cfg(feature = "items")]
1045 app.add_plugins(HotbarUiPlugin);
1046 #[cfg(feature = "items")]
1047 app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
1048 }
1049}