1#![expect(non_local_definitions)] mod animation;
3mod bag;
4mod buffs;
5mod buttons;
6mod change_notification;
7mod chat;
8mod crafting;
9mod diary;
10mod esc_menu;
11mod group;
12mod hotbar;
13mod loot_scroller;
14mod map;
15mod minimap;
16mod overhead;
17mod overitem;
18mod popup;
19mod prompt_dialog;
20mod quest;
21mod settings_window;
22mod skillbar;
23mod slots;
24mod social;
25mod subtitles;
26mod trade;
27
28pub mod img_ids;
29pub mod item_imgs;
30pub mod util;
31
32pub use chat::MessageBacklog;
33pub use crafting::CraftingTab;
34pub use hotbar::{SlotContents as HotbarSlotContents, State as HotbarState};
35pub use item_imgs::animate_by_pulse;
36pub use loot_scroller::LootMessage;
37pub use settings_window::ScaleChange;
38pub use subtitles::Subtitle;
39
40use bag::Bag;
41use buffs::BuffsBar;
42use buttons::Buttons;
43use change_notification::{ChangeNotification, NotificationReason};
44use chat::Chat;
45use chrono::NaiveTime;
46use crafting::Crafting;
47use diary::{Diary, SelectedSkillTree};
48use esc_menu::EscMenu;
49use group::Group;
50use img_ids::Imgs;
51use item_imgs::ItemImgs;
52use loot_scroller::LootScroller;
53use map::Map;
54use minimap::{MiniMap, VoxelMinimap};
55use popup::Popup;
56use prompt_dialog::PromptDialog;
57use quest::Quest;
58use serde::{Deserialize, Serialize};
59use settings_window::{SettingsTab, SettingsWindow};
60use skillbar::Skillbar;
61use social::Social;
62use subtitles::Subtitles;
63use trade::Trade;
64
65use crate::{
66 GlobalState,
67 audio::ActiveChannels,
68 ecs::comp::{self as vcomp, HpFloater, HpFloaterList},
69 game_input::GameInput,
70 hud::{img_ids::ImgsRot, prompt_dialog::DialogOutcomeEvent},
71 key_state::KeyState,
72 render::UiDrawer,
73 scene::{
74 SceneData,
75 camera::{self, Camera},
76 },
77 session::{
78 interactable::{self, BlockInteraction, EntityInteraction},
79 settings_change::{
80 Audio, Chat as ChatChange, Interface as InterfaceChange, Inventory, SettingsChange,
81 },
82 },
83 settings::chat::ChatFilter,
84 ui::{
85 Graphic, Ingameable, ScaleMode, Ui,
86 fonts::Fonts,
87 img_ids::Rotations,
88 slot::{self, SlotKey},
89 },
90 window::Event as WinEvent,
91};
92use client::{Client, UserNotification};
93use common::{
94 combat,
95 comp::{
96 self, BuffData, BuffKind, Content, Health, Item, MapMarkerChange, PickupItem, PresenceKind,
97 ability::{AuxiliaryAbility, Stance},
98 fluid_dynamics,
99 inventory::{
100 CollectFailedReason, InventorySortOrder,
101 slot::{InvSlotId, Slot},
102 trade_pricing::TradePricing,
103 },
104 item::{
105 ItemDefinitionIdOwned, ItemDesc, ItemI18n, MaterialStatManifest, Quality,
106 tool::{AbilityContext, ToolKind},
107 },
108 loot_owner::LootOwnerKind,
109 skillset::{SkillGroupKind, SkillsPersistenceError, skills::Skill},
110 },
111 consts::{MAX_NPCINTERACT_RANGE, MAX_PICKUP_RANGE},
112 link::Is,
113 mounting::{Mount, Rider, VolumePos},
114 outcome::Outcome,
115 recipe::RecipeBookManifest,
116 resources::{BattleMode, Secs, Time},
117 rtsim,
118 slowjob::SlowJobPool,
119 terrain::{Block, SpriteKind, TerrainChunk, UnlockKind},
120 trade::{ReducedInventory, TradeAction},
121 uid::Uid,
122 util::{Dir, srgba_to_linear},
123 vol::RectRasterableVol,
124};
125use common_base::{prof_span, span};
126use common_net::{msg::world_msg::SiteId, sync::WorldSyncExt};
127use conrod_core::{
128 Color, Colorable, Labelable, Positionable, Sizeable, Widget,
129 text::cursor::Index,
130 widget::{self, Button, Image, Rectangle, Text},
131 widget_ids,
132};
133use hashbrown::{HashMap, HashSet};
134use i18n::Localization;
135use rand::Rng;
136use specs::{Entity as EcsEntity, Join, LendJoin, WorldExt};
137use std::{
138 borrow::Cow,
139 cell::RefCell,
140 cmp::Ordering,
141 collections::VecDeque,
142 rc::Rc,
143 sync::Arc,
144 time::{Duration, Instant},
145};
146use tracing::{instrument, trace, warn};
147use vek::*;
148
149const TEXT_COLOR: Color = Color::Rgba(1.0, 1.0, 1.0, 1.0);
150const TEXT_VELORITE: Color = Color::Rgba(0.0, 0.66, 0.66, 1.0);
151const TEXT_BLUE_COLOR: Color = Color::Rgba(0.8, 0.9, 1.0, 1.0);
152const TEXT_GRAY_COLOR: Color = Color::Rgba(0.5, 0.5, 0.5, 1.0);
153const TEXT_DULL_RED_COLOR: Color = Color::Rgba(0.56, 0.2, 0.2, 1.0);
154const TEXT_BG: Color = Color::Rgba(0.0, 0.0, 0.0, 1.0);
155const TEXT_COLOR_GREY: Color = Color::Rgba(1.0, 1.0, 1.0, 0.5);
156const TEXT_COLOR_3: Color = Color::Rgba(1.0, 1.0, 1.0, 0.1);
158const TEXT_BIND_CONFLICT_COLOR: Color = Color::Rgba(1.0, 0.0, 0.0, 1.0);
159const BLACK: Color = Color::Rgba(0.0, 0.0, 0.0, 1.0);
160const HP_COLOR: Color = Color::Rgba(0.33, 0.63, 0.0, 1.0);
162const LOW_HP_COLOR: Color = Color::Rgba(0.93, 0.59, 0.03, 1.0);
163const CRITICAL_HP_COLOR: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0);
164const STAMINA_COLOR: Color = Color::Rgba(0.29, 0.62, 0.75, 0.9);
165const ENEMY_HP_COLOR: Color = Color::Rgba(0.93, 0.1, 0.29, 1.0);
166const XP_COLOR: Color = Color::Rgba(0.59, 0.41, 0.67, 1.0);
167const POISE_COLOR: Color = Color::Rgba(0.70, 0.0, 0.60, 1.0);
168const POISEBAR_TICK_COLOR: Color = Color::Rgba(0.70, 0.90, 0.0, 1.0);
169const BUFF_COLOR: Color = Color::Rgba(0.06, 0.69, 0.12, 1.0);
173const DEBUFF_COLOR: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0);
174
175const QUALITY_LOW: Color = Color::Rgba(0.60, 0.60, 0.60, 1.0); const QUALITY_COMMON: Color = Color::Rgba(0.79, 1.00, 1.00, 1.0); const QUALITY_MODERATE: Color = Color::Rgba(0.06, 0.69, 0.12, 1.0); const QUALITY_HIGH: Color = Color::Rgba(0.18, 0.32, 0.9, 1.0); const QUALITY_EPIC: Color = Color::Rgba(0.58, 0.29, 0.93, 1.0); const QUALITY_LEGENDARY: Color = Color::Rgba(0.92, 0.76, 0.0, 1.0); const QUALITY_ARTIFACT: Color = Color::Rgba(0.74, 0.24, 0.11, 1.0); const QUALITY_DEBUG: Color = Color::Rgba(0.79, 0.19, 0.17, 1.0); const ERROR_COLOR: Color = Color::Rgba(1.0, 1.0, 0.0, 1.0);
189const INFO_COLOR: Color = Color::Rgba(0.28, 0.83, 0.71, 1.0);
191const ONLINE_COLOR: Color = Color::Rgba(0.3, 1.0, 0.3, 1.0);
193const OFFLINE_COLOR: Color = Color::Rgba(1.0, 0.3, 0.3, 1.0);
195const TELL_COLOR: Color = Color::Rgba(0.98, 0.71, 1.0, 1.0);
197const SAY_COLOR: Color = Color::Rgba(1.0, 0.8, 0.8, 1.0);
199const GROUP_COLOR: Color = Color::Rgba(0.47, 0.84, 1.0, 1.0);
201const FACTION_COLOR: Color = Color::Rgba(0.24, 1.0, 0.48, 1.0);
203const REGION_COLOR: Color = Color::Rgba(0.8, 1.0, 0.8, 1.0);
205const KILL_COLOR: Color = Color::Rgba(1.0, 0.17, 0.17, 1.0);
207const WORLD_COLOR: Color = Color::Rgba(0.95, 1.0, 0.95, 1.0);
209
210const GROUP_MEMBER: Color = Color::Rgba(0.47, 0.84, 1.0, 1.0);
212const DEFAULT_NPC: Color = Color::Rgba(1.0, 1.0, 1.0, 1.0);
213
214const UI_MAIN: Color = Color::Rgba(0.61, 0.70, 0.70, 1.0); const UI_SUBTLE: Color = Color::Rgba(0.2, 0.24, 0.24, 1.0); const UI_HIGHLIGHT_0: Color = Color::Rgba(0.79, 1.09, 1.09, 1.0);
219const MENU_BG: Color = Color::Rgba(0.1, 0.12, 0.12, 1.0);
221const NAMETAG_GROUP_RANGE: f32 = 1000.0;
225const NAMETAG_RANGE: f32 = 40.0;
227const NAMETAG_DMG_TIME: f32 = 60.0;
230const NAMETAG_DMG_RANGE: f32 = 120.0;
232const SPEECH_BUBBLE_RANGE: f32 = NAMETAG_RANGE;
234const EXP_FLOATER_LIFETIME: f32 = 2.0;
235const EXP_ACCUMULATION_DURATION: f32 = 0.5;
236
237pub fn default_water_color() -> Rgba<f32> { srgba_to_linear(Rgba::new(0.0, 0.18, 0.37, 1.0)) }
239
240widget_ids! {
241 struct Ids {
242 crosshair_inner,
244 crosshair_outer,
245
246 player_scts[],
248 player_sct_bgs[],
249 player_rank_up,
250 player_rank_up_txt_number,
251 player_rank_up_txt_0,
252 player_rank_up_txt_0_bg,
253 player_rank_up_txt_1,
254 player_rank_up_txt_1_bg,
255 player_rank_up_icon,
256 sct_exp_bgs[],
257 sct_exps[],
258 sct_exp_icons[],
259 sct_lvl_bg,
260 sct_lvl,
261 hurt_bg,
262 death_bg,
263 sct_bgs[],
264 scts[],
265
266 overheads[],
267 overitems[],
268
269 alpha_text,
271
272 debug_bg,
274 fps_counter,
275 ping,
276 coordinates,
277 velocity,
278 glide_ratio,
279 glide_aoe,
280 air_vel,
281 orientation,
282 look_direction,
283 loaded_distance,
284 time,
285 entity_count,
286 num_chunks,
287 num_lights,
288 num_figures,
289 num_particles,
290 current_biome,
291 current_site,
292 graphics_backend,
293 gpu_timings[],
294 weather,
295 song_info,
296 active_channels,
297
298 version,
300
301 help,
303 help_info,
304 debug_info,
305 lantern_info,
306
307 window_frame_0,
309 window_frame_1,
310 window_frame_2,
311 window_frame_3,
312 window_frame_4,
313 window_frame_5,
314
315 button_help2,
316 button_help3,
317
318 chat,
320 loot_scroller,
321 map,
322 world_map,
323 character_window,
324 popup,
325 minimap,
326 prompt_dialog,
327 bag,
328 trade,
329 social,
330 quest,
331 diary,
332 skillbar,
333 buttons,
334 buffs,
335 esc_menu,
336 small_window,
337 social_window,
338 quest_window,
339 crafting_window,
340 settings_window,
341 group_window,
342 item_info,
343 subtitles,
344
345 free_look_txt,
347 free_look_bg,
348
349 auto_walk_txt,
351 auto_walk_bg,
352
353 walking_speed_txt,
355 walking_speed_bg,
356
357 zoom_lock_txt,
359 zoom_lock_bg,
360
361 camera_clamp_txt,
363 camera_clamp_bg,
364
365 quest_bg,
367 q_headline_bg,
368 q_headline,
369 q_text_bg,
370 q_text,
371 accept_button,
372 intro_button,
373 tut_arrow,
374 tut_arrow_txt_bg,
375 tut_arrow_txt,
376 }
377}
378
379#[derive(Clone, Copy)]
383pub enum PositionSpecifier {
384 TopLeftWithMarginsOn(widget::Id, f64, f64),
386 TopRightWithMarginsOn(widget::Id, f64, f64),
387 MidBottomWithMarginOn(widget::Id, f64),
388 BottomLeftWithMarginsOn(widget::Id, f64, f64),
389 BottomRightWithMarginsOn(widget::Id, f64, f64),
390 MidTopWithMarginOn(widget::Id, f64),
392 MiddleOf(widget::Id),
394 UpFrom(widget::Id, f64),
395 DownFrom(widget::Id, f64),
396 LeftFrom(widget::Id, f64),
397 RightFrom(widget::Id, f64),
398}
399
400pub trait Position {
447 #[must_use]
448 fn position(self, request: PositionSpecifier) -> Self;
449}
450
451impl<W: Positionable> Position for W {
452 fn position(self, request: PositionSpecifier) -> Self {
453 match request {
454 PositionSpecifier::TopLeftWithMarginsOn(other, top, left) => {
456 self.top_left_with_margins_on(other, top, left)
457 },
458 PositionSpecifier::TopRightWithMarginsOn(other, top, right) => {
459 self.top_right_with_margins_on(other, top, right)
460 },
461 PositionSpecifier::MidBottomWithMarginOn(other, margin) => {
462 self.mid_bottom_with_margin_on(other, margin)
463 },
464 PositionSpecifier::BottomRightWithMarginsOn(other, bottom, right) => {
465 self.bottom_right_with_margins_on(other, bottom, right)
466 },
467 PositionSpecifier::BottomLeftWithMarginsOn(other, bottom, left) => {
468 self.bottom_left_with_margins_on(other, bottom, left)
469 },
470 PositionSpecifier::MidTopWithMarginOn(other, margin) => {
472 self.mid_top_with_margin_on(other, margin)
473 },
474 PositionSpecifier::MiddleOf(other) => self.middle_of(other),
476 PositionSpecifier::UpFrom(other, offset) => self.up_from(other, offset),
477 PositionSpecifier::DownFrom(other, offset) => self.down_from(other, offset),
478 PositionSpecifier::LeftFrom(other, offset) => self.left_from(other, offset),
479 PositionSpecifier::RightFrom(other, offset) => self.right_from(other, offset),
480 }
481 }
482}
483
484#[derive(Clone, Copy, Debug)]
485pub enum BuffIconKind {
486 Buff {
487 kind: BuffKind,
488 data: BuffData,
489 multiplicity: usize,
490 },
491 Stance(Stance),
492}
493
494impl BuffIconKind {
495 pub fn image(&self, imgs: &Imgs) -> conrod_core::image::Id {
496 match self {
497 Self::Buff { kind, .. } => get_buff_image(*kind, imgs),
498 Self::Stance(stance) => util::ability_image(imgs, stance.pseudo_ability_id()),
499 }
500 }
501
502 pub fn max_duration(&self) -> Option<Secs> {
503 match self {
504 Self::Buff { data, .. } => data.duration,
505 Self::Stance(_) => None,
506 }
507 }
508
509 pub fn title_description<'b>(
510 &self,
511 localized_strings: &'b Localization,
512 ) -> (Cow<'b, str>, Cow<'b, str>) {
513 match self {
514 Self::Buff {
515 kind,
516 data,
517 multiplicity: _,
518 } => (
519 util::get_buff_title(*kind, localized_strings),
520 util::get_buff_desc(*kind, *data, localized_strings),
521 ),
522 Self::Stance(stance) => {
523 util::ability_description(stance.pseudo_ability_id(), localized_strings)
524 },
525 }
526 }
527}
528
529impl PartialOrd for BuffIconKind {
530 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
531}
532
533impl Ord for BuffIconKind {
534 fn cmp(&self, other: &Self) -> Ordering {
535 match (self, other) {
536 (
537 BuffIconKind::Buff { kind, .. },
538 BuffIconKind::Buff {
539 kind: other_kind, ..
540 },
541 ) => kind.cmp(other_kind),
542 (BuffIconKind::Buff { .. }, BuffIconKind::Stance(_)) => Ordering::Greater,
543 (BuffIconKind::Stance(_), BuffIconKind::Buff { .. }) => Ordering::Less,
544 (BuffIconKind::Stance(stance), BuffIconKind::Stance(stance_other)) => {
545 stance.cmp(stance_other)
546 },
547 }
548 }
549}
550
551impl PartialEq for BuffIconKind {
552 fn eq(&self, other: &Self) -> bool {
553 match (self, other) {
554 (
555 BuffIconKind::Buff { kind, .. },
556 BuffIconKind::Buff {
557 kind: other_kind, ..
558 },
559 ) => kind == other_kind,
560 (BuffIconKind::Stance(stance), BuffIconKind::Stance(stance_other)) => {
561 stance == stance_other
562 },
563 _ => false,
564 }
565 }
566}
567
568impl Eq for BuffIconKind {}
569
570#[derive(Clone, Copy, Debug)]
571pub struct BuffIcon {
572 kind: BuffIconKind,
573 is_buff: bool,
574 end_time: Option<f64>,
575}
576
577impl BuffIcon {
578 pub fn multiplicity(&self) -> usize {
579 match self.kind {
580 BuffIconKind::Buff { multiplicity, .. } => multiplicity,
581 BuffIconKind::Stance(_) => 1,
582 }
583 }
584
585 pub fn get_buff_time(&self, time: Time) -> String {
586 if let Some(end) = self.end_time {
587 format!("{:.0}s", end - time.0)
588 } else {
589 "".to_string()
590 }
591 }
592
593 pub fn icons_vec(buffs: &comp::Buffs, stance: Option<&comp::Stance>) -> Vec<Self> {
594 buffs
595 .iter_active()
596 .filter_map(BuffIcon::from_buffs)
597 .chain(stance.and_then(BuffIcon::from_stance))
598 .collect::<Vec<_>>()
599 }
600
601 fn from_stance(stance: &comp::Stance) -> Option<Self> {
602 let stance = if let Stance::None = stance {
603 return None;
604 } else {
605 stance
606 };
607 Some(BuffIcon {
608 kind: BuffIconKind::Stance(*stance),
609 is_buff: true,
610 end_time: None,
611 })
612 }
613
614 fn from_buffs<'b, I: Iterator<Item = &'b comp::Buff>>(buffs: I) -> Option<Self> {
615 let (buff, count) = buffs.fold((None, 0), |(strongest, count), buff| {
616 (strongest.or(Some(buff)), count + 1)
617 });
618 let buff = buff?;
619 Some(Self {
620 kind: BuffIconKind::Buff {
621 kind: buff.kind,
622 data: buff.data,
623 multiplicity: count,
624 },
625 is_buff: buff.kind.is_buff(),
626 end_time: buff.end_time.map(|end| end.0),
627 })
628 }
629}
630
631pub struct ExpFloater {
632 pub owner: Uid,
633 pub exp_change: u32,
634 pub timer: f32,
635 pub jump_timer: f32,
636 pub rand_offset: (f32, f32),
637 pub xp_pools: HashSet<SkillGroupKind>,
638}
639
640pub struct SkillPointGain {
641 pub skill_tree: SkillGroupKind,
642 pub total_points: u16,
643 pub timer: f32,
644}
645
646#[derive(Debug, Clone, Copy)]
647pub struct ComboFloater {
648 pub combo: u32,
649 pub timer: f64,
650}
651
652pub struct BlockFloater {
653 pub timer: f32,
654}
655
656pub struct DebugInfo {
657 pub tps: f64,
658 pub frame_time: Duration,
659 pub ping_ms: f64,
660 pub coordinates: Option<comp::Pos>,
661 pub velocity: Option<comp::Vel>,
662 pub ori: Option<comp::Ori>,
663 pub character_state: Option<comp::CharacterState>,
664 pub look_dir: Dir,
665 pub in_fluid: Option<comp::Fluid>,
666 pub num_chunks: u32,
667 pub num_lights: u32,
668 pub num_visible_chunks: u32,
669 pub num_shadow_chunks: u32,
670 pub num_figures: u32,
671 pub num_figures_visible: u32,
672 pub num_particles: u32,
673 pub num_particles_visible: u32,
674 pub current_track: String,
675 pub current_artist: String,
676 pub active_channels: ActiveChannels,
677 pub audio_cpu_usage: f32,
678}
679
680pub struct HudInfo<'a> {
681 pub is_aiming: bool,
682 pub active_mine_tool: Option<ToolKind>,
683 pub is_first_person: bool,
684 pub viewpoint_entity: specs::Entity,
685 pub mutable_viewpoint: bool,
686 pub target_entity: Option<specs::Entity>,
687 pub selected_entity: Option<(specs::Entity, Instant)>,
688 pub persistence_load_error: Option<SkillsPersistenceError>,
689 pub key_state: &'a KeyState,
690}
691
692#[derive(Clone)]
693pub enum Event {
694 SendMessage(String),
695 SendCommand(String, Vec<String>),
696
697 CharacterSelection,
698 UseSlot {
699 slot: comp::slot::Slot,
700 bypass_dialog: bool,
701 },
702 SwapEquippedWeapons,
703 SwapSlots {
704 slot_a: comp::slot::Slot,
705 slot_b: comp::slot::Slot,
706 bypass_dialog: bool,
707 },
708 SplitSwapSlots {
709 slot_a: comp::slot::Slot,
710 slot_b: comp::slot::Slot,
711 bypass_dialog: bool,
712 },
713 DropSlot(comp::slot::Slot),
714 SplitDropSlot(comp::slot::Slot),
715 SortInventory(InventorySortOrder),
716 ChangeHotbarState(Box<HotbarState>),
717 TradeAction(TradeAction),
718 Ability {
719 idx: usize,
720 state: bool,
721 },
722 Logout,
723 Quit,
724
725 CraftRecipe {
726 recipe_name: String,
727 craft_sprite: Option<(VolumePos, SpriteKind)>,
728 amount: u32,
729 },
730 SalvageItem {
731 slot: InvSlotId,
732 salvage_pos: VolumePos,
733 },
734 CraftModularWeapon {
735 primary_slot: InvSlotId,
736 secondary_slot: InvSlotId,
737 craft_sprite: Option<VolumePos>,
738 },
739 CraftModularWeaponComponent {
740 toolkind: ToolKind,
741 material: InvSlotId,
742 modifier: Option<InvSlotId>,
743 craft_sprite: Option<VolumePos>,
744 },
745 RepairItem {
746 item: Slot,
747 sprite_pos: VolumePos,
748 },
749 InviteMember(Uid),
750 AcceptInvite,
751 DeclineInvite,
752 KickMember(Uid),
753 LeaveGroup,
754 AssignLeader(Uid),
755 RemoveBuff(BuffKind),
756 LeaveStance,
757 UnlockSkill(Skill),
758 SelectExpBar(Option<SkillGroupKind>),
759
760 RequestSiteInfo(SiteId),
761 ChangeAbility(usize, AuxiliaryAbility),
762
763 SettingsChange(SettingsChange),
764 AcknowledgePersistenceLoadError,
765 MapMarkerEvent(MapMarkerChange),
766 Dialogue(EcsEntity, rtsim::Dialogue),
767 SetBattleMode(BattleMode),
768}
769
770#[derive(PartialEq, Eq)]
775pub enum Windows {
776 Settings, None,
778}
779
780#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
781pub enum CrosshairType {
782 RoundEdges,
783 Edges,
784 #[serde(other)]
785 Round,
786}
787#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
788pub enum Intro {
789 Never,
790 #[serde(other)]
791 Show,
792}
793#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
794pub enum XpBar {
795 OnGain,
796 #[serde(other)]
797 Always,
798}
799
800#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
801pub enum BarNumbers {
802 Percent,
803 Off,
804 #[serde(other)]
805 Values,
806}
807#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
808pub enum ShortcutNumbers {
809 Off,
810 #[serde(other)]
811 On,
812}
813
814#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
815pub enum BuffPosition {
816 Map,
817 #[serde(other)]
818 Bar,
819}
820
821#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
822pub enum PressBehavior {
823 Hold = 1,
824 #[serde(other)]
825 Toggle = 0,
826}
827#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
832pub enum AutoPressBehavior {
833 Auto = 1,
834 #[serde(other)]
835 Toggle = 0,
836}
837#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
838pub struct ChatTab {
839 pub label: String,
840 pub filter: ChatFilter,
841}
842impl Default for ChatTab {
843 fn default() -> Self {
844 Self {
845 label: String::from("Chat"),
846 filter: ChatFilter::default(),
847 }
848 }
849}
850
851impl PressBehavior {
852 pub fn update(&self, keystate: bool, setting: &mut bool, f: impl FnOnce(bool)) {
853 match (self, keystate) {
854 (PressBehavior::Toggle, true) => {
856 *setting ^= true;
857 f(*setting);
858 },
859 (PressBehavior::Toggle, false) => {},
861 (PressBehavior::Hold, state) => {
863 *setting = state;
864 f(*setting);
865 },
866 }
867 }
868}
869
870#[derive(Default, Clone)]
871pub struct MapMarkers {
872 owned: Option<Vec2<i32>>,
873 group: HashMap<Uid, Vec2<i32>>,
874}
875
876impl MapMarkers {
877 pub fn update(&mut self, event: comp::MapMarkerUpdate) {
878 match event {
879 comp::MapMarkerUpdate::Owned(event) => match event {
880 MapMarkerChange::Update(waypoint) => self.owned = Some(waypoint),
881 MapMarkerChange::Remove => self.owned = None,
882 },
883 comp::MapMarkerUpdate::GroupMember(user, event) => match event {
884 MapMarkerChange::Update(waypoint) => {
885 self.group.insert(user, waypoint);
886 },
887 MapMarkerChange::Remove => {
888 self.group.remove(&user);
889 },
890 },
891 comp::MapMarkerUpdate::ClearGroup => {
892 self.group.clear();
893 },
894 }
895 }
896}
897
898pub struct TradeAmountInput {
901 slot: InvSlotId,
902 input: String,
903 inv: u32,
904 ours: bool,
905 err: Option<String>,
906 who: usize,
907 input_painted: bool,
908 submit_action: Option<TradeAction>,
909}
910
911impl TradeAmountInput {
912 pub fn new(slot: InvSlotId, input: String, inv: u32, ours: bool, who: usize) -> Self {
913 Self {
914 slot,
915 input,
916 inv,
917 ours,
918 who,
919 err: None,
920 input_painted: false,
921 submit_action: None,
922 }
923 }
924}
925
926pub struct Show {
927 ui: bool,
928 intro: bool,
929 crafting: bool,
930 bag: bool,
931 bag_inv: bool,
932 bag_details: bool,
933 trade: bool,
934 trade_details: bool,
935 social: bool,
936 diary: bool,
937 group: bool,
938 quest: bool,
939 group_menu: bool,
940 esc_menu: bool,
941 open_windows: Windows,
942 map: bool,
943 ingame: bool,
944 chat_tab_settings_index: Option<usize>,
945 settings_tab: SettingsTab,
946 diary_fields: diary::DiaryShow,
947 crafting_fields: crafting::CraftingShow,
948 social_search_key: Option<String>,
949 want_grab: bool,
950 stats: bool,
951 free_look: bool,
952 auto_walk: bool,
953 zoom_lock: ChangeNotification,
954 camera_clamp: bool,
955 prompt_dialog: Option<PromptDialogSettings>,
956 trade_amount_input_key: Option<TradeAmountInput>,
957}
958impl Show {
959 fn bag(&mut self, open: bool) {
960 if !self.esc_menu {
961 self.bag = open;
962 self.map = false;
963 self.crafting_fields.salvage = false;
964
965 if !open {
966 self.crafting = false;
967 }
968
969 self.want_grab = !self.any_window_requires_cursor();
970 }
971 }
972
973 fn trade(&mut self, open: bool) {
974 if !self.esc_menu {
975 self.bag = open;
976 self.trade = open;
977 self.map = false;
978 self.want_grab = !self.any_window_requires_cursor();
979 }
980 }
981
982 fn map(&mut self, open: bool) {
983 if !self.esc_menu {
984 self.map = open;
985 self.bag = false;
986 self.crafting = false;
987 self.crafting_fields.salvage = false;
988 self.social = false;
989 self.quest = false;
990 self.diary = false;
991 self.want_grab = !self.any_window_requires_cursor();
992 }
993 }
994
995 fn social(&mut self, open: bool) {
996 if !self.esc_menu {
997 if !self.social && open {
998 self.search_social_players(None);
1000 }
1001 self.social = open;
1002 self.diary = false;
1003 self.want_grab = !self.any_window_requires_cursor();
1004 }
1005 }
1006
1007 fn quest(&mut self, open: bool) {
1008 if !self.esc_menu {
1009 self.quest = open;
1010 self.diary = false;
1011 self.map = false;
1012 self.want_grab = !self.any_window_requires_cursor();
1013 }
1014 }
1015
1016 fn crafting(&mut self, open: bool) {
1017 if !self.esc_menu {
1018 if !self.crafting && open {
1019 self.search_crafting_recipe(None);
1021 }
1022 self.crafting = open;
1023 self.crafting_fields.salvage = false;
1024 self.crafting_fields.recipe_inputs = HashMap::new();
1025 self.bag = open;
1026 self.map = false;
1027 self.want_grab = !self.any_window_requires_cursor();
1028 }
1029 }
1030
1031 pub fn open_crafting_tab(
1032 &mut self,
1033 tab: CraftingTab,
1034 craft_sprite: Option<(VolumePos, SpriteKind)>,
1035 ) {
1036 self.selected_crafting_tab(tab);
1037 self.crafting(true);
1038 self.crafting_fields.craft_sprite = self.crafting_fields.craft_sprite.or(craft_sprite);
1039 self.crafting_fields.salvage = matches!(
1040 self.crafting_fields.craft_sprite,
1041 Some((_, SpriteKind::DismantlingBench))
1042 ) && matches!(tab, CraftingTab::Dismantle);
1043 self.crafting_fields.initialize_repair = matches!(
1044 self.crafting_fields.craft_sprite,
1045 Some((_, SpriteKind::RepairBench))
1046 );
1047 }
1048
1049 fn diary(&mut self, open: bool) {
1050 if !self.esc_menu {
1051 self.social = false;
1052 self.quest = false;
1053 self.crafting = false;
1054 self.crafting_fields.salvage = false;
1055 self.bag = false;
1056 self.map = false;
1057 self.diary_fields = diary::DiaryShow::default();
1058 self.diary = open;
1059 self.want_grab = !self.any_window_requires_cursor();
1060 }
1061 }
1062
1063 fn settings(&mut self, open: bool) {
1064 if !self.esc_menu {
1065 self.open_windows = if open {
1066 Windows::Settings
1067 } else {
1068 Windows::None
1069 };
1070 self.bag = false;
1071 self.social = false;
1072 self.quest = false;
1073 self.crafting = false;
1074 self.crafting_fields.salvage = false;
1075 self.diary = false;
1076 self.want_grab = !self.any_window_requires_cursor();
1077 }
1078 }
1079
1080 fn toggle_trade(&mut self) { self.trade(!self.trade); }
1081
1082 fn toggle_map(&mut self) { self.map(!self.map) }
1083
1084 fn toggle_social(&mut self) { self.social(!self.social); }
1085
1086 fn toggle_crafting(&mut self) { self.crafting(!self.crafting) }
1087
1088 fn toggle_diary(&mut self) { self.diary(!self.diary) }
1089
1090 fn toggle_ui(&mut self) { self.ui = !self.ui; }
1091
1092 fn toggle_settings(&mut self, global_state: &GlobalState) {
1093 match self.open_windows {
1094 Windows::Settings => {
1095 #[cfg(feature = "singleplayer")]
1096 global_state.unpause();
1097
1098 self.settings(false);
1099 },
1100 _ => {
1101 #[cfg(feature = "singleplayer")]
1102 global_state.pause();
1103
1104 self.settings(true)
1105 },
1106 };
1107 #[cfg(not(feature = "singleplayer"))]
1108 let _global_state = global_state;
1109 }
1110
1111 fn any_window_requires_cursor(&self) -> bool {
1114 self.bag
1115 || self.trade
1116 || self.esc_menu
1117 || self.map
1118 || self.social
1119 || self.crafting
1120 || self.diary
1121 || self.intro
1122 || self.quest
1123 || !matches!(self.open_windows, Windows::None)
1124 }
1125
1126 fn toggle_windows(&mut self, global_state: &mut GlobalState) {
1127 if self.any_window_requires_cursor() {
1128 self.bag = false;
1129 self.trade = false;
1130 self.esc_menu = false;
1131 self.intro = false;
1132 self.map = false;
1133 self.social = false;
1134 self.quest = false;
1135 self.diary = false;
1136 self.crafting = false;
1137 self.open_windows = Windows::None;
1138 self.want_grab = true;
1139
1140 #[cfg(feature = "singleplayer")]
1142 global_state.unpause();
1143 } else {
1144 self.esc_menu = true;
1145 self.want_grab = false;
1146
1147 #[cfg(feature = "singleplayer")]
1149 global_state.pause();
1150 }
1151 #[cfg(not(feature = "singleplayer"))]
1152 let _global_state = global_state;
1153 }
1154
1155 fn open_setting_tab(&mut self, tab: SettingsTab) {
1156 self.open_windows = Windows::Settings;
1157 self.esc_menu = false;
1158 self.settings_tab = tab;
1159 self.bag = false;
1160 self.want_grab = false;
1161 }
1162
1163 fn open_skill_tree(&mut self, tree_sel: SelectedSkillTree) {
1164 self.diary_fields.skilltreetab = tree_sel;
1165 self.social = false;
1166 }
1167
1168 fn selected_crafting_tab(&mut self, sel_cat: CraftingTab) {
1169 self.crafting_fields.crafting_tab = sel_cat;
1170 }
1171
1172 fn search_crafting_recipe(&mut self, search_key: Option<String>) {
1173 self.crafting_fields.crafting_search_key = search_key;
1174 }
1175
1176 fn search_social_players(&mut self, search_key: Option<String>) {
1177 self.social_search_key = search_key;
1178 }
1179}
1180
1181pub struct PromptDialogSettings {
1182 message: String,
1183 affirmative_event: Event,
1184 negative_option: bool,
1185 negative_event: Option<Event>,
1186 outcome_via_keypress: Option<bool>,
1187}
1188
1189impl PromptDialogSettings {
1190 pub fn new(message: String, affirmative_event: Event, negative_event: Option<Event>) -> Self {
1191 Self {
1192 message,
1193 affirmative_event,
1194 negative_option: true,
1195 negative_event,
1196 outcome_via_keypress: None,
1197 }
1198 }
1199
1200 pub fn set_outcome_via_keypress(&mut self, outcome: bool) {
1201 self.outcome_via_keypress = Some(outcome);
1202 }
1203
1204 #[must_use]
1205 pub fn with_no_negative_option(mut self) -> Self {
1206 self.negative_option = false;
1207 self
1208 }
1209}
1210
1211pub struct Floaters {
1212 pub exp_floaters: Vec<ExpFloater>,
1213 pub skill_point_displays: Vec<SkillPointGain>,
1214 pub combo_floater: Option<ComboFloater>,
1215 pub block_floaters: Vec<BlockFloater>,
1216}
1217
1218#[derive(Clone)]
1219pub enum HudLootOwner {
1220 Name(Content),
1221 Group,
1222 Unknown,
1223}
1224
1225#[derive(Clone)]
1226pub enum HudCollectFailedReason {
1227 InventoryFull,
1228 LootOwned {
1229 owner: HudLootOwner,
1230 expiry_secs: u64,
1231 },
1232}
1233
1234impl HudCollectFailedReason {
1235 pub fn from_server_reason(reason: &CollectFailedReason, ecs: &specs::World) -> Self {
1236 match reason {
1237 CollectFailedReason::InventoryFull => HudCollectFailedReason::InventoryFull,
1238 CollectFailedReason::LootOwned { owner, expiry_secs } => {
1239 let owner = match owner {
1240 LootOwnerKind::Player(owner_uid) => {
1241 let maybe_owner_name = ecs.entity_from_uid(*owner_uid).and_then(|entity| {
1242 ecs.read_storage::<comp::Stats>()
1243 .get(entity)
1244 .map(|stats| stats.name.clone())
1245 });
1246
1247 if let Some(name) = maybe_owner_name {
1248 HudLootOwner::Name(name)
1249 } else {
1250 HudLootOwner::Unknown
1251 }
1252 },
1253 LootOwnerKind::Group(_) => HudLootOwner::Group,
1254 };
1255
1256 HudCollectFailedReason::LootOwned {
1257 owner,
1258 expiry_secs: *expiry_secs,
1259 }
1260 },
1261 }
1262 }
1263}
1264#[derive(Clone)]
1265pub struct CollectFailedData {
1266 pulse: f32,
1267 reason: HudCollectFailedReason,
1268}
1269
1270impl CollectFailedData {
1271 pub fn new(pulse: f32, reason: HudCollectFailedReason) -> Self { Self { pulse, reason } }
1272}
1273
1274#[derive(Default)]
1277pub struct PersistedHudState {
1278 pub message_backlog: MessageBacklog,
1284 pub location_markers: MapMarkers,
1285}
1286
1287pub struct Hud {
1288 ui: Ui,
1289 ids: Ids,
1290 world_map: (Vec<Rotations>, Vec2<u32>),
1291 imgs: Imgs,
1292 item_imgs: ItemImgs,
1293 item_i18n: ItemI18n,
1294 fonts: Fonts,
1295 rot_imgs: ImgsRot,
1296 failed_block_pickups: HashMap<VolumePos, CollectFailedData>,
1297 failed_entity_pickups: HashMap<EcsEntity, CollectFailedData>,
1298 new_loot_messages: VecDeque<LootMessage>,
1299 new_messages: VecDeque<comp::ChatMsg>,
1300 new_notifications: VecDeque<UserNotification>,
1301 speech_bubbles: HashMap<Uid, comp::SpeechBubble>,
1302 content_bubbles: Vec<(Vec3<f32>, comp::SpeechBubble)>,
1303 pub persisted_state: Rc<RefCell<PersistedHudState>>,
1304 pub show: Show,
1305 to_focus: Option<Option<widget::Id>>,
1309 force_ungrab: bool,
1310 force_chat_input: Option<String>,
1311 force_chat_cursor: Option<Index>,
1312 tab_complete: Option<String>,
1313 pulse: f32,
1314 hp_pulse: f32,
1315 slot_manager: slots::SlotManager,
1316 hotbar: hotbar::State,
1317 events: Vec<Event>,
1318 crosshair_opacity: f32,
1319 floaters: Floaters,
1320 voxel_minimap: VoxelMinimap,
1321 map_drag: Vec2<f64>,
1322 force_chat: bool,
1323 clear_chat: bool,
1324 current_dialogue: Option<(EcsEntity, Instant, rtsim::Dialogue<true>)>,
1325 extra_markers: Vec<map::ExtraMarker>,
1326}
1327
1328impl Hud {
1329 pub fn new(
1330 global_state: &mut GlobalState,
1331 persisted_state: Rc<RefCell<PersistedHudState>>,
1332 client: &Client,
1333 ) -> Self {
1334 let window = &mut global_state.window;
1335 let settings = &global_state.settings;
1336
1337 let mut ui = Ui::new(window).unwrap();
1338 ui.set_scaling_mode(settings.interface.ui_scale);
1339 let ids = Ids::new(ui.id_generator());
1341 let mut layers = Vec::new();
1343 for layer in client.world_data().map_layers() {
1344 layers.push(ui.add_graphic_with_rotations(Graphic::Image(
1347 Arc::clone(layer),
1348 Some(default_water_color()),
1349 )));
1350 }
1351 let world_map = (layers, client.world_data().chunk_size().map(|e| e as u32));
1352 let imgs = Imgs::load(&mut ui).expect("Failed to load images!");
1354 let rot_imgs = ImgsRot::load(&mut ui).expect("Failed to load rot images!");
1356 let item_imgs = ItemImgs::new(&mut ui, imgs.not_found);
1358 let item_i18n = ItemI18n::new_expect();
1360 let fonts = Fonts::load(global_state.i18n.read().fonts(), &mut ui)
1362 .expect("Impossible to load fonts!");
1363 let server = &client.server_info().name;
1365 let character_id = match client.presence().unwrap() {
1369 PresenceKind::Character(id) => Some(id),
1370 PresenceKind::LoadingCharacter(id) => Some(id),
1371 PresenceKind::Spectator => None,
1372 PresenceKind::Possessor => None,
1373 };
1374
1375 let hotbar_state =
1377 HotbarState::new(global_state.profile.get_hotbar_slots(server, character_id));
1378
1379 let slot_manager = slots::SlotManager::new(
1380 ui.id_generator(),
1381 Vec2::broadcast(40.0),
1382 global_state.settings.interface.slots_use_prefixes,
1383 global_state.settings.interface.slots_prefix_switch_point,
1384 );
1391
1392 Self {
1393 voxel_minimap: VoxelMinimap::new(&mut ui),
1394 ui,
1395 imgs,
1396 world_map,
1397 rot_imgs,
1398 item_imgs,
1399 item_i18n,
1400 fonts,
1401 ids,
1402 failed_block_pickups: HashMap::default(),
1403 failed_entity_pickups: HashMap::default(),
1404 new_loot_messages: VecDeque::new(),
1405 new_messages: VecDeque::new(),
1406 new_notifications: VecDeque::new(),
1407 persisted_state,
1408 speech_bubbles: HashMap::new(),
1409 content_bubbles: Vec::new(),
1410 show: Show {
1413 intro: false,
1414 bag: false,
1415 bag_inv: false,
1416 bag_details: false,
1417 trade: false,
1418 trade_details: false,
1419 esc_menu: false,
1420 open_windows: Windows::None,
1421 map: false,
1422 crafting: false,
1423 ui: true,
1424 social: false,
1425 diary: false,
1426 group: false,
1427 quest: false,
1429 group_menu: false,
1430 chat_tab_settings_index: None,
1431 settings_tab: SettingsTab::Interface,
1432 diary_fields: diary::DiaryShow::default(),
1433 crafting_fields: crafting::CraftingShow::default(),
1434 social_search_key: None,
1435 want_grab: true,
1436 ingame: true,
1437 stats: false,
1438 free_look: false,
1439 auto_walk: false,
1440 zoom_lock: ChangeNotification::default(),
1441 camera_clamp: false,
1442 prompt_dialog: None,
1443 trade_amount_input_key: None,
1444 },
1445 to_focus: None,
1446 force_ungrab: false,
1448 force_chat_input: None,
1449 force_chat_cursor: None,
1450 tab_complete: None,
1451 pulse: 0.0,
1452 hp_pulse: 0.0,
1453 slot_manager,
1454 hotbar: hotbar_state,
1455 events: Vec::new(),
1456 crosshair_opacity: 0.0,
1457 floaters: Floaters {
1458 exp_floaters: Vec::new(),
1459 skill_point_displays: Vec::new(),
1460 combo_floater: None,
1461 block_floaters: Vec::new(),
1462 },
1463 map_drag: Vec2::zero(),
1464 force_chat: false,
1465 clear_chat: false,
1466 current_dialogue: None,
1467 extra_markers: Vec::new(),
1468 }
1469 }
1470
1471 pub fn clear_chat(&mut self) { self.clear_chat = true; }
1472
1473 pub fn set_prompt_dialog(&mut self, prompt_dialog: PromptDialogSettings) {
1474 self.show.prompt_dialog = Some(prompt_dialog);
1475 }
1476
1477 pub fn update_fonts(&mut self, i18n: &Localization) {
1478 self.fonts = Fonts::load(i18n.fonts(), &mut self.ui).expect("Impossible to load fonts!");
1479 }
1480
1481 pub fn set_slots_use_prefixes(&mut self, use_prefixes: bool) {
1482 self.slot_manager.set_use_prefixes(use_prefixes);
1483 }
1484
1485 pub fn set_slots_prefix_switch_point(&mut self, prefix_switch_point: u32) {
1486 self.slot_manager
1487 .set_prefix_switch_point(prefix_switch_point);
1488 }
1489
1490 pub fn current_dialogue(&self) -> Option<EcsEntity> {
1491 self.current_dialogue.as_ref().map(|(e, _, _)| *e)
1492 }
1493
1494 #[expect(clippy::single_match)] fn update_layout(
1496 &mut self,
1497 client: &Client,
1498 global_state: &mut GlobalState,
1499 debug_info: &Option<DebugInfo>,
1500 dt: Duration,
1501 info: HudInfo,
1502 camera: &Camera,
1503 (entity_interactables, block_interactables): (
1504 HashMap<specs::Entity, Vec<interactable::EntityInteraction>>,
1505 HashMap<VolumePos, (Block, Vec<&interactable::BlockInteraction>)>,
1506 ),
1507 ) -> Vec<Event> {
1508 span!(_guard, "update_layout", "Hud::update_layout");
1509 let mut events = core::mem::take(&mut self.events);
1510 if global_state.settings.interface.map_show_voxel_map {
1511 self.voxel_minimap.maintain(client, &mut self.ui);
1512 }
1513 let scale = self.ui.scale();
1514 let (ui_widgets, item_tooltip_manager, tooltip_manager) = &mut self.ui.set_widgets();
1515 self.pulse += dt.as_secs_f32();
1517 let fps = global_state.clock.stats().average_tps;
1519 let version = common::util::DISPLAY_VERSION_LONG.clone();
1520 let i18n = &global_state.i18n.read();
1521
1522 if self.show.ingame {
1523 prof_span!("ingame elements");
1524
1525 let ecs = client.state().ecs();
1526 let pos = ecs.read_storage::<comp::Pos>();
1527 let stats = ecs.read_storage::<comp::Stats>();
1528 let skill_sets = ecs.read_storage::<comp::SkillSet>();
1529 let healths = ecs.read_storage::<Health>();
1530 let hardcore = ecs.read_storage::<comp::Hardcore>();
1531 let buffs = ecs.read_storage::<comp::Buffs>();
1532 let energy = ecs.read_storage::<comp::Energy>();
1533 let mut hp_floater_lists = ecs.write_storage::<HpFloaterList>();
1534 let uids = ecs.read_storage::<Uid>();
1535 let interpolated = ecs.read_storage::<vcomp::Interpolated>();
1536 let scales = ecs.read_storage::<comp::Scale>();
1537 let bodies = ecs.read_storage::<comp::Body>();
1538 let items = ecs.read_storage::<PickupItem>();
1539 let inventories = ecs.read_storage::<comp::Inventory>();
1540 let msm = ecs.read_resource::<MaterialStatManifest>();
1541 let entities = ecs.entities();
1542 let me = info.viewpoint_entity;
1543 let poises = ecs.read_storage::<comp::Poise>();
1544 let is_mounts = ecs.read_storage::<Is<Mount>>();
1545 let is_riders = ecs.read_storage::<Is<Rider>>();
1546 let stances = ecs.read_storage::<comp::Stance>();
1547 let char_activities = ecs.read_storage::<comp::CharacterActivity>();
1548 let time = ecs.read_resource::<Time>();
1549 let id_maps = ecs.read_resource::<common::uid::IdMaps>();
1550 let terrain = ecs.read_resource::<common::terrain::TerrainGrid>();
1551 let colliders = ecs.read_storage::<comp::Collider>();
1552
1553 if self.show.prompt_dialog.is_none()
1556 && let Some(persistence_error) = info.persistence_load_error
1557 {
1558 let persistence_error = match persistence_error {
1559 SkillsPersistenceError::HashMismatch => "hud-skill-persistence-hash_mismatch",
1560 SkillsPersistenceError::DeserializationFailure => {
1561 "hud-skill-persistence-deserialization_failure"
1562 },
1563 SkillsPersistenceError::SpentExpMismatch => {
1564 "hud-skill-persistence-spent_experience_missing"
1565 },
1566 SkillsPersistenceError::SkillsUnlockFailed => {
1567 "hud-skill-persistence-skills_unlock_failed"
1568 },
1569 };
1570 let persistence_error = global_state
1571 .i18n
1572 .read()
1573 .get_content(&Content::localized(persistence_error));
1574
1575 let common_message = global_state
1576 .i18n
1577 .read()
1578 .get_content(&Content::localized("hud-skill-persistence-common_message"));
1579
1580 warn!("{}\n{}", persistence_error, common_message);
1581 let prompt_dialog = PromptDialogSettings::new(
1583 format!("{}\n", common_message),
1584 Event::AcknowledgePersistenceLoadError,
1585 None,
1586 )
1587 .with_no_negative_option();
1588 self.show.prompt_dialog = Some(prompt_dialog);
1590 }
1591
1592 if (client.pending_trade().is_some() && !self.show.trade)
1593 || (client.pending_trade().is_none() && self.show.trade)
1594 {
1595 self.show.toggle_trade();
1596 }
1597
1598 if let Some(health) = healths.get(me) {
1600 let hp_percentage = health.current() / health.maximum() * 100.0;
1602 self.hp_pulse += dt.as_secs_f32() * 10.0 / hp_percentage.clamp(3.0, 7.0);
1603 if hp_percentage < 10.0 && !health.is_dead {
1604 let hurt_fade = (self.hp_pulse).sin() * 0.5 + 0.6; Image::new(self.imgs.hurt_bg)
1606 .wh_of(ui_widgets.window)
1607 .middle_of(ui_widgets.window)
1608 .graphics_for(ui_widgets.window)
1609 .color(Some(Color::Rgba(1.0, 1.0, 1.0, hurt_fade)))
1610 .set(self.ids.hurt_bg, ui_widgets);
1611 }
1612 Text::new(&format!("Veloren {}", &version))
1614 .font_id(self.fonts.cyri.conrod_id)
1615 .font_size(self.fonts.cyri.scale(10))
1616 .color(TEXT_COLOR)
1617 .mid_top_with_margin_on(ui_widgets.window, 2.0)
1618 .set(self.ids.alpha_text, ui_widgets);
1619
1620 if health.is_dead {
1622 Image::new(self.imgs.death_bg)
1623 .wh_of(ui_widgets.window)
1624 .middle_of(ui_widgets.window)
1625 .graphics_for(ui_widgets.window)
1626 .color(Some(Color::Rgba(0.0, 0.0, 0.0, 1.0)))
1627 .set(self.ids.death_bg, ui_widgets);
1628 }
1629 let show_crosshair = (info.is_aiming || info.is_first_person) && !health.is_dead;
1631 self.crosshair_opacity = Lerp::lerp(
1632 self.crosshair_opacity,
1633 if show_crosshair { 1.0 } else { 0.0 },
1634 5.0 * dt.as_secs_f32(),
1635 );
1636
1637 Image::new(
1638 match global_state.settings.interface.crosshair_type {
1640 CrosshairType::Round => self.imgs.crosshair_outer_round,
1641 CrosshairType::RoundEdges => self.imgs.crosshair_outer_round_edges,
1642 CrosshairType::Edges => self.imgs.crosshair_outer_edges,
1643 },
1644 )
1645 .w_h(21.0 * 1.5, 21.0 * 1.5)
1646 .middle_of(ui_widgets.window)
1647 .color(Some(Color::Rgba(
1648 1.0,
1649 1.0,
1650 1.0,
1651 self.crosshair_opacity * global_state.settings.interface.crosshair_opacity,
1652 )))
1653 .set(self.ids.crosshair_outer, ui_widgets);
1654 Image::new(self.imgs.crosshair_inner)
1655 .w_h(21.0 * 2.0, 21.0 * 2.0)
1656 .middle_of(self.ids.crosshair_outer)
1657 .color(Some(Color::Rgba(1.0, 1.0, 1.0, 0.6)))
1658 .set(self.ids.crosshair_inner, ui_widgets);
1659 }
1660
1661 const FLASH_MAX: u32 = 2;
1663
1664 let player_pos = client
1666 .state()
1667 .ecs()
1668 .read_storage::<comp::Pos>()
1669 .get(client.entity())
1670 .map_or(Vec3::zero(), |pos| pos.0);
1671 if global_state.settings.interface.sct {
1674 let mut player_sct_bg_id_walker = self.ids.player_sct_bgs.walk();
1676 let mut player_sct_id_walker = self.ids.player_scts.walk();
1677 if let (Some(HpFloaterList { floaters, .. }), Some(health)) = (
1678 hp_floater_lists
1679 .get_mut(me)
1680 .filter(|fl| !fl.floaters.is_empty()),
1681 healths.get(me),
1682 ) {
1683 let player_font_col = |precise: bool| {
1684 if precise {
1685 Rgb::new(1.0, 0.9, 0.0)
1686 } else {
1687 Rgb::new(1.0, 0.1, 0.0)
1688 }
1689 };
1690
1691 fn calc_fade(floater: &HpFloater) -> f32 {
1692 ((crate::ecs::sys::floater::MY_HP_SHOWTIME - floater.timer) * 0.25) + 0.2
1693 }
1694
1695 floaters.retain(|fl| calc_fade(fl) > 0.0);
1696
1697 for floater in floaters {
1698 let number_speed = 50.0; let player_sct_bg_id = player_sct_bg_id_walker.next(
1700 &mut self.ids.player_sct_bgs,
1701 &mut ui_widgets.widget_id_generator(),
1702 );
1703 let player_sct_id = player_sct_id_walker.next(
1704 &mut self.ids.player_scts,
1705 &mut ui_widgets.widget_id_generator(),
1706 );
1707 let max_hp_frac = floater
1709 .info
1710 .amount
1711 .abs()
1712 .clamp(Health::HEALTH_EPSILON, health.maximum() * 1.25)
1713 / health.maximum();
1714 let hp_dmg_text = if floater.info.amount.abs() < 0.1 {
1715 String::new()
1716 } else if global_state.settings.interface.sct_damage_rounding
1717 && floater.info.amount.abs() >= 1.0
1718 {
1719 format!("{:.0}", floater.info.amount.abs())
1720 } else {
1721 format!("{:.1}", floater.info.amount.abs())
1722 };
1723 let precise = floater.info.precise;
1724
1725 let hp_fade = calc_fade(floater);
1727
1728 let font_size =
1731 30 + (if precise {
1732 (max_hp_frac * 10.0) as u32 * 3 + 10
1733 } else {
1734 (max_hp_frac * 10.0) as u32 * 3
1735 }) + if floater.jump_timer < 0.1 {
1736 FLASH_MAX
1737 * (((1.0 - floater.jump_timer * 10.0)
1738 * 10.0
1739 * if precise { 1.25 } else { 1.0 })
1740 as u32)
1741 } else {
1742 0
1743 };
1744 let font_col = player_font_col(precise);
1745 let y = if floater.info.amount < 0.0 {
1747 floater.timer as f64
1748 * number_speed
1749 * floater.info.amount.signum() as f64
1750 + 300.0
1752 - ui_widgets.win_h * 0.5
1753 } else {
1754 -(floater.timer as f64
1755 * number_speed
1756 * floater.info.amount.signum() as f64)
1757 + 300.0
1758 - ui_widgets.win_h * 0.5
1759 };
1760 let x = if floater.info.amount < 0.0 {
1762 0.0
1763 } else {
1764 (floater.rand as f64 - 0.5) * 0.08 * ui_widgets.win_w
1765 + (0.03 * ui_widgets.win_w * (floater.rand as f64 - 0.5).signum())
1766 };
1767 Text::new(&hp_dmg_text)
1768 .font_size(font_size)
1769 .font_id(self.fonts.cyri.conrod_id)
1770 .color(Color::Rgba(0.0, 0.0, 0.0, hp_fade))
1771 .x_y(x, y - 3.0)
1772 .set(player_sct_bg_id, ui_widgets);
1773 Text::new(&hp_dmg_text)
1774 .font_size(font_size)
1775 .font_id(self.fonts.cyri.conrod_id)
1776 .color(if floater.info.amount < 0.0 {
1777 Color::Rgba(font_col.r, font_col.g, font_col.b, hp_fade)
1778 } else {
1779 Color::Rgba(0.1, 1.0, 0.1, hp_fade)
1780 })
1781 .x_y(x, y)
1782 .set(player_sct_id, ui_widgets);
1783 }
1784 }
1785 self.floaters.exp_floaters.iter_mut().for_each(|f| {
1787 f.timer -= dt.as_secs_f32();
1788 f.jump_timer += dt.as_secs_f32();
1789 });
1790 self.floaters.exp_floaters.retain(|f| f.timer > 0.0);
1791 for floater in self.floaters.exp_floaters.iter_mut() {
1792 let number_speed = 50.0; let player_sct_bg_id = player_sct_bg_id_walker.next(
1794 &mut self.ids.player_sct_bgs,
1795 &mut ui_widgets.widget_id_generator(),
1796 );
1797 let player_sct_id = player_sct_id_walker.next(
1798 &mut self.ids.player_scts,
1799 &mut ui_widgets.widget_id_generator(),
1800 );
1801 let font_size_xp = 30
1808 + ((floater.exp_change as f32 / 300.0).min(1.0) * 50.0) as u32
1809 + if floater.jump_timer < 0.1 {
1810 FLASH_MAX * (((1.0 - floater.jump_timer * 10.0) * 10.0) as u32)
1811 } else {
1812 0
1813 };
1814 let y = floater.timer as f64 * number_speed; let fade = floater.timer.min(1.0);
1818
1819 if floater.exp_change > 0 {
1820 let xp_pool = &floater.xp_pools;
1821 let exp_string =
1822 &i18n.get_msg_ctx("hud-sct-experience", &i18n::fluent_args! {
1823 "amount" => &floater.exp_change.max(1),
1825 });
1826 Text::new(exp_string)
1827 .font_size(font_size_xp)
1828 .font_id(self.fonts.cyri.conrod_id)
1829 .color(Color::Rgba(0.0, 0.0, 0.0, fade))
1830 .x_y(
1831 ui_widgets.win_w * (0.5 * floater.rand_offset.0 as f64 - 0.25),
1832 ui_widgets.win_h * (0.15 * floater.rand_offset.1 as f64) + y - 3.0,
1833 )
1834 .set(player_sct_bg_id, ui_widgets);
1835 Text::new(exp_string)
1836 .font_size(font_size_xp)
1837 .font_id(self.fonts.cyri.conrod_id)
1838 .color(
1839 if xp_pool.contains(&SkillGroupKind::Weapon(ToolKind::Pick)) {
1840 Color::Rgba(0.18, 0.32, 0.9, fade)
1841 } else {
1842 Color::Rgba(0.59, 0.41, 0.67, fade)
1843 },
1844 )
1845 .x_y(
1846 ui_widgets.win_w * (0.5 * floater.rand_offset.0 as f64 - 0.25),
1847 ui_widgets.win_h * (0.15 * floater.rand_offset.1 as f64) + y,
1848 )
1849 .set(player_sct_id, ui_widgets);
1850 }
1858 }
1859
1860 self.floaters
1862 .skill_point_displays
1863 .iter_mut()
1864 .for_each(|f| f.timer -= dt.as_secs_f32());
1865 self.floaters
1866 .skill_point_displays
1867 .retain(|d| d.timer > 0_f32);
1868 if let Some(display) = self.floaters.skill_point_displays.iter_mut().next() {
1869 let fade = if display.timer < 3.0 {
1870 display.timer * 0.33
1871 } else if display.timer < 2.0 {
1872 display.timer * 0.33 * 0.1
1873 } else {
1874 1.0
1875 };
1876 let offset = if display.timer < 2.0 {
1878 300.0 - (display.timer as f64 - 2.0) * -300.0
1879 } else {
1880 300.0
1881 };
1882 Image::new(self.imgs.level_up)
1883 .w_h(328.0, 126.0)
1884 .mid_top_with_margin_on(ui_widgets.window, offset)
1885 .graphics_for(ui_widgets.window)
1886 .color(Some(Color::Rgba(1.0, 1.0, 1.0, fade)))
1887 .set(self.ids.player_rank_up, ui_widgets);
1888 let rank = display.total_points;
1890 let fontsize = match rank {
1891 1..=99 => (20, 8.0),
1892 100..=999 => (18, 9.0),
1893 1000..=9999 => (17, 10.0),
1894 _ => (14, 12.0),
1895 };
1896 Text::new(&format!("{}", rank))
1897 .font_size(fontsize.0)
1898 .font_id(self.fonts.cyri.conrod_id)
1899 .color(Color::Rgba(1.0, 1.0, 1.0, fade))
1900 .mid_top_with_margin_on(self.ids.player_rank_up, fontsize.1)
1901 .set(self.ids.player_rank_up_txt_number, ui_widgets);
1902 Text::new(&i18n.get_msg("hud-rank_up"))
1904 .font_size(40)
1905 .font_id(self.fonts.cyri.conrod_id)
1906 .color(Color::Rgba(0.0, 0.0, 0.0, fade))
1907 .mid_bottom_with_margin_on(self.ids.player_rank_up, 20.0)
1908 .set(self.ids.player_rank_up_txt_0_bg, ui_widgets);
1909 Text::new(&i18n.get_msg("hud-rank_up"))
1910 .font_size(40)
1911 .font_id(self.fonts.cyri.conrod_id)
1912 .color(Color::Rgba(1.0, 1.0, 1.0, fade))
1913 .bottom_left_with_margins_on(self.ids.player_rank_up_txt_0_bg, 2.0, 2.0)
1914 .set(self.ids.player_rank_up_txt_0, ui_widgets);
1915 let skill = match display.skill_tree {
1917 General => i18n.get_msg("common-weapons-general"),
1918 Weapon(ToolKind::Hammer) => i18n.get_msg("common-weapons-hammer"),
1919 Weapon(ToolKind::Axe) => i18n.get_msg("common-weapons-axe"),
1920 Weapon(ToolKind::Sword) => i18n.get_msg("common-weapons-sword"),
1921 Weapon(ToolKind::Sceptre) => i18n.get_msg("common-weapons-sceptre"),
1922 Weapon(ToolKind::Bow) => i18n.get_msg("common-weapons-bow"),
1923 Weapon(ToolKind::Staff) => i18n.get_msg("common-weapons-staff"),
1924 Weapon(ToolKind::Pick) => i18n.get_msg("common-tool-mining"),
1925 _ => Cow::Borrowed("Unknown"),
1926 };
1927 Text::new(&skill)
1928 .font_size(20)
1929 .font_id(self.fonts.cyri.conrod_id)
1930 .color(Color::Rgba(0.0, 0.0, 0.0, fade))
1931 .mid_top_with_margin_on(self.ids.player_rank_up, 45.0)
1932 .set(self.ids.player_rank_up_txt_1_bg, ui_widgets);
1933 Text::new(&skill)
1934 .font_size(20)
1935 .font_id(self.fonts.cyri.conrod_id)
1936 .color(Color::Rgba(1.0, 1.0, 1.0, fade))
1937 .bottom_left_with_margins_on(self.ids.player_rank_up_txt_1_bg, 2.0, 2.0)
1938 .set(self.ids.player_rank_up_txt_1, ui_widgets);
1939 use crate::hud::SkillGroupKind::{General, Weapon};
1941 Image::new(match display.skill_tree {
1942 General => self.imgs.swords_crossed,
1943 Weapon(ToolKind::Hammer) => self.imgs.hammer,
1944 Weapon(ToolKind::Axe) => self.imgs.axe,
1945 Weapon(ToolKind::Sword) => self.imgs.sword,
1946 Weapon(ToolKind::Sceptre) => self.imgs.sceptre,
1947 Weapon(ToolKind::Bow) => self.imgs.bow,
1948 Weapon(ToolKind::Staff) => self.imgs.staff,
1949 Weapon(ToolKind::Pick) => self.imgs.mining,
1950 _ => self.imgs.swords_crossed,
1951 })
1952 .w_h(20.0, 20.0)
1953 .left_from(self.ids.player_rank_up_txt_1_bg, 5.0)
1954 .color(Some(Color::Rgba(1.0, 1.0, 1.0, fade)))
1955 .set(self.ids.player_rank_up_icon, ui_widgets);
1956 }
1957
1958 self.floaters
1960 .block_floaters
1961 .iter_mut()
1962 .for_each(|f| f.timer -= dt.as_secs_f32());
1963 self.floaters.block_floaters.retain(|f| f.timer > 0_f32);
1964 for floater in self.floaters.block_floaters.iter_mut() {
1965 let number_speed = 50.0;
1966 let player_sct_bg_id = player_sct_bg_id_walker.next(
1967 &mut self.ids.player_sct_bgs,
1968 &mut ui_widgets.widget_id_generator(),
1969 );
1970 let player_sct_id = player_sct_id_walker.next(
1971 &mut self.ids.player_scts,
1972 &mut ui_widgets.widget_id_generator(),
1973 );
1974 let font_size = 30;
1975 let y = floater.timer as f64 * number_speed; let fade = if floater.timer < 0.25 {
1978 floater.timer / 0.25
1979 } else {
1980 1.0
1981 };
1982
1983 Text::new(&i18n.get_msg("hud-sct-block"))
1984 .font_size(font_size)
1985 .font_id(self.fonts.cyri.conrod_id)
1986 .color(Color::Rgba(0.0, 0.0, 0.0, fade))
1987 .x_y(
1988 ui_widgets.win_w * (0.0),
1989 ui_widgets.win_h * (-0.3) + y - 3.0,
1990 )
1991 .set(player_sct_bg_id, ui_widgets);
1992 Text::new(&i18n.get_msg("hud-sct-block"))
1993 .font_size(font_size)
1994 .font_id(self.fonts.cyri.conrod_id)
1995 .color(Color::Rgba(0.69, 0.82, 0.88, fade))
1996 .x_y(ui_widgets.win_w * 0.0, ui_widgets.win_h * -0.3 + y)
1997 .set(player_sct_id, ui_widgets);
1998 }
1999 }
2000
2001 let now = Instant::now();
2003 self.speech_bubbles
2004 .retain(|_uid, bubble| bubble.timeout > now);
2005 self.content_bubbles
2006 .retain(|(_pos, bubble)| bubble.timeout > now);
2007
2008 self.new_messages
2010 .retain(|msg| !chat::is_muted(client, &global_state.profile, msg));
2011
2012 for msg in self.new_messages.iter() {
2014 if let Some((bubble, uid)) = msg.to_bubble() {
2015 self.speech_bubbles.insert(uid, bubble);
2016 }
2017 }
2018
2019 let mut overhead_walker = self.ids.overheads.walk();
2020 let mut overitem_walker = self.ids.overitems.walk();
2021 let mut sct_walker = self.ids.scts.walk();
2022 let mut sct_bg_walker = self.ids.sct_bgs.walk();
2023 let pulse = self.pulse;
2024
2025 let make_overitem =
2026 |item: &PickupItem, pos, distance, properties, fonts, interaction_options| {
2027 let quality = get_quality_col(item.quality());
2028
2029 overitem::Overitem::new(
2031 util::describe(item, i18n, &self.item_i18n).into(),
2032 quality,
2033 distance,
2034 fonts,
2035 i18n,
2036 &global_state.settings.controls,
2037 properties,
2038 pulse,
2039 interaction_options,
2040 )
2041 .x_y(0.0, 100.0)
2042 .position_ingame(pos)
2043 };
2044
2045 self.failed_block_pickups
2046 .retain(|_, t| pulse - t.pulse < overitem::PICKUP_FAILED_FADE_OUT_TIME);
2047 self.failed_entity_pickups
2048 .retain(|_, t| pulse - t.pulse < overitem::PICKUP_FAILED_FADE_OUT_TIME);
2049
2050 for (entity, pos, item, distance) in (&entities, &pos, &items)
2052 .join()
2053 .map(|(entity, pos, item)| (entity, pos, item, pos.0.distance_squared(player_pos)))
2054 .filter(|(_, _, _, distance)| distance < &MAX_PICKUP_RANGE.powi(2))
2055 {
2056 let overitem_id = overitem_walker.next(
2057 &mut self.ids.overitems,
2058 &mut ui_widgets.widget_id_generator(),
2059 );
2060
2061 make_overitem(
2062 item,
2063 pos.0 + Vec3::unit_z() * 1.2,
2064 distance,
2065 overitem::OveritemProperties {
2066 active: entity_interactables.contains_key(&entity),
2067 pickup_failed_pulse: self.failed_entity_pickups.get(&entity).cloned(),
2068 },
2069 &self.fonts,
2070 vec![(
2071 Some(GameInput::Interact),
2072 i18n.get_msg("hud-pick_up").to_string(),
2073 overitem::TEXT_COLOR,
2074 )],
2075 )
2076 .set(overitem_id, ui_widgets);
2077 }
2078
2079 for (mat, pos, interactions, block) in
2081 block_interactables
2082 .iter()
2083 .filter_map(|(position, (block, interactions))| {
2084 position
2085 .get_block_and_transform(
2086 &terrain,
2087 &id_maps,
2088 |e| {
2090 interpolated.get(e).map(|interpolated| {
2091 (comp::Pos(interpolated.pos), interpolated.ori)
2092 })
2093 },
2094 &colliders,
2095 )
2096 .map(|(mat, _)| (mat, *position, interactions, *block))
2097 })
2098 {
2099 let overitem_id = overitem_walker.next(
2100 &mut self.ids.overitems,
2101 &mut ui_widgets.widget_id_generator(),
2102 );
2103
2104 let overitem_properties = overitem::OveritemProperties {
2105 active: true,
2106 pickup_failed_pulse: self.failed_block_pickups.get(&pos).cloned(),
2107 };
2108
2109 let pos = mat.mul_point(Vec3::broadcast(0.5));
2110 let over_pos = pos + Vec3::unit_z() * 0.7;
2111
2112 let interaction_text = |interaction: &BlockInteraction| match interaction {
2113 BlockInteraction::Collect { steal } => (
2114 Some(GameInput::Interact),
2115 i18n.get_msg(if *steal { "hud-steal" } else { "hud-collect" })
2116 .to_string(),
2117 if *steal {
2118 overitem::NEGATIVE_TEXT_COLOR
2119 } else {
2120 overitem::TEXT_COLOR
2121 },
2122 ),
2123 BlockInteraction::Craft(_) => (
2124 Some(GameInput::Interact),
2125 i18n.get_msg("hud-use").to_string(),
2126 overitem::TEXT_COLOR,
2127 ),
2128 BlockInteraction::Unlock { kind, steal } => {
2129 let item_name = |item_id: &ItemDefinitionIdOwned| {
2130 item_id
2132 .as_ref()
2133 .itemdef_id()
2134 .map(|id| {
2135 let item = Item::new_from_asset_expect(id);
2136 util::describe(&item, i18n, &self.item_i18n)
2137 })
2138 .unwrap_or_else(|| "modular item".to_string())
2139 };
2140
2141 (
2142 Some(GameInput::Interact),
2143 match kind {
2144 UnlockKind::Free => i18n
2145 .get_msg(if *steal { "hud-steal" } else { "hud-open" })
2146 .to_string(),
2147 UnlockKind::Requires(item_id) => i18n
2148 .get_msg_ctx(
2149 if *steal {
2150 "hud-steal-requires"
2151 } else {
2152 "hud-unlock-requires"
2153 },
2154 &i18n::fluent_args! {
2155 "item" => item_name(item_id),
2156 },
2157 )
2158 .to_string(),
2159 UnlockKind::Consumes(item_id) => i18n
2160 .get_msg_ctx(
2161 if *steal {
2162 "hud-steal-consumes"
2163 } else {
2164 "hud-unlock-consumes"
2165 },
2166 &i18n::fluent_args! {
2167 "item" => item_name(item_id),
2168 },
2169 )
2170 .to_string(),
2171 },
2172 if *steal {
2173 overitem::NEGATIVE_TEXT_COLOR
2174 } else {
2175 overitem::TEXT_COLOR
2176 },
2177 )
2178 },
2179 BlockInteraction::Mine(mine_tool) => {
2180 match (mine_tool, &info.active_mine_tool) {
2181 (ToolKind::Pick, Some(ToolKind::Pick)) => (
2182 Some(GameInput::Primary),
2183 i18n.get_msg("hud-mine").to_string(),
2184 overitem::TEXT_COLOR,
2185 ),
2186 (ToolKind::Pick, _) => (
2187 None,
2188 i18n.get_msg("hud-mine-needs_pickaxe").to_string(),
2189 overitem::TEXT_COLOR,
2190 ),
2191 (ToolKind::Shovel, Some(ToolKind::Shovel)) => (
2192 Some(GameInput::Primary),
2193 i18n.get_msg("hud-dig").to_string(),
2194 overitem::TEXT_COLOR,
2195 ),
2196 (ToolKind::Shovel, _) => (
2197 None,
2198 i18n.get_msg("hud-mine-needs_shovel").to_string(),
2199 overitem::TEXT_COLOR,
2200 ),
2201 _ => (
2202 None,
2203 i18n.get_msg("hud-mine-needs_unhandled_case").to_string(),
2204 overitem::TEXT_COLOR,
2205 ),
2206 }
2207 },
2208 BlockInteraction::Mount => {
2209 let key = match block.get_sprite() {
2210 Some(sprite) if sprite.is_controller() => "hud-steer",
2211 Some(sprite) if sprite.is_bed() => "hud-rest",
2212 _ => "hud-sit",
2213 };
2214 (
2215 Some(GameInput::Mount),
2216 i18n.get_msg(key).to_string(),
2217 overitem::TEXT_COLOR,
2218 )
2219 },
2220 BlockInteraction::Read(_) => (
2221 Some(GameInput::Interact),
2222 i18n.get_msg("hud-read").to_string(),
2223 overitem::TEXT_COLOR,
2224 ),
2225 BlockInteraction::LightToggle(enable) => (
2227 Some(GameInput::Interact),
2228 i18n.get_msg(if *enable {
2229 "hud-activate"
2230 } else {
2231 "hud-deactivate"
2232 })
2233 .to_string(),
2234 overitem::TEXT_COLOR,
2235 ),
2236 };
2237
2238 if let Some(sprite) = block.get_sprite() {
2239 let interactable_item = if sprite.should_drop_mystery() {
2243 None
2244 } else {
2245 Item::try_reclaim_from_block(block, None).and_then(|mut items| {
2246 debug_assert!(
2247 items.len() <= 1,
2248 "The amount of items returned from Item::try_reclaim_from_block \
2249 for non-container items must not be higher than one"
2250 );
2251 let (amount, mut item) = items.pop()?;
2252 item.set_amount(amount.clamp(1, item.max_amount())).expect(
2253 "Setting an item amount between 1 and item.max_amount() must \
2254 succeed",
2255 );
2256 Some(item)
2257 })
2258 };
2259
2260 let (desc, quality) = interactable_item.map_or_else(
2261 || (get_sprite_desc(sprite, i18n), overitem::TEXT_COLOR),
2262 |item| {
2263 (
2264 Some(util::describe(&item, i18n, &self.item_i18n).into()),
2265 get_quality_col(item.quality()),
2266 )
2267 },
2268 );
2269 let desc = desc.unwrap_or(Cow::Borrowed(""));
2270 overitem::Overitem::new(
2271 desc,
2272 quality,
2273 pos.distance_squared(player_pos),
2274 &self.fonts,
2275 i18n,
2276 &global_state.settings.controls,
2277 overitem_properties,
2278 self.pulse,
2279 interactions
2280 .iter()
2281 .map(|interaction| interaction_text(interaction))
2282 .collect(),
2283 )
2284 .x_y(0.0, 100.0)
2285 .position_ingame(over_pos)
2286 .set(overitem_id, ui_widgets);
2287 }
2288 }
2289
2290 for (entity, interaction) in
2292 entity_interactables
2293 .iter()
2294 .filter_map(|(entity, interactions)| {
2295 interactions.iter().find_map(|interaction| {
2296 matches!(
2297 interaction,
2298 EntityInteraction::CampfireSit | EntityInteraction::ActivatePortal
2299 )
2300 .then_some((*entity, *interaction))
2301 })
2302 })
2303 {
2304 let overitem_id = overitem_walker.next(
2305 &mut self.ids.overitems,
2306 &mut ui_widgets.widget_id_generator(),
2307 );
2308
2309 let overitem_properties = overitem::OveritemProperties {
2310 active: true,
2311 pickup_failed_pulse: None,
2312 };
2313 let pos = client
2314 .state()
2315 .ecs()
2316 .read_storage::<comp::Pos>()
2317 .get(entity)
2318 .map_or(Vec3::zero(), |e| e.0);
2319 let over_pos = pos + Vec3::unit_z() * 1.5;
2320
2321 let (name, interaction_text) = match interaction {
2322 EntityInteraction::CampfireSit => {
2323 ("hud-crafting-campfire", "hud-waypoint_interact")
2324 },
2325 EntityInteraction::ActivatePortal => ("hud-portal", "hud-activate"),
2326 _ => unreachable!(),
2327 };
2328
2329 overitem::Overitem::new(
2330 i18n.get_msg(name),
2331 overitem::TEXT_COLOR,
2332 pos.distance_squared(player_pos),
2333 &self.fonts,
2334 i18n,
2335 &global_state.settings.controls,
2336 overitem_properties,
2337 self.pulse,
2338 vec![(
2339 Some(interaction.game_input()),
2340 i18n.get_msg(interaction_text).to_string(),
2341 overitem::TEXT_COLOR,
2342 )],
2343 )
2344 .x_y(0.0, 100.0)
2345 .position_ingame(over_pos)
2346 .set(overitem_id, ui_widgets);
2347 }
2348
2349 let speech_bubbles = &self.speech_bubbles;
2350 for (
2352 entity,
2353 pos,
2354 info,
2355 bubble,
2356 _,
2357 _,
2358 health,
2359 _,
2360 scale,
2361 body,
2362 hpfl,
2363 in_group,
2364 character_activity,
2365 ) in (
2366 &entities,
2367 &pos,
2368 interpolated.maybe(),
2369 &stats,
2370 &skill_sets,
2371 healths.maybe(),
2372 &buffs,
2373 energy.maybe(),
2374 scales.maybe(),
2375 &bodies,
2376 &mut hp_floater_lists,
2377 &uids,
2378 &inventories,
2379 char_activities.maybe(),
2380 poises.maybe(),
2381 (is_mounts.maybe(), is_riders.maybe(), stances.maybe()),
2382 )
2383 .join()
2384 .filter(|t| {
2385 let health = t.5;
2386 !health.is_some_and(|h| h.is_dead)
2387 })
2388 .filter_map(
2389 |(
2390 entity,
2391 pos,
2392 interpolated,
2393 stats,
2394 skill_set,
2395 health,
2396 buffs,
2397 energy,
2398 scale,
2399 body,
2400 hpfl,
2401 uid,
2402 inventory,
2403 character_activity,
2404 poise,
2405 (is_mount, is_rider, stance),
2406 )| {
2407 let pos = interpolated.map_or(pos.0, |i| i.pos);
2409 let in_group = client.group_members().contains_key(uid);
2410 let is_me = entity == me;
2411 let dist_sqr = pos.distance_squared(player_pos);
2412
2413 let display_overhead_info = !is_me
2419 && (is_mount.is_none()
2420 || health.is_none_or(overhead::should_show_healthbar))
2421 && is_rider
2422 .is_none_or(|is_rider| Some(&is_rider.mount) != uids.get(me))
2423 && ((info.target_entity == Some(entity))
2424 || info.selected_entity.is_some_and(|s| s.0 == entity)
2425 || health.is_none_or(overhead::should_show_healthbar)
2426 || in_group)
2427 && dist_sqr
2428 < (if in_group {
2429 NAMETAG_GROUP_RANGE
2430 } else if hpfl
2431 .time_since_last_dmg_by_me
2432 .is_some_and(|t| t < NAMETAG_DMG_TIME)
2433 {
2434 NAMETAG_DMG_RANGE
2435 } else {
2436 NAMETAG_RANGE
2437 })
2438 .powi(2);
2439
2440 let info = display_overhead_info.then(|| overhead::Info {
2441 name: Some(i18n.get_content(&stats.name)),
2442 health,
2443 buffs: Some(buffs),
2444 energy,
2445 combat_rating: if let (Some(health), Some(energy), Some(poise)) =
2446 (health, energy, poise)
2447 {
2448 Some(combat::combat_rating(
2449 inventory, health, energy, poise, skill_set, *body, &msm,
2450 ))
2451 } else {
2452 None
2453 },
2454 hardcore: hardcore.contains(entity),
2455 stance,
2456 });
2457 let bubble = if (dist_sqr < SPEECH_BUBBLE_RANGE.powi(2) && !is_me)
2459 || (is_me && global_state.settings.interface.speech_bubble_self)
2460 {
2461 speech_bubbles.get(uid)
2462 } else {
2463 None
2464 };
2465 (info.is_some() || bubble.is_some()).then_some({
2466 (
2467 entity,
2468 pos,
2469 info,
2470 bubble,
2471 stats,
2472 skill_set,
2473 health,
2474 buffs,
2475 scale,
2476 body,
2477 hpfl,
2478 in_group,
2479 character_activity,
2480 )
2481 })
2482 },
2483 )
2484 {
2485 let overhead_id = overhead_walker.next(
2486 &mut self.ids.overheads,
2487 &mut ui_widgets.widget_id_generator(),
2488 );
2489
2490 let height_offset = body.height() * scale.map_or(1.0, |s| s.0) + 0.5;
2491 let ingame_pos = pos + Vec3::unit_z() * height_offset;
2492
2493 let interaction_options =
2494 entity_interactables
2495 .get(&entity)
2496 .map_or_else(Vec::new, |interactions| {
2497 interactions
2498 .iter()
2499 .filter_map(|interaction| {
2500 let message = match interaction {
2501 EntityInteraction::HelpDowned => "hud-help",
2502 EntityInteraction::Pet => "hud-pet",
2503 EntityInteraction::Trade => "hud-trade",
2504 EntityInteraction::Mount => "hud-mount",
2505 EntityInteraction::Talk => "hud-talk",
2506 EntityInteraction::StayFollow => {
2507 let is_staying = character_activity
2508 .is_some_and(|activity| activity.is_pet_staying);
2509
2510 if is_staying { "hud-follow" } else { "hud-stay" }
2511 },
2512 EntityInteraction::PickupItem
2514 | EntityInteraction::CampfireSit
2515 | EntityInteraction::ActivatePortal => return None,
2516 };
2517
2518 Some((
2519 interaction.game_input(),
2520 i18n.get_msg(message).to_string(),
2521 ))
2522 })
2523 .collect()
2524 });
2525
2526 overhead::Overhead::new(
2528 info,
2529 bubble,
2530 in_group,
2531 &global_state.settings.interface,
2532 self.pulse,
2533 i18n,
2534 &global_state.settings.controls,
2535 &self.imgs,
2536 &self.fonts,
2537 interaction_options,
2538 &time,
2539 )
2540 .x_y(0.0, 100.0)
2541 .position_ingame(ingame_pos)
2542 .set(overhead_id, ui_widgets);
2543
2544 if global_state.settings.interface.sct && !hpfl.floaters.is_empty() {
2546 fn calc_fade(floater: &HpFloater) -> f32 {
2547 if floater.info.precise {
2548 ((crate::ecs::sys::floater::PRECISE_SHOWTIME - floater.timer) * 0.75)
2549 + 0.5
2550 } else {
2551 ((crate::ecs::sys::floater::HP_SHOWTIME - floater.timer) * 0.25) + 0.2
2552 }
2553 }
2554
2555 hpfl.floaters.retain(|fl| calc_fade(fl) > 0.0);
2556 let floaters = &hpfl.floaters;
2557
2558 const WHITE: Rgb<f32> = Rgb::new(1.0, 0.9, 0.8);
2560 const LIGHT_OR: Rgb<f32> = Rgb::new(1.0, 0.925, 0.749);
2561 const LIGHT_MED_OR: Rgb<f32> = Rgb::new(1.0, 0.85, 0.498);
2562 const MED_OR: Rgb<f32> = Rgb::new(1.0, 0.776, 0.247);
2563 const DARK_ORANGE: Rgb<f32> = Rgb::new(1.0, 0.7, 0.0);
2564 const RED_ORANGE: Rgb<f32> = Rgb::new(1.0, 0.349, 0.0);
2565 const DAMAGE_COLORS: [Rgb<f32>; 6] = [
2566 WHITE,
2567 LIGHT_OR,
2568 LIGHT_MED_OR,
2569 MED_OR,
2570 DARK_ORANGE,
2571 RED_ORANGE,
2572 ];
2573 let font_col = |font_size: u32, precise: bool| {
2576 if precise {
2577 Rgb::new(1.0, 0.9, 0.0)
2578 } else {
2579 DAMAGE_COLORS[(font_size.saturating_sub(36) / 5).min(5) as usize]
2580 }
2581 };
2582
2583 for floater in floaters {
2584 let number_speed = 250.0; let sct_id = sct_walker
2586 .next(&mut self.ids.scts, &mut ui_widgets.widget_id_generator());
2587 let sct_bg_id = sct_bg_walker
2588 .next(&mut self.ids.sct_bgs, &mut ui_widgets.widget_id_generator());
2589 let max_hp_frac = floater
2591 .info
2592 .amount
2593 .abs()
2594 .clamp(Health::HEALTH_EPSILON, health.map_or(1.0, |h| h.maximum()))
2595 / health.map_or(1.0, |h| h.maximum());
2596 let hp_dmg_text = if floater.info.amount.abs() < 0.1 {
2597 String::new()
2598 } else if global_state.settings.interface.sct_damage_rounding
2599 && floater.info.amount.abs() >= 1.0
2600 {
2601 format!("{:.0}", floater.info.amount.abs())
2602 } else {
2603 format!("{:.1}", floater.info.amount.abs())
2604 };
2605 let precise = floater.info.precise;
2606 let fade = calc_fade(floater);
2608 let font_size =
2611 30 + (if precise {
2612 (max_hp_frac * 10.0) as u32 * 3 + 10
2613 } else {
2614 (max_hp_frac * 10.0) as u32 * 3
2615 }) + if floater.jump_timer < 0.1 {
2616 FLASH_MAX
2617 * (((1.0 - floater.jump_timer * 10.0)
2618 * 10.0
2619 * if precise { 1.25 } else { 1.0 })
2620 as u32)
2621 } else {
2622 0
2623 };
2624 let font_col = font_col(font_size, precise);
2625 let y = if precise {
2627 ui_widgets.win_h * (floater.rand as f64 % 0.075)
2628 + ui_widgets.win_h * 0.05
2629 } else {
2630 (floater.timer as f64 / crate::ecs::sys::floater::HP_SHOWTIME as f64
2631 * number_speed)
2632 + 100.0
2633 };
2634
2635 let x = if !precise {
2636 0.0
2637 } else {
2638 (floater.rand as f64 - 0.5) * 0.075 * ui_widgets.win_w
2639 + (0.03 * ui_widgets.win_w * (floater.rand as f64 - 0.5).signum())
2640 };
2641
2642 Text::new(&hp_dmg_text)
2643 .font_size(font_size)
2644 .font_id(self.fonts.cyri.conrod_id)
2645 .color(if floater.info.amount < 0.0 {
2646 Color::Rgba(0.0, 0.0, 0.0, fade)
2647 } else {
2648 Color::Rgba(0.0, 0.0, 0.0, 1.0)
2649 })
2650 .x_y(x, y - 3.0)
2651 .position_ingame(ingame_pos)
2652 .set(sct_bg_id, ui_widgets);
2653 Text::new(&hp_dmg_text)
2654 .font_size(font_size)
2655 .font_id(self.fonts.cyri.conrod_id)
2656 .x_y(x, y)
2657 .color(if floater.info.amount < 0.0 {
2658 Color::Rgba(font_col.r, font_col.g, font_col.b, fade)
2659 } else {
2660 Color::Rgba(0.1, 1.0, 0.1, 1.0)
2661 })
2662 .position_ingame(ingame_pos)
2663 .set(sct_id, ui_widgets);
2664 }
2665 }
2666 }
2667
2668 for (pos, bubble) in &self.content_bubbles {
2669 let overhead_id = overhead_walker.next(
2670 &mut self.ids.overheads,
2671 &mut ui_widgets.widget_id_generator(),
2672 );
2673
2674 overhead::Overhead::new(
2675 None,
2676 Some(bubble),
2677 false,
2678 &global_state.settings.interface,
2679 self.pulse,
2680 i18n,
2681 &global_state.settings.controls,
2682 &self.imgs,
2683 &self.fonts,
2684 Vec::new(),
2685 &time,
2686 )
2687 .x_y(0.0, 100.0)
2688 .position_ingame(*pos)
2689 .set(overhead_id, ui_widgets);
2690 }
2691 }
2692
2693 if let Some(debug_info) = debug_info {
2697 prof_span!("debug info");
2698
2699 const V_PAD: f64 = 5.0;
2700 const H_PAD: f64 = 5.0;
2701
2702 Text::new(&version)
2704 .top_left_with_margins_on(self.ids.debug_bg, V_PAD, H_PAD)
2705 .font_size(self.fonts.cyri.scale(14))
2706 .font_id(self.fonts.cyri.conrod_id)
2707 .color(TEXT_COLOR)
2708 .set(self.ids.version, ui_widgets);
2709 Text::new(&format!(
2711 "FPS: {:.0} ({}ms)",
2712 debug_info.tps,
2713 debug_info.frame_time.as_millis()
2714 ))
2715 .color(TEXT_COLOR)
2716 .down_from(self.ids.version, V_PAD)
2717 .font_id(self.fonts.cyri.conrod_id)
2718 .font_size(self.fonts.cyri.scale(14))
2719 .set(self.ids.fps_counter, ui_widgets);
2720 Text::new(&format!("Ping: {:.0}ms", debug_info.ping_ms))
2722 .color(TEXT_COLOR)
2723 .down_from(self.ids.fps_counter, V_PAD)
2724 .font_id(self.fonts.cyri.conrod_id)
2725 .font_size(self.fonts.cyri.scale(14))
2726 .set(self.ids.ping, ui_widgets);
2727 let coordinates_text = match debug_info.coordinates {
2729 Some(coordinates) => format!(
2730 "Coordinates: ({:.0}, {:.0}, {:.0})",
2731 coordinates.0.x, coordinates.0.y, coordinates.0.z,
2732 ),
2733 None => "Player has no Pos component".to_owned(),
2734 };
2735 Text::new(&coordinates_text)
2736 .color(TEXT_COLOR)
2737 .down_from(self.ids.ping, V_PAD)
2738 .font_id(self.fonts.cyri.conrod_id)
2739 .font_size(self.fonts.cyri.scale(14))
2740 .set(self.ids.coordinates, ui_widgets);
2741 let (velocity_text, glide_ratio_text) = match debug_info.velocity {
2743 Some(velocity) => {
2744 let velocity = velocity.0;
2745 let velocity_text = format!(
2746 "Velocity: ({:.1}, {:.1}, {:.1}) [{:.1} u/s]",
2747 velocity.x,
2748 velocity.y,
2749 velocity.z,
2750 velocity.magnitude()
2751 );
2752 let horizontal_velocity = velocity.xy().magnitude();
2753 let dz = velocity.z;
2754 let glide_ratio_text = if dz.abs() > 0.0001 {
2756 format!("Glide Ratio: {:.1}", -(horizontal_velocity / dz))
2757 } else {
2758 "Glide Ratio: Altitude is constant".to_owned()
2759 };
2760
2761 (velocity_text, glide_ratio_text)
2762 },
2763 None => {
2764 let err = "Player has no Vel component";
2765 (err.to_owned(), err.to_owned())
2766 },
2767 };
2768 Text::new(&velocity_text)
2769 .color(TEXT_COLOR)
2770 .down_from(self.ids.coordinates, V_PAD)
2771 .font_id(self.fonts.cyri.conrod_id)
2772 .font_size(self.fonts.cyri.scale(14))
2773 .set(self.ids.velocity, ui_widgets);
2774 Text::new(&glide_ratio_text)
2775 .color(TEXT_COLOR)
2776 .down_from(self.ids.velocity, V_PAD)
2777 .font_id(self.fonts.cyri.conrod_id)
2778 .font_size(self.fonts.cyri.scale(14))
2779 .set(self.ids.glide_ratio, ui_widgets);
2780 let glide_angle_text = angle_of_attack_text(
2782 debug_info.in_fluid,
2783 debug_info.velocity,
2784 debug_info.character_state.as_ref(),
2785 );
2786 Text::new(&glide_angle_text)
2787 .color(TEXT_COLOR)
2788 .down_from(self.ids.glide_ratio, V_PAD)
2789 .font_id(self.fonts.cyri.conrod_id)
2790 .font_size(self.fonts.cyri.scale(14))
2791 .set(self.ids.glide_aoe, ui_widgets);
2792 let air_vel_text = air_velocity(debug_info.in_fluid);
2794 Text::new(&air_vel_text)
2795 .color(TEXT_COLOR)
2796 .down_from(self.ids.glide_aoe, V_PAD)
2797 .font_id(self.fonts.cyri.conrod_id)
2798 .font_size(self.fonts.cyri.scale(14))
2799 .set(self.ids.air_vel, ui_widgets);
2800 let orientation_text = match debug_info.ori {
2802 Some(ori) => {
2803 let orientation = ori.look_dir();
2804 format!(
2805 "Orientation: ({:.2}, {:.2}, {:.2})",
2806 orientation.x, orientation.y, orientation.z,
2807 )
2808 },
2809 None => "Player has no Ori component".to_owned(),
2810 };
2811 Text::new(&orientation_text)
2812 .color(TEXT_COLOR)
2813 .down_from(self.ids.air_vel, V_PAD)
2814 .font_id(self.fonts.cyri.conrod_id)
2815 .font_size(self.fonts.cyri.scale(14))
2816 .set(self.ids.orientation, ui_widgets);
2817 let look_dir_text = {
2818 let look_vec = debug_info.look_dir.to_vec();
2819
2820 format!(
2821 "Look Direction: ({:.2}, {:.2}, {:.2})",
2822 look_vec.x, look_vec.y, look_vec.z,
2823 )
2824 };
2825 Text::new(&look_dir_text)
2826 .color(TEXT_COLOR)
2827 .down_from(self.ids.orientation, V_PAD)
2828 .font_id(self.fonts.cyri.conrod_id)
2829 .font_size(self.fonts.cyri.scale(14))
2830 .set(self.ids.look_direction, ui_widgets);
2831 Text::new(&format!(
2833 "View distance: {:.2} blocks ({:.2} chunks)",
2834 client.loaded_distance(),
2835 client.loaded_distance() / TerrainChunk::RECT_SIZE.x as f32,
2836 ))
2837 .color(TEXT_COLOR)
2838 .down_from(self.ids.look_direction, V_PAD)
2839 .font_id(self.fonts.cyri.conrod_id)
2840 .font_size(self.fonts.cyri.scale(14))
2841 .set(self.ids.loaded_distance, ui_widgets);
2842 let time_in_seconds = client.state().get_time_of_day();
2844 let current_time = NaiveTime::from_num_seconds_from_midnight_opt(
2845 (time_in_seconds as u64 % 86400) as u32,
2847 0,
2848 )
2849 .expect("time always valid");
2850 Text::new(&format!("Time: {}", current_time.format("%H:%M")))
2851 .color(TEXT_COLOR)
2852 .down_from(self.ids.loaded_distance, V_PAD)
2853 .font_id(self.fonts.cyri.conrod_id)
2854 .font_size(self.fonts.cyri.scale(14))
2855 .set(self.ids.time, ui_widgets);
2856 let weather = client.weather_at_player();
2858 Text::new(&format!(
2859 "Weather({kind}): {{cloud: {cloud:.2}, rain: {rain:.2}, wind: <{wind_x:.0}, \
2860 {wind_y:.0}>}}",
2861 kind = weather.get_kind(),
2862 cloud = weather.cloud,
2863 rain = weather.rain,
2864 wind_x = weather.wind.x,
2865 wind_y = weather.wind.y
2866 ))
2867 .color(TEXT_COLOR)
2868 .down_from(self.ids.time, V_PAD)
2869 .font_id(self.fonts.cyri.conrod_id)
2870 .font_size(self.fonts.cyri.scale(14))
2871 .set(self.ids.weather, ui_widgets);
2872
2873 let entity_count = client.state().ecs().entities().join().count();
2875 Text::new(&format!("Entity count: {}", entity_count))
2876 .color(TEXT_COLOR)
2877 .down_from(self.ids.weather, V_PAD)
2878 .font_id(self.fonts.cyri.conrod_id)
2879 .font_size(self.fonts.cyri.scale(14))
2880 .set(self.ids.entity_count, ui_widgets);
2881
2882 Text::new(&format!(
2884 "Chunks: {} ({} visible) & {} (shadow)",
2885 debug_info.num_chunks, debug_info.num_visible_chunks, debug_info.num_shadow_chunks,
2886 ))
2887 .color(TEXT_COLOR)
2888 .down_from(self.ids.entity_count, V_PAD)
2889 .font_id(self.fonts.cyri.conrod_id)
2890 .font_size(self.fonts.cyri.scale(14))
2891 .set(self.ids.num_chunks, ui_widgets);
2892
2893 Text::new(&format!("Biome: {:?}", client.current_biome()))
2895 .color(TEXT_COLOR)
2896 .down_from(self.ids.num_chunks, V_PAD)
2897 .font_id(self.fonts.cyri.conrod_id)
2898 .font_size(self.fonts.cyri.scale(14))
2899 .set(self.ids.current_biome, ui_widgets);
2900
2901 Text::new(&format!("Site: {:?}", client.current_site()))
2903 .color(TEXT_COLOR)
2904 .down_from(self.ids.current_biome, V_PAD)
2905 .font_id(self.fonts.cyri.conrod_id)
2906 .font_size(self.fonts.cyri.scale(14))
2907 .set(self.ids.current_site, ui_widgets);
2908
2909 Text::new(&format!(
2911 "Now playing: {} [{}]",
2912 debug_info.current_track, debug_info.current_artist,
2913 ))
2914 .color(TEXT_COLOR)
2915 .down_from(self.ids.current_site, V_PAD)
2916 .font_id(self.fonts.cyri.conrod_id)
2917 .font_size(self.fonts.cyri.scale(14))
2918 .set(self.ids.song_info, ui_widgets);
2919 Text::new(&format!(
2920 "Active channels: M{}, A{}, S{}, U{}, CPU: {:2.0}%",
2921 debug_info.active_channels.music,
2922 debug_info.active_channels.ambience,
2923 debug_info.active_channels.sfx,
2924 debug_info.active_channels.ui,
2925 debug_info.audio_cpu_usage * 100.0,
2926 ))
2927 .color(TEXT_COLOR)
2928 .down_from(self.ids.song_info, V_PAD)
2929 .font_id(self.fonts.cyri.conrod_id)
2930 .font_size(self.fonts.cyri.scale(14))
2931 .set(self.ids.active_channels, ui_widgets);
2932
2933 Text::new(&format!("Lights: {}", debug_info.num_lights,))
2935 .color(TEXT_COLOR)
2936 .down_from(self.ids.active_channels, V_PAD)
2937 .font_id(self.fonts.cyri.conrod_id)
2938 .font_size(self.fonts.cyri.scale(14))
2939 .set(self.ids.num_lights, ui_widgets);
2940
2941 Text::new(&format!(
2943 "Figures: {} ({} visible)",
2944 debug_info.num_figures, debug_info.num_figures_visible,
2945 ))
2946 .color(TEXT_COLOR)
2947 .down_from(self.ids.num_lights, V_PAD)
2948 .font_id(self.fonts.cyri.conrod_id)
2949 .font_size(self.fonts.cyri.scale(14))
2950 .set(self.ids.num_figures, ui_widgets);
2951
2952 Text::new(&format!(
2954 "Particles: {} ({} visible)",
2955 debug_info.num_particles, debug_info.num_particles_visible,
2956 ))
2957 .color(TEXT_COLOR)
2958 .down_from(self.ids.num_figures, V_PAD)
2959 .font_id(self.fonts.cyri.conrod_id)
2960 .font_size(self.fonts.cyri.scale(14))
2961 .set(self.ids.num_particles, ui_widgets);
2962
2963 Text::new(&format!(
2965 "Graphics backend: {}",
2966 global_state.window.renderer().graphics_backend(),
2967 ))
2968 .color(TEXT_COLOR)
2969 .down_from(self.ids.num_particles, V_PAD)
2970 .font_id(self.fonts.cyri.conrod_id)
2971 .font_size(self.fonts.cyri.scale(14))
2972 .set(self.ids.graphics_backend, ui_widgets);
2973
2974 let gpu_timings = global_state.window.renderer().timings();
2975 let mut timings_height = 0.0;
2976
2977 if !gpu_timings.is_empty() {
2979 let num_timings = gpu_timings.len();
2980 if self.ids.gpu_timings.len() < num_timings {
2982 self.ids
2983 .gpu_timings
2984 .resize(num_timings, &mut ui_widgets.widget_id_generator());
2985 }
2986
2987 for (i, timing) in gpu_timings.iter().enumerate() {
2988 let label = timing.1;
2989 if label.starts_with(crate::render::UI_PREMULTIPLY_PASS) {
2991 continue;
2992 }
2993 let timings_text =
2994 &format!("{:16}{:.3} ms", &format!("{label}:"), timing.2 * 1000.0,);
2995 let timings_widget = Text::new(timings_text)
2996 .color(TEXT_COLOR)
2997 .down(V_PAD)
2998 .x_place_on(
2999 self.ids.debug_bg,
3000 conrod_core::position::Place::Start(Some(
3001 H_PAD + 10.0 * timing.0 as f64,
3002 )),
3003 )
3004 .font_id(self.fonts.cyri.conrod_id)
3005 .font_size(self.fonts.cyri.scale(14));
3006
3007 timings_height += timings_widget.get_h(ui_widgets).unwrap_or(0.0) + V_PAD;
3009
3010 timings_widget.set(self.ids.gpu_timings[i], ui_widgets);
3011 }
3012 }
3013
3014 let debug_bg_size = [375.0, 405.0 + timings_height];
3018
3019 Rectangle::fill(debug_bg_size)
3020 .rgba(0.0, 0.0, 0.0, global_state.settings.chat.chat_opacity)
3021 .top_left_with_margins_on(ui_widgets.window, 10.0, 10.0)
3022 .set(self.ids.debug_bg, ui_widgets);
3023 }
3024
3025 if global_state.settings.interface.toggle_hotkey_hints {
3026 if let Some(help_key) = global_state
3028 .settings
3029 .controls
3030 .get_binding(GameInput::Controls)
3031 {
3032 Text::new(&i18n.get_msg_ctx(
3033 "hud-press_key_to_show_keybindings_fmt",
3034 &i18n::fluent_args! {
3035 "key" => help_key.display_string(),
3036 },
3037 ))
3038 .color(TEXT_COLOR)
3039 .bottom_left_with_margins_on(ui_widgets.window, 210.0, 10.0)
3040 .font_id(self.fonts.cyri.conrod_id)
3041 .font_size(self.fonts.cyri.scale(12))
3042 .set(self.ids.help_info, ui_widgets);
3043 }
3044 if let Some(toggle_lantern_key) = global_state
3046 .settings
3047 .controls
3048 .get_binding(GameInput::ToggleLantern)
3049 {
3050 Text::new(&i18n.get_msg_ctx(
3051 "hud-press_key_to_toggle_lantern_fmt",
3052 &i18n::fluent_args! {
3053 "key" => toggle_lantern_key.display_string(),
3054 },
3055 ))
3056 .color(TEXT_COLOR)
3057 .up_from(self.ids.help_info, 2.0)
3058 .font_id(self.fonts.cyri.conrod_id)
3059 .font_size(self.fonts.cyri.scale(12))
3060 .set(self.ids.lantern_info, ui_widgets);
3061 }
3062 }
3063
3064 let ecs = client.state().ecs();
3066 let stats = ecs.read_storage::<comp::Stats>();
3068 let skill_sets = ecs.read_storage::<comp::SkillSet>();
3069 let buffs = ecs.read_storage::<comp::Buffs>();
3070 let msm = ecs.read_resource::<MaterialStatManifest>();
3071 let time = ecs.read_resource::<Time>();
3072
3073 match Buttons::new(
3074 &self.imgs,
3075 &self.fonts,
3076 global_state,
3077 &self.rot_imgs,
3078 tooltip_manager,
3079 i18n,
3080 )
3081 .set(self.ids.buttons, ui_widgets)
3082 {
3083 Some(buttons::Event::ToggleSettings) => self.show.toggle_settings(global_state),
3084 Some(buttons::Event::ToggleSocial) => self.show.toggle_social(),
3085 Some(buttons::Event::ToggleMap) => self.show.toggle_map(),
3086 Some(buttons::Event::ToggleCrafting) => self.show.toggle_crafting(),
3087 None => {},
3088 }
3089
3090 for event in Group::new(
3092 &mut self.show,
3093 client,
3094 &global_state.settings,
3095 &self.imgs,
3096 &self.rot_imgs,
3097 &self.fonts,
3098 i18n,
3099 self.pulse,
3100 global_state,
3101 tooltip_manager,
3102 &msm,
3103 &time,
3104 )
3105 .set(self.ids.group_window, ui_widgets)
3106 {
3107 match event {
3108 group::Event::Accept => events.push(Event::AcceptInvite),
3109 group::Event::Decline => events.push(Event::DeclineInvite),
3110 group::Event::Kick(uid) => events.push(Event::KickMember(uid)),
3111 group::Event::LeaveGroup => events.push(Event::LeaveGroup),
3112 group::Event::AssignLeader(uid) => events.push(Event::AssignLeader(uid)),
3113 }
3114 }
3115 Popup::new(
3117 i18n,
3118 client,
3119 &self.new_notifications,
3120 &self.fonts,
3121 &self.show,
3122 )
3123 .set(self.ids.popup, ui_widgets);
3124
3125 let persisted_state = self.persisted_state.borrow();
3126 for event in MiniMap::new(
3128 client,
3129 &self.imgs,
3130 &self.rot_imgs,
3131 &self.world_map,
3132 &self.fonts,
3133 self.pulse,
3134 camera.get_orientation(),
3135 global_state,
3136 &persisted_state.location_markers,
3137 &self.voxel_minimap,
3138 &self.extra_markers,
3139 )
3140 .set(self.ids.minimap, ui_widgets)
3141 {
3142 match event {
3143 minimap::Event::SettingsChange(interface_change) => {
3144 events.push(Event::SettingsChange(interface_change.into()));
3145 },
3146 }
3147 }
3148 drop(persisted_state);
3149
3150 if let Some(prompt_dialog_settings) = &self.show.prompt_dialog {
3151 match PromptDialog::new(
3153 &self.imgs,
3154 &self.fonts,
3155 &global_state.i18n,
3156 &global_state.settings,
3157 prompt_dialog_settings,
3158 )
3159 .set(self.ids.prompt_dialog, ui_widgets)
3160 {
3161 Some(dialog_outcome_event) => {
3162 match dialog_outcome_event {
3163 DialogOutcomeEvent::Affirmative(event) => events.push(event),
3164 DialogOutcomeEvent::Negative(event) => {
3165 if let Some(event) = event {
3166 events.push(event);
3167 };
3168 },
3169 };
3170
3171 self.show.prompt_dialog = None;
3173 },
3174 None => {},
3175 }
3176 }
3177
3178 let ecs = client.state().ecs();
3181 let entity = info.viewpoint_entity;
3182 let healths = ecs.read_storage::<Health>();
3183 let inventories = ecs.read_storage::<comp::Inventory>();
3184 let rbm = ecs.read_resource::<RecipeBookManifest>();
3185 let energies = ecs.read_storage::<comp::Energy>();
3186 let skillsets = ecs.read_storage::<comp::SkillSet>();
3187 let active_abilities = ecs.read_storage::<comp::ActiveAbilities>();
3188 let bodies = ecs.read_storage::<comp::Body>();
3189 let poises = ecs.read_storage::<comp::Poise>();
3190 let uids = ecs.read_storage::<Uid>();
3191 let combos = ecs.read_storage::<comp::Combo>();
3192 let combo = combos.get(entity);
3193 let time = ecs.read_resource::<Time>();
3194 let stances = ecs.read_storage::<comp::Stance>();
3195 let char_states = ecs.read_storage::<comp::CharacterState>();
3196 self.floaters.combo_floater = self.floaters.combo_floater.map(|mut f| {
3198 f.timer -= dt.as_secs_f64();
3199 f
3200 });
3201 self.floaters.combo_floater = self.floaters.combo_floater.filter(|f| f.timer > 0_f64);
3202
3203 if let (
3204 Some(health),
3205 Some(inventory),
3206 Some(energy),
3207 Some(poise),
3208 Some(skillset),
3209 Some(body),
3210 ) = (
3211 healths.get(entity),
3212 inventories.get(entity),
3213 energies.get(entity),
3214 poises.get(entity),
3215 skillsets.get(entity),
3216 bodies.get(entity),
3217 ) {
3218 let stance = stances.get(entity);
3219 let context = AbilityContext::from(stance, Some(inventory), combo);
3220
3221 let skillbar_events = Skillbar::new(
3222 client,
3223 &info,
3224 global_state,
3225 &self.imgs,
3226 &self.item_imgs,
3227 &self.fonts,
3228 &self.rot_imgs,
3229 health,
3230 inventory,
3231 energy,
3232 poise,
3233 skillset,
3234 active_abilities.get(entity),
3235 body,
3236 self.pulse,
3238 &self.hotbar,
3240 tooltip_manager,
3241 item_tooltip_manager,
3242 &mut self.slot_manager,
3243 i18n,
3244 &self.item_i18n,
3245 &msm,
3246 &rbm,
3247 self.floaters.combo_floater,
3248 &context,
3249 combo,
3250 char_states.get(entity),
3251 stance,
3252 stats.get(entity),
3253 )
3254 .set(self.ids.skillbar, ui_widgets);
3255
3256 for event in skillbar_events {
3257 match event {
3258 skillbar::Event::OpenDiary(skillgroup) => {
3259 self.show.diary(true);
3260 self.show.open_skill_tree(skillgroup);
3261 },
3262 skillbar::Event::OpenBag => self.show.bag(!self.show.bag),
3263 }
3264 }
3265 }
3266 if self.show.bag
3268 && let (
3269 Some(player_stats),
3270 Some(skill_set),
3271 Some(health),
3272 Some(energy),
3273 Some(body),
3274 Some(poise),
3275 ) = (
3276 stats.get(info.viewpoint_entity),
3277 skill_sets.get(info.viewpoint_entity),
3278 healths.get(entity),
3279 energies.get(entity),
3280 bodies.get(entity),
3281 poises.get(entity),
3282 )
3283 {
3284 match Bag::new(
3285 client,
3286 &info,
3287 global_state,
3288 &self.imgs,
3289 &self.item_imgs,
3290 &self.fonts,
3291 &self.rot_imgs,
3292 tooltip_manager,
3293 item_tooltip_manager,
3294 &mut self.slot_manager,
3295 self.pulse,
3296 i18n,
3297 &self.item_i18n,
3298 player_stats,
3299 skill_set,
3300 health,
3301 energy,
3302 &self.show,
3303 body,
3304 &msm,
3305 &rbm,
3306 poise,
3307 )
3308 .set(self.ids.bag, ui_widgets)
3309 {
3310 Some(bag::Event::BagExpand) => self.show.bag_inv = !self.show.bag_inv,
3311 Some(bag::Event::SetDetailsMode(mode)) => self.show.bag_details = mode,
3312 Some(bag::Event::Close) => {
3313 self.show.stats = false;
3314 Self::show_bag(&mut self.slot_manager, &mut self.show, false);
3315 if !self.show.social {
3316 self.show.want_grab = true;
3317 self.force_ungrab = false;
3318 } else {
3319 self.force_ungrab = true
3320 };
3321 },
3322 Some(bag::Event::ChangeInventorySortOrder(sort_order)) => {
3323 self.events
3324 .push(Event::SettingsChange(SettingsChange::Inventory(
3325 Inventory::ChangeSortOrder(sort_order),
3326 )));
3327 },
3328 Some(bag::Event::SortInventory(sort_order)) => {
3329 self.events.push(Event::SortInventory(sort_order))
3330 },
3331 Some(bag::Event::SwapEquippedWeapons) => {
3332 self.events.push(Event::SwapEquippedWeapons)
3333 },
3334 None => {},
3335 }
3336 }
3337 if self.show.trade
3339 && let Some(action) = Trade::new(
3340 client,
3341 &info,
3342 &self.imgs,
3343 &self.item_imgs,
3344 &self.fonts,
3345 &self.rot_imgs,
3346 tooltip_manager,
3347 item_tooltip_manager,
3348 &mut self.slot_manager,
3349 i18n,
3350 &self.item_i18n,
3351 &msm,
3352 &rbm,
3353 self.pulse,
3354 &mut self.show,
3355 )
3356 .set(self.ids.trade, ui_widgets)
3357 {
3358 match action {
3359 trade::TradeEvent::HudUpdate(update) => match update {
3360 trade::HudUpdate::Focus(idx) => self.to_focus = Some(Some(idx)),
3361 trade::HudUpdate::Submit => {
3362 let key = self.show.trade_amount_input_key.take();
3363 key.map(|k| {
3364 k.submit_action.map(|action| {
3365 self.events.push(Event::TradeAction(action));
3366 });
3367 });
3368 },
3369 },
3370 trade::TradeEvent::TradeAction(action) => {
3371 if let TradeAction::Decline = action {
3372 self.show.stats = false;
3373 self.show.trade(false);
3374 if !self.show.social {
3375 self.show.want_grab = true;
3376 self.force_ungrab = false;
3377 } else {
3378 self.force_ungrab = true
3379 };
3380 self.show.prompt_dialog = None;
3381 }
3382 events.push(Event::TradeAction(action));
3383 },
3384 trade::TradeEvent::SetDetailsMode(mode) => {
3385 self.show.trade_details = mode;
3386 },
3387 trade::TradeEvent::ShowPrompt(prompt) => {
3388 self.show.prompt_dialog = Some(prompt);
3389 },
3390 }
3391 }
3392
3393 if let (Some(player_buffs), Some(health), Some(energy)) = (
3395 buffs.get(info.viewpoint_entity),
3396 healths.get(entity),
3397 energies.get(entity),
3398 ) {
3399 for event in BuffsBar::new(
3400 &self.imgs,
3401 &self.fonts,
3402 &self.rot_imgs,
3403 tooltip_manager,
3404 i18n,
3405 player_buffs,
3406 stances.get(entity),
3407 self.pulse,
3408 global_state,
3409 health,
3410 energy,
3411 &time,
3412 )
3413 .set(self.ids.buffs, ui_widgets)
3414 {
3415 match event {
3416 buffs::Event::RemoveBuff(buff_id) => events.push(Event::RemoveBuff(buff_id)),
3417 buffs::Event::LeaveStance => events.push(Event::LeaveStance),
3418 }
3419 }
3420 }
3421 if self.show.crafting
3423 && let Some(inventory) = inventories.get(entity)
3424 {
3425 for event in Crafting::new(
3426 client,
3428 &info,
3429 &self.imgs,
3430 &self.fonts,
3431 i18n,
3432 &self.item_i18n,
3433 self.pulse,
3434 &self.rot_imgs,
3435 item_tooltip_manager,
3436 &mut self.slot_manager,
3437 &self.item_imgs,
3438 inventory,
3439 &rbm,
3440 &msm,
3441 tooltip_manager,
3442 &mut self.show,
3443 &global_state.settings,
3444 )
3445 .set(self.ids.crafting_window, ui_widgets)
3446 {
3447 match event {
3448 crafting::Event::CraftRecipe {
3449 recipe_name,
3450 amount,
3451 } => {
3452 events.push(Event::CraftRecipe {
3453 recipe_name,
3454 craft_sprite: self.show.crafting_fields.craft_sprite,
3455 amount,
3456 });
3457 },
3458 crafting::Event::CraftModularWeapon {
3459 primary_slot,
3460 secondary_slot,
3461 } => {
3462 events.push(Event::CraftModularWeapon {
3463 primary_slot,
3464 secondary_slot,
3465 craft_sprite: self
3466 .show
3467 .crafting_fields
3468 .craft_sprite
3469 .map(|(pos, _sprite)| pos),
3470 });
3471 },
3472 crafting::Event::CraftModularWeaponComponent {
3473 toolkind,
3474 material,
3475 modifier,
3476 } => {
3477 events.push(Event::CraftModularWeaponComponent {
3478 toolkind,
3479 material,
3480 modifier,
3481 craft_sprite: self
3482 .show
3483 .crafting_fields
3484 .craft_sprite
3485 .map(|(pos, _sprite)| pos),
3486 });
3487 },
3488 crafting::Event::Close => {
3489 self.show.stats = false;
3490 self.show.crafting(false);
3491 if !self.show.social {
3492 self.show.want_grab = true;
3493 self.force_ungrab = false;
3494 } else {
3495 self.force_ungrab = true
3496 };
3497 },
3498 crafting::Event::ChangeCraftingTab(sel_cat) => {
3499 self.show.open_crafting_tab(sel_cat, None);
3500 },
3501 crafting::Event::Focus(widget_id) => {
3502 self.to_focus = Some(Some(widget_id));
3503 },
3504 crafting::Event::SearchRecipe(search_key) => {
3505 self.show.search_crafting_recipe(search_key);
3506 },
3507 crafting::Event::ClearRecipeInputs => {
3508 self.show.crafting_fields.recipe_inputs.clear();
3509 },
3510 crafting::Event::RepairItem { slot } => {
3511 if let Some(sprite_pos) = self
3512 .show
3513 .crafting_fields
3514 .craft_sprite
3515 .map(|(pos, _sprite)| pos)
3516 {
3517 events.push(Event::RepairItem {
3518 item: slot,
3519 sprite_pos,
3520 });
3521 }
3522 },
3523 crafting::Event::ShowAllRecipes(show) => {
3524 events.push(Event::SettingsChange(SettingsChange::Gameplay(
3525 crate::session::settings_change::Gameplay::ChangeShowAllRecipes(show),
3526 )));
3527 },
3528 }
3529 }
3530 }
3531
3532 if global_state.settings.audio.subtitles {
3533 Subtitles::new(
3534 client,
3535 &global_state.settings,
3536 global_state.audio.get_listener_pos(),
3537 global_state.audio.get_listener_ori(),
3538 &mut global_state.audio.subtitles,
3539 &self.fonts,
3540 i18n,
3541 )
3542 .set(self.ids.subtitles, ui_widgets);
3543 }
3544 let inventory = inventories.get(entity);
3545 LootScroller::new(
3547 &mut self.new_loot_messages,
3548 client,
3549 &info,
3550 &self.show,
3551 &self.imgs,
3552 &self.item_imgs,
3553 &self.rot_imgs,
3554 &self.fonts,
3555 i18n,
3556 &self.item_i18n,
3557 &msm,
3558 &rbm,
3559 inventory,
3560 item_tooltip_manager,
3561 self.pulse,
3562 )
3563 .set(self.ids.loot_scroller, ui_widgets);
3564
3565 self.new_loot_messages.clear();
3566
3567 self.new_messages.retain(chat::show_in_chatbox);
3568
3569 if global_state.settings.interface.toggle_chat || self.force_chat {
3574 for hidden in self
3577 .persisted_state
3578 .borrow_mut()
3579 .message_backlog
3580 .0
3581 .drain(..)
3582 .rev()
3583 {
3584 self.new_messages.push_front(hidden);
3585 }
3586 for event in Chat::new(
3587 &mut self.new_messages,
3588 client,
3589 global_state,
3590 self.pulse,
3591 &self.imgs,
3592 &self.fonts,
3593 i18n,
3594 scale,
3595 self.clear_chat,
3596 )
3597 .and_then(self.force_chat_input.take(), |c, input| c.input(input))
3598 .and_then(self.tab_complete.take(), |c, input| {
3599 c.prepare_tab_completion(input)
3600 })
3601 .and_then(self.force_chat_cursor.take(), |c, pos| c.cursor_pos(pos))
3602 .set(self.ids.chat, ui_widgets)
3603 {
3604 match event {
3605 chat::Event::TabCompletionStart(input) => {
3606 self.tab_complete = Some(input);
3607 },
3608 chat::Event::SendMessage(message) => {
3609 events.push(Event::SendMessage(message));
3610 },
3611 chat::Event::SendCommand(name, args) => {
3612 events.push(Event::SendCommand(name, args));
3613 },
3614 chat::Event::Focus(focus_id) => {
3615 self.to_focus = Some(Some(focus_id));
3616 },
3617 chat::Event::ChangeChatTab(tab) => {
3618 events.push(Event::SettingsChange(ChatChange::ChangeChatTab(tab).into()));
3619 },
3620 chat::Event::ShowChatTabSettings(tab) => {
3621 self.show.chat_tab_settings_index = Some(tab);
3622 self.show.settings_tab = SettingsTab::Chat;
3623 self.show.settings(true);
3624 },
3625 chat::Event::ResizeChat(size) => {
3626 global_state.settings.chat.chat_size_x = size.x;
3627 global_state.settings.chat.chat_size_y = size.y;
3628 },
3629 chat::Event::MoveChat(pos) => {
3630 global_state.settings.chat.chat_pos_x = pos.x;
3631 global_state.settings.chat.chat_pos_y = pos.y;
3632 },
3633 chat::Event::DisableForceChat => {
3634 self.force_chat = false;
3635 },
3636 }
3637 }
3638
3639 self.clear_chat = false;
3641 } else {
3642 let mut persisted_state = self.persisted_state.borrow_mut();
3643 for message in self.new_messages.drain(..) {
3644 persisted_state
3645 .message_backlog
3646 .new_message(client, &global_state.profile, message);
3647 }
3648 }
3649
3650 self.new_messages.clear();
3651 self.new_notifications.clear();
3652
3653 if let Windows::Settings = self.show.open_windows {
3661 for event in SettingsWindow::new(
3662 global_state,
3663 &self.show,
3664 &self.imgs,
3665 &self.fonts,
3666 i18n,
3667 client.server_view_distance_limit(),
3668 fps as f32,
3669 )
3670 .set(self.ids.settings_window, ui_widgets)
3671 {
3672 match event {
3673 settings_window::Event::ChangeTab(tab) => self.show.open_setting_tab(tab),
3674 settings_window::Event::Close => {
3675 #[cfg(feature = "singleplayer")]
3677 global_state.unpause();
3678 self.show.want_grab = true;
3679 self.force_ungrab = false;
3680
3681 self.show.settings(false)
3682 },
3683 settings_window::Event::ChangeChatSettingsTab(tab) => {
3684 self.show.chat_tab_settings_index = tab;
3685 },
3686 settings_window::Event::SettingsChange(settings_change) => {
3687 events.push(Event::SettingsChange(settings_change));
3688 },
3689 }
3690 }
3691 }
3692 let stats = client.state().ecs().read_storage::<comp::Stats>();
3694 let interpolated = client.state().ecs().read_storage::<vcomp::Interpolated>();
3695 if let Some((sender, _, dialogue)) = &self.current_dialogue
3696 && let Some(i) = interpolated.get(*sender)
3697 && let Some(player_i) = interpolated.get(client.entity())
3698 && i.pos.distance_squared(player_i.pos) > MAX_NPCINTERACT_RANGE.powi(2)
3699 {
3700 self.show.quest(false);
3701 events.push(Event::Dialogue(*sender, rtsim::Dialogue {
3702 id: dialogue.id,
3703 kind: rtsim::DialogueKind::End,
3704 }));
3705 }
3706
3707 let dialogue_open = if self.show.quest
3708 && let Some((sender, time, dialogue)) = &self.current_dialogue
3709 {
3710 match Quest::new(
3711 &self.show,
3712 client,
3713 &self.imgs,
3714 &self.fonts,
3715 i18n,
3716 global_state,
3717 &self.rot_imgs,
3718 tooltip_manager,
3719 &self.item_imgs,
3720 *sender,
3721 dialogue,
3722 *time,
3723 self.pulse,
3724 )
3725 .set(self.ids.quest_window, ui_widgets)
3726 {
3727 Some(quest::Event::Dialogue(target, dialogue)) => {
3728 events.push(Event::Dialogue(target, dialogue));
3729 true
3730 },
3731 Some(quest::Event::Close) => {
3732 self.show.quest(false);
3733 if !self.show.bag {
3734 self.show.want_grab = true;
3735 self.force_ungrab = false;
3736 } else {
3737 self.force_ungrab = true
3738 };
3739 false
3740 },
3741 None => true,
3742 }
3743 } else {
3744 false
3745 };
3746
3747 if !dialogue_open && let Some((sender, _, dialogue)) = self.current_dialogue.take() {
3748 events.push(Event::Dialogue(sender, rtsim::Dialogue {
3749 id: dialogue.id,
3750 kind: rtsim::DialogueKind::End,
3751 }));
3752 }
3753
3754 if self.show.social {
3756 let ecs = client.state().ecs();
3757 let _stats = ecs.read_storage::<comp::Stats>();
3758 for event in Social::new(
3759 &self.show,
3760 client,
3761 &self.imgs,
3762 &self.fonts,
3763 i18n,
3764 info.selected_entity,
3765 &self.rot_imgs,
3766 tooltip_manager,
3767 global_state,
3768 )
3769 .set(self.ids.social_window, ui_widgets)
3770 {
3771 match event {
3772 social::Event::Close => {
3773 self.show.social(false);
3774 if !self.show.bag {
3775 self.show.want_grab = true;
3776 self.force_ungrab = false;
3777 } else {
3778 self.force_ungrab = true
3779 };
3780 },
3781 social::Event::Focus(widget_id) => {
3782 self.to_focus = Some(Some(widget_id));
3783 },
3784 social::Event::Invite(uid) => events.push(Event::InviteMember(uid)),
3785 social::Event::SearchPlayers(search_key) => {
3786 self.show.search_social_players(search_key)
3787 },
3788 social::Event::SetBattleMode(mode) => {
3789 events.push(Event::SetBattleMode(mode));
3790 },
3791 }
3792 }
3793 }
3794
3795 if self.show.diary {
3797 let entity = info.viewpoint_entity;
3798 let skill_sets = ecs.read_storage::<comp::SkillSet>();
3799 if let (
3800 Some(skill_set),
3801 Some(inventory),
3802 Some(char_state),
3803 Some(health),
3804 Some(energy),
3805 Some(body),
3806 Some(poise),
3807 Some(uid),
3808 ) = (
3809 skill_sets.get(entity),
3810 inventories.get(entity),
3811 char_states.get(entity),
3812 healths.get(entity),
3813 energies.get(entity),
3814 bodies.get(entity),
3815 poises.get(entity),
3816 uids.get(entity),
3817 ) {
3818 let context = AbilityContext::from(stances.get(entity), Some(inventory), combo);
3819 for event in Diary::new(
3820 &self.show,
3821 client,
3822 global_state,
3823 skill_set,
3824 active_abilities.get(entity).unwrap_or(&Default::default()),
3825 inventory,
3826 char_state,
3827 health,
3828 energy,
3829 poise,
3830 body,
3831 uid,
3832 &msm,
3833 &self.imgs,
3834 &self.item_imgs,
3835 &self.fonts,
3836 i18n,
3837 &self.item_i18n,
3838 &self.rot_imgs,
3839 tooltip_manager,
3840 &mut self.slot_manager,
3841 self.pulse,
3842 &context,
3843 stats.get(entity),
3844 )
3845 .set(self.ids.diary, ui_widgets)
3846 {
3847 match event {
3848 diary::Event::Close => {
3849 self.show.diary(false);
3850 self.show.want_grab = true;
3851 self.force_ungrab = false;
3852 },
3853 diary::Event::ChangeSkillTree(tree_sel) => {
3854 self.show.open_skill_tree(tree_sel)
3855 },
3856 diary::Event::UnlockSkill(skill) => events.push(Event::UnlockSkill(skill)),
3857 diary::Event::ChangeSection(section) => {
3858 self.show.diary_fields.section = section;
3859 },
3860 diary::Event::SelectExpBar(xp_bar) => {
3861 events.push(Event::SelectExpBar(xp_bar))
3862 },
3863 }
3864 }
3865 }
3866 }
3867 if self.show.map {
3869 let mut persisted_state = self.persisted_state.borrow_mut();
3870 for event in Map::new(
3871 client,
3872 &self.imgs,
3873 &self.rot_imgs,
3874 &self.world_map,
3875 &self.fonts,
3876 self.pulse,
3877 i18n,
3878 global_state,
3879 tooltip_manager,
3880 &persisted_state.location_markers,
3881 self.map_drag,
3882 &self.extra_markers,
3883 )
3884 .set(self.ids.map, ui_widgets)
3885 {
3886 match event {
3887 map::Event::Close => {
3888 self.show.map(false);
3889 self.show.want_grab = true;
3890 self.force_ungrab = false;
3891 },
3892 map::Event::SettingsChange(settings_change) => {
3893 events.push(Event::SettingsChange(settings_change.into()));
3894 },
3895 map::Event::RequestSiteInfo(id) => {
3896 events.push(Event::RequestSiteInfo(id));
3897 },
3898 map::Event::SetLocationMarker(pos) => {
3899 events.push(Event::MapMarkerEvent(MapMarkerChange::Update(pos)));
3900 persisted_state
3901 .location_markers
3902 .update(comp::MapMarkerUpdate::Owned(MapMarkerChange::Update(pos)));
3903 },
3904 map::Event::MapDrag(new_drag) => {
3905 self.map_drag = new_drag;
3906 },
3907 map::Event::RemoveMarker => {
3908 persisted_state
3909 .location_markers
3910 .update(comp::MapMarkerUpdate::Owned(MapMarkerChange::Remove));
3911 events.push(Event::MapMarkerEvent(MapMarkerChange::Remove));
3912 },
3913 }
3914 }
3915 } else {
3916 self.map_drag = Vec2::zero();
3918 }
3919
3920 if self.show.esc_menu {
3921 match EscMenu::new(&self.imgs, &self.fonts, i18n).set(self.ids.esc_menu, ui_widgets) {
3922 Some(esc_menu::Event::OpenSettings(tab)) => {
3923 self.show.open_setting_tab(tab);
3924 },
3925 Some(esc_menu::Event::Close) => {
3926 self.show.esc_menu = false;
3927 self.show.want_grab = true;
3928 self.force_ungrab = false;
3929
3930 #[cfg(feature = "singleplayer")]
3932 global_state.unpause();
3933 },
3934 Some(esc_menu::Event::Logout) => {
3935 #[cfg(feature = "singleplayer")]
3937 global_state.unpause();
3938
3939 events.push(Event::Logout);
3940 },
3941 Some(esc_menu::Event::Quit) => events.push(Event::Quit),
3942 Some(esc_menu::Event::CharacterSelection) => {
3943 #[cfg(feature = "singleplayer")]
3945 global_state.unpause();
3946
3947 events.push(Event::CharacterSelection)
3948 },
3949 None => {},
3950 }
3951 }
3952
3953 let mut indicator_offset = 40.0;
3954
3955 if let Some(freelook_key) = global_state
3957 .settings
3958 .controls
3959 .get_binding(GameInput::FreeLook)
3960 && self.show.free_look
3961 {
3962 let msg = i18n.get_msg_ctx("hud-free_look_indicator", &i18n::fluent_args! {
3963 "key" => freelook_key.display_string(),
3964 });
3965 Text::new(&msg)
3966 .color(TEXT_BG)
3967 .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
3968 .font_id(self.fonts.cyri.conrod_id)
3969 .font_size(self.fonts.cyri.scale(20))
3970 .set(self.ids.free_look_bg, ui_widgets);
3971 indicator_offset += 30.0;
3972 Text::new(&msg)
3973 .color(KILL_COLOR)
3974 .top_left_with_margins_on(self.ids.free_look_bg, -1.0, -1.0)
3975 .font_id(self.fonts.cyri.conrod_id)
3976 .font_size(self.fonts.cyri.scale(20))
3977 .set(self.ids.free_look_txt, ui_widgets);
3978 };
3979
3980 if self.show.auto_walk {
3982 Text::new(&i18n.get_msg("hud-auto_walk_indicator"))
3983 .color(TEXT_BG)
3984 .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
3985 .font_id(self.fonts.cyri.conrod_id)
3986 .font_size(self.fonts.cyri.scale(20))
3987 .set(self.ids.auto_walk_bg, ui_widgets);
3988 indicator_offset += 30.0;
3989 Text::new(&i18n.get_msg("hud-auto_walk_indicator"))
3990 .color(KILL_COLOR)
3991 .top_left_with_margins_on(self.ids.auto_walk_bg, -1.0, -1.0)
3992 .font_id(self.fonts.cyri.conrod_id)
3993 .font_size(self.fonts.cyri.scale(20))
3994 .set(self.ids.auto_walk_txt, ui_widgets);
3995 }
3996
3997 self.show.zoom_lock.update(dt);
3999
4000 if let Some(zoom_lock) = self.show.zoom_lock.reason {
4001 let zoom_lock_message = match zoom_lock {
4002 NotificationReason::Remind => "hud-zoom_lock_indicator-remind",
4003 NotificationReason::Enable => "hud-zoom_lock_indicator-enable",
4004 NotificationReason::Disable => "hud-zoom_lock_indicator-disable",
4005 };
4006
4007 Text::new(&i18n.get_msg(zoom_lock_message))
4008 .color(TEXT_BG.alpha(self.show.zoom_lock.alpha))
4009 .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
4010 .font_id(self.fonts.cyri.conrod_id)
4011 .font_size(self.fonts.cyri.scale(20))
4012 .set(self.ids.zoom_lock_bg, ui_widgets);
4013 indicator_offset += 30.0;
4014 Text::new(&i18n.get_msg(zoom_lock_message))
4015 .color(TEXT_COLOR.alpha(self.show.zoom_lock.alpha))
4016 .top_left_with_margins_on(self.ids.zoom_lock_bg, -1.0, -1.0)
4017 .font_id(self.fonts.cyri.conrod_id)
4018 .font_size(self.fonts.cyri.scale(20))
4019 .set(self.ids.zoom_lock_txt, ui_widgets);
4020 }
4021
4022 if let Some(cameraclamp_key) = global_state
4024 .settings
4025 .controls
4026 .get_binding(GameInput::CameraClamp)
4027 && self.show.camera_clamp
4028 {
4029 let msg = i18n.get_msg_ctx("hud-camera_clamp_indicator", &i18n::fluent_args! {
4030 "key" => cameraclamp_key.display_string(),
4031 });
4032 Text::new(&msg)
4033 .color(TEXT_BG)
4034 .mid_top_with_margin_on(ui_widgets.window, indicator_offset)
4035 .font_id(self.fonts.cyri.conrod_id)
4036 .font_size(self.fonts.cyri.scale(20))
4037 .set(self.ids.camera_clamp_bg, ui_widgets);
4038 Text::new(&msg)
4039 .color(KILL_COLOR)
4040 .top_left_with_margins_on(self.ids.camera_clamp_bg, -1.0, -1.0)
4041 .font_id(self.fonts.cyri.conrod_id)
4042 .font_size(self.fonts.cyri.scale(20))
4043 .set(self.ids.camera_clamp_txt, ui_widgets);
4044 }
4045
4046 'slot_events: for event in self.slot_manager.maintain(ui_widgets) {
4048 use slots::{AbilitySlot, InventorySlot, SlotKind::*};
4049 let to_slot = |slot_kind| match slot_kind {
4050 Inventory(
4051 i @ InventorySlot {
4052 slot: Slot::Inventory(_) | Slot::Overflow(_),
4053 ours: true,
4054 ..
4055 },
4056 ) => Some(i.slot),
4057 Inventory(InventorySlot {
4058 slot: Slot::Equip(_),
4059 ours: true,
4060 ..
4061 }) => None,
4062 Inventory(InventorySlot { ours: false, .. }) => None,
4063 Equip(e) => Some(Slot::Equip(e)),
4064 Hotbar(_) => None,
4065 Trade(_) => None,
4066 Ability(_) => None,
4067 Crafting(_) => None,
4068 };
4069 match event {
4070 slot::Event::Dragged(a, b) => {
4071 if let (Some(a), Some(b)) = (to_slot(a), to_slot(b)) {
4073 events.push(Event::SwapSlots {
4074 slot_a: a,
4075 slot_b: b,
4076 bypass_dialog: false,
4077 });
4078 } else if let (
4079 Inventory(InventorySlot {
4080 slot, ours: true, ..
4081 }),
4082 Hotbar(h),
4083 ) = (a, b)
4084 {
4085 if let Slot::Inventory(slot) = slot
4086 && let Some(item) = inventories
4087 .get(info.viewpoint_entity)
4088 .and_then(|inv| inv.get(slot))
4089 {
4090 self.hotbar.add_inventory_link(h, item);
4091 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4092 }
4093 } else if let (Hotbar(a), Hotbar(b)) = (a, b) {
4094 self.hotbar.swap(a, b);
4095 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4096 } else if let (Inventory(i), Trade(t)) = (a, b) {
4097 if i.ours == t.ours
4098 && let (Some(inventory), Slot::Inventory(slot)) =
4099 (inventories.get(t.entity), i.slot)
4100 {
4101 events.push(Event::TradeAction(TradeAction::AddItem {
4102 item: slot,
4103 quantity: i.amount(inventory).unwrap_or(1),
4104 ours: i.ours,
4105 }));
4106 }
4107 } else if let (Trade(t), Inventory(i)) = (a, b) {
4108 if i.ours == t.ours
4109 && let Some(inventory) = inventories.get(t.entity)
4110 && let Some(invslot) = t.invslot
4111 {
4112 events.push(Event::TradeAction(TradeAction::RemoveItem {
4113 item: invslot,
4114 quantity: t.amount(inventory).unwrap_or(1),
4115 ours: t.ours,
4116 }));
4117 }
4118 } else if let (Ability(a), Ability(b)) = (a, b) {
4119 match (a, b) {
4120 (AbilitySlot::Ability(ability), AbilitySlot::Slot(index)) => {
4121 events.push(Event::ChangeAbility(index, ability));
4122 },
4123 (AbilitySlot::Slot(a), AbilitySlot::Slot(b)) => {
4124 let me = info.viewpoint_entity;
4125 if let Some(active_abilities) = active_abilities.get(me) {
4126 let ability_a = active_abilities
4127 .auxiliary_set(inventories.get(me), skill_sets.get(me))
4128 .get(a)
4129 .copied()
4130 .unwrap_or(AuxiliaryAbility::Empty);
4131 let ability_b = active_abilities
4132 .auxiliary_set(inventories.get(me), skill_sets.get(me))
4133 .get(b)
4134 .copied()
4135 .unwrap_or(AuxiliaryAbility::Empty);
4136 events.push(Event::ChangeAbility(a, ability_b));
4137 events.push(Event::ChangeAbility(b, ability_a));
4138 }
4139 },
4140 (AbilitySlot::Slot(index), _) => {
4141 events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
4142 },
4143 (AbilitySlot::Ability(_), AbilitySlot::Ability(_)) => {},
4144 }
4145 } else if let (Inventory(i), Crafting(c)) = (a, b) {
4146 if let Slot::Inventory(slot) = i.slot {
4147 if inventories
4149 .get(info.viewpoint_entity)
4150 .and_then(|inv| inv.get(slot))
4151 .is_some_and(|item| {
4152 (c.requirement)(item, client.component_recipe_book(), c.info)
4153 })
4154 {
4155 self.show
4156 .crafting_fields
4157 .recipe_inputs
4158 .insert(c.index, i.slot);
4159 }
4160 }
4161 } else if let (Equip(e), Crafting(c)) = (a, b) {
4162 if inventories
4164 .get(client.entity())
4165 .and_then(|inv| inv.equipped(e))
4166 .is_some_and(|item| {
4167 (c.requirement)(item, client.component_recipe_book(), c.info)
4168 })
4169 {
4170 self.show
4171 .crafting_fields
4172 .recipe_inputs
4173 .insert(c.index, Slot::Equip(e));
4174 }
4175 } else if let (Crafting(c), Inventory(_)) = (a, b) {
4176 self.show.crafting_fields.recipe_inputs.remove(&c.index);
4178 } else if let (Ability(AbilitySlot::Ability(ability)), Hotbar(slot)) = (a, b)
4179 && let Some(Some(HotbarSlotContents::Ability(index))) =
4180 self.hotbar.slots.get(slot as usize)
4181 {
4182 events.push(Event::ChangeAbility(*index, ability));
4183 }
4184 },
4185 slot::Event::Dropped(from) => {
4186 if let Some(from) = to_slot(from) {
4188 events.push(Event::DropSlot(from));
4189 } else if let Hotbar(h) = from {
4190 self.hotbar.clear_slot(h);
4191 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4192 } else if let Trade(t) = from {
4193 if let Some(inventory) = inventories.get(t.entity)
4194 && let Some(invslot) = t.invslot
4195 {
4196 events.push(Event::TradeAction(TradeAction::RemoveItem {
4197 item: invslot,
4198 quantity: t.amount(inventory).unwrap_or(1),
4199 ours: t.ours,
4200 }));
4201 }
4202 } else if let Ability(AbilitySlot::Slot(index)) = from {
4203 events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
4204 } else if let Crafting(c) = from {
4205 self.show.crafting_fields.recipe_inputs.remove(&c.index);
4207 }
4208 },
4209 slot::Event::SplitDropped(from) => {
4210 if let Some(from) = to_slot(from) {
4212 events.push(Event::SplitDropSlot(from));
4213 } else if let Hotbar(h) = from {
4214 self.hotbar.clear_slot(h);
4215 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4216 } else if let Ability(AbilitySlot::Slot(index)) = from {
4217 events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
4218 }
4219 },
4220 slot::Event::SplitDragged(a, b) => {
4221 if let (Some(a), Some(b)) = (to_slot(a), to_slot(b)) {
4223 events.push(Event::SplitSwapSlots {
4224 slot_a: a,
4225 slot_b: b,
4226 bypass_dialog: false,
4227 });
4228 } else if let (Inventory(i), Hotbar(h)) = (a, b) {
4229 if let Slot::Inventory(slot) = i.slot
4230 && let Some(item) = inventories
4231 .get(info.viewpoint_entity)
4232 .and_then(|inv| inv.get(slot))
4233 {
4234 self.hotbar.add_inventory_link(h, item);
4235 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4236 }
4237 } else if let (Hotbar(a), Hotbar(b)) = (a, b) {
4238 self.hotbar.swap(a, b);
4239 events.push(Event::ChangeHotbarState(Box::new(self.hotbar.to_owned())));
4240 } else if let (Inventory(i), Trade(t)) = (a, b) {
4241 if i.ours == t.ours
4242 && let (Some(inventory), Slot::Inventory(slot)) =
4243 (inventories.get(t.entity), i.slot)
4244 {
4245 events.push(Event::TradeAction(TradeAction::AddItem {
4246 item: slot,
4247 quantity: i.amount(inventory).unwrap_or(1) / 2,
4248 ours: i.ours,
4249 }));
4250 }
4251 } else if let (Trade(t), Inventory(i)) = (a, b) {
4252 if i.ours == t.ours
4253 && let Some(inventory) = inventories.get(t.entity)
4254 && let Some(invslot) = t.invslot
4255 {
4256 events.push(Event::TradeAction(TradeAction::RemoveItem {
4257 item: invslot,
4258 quantity: t.amount(inventory).unwrap_or(1) / 2,
4259 ours: t.ours,
4260 }));
4261 }
4262 } else if let (Ability(a), Ability(b)) = (a, b) {
4263 match (a, b) {
4264 (AbilitySlot::Ability(ability), AbilitySlot::Slot(index)) => {
4265 events.push(Event::ChangeAbility(index, ability));
4266 },
4267 (AbilitySlot::Slot(a), AbilitySlot::Slot(b)) => {
4268 let me = info.viewpoint_entity;
4269 if let Some(active_abilities) = active_abilities.get(me) {
4270 let ability_a = active_abilities
4271 .auxiliary_set(inventories.get(me), skill_sets.get(me))
4272 .get(a)
4273 .copied()
4274 .unwrap_or(AuxiliaryAbility::Empty);
4275 let ability_b = active_abilities
4276 .auxiliary_set(inventories.get(me), skill_sets.get(me))
4277 .get(b)
4278 .copied()
4279 .unwrap_or(AuxiliaryAbility::Empty);
4280 events.push(Event::ChangeAbility(a, ability_b));
4281 events.push(Event::ChangeAbility(b, ability_a));
4282 }
4283 },
4284 (AbilitySlot::Slot(index), _) => {
4285 events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
4286 },
4287 (AbilitySlot::Ability(_), AbilitySlot::Ability(_)) => {},
4288 }
4289 }
4290 },
4291 slot::Event::Used(from) => {
4292 if let Some(from) = to_slot(from) {
4294 if self.show.crafting_fields.salvage
4295 && matches!(
4296 self.show.crafting_fields.crafting_tab,
4297 CraftingTab::Dismantle
4298 )
4299 {
4300 if let (Slot::Inventory(slot), Some((salvage_pos, _sprite_kind))) =
4301 (from, self.show.crafting_fields.craft_sprite)
4302 {
4303 events.push(Event::SalvageItem { slot, salvage_pos })
4304 }
4305 } else {
4306 events.push(Event::UseSlot {
4307 slot: from,
4308 bypass_dialog: false,
4309 });
4310 }
4311 } else if let Hotbar(h) = from {
4312 self.hotbar.get(h).map(|s| match s {
4314 hotbar::SlotContents::Inventory(i, _) => {
4315 if let Some(inv) = inventories.get(info.viewpoint_entity) {
4316 if inv
4321 .equipped(comp::slot::EquipSlot::InactiveMainhand)
4322 .is_some_and(|item| item.item_hash() == i)
4323 {
4324 events.push(Event::SwapEquippedWeapons);
4325 } else if let Some(slot) = inv.get_slot_from_hash(i) {
4326 events.push(Event::UseSlot {
4327 slot: Slot::Inventory(slot),
4328 bypass_dialog: false,
4329 });
4330 }
4331 }
4332 },
4333 hotbar::SlotContents::Ability(_) => {},
4334 });
4335 } else if let Ability(AbilitySlot::Slot(index)) = from {
4336 events.push(Event::ChangeAbility(index, AuxiliaryAbility::Empty));
4337 } else if let Crafting(c) = from {
4338 self.show.crafting_fields.recipe_inputs.remove(&c.index);
4340 }
4341 },
4342 slot::Event::Request {
4343 slot,
4344 auto_quantity,
4345 } => {
4346 if let Some((_, trade, prices)) = client.pending_trade() {
4347 let ecs = client.state().ecs();
4348 let inventories = ecs.read_component::<comp::Inventory>();
4349 let get_inventory = |uid: Uid| {
4350 if let Some(entity) = ecs.entity_from_uid(uid) {
4351 inventories.get(entity)
4352 } else {
4353 None
4354 }
4355 };
4356 let mut r_inventories = [None, None];
4357 for (i, party) in trade.parties.iter().enumerate() {
4358 match get_inventory(*party) {
4359 Some(inventory) => {
4360 r_inventories[i] = Some(ReducedInventory::from(inventory))
4361 },
4362 None => continue 'slot_events,
4363 };
4364 }
4365 let who = match ecs
4366 .uid_from_entity(info.viewpoint_entity)
4367 .and_then(|uid| trade.which_party(uid))
4368 {
4369 Some(who) => who,
4370 None => continue 'slot_events,
4371 };
4372 let do_auto_quantity =
4373 |inventory: &comp::Inventory,
4374 slot,
4375 ours,
4376 remove,
4377 quantity: &mut u32| {
4378 if let Some(prices) = prices
4379 && let Some((balance0, balance1)) = prices
4380 .balance(&trade.offers, &r_inventories, who, true)
4381 .zip(prices.balance(
4382 &trade.offers,
4383 &r_inventories,
4384 1 - who,
4385 false,
4386 ))
4387 && let Some(item) = inventory.get(slot)
4388 && let Some(materials) =
4389 TradePricing::get_materials(&item.item_definition_id())
4390 {
4391 let unit_price: f32 = materials
4392 .iter()
4393 .map(|e| {
4394 prices.values.get(&e.1).cloned().unwrap_or_default()
4395 * e.0
4396 * (if ours { e.1.trade_margin() } else { 1.0 })
4397 })
4398 .sum();
4399
4400 let mut float_delta = if ours ^ remove {
4401 (balance1 - balance0) / unit_price
4402 } else {
4403 (balance0 - balance1) / unit_price
4404 };
4405 if ours ^ remove {
4406 float_delta = float_delta.ceil();
4407 } else {
4408 float_delta = float_delta.floor();
4409 }
4410 *quantity = float_delta.max(0.0) as u32;
4411 }
4412 };
4413 match slot {
4414 Inventory(i) => {
4415 if let Some(inventory) = inventories.get(i.entity)
4416 && let Slot::Inventory(slot) = i.slot
4417 {
4418 let mut quantity = 1;
4419 if auto_quantity {
4420 do_auto_quantity(
4421 inventory,
4422 slot,
4423 i.ours,
4424 false,
4425 &mut quantity,
4426 );
4427 let inv_quantity = i.amount(inventory).unwrap_or(1);
4428 quantity = quantity.min(inv_quantity);
4429 }
4430
4431 events.push(Event::TradeAction(TradeAction::AddItem {
4432 item: slot,
4433 quantity,
4434 ours: i.ours,
4435 }));
4436 }
4437 },
4438 Trade(t) => {
4439 if let Some(inventory) = inventories.get(t.entity)
4440 && let Some(invslot) = t.invslot
4441 {
4442 let mut quantity = 1;
4443 if auto_quantity {
4444 do_auto_quantity(
4445 inventory,
4446 invslot,
4447 t.ours,
4448 true,
4449 &mut quantity,
4450 );
4451 let inv_quantity = t.amount(inventory).unwrap_or(1);
4452 quantity = quantity.min(inv_quantity);
4453 }
4454 events.push(Event::TradeAction(TradeAction::RemoveItem {
4455 item: invslot,
4456 quantity,
4457 ours: t.ours,
4458 }));
4459 }
4460 },
4461 _ => {},
4462 }
4463 }
4464 },
4465 }
4466 }
4467 self.hotbar.maintain_abilities(client, &info);
4468
4469 let arrow_ani = (self.pulse * 4.0).cos() * 0.5 + 0.8; let show_intro = self.show.intro; if let Some(toggle_cursor_key) = global_state
4473 .settings
4474 .controls
4475 .get_binding(GameInput::ToggleCursor)
4476 .filter(|_| !show_intro)
4477 {
4478 prof_span!("temporary example quest");
4479 match global_state.settings.interface.intro_show {
4480 Intro::Show => {
4481 if Button::image(self.imgs.button)
4482 .w_h(200.0, 60.0)
4483 .hover_image(self.imgs.button_hover)
4484 .press_image(self.imgs.button_press)
4485 .bottom_left_with_margins_on(ui_widgets.window, 350.0, 150.0)
4486 .label(&i18n.get_msg("hud-tutorial_btn"))
4487 .label_font_id(self.fonts.cyri.conrod_id)
4488 .label_font_size(self.fonts.cyri.scale(18))
4489 .label_color(TEXT_COLOR)
4490 .label_y(conrod_core::position::Relative::Scalar(2.0))
4491 .image_color(ENEMY_HP_COLOR)
4492 .set(self.ids.intro_button, ui_widgets)
4493 .was_clicked()
4494 {
4495 self.show.intro = true;
4496 self.show.want_grab = true;
4497 }
4498 let tutorial_click_msg =
4499 i18n.get_msg_ctx("hud-tutorial_click_here", &i18n::fluent_args! {
4500 "key" => toggle_cursor_key.display_string(),
4501 });
4502 Image::new(self.imgs.sp_indicator_arrow)
4503 .w_h(20.0, 11.0)
4504 .mid_top_with_margin_on(self.ids.intro_button, -20.0 + arrow_ani as f64)
4505 .color(Some(QUALITY_LEGENDARY))
4506 .set(self.ids.tut_arrow, ui_widgets);
4507 Text::new(&tutorial_click_msg)
4508 .mid_top_with_margin_on(self.ids.tut_arrow, -40.0)
4509 .font_id(self.fonts.cyri.conrod_id)
4510 .font_size(self.fonts.cyri.scale(14))
4511 .center_justify()
4512 .color(BLACK)
4513 .set(self.ids.tut_arrow_txt_bg, ui_widgets);
4514 Text::new(&tutorial_click_msg)
4515 .bottom_right_with_margins_on(self.ids.tut_arrow_txt_bg, 1.0, 1.0)
4516 .center_justify()
4517 .font_id(self.fonts.cyri.conrod_id)
4518 .font_size(self.fonts.cyri.scale(14))
4519 .color(QUALITY_LEGENDARY)
4520 .set(self.ids.tut_arrow_txt, ui_widgets);
4521 },
4522 Intro::Never => {
4523 self.show.intro = false;
4524 },
4525 }
4526 }
4527 if self.show.intro && !self.show.esc_menu {
4529 prof_span!("intro show");
4530 match global_state.settings.interface.intro_show {
4531 Intro::Show => {
4532 if self.show.intro {
4533 self.show.want_grab = false;
4534 let quest_headline = i18n.get_msg("hud-temp_quest_headline");
4535 let quest_text = i18n.get_msg("hud-temp_quest_text");
4536 Image::new(self.imgs.quest_bg0)
4537 .w_h(404.0, 858.0)
4538 .middle_of(ui_widgets.window)
4539 .set(self.ids.quest_bg, ui_widgets);
4540
4541 Text::new(&quest_headline)
4542 .mid_top_with_margin_on(self.ids.quest_bg, 310.0)
4543 .font_size(self.fonts.cyri.scale(30))
4544 .font_id(self.fonts.cyri.conrod_id)
4545 .color(TEXT_BG)
4546 .set(self.ids.q_headline_bg, ui_widgets);
4547 Text::new(&quest_headline)
4548 .bottom_left_with_margins_on(self.ids.q_headline_bg, 1.0, 1.0)
4549 .font_size(self.fonts.cyri.scale(30))
4550 .font_id(self.fonts.cyri.conrod_id)
4551 .color(TEXT_COLOR)
4552 .set(self.ids.q_headline, ui_widgets);
4553
4554 Text::new(&quest_text)
4555 .mid_top_with_margin_on(self.ids.quest_bg, 360.0)
4556 .w(350.0)
4557 .font_size(self.fonts.cyri.scale(17))
4558 .font_id(self.fonts.cyri.conrod_id)
4559 .color(TEXT_BG)
4560 .set(self.ids.q_text_bg, ui_widgets);
4561 Text::new(&quest_text)
4562 .bottom_left_with_margins_on(self.ids.q_text_bg, 1.0, 1.0)
4563 .w(350.0)
4564 .font_size(self.fonts.cyri.scale(17))
4565 .font_id(self.fonts.cyri.conrod_id)
4566 .color(TEXT_COLOR)
4567 .set(self.ids.q_text, ui_widgets);
4568
4569 if Button::image(self.imgs.button)
4570 .w_h(212.0, 52.0)
4571 .hover_image(self.imgs.button_hover)
4572 .press_image(self.imgs.button_press)
4573 .mid_bottom_with_margin_on(self.ids.q_text_bg, -80.0)
4574 .label(&i18n.get_msg("common-close"))
4575 .label_font_id(self.fonts.cyri.conrod_id)
4576 .label_font_size(self.fonts.cyri.scale(22))
4577 .label_color(TEXT_COLOR)
4578 .label_y(conrod_core::position::Relative::Scalar(2.0))
4579 .set(self.ids.accept_button, ui_widgets)
4580 .was_clicked()
4581 {
4582 self.show.intro = false;
4583 events.push(Event::SettingsChange(
4584 InterfaceChange::Intro(Intro::Never).into(),
4585 ));
4586 self.show.want_grab = true;
4587 }
4588 if !self.show.crafting && !self.show.bag {
4589 Image::new(self.imgs.sp_indicator_arrow)
4590 .w_h(20.0, 11.0)
4591 .bottom_right_with_margins_on(
4592 ui_widgets.window,
4593 40.0 + arrow_ani as f64,
4594 205.0,
4595 )
4596 .color(Some(QUALITY_LEGENDARY))
4597 .set(self.ids.tut_arrow, ui_widgets);
4598 Text::new(&i18n.get_msg("hud-tutorial_elements"))
4599 .mid_top_with_margin_on(self.ids.tut_arrow, -50.0)
4600 .font_id(self.fonts.cyri.conrod_id)
4601 .font_size(self.fonts.cyri.scale(40))
4602 .color(BLACK)
4603 .floating(true)
4604 .set(self.ids.tut_arrow_txt_bg, ui_widgets);
4605 Text::new(&i18n.get_msg("hud-tutorial_elements"))
4606 .bottom_right_with_margins_on(self.ids.tut_arrow_txt_bg, 1.0, 1.0)
4607 .font_id(self.fonts.cyri.conrod_id)
4608 .font_size(self.fonts.cyri.scale(40))
4609 .color(QUALITY_LEGENDARY)
4610 .floating(true)
4611 .set(self.ids.tut_arrow_txt, ui_widgets);
4612 }
4613 }
4614 },
4615 Intro::Never => {
4616 self.show.intro = false;
4617 },
4618 }
4619 }
4620
4621 events
4622 }
4623
4624 fn show_bag(slot_manager: &mut slots::SlotManager, show: &mut Show, state: bool) {
4625 show.bag(state);
4626 if !state {
4627 slot_manager.idle();
4628 }
4629 }
4630
4631 pub fn add_failed_block_pickup(&mut self, pos: VolumePos, reason: HudCollectFailedReason) {
4632 self.failed_block_pickups
4633 .insert(pos, CollectFailedData::new(self.pulse, reason));
4634 }
4635
4636 pub fn add_failed_entity_pickup(&mut self, entity: EcsEntity, reason: HudCollectFailedReason) {
4637 self.failed_entity_pickups
4638 .insert(entity, CollectFailedData::new(self.pulse, reason));
4639 }
4640
4641 pub fn new_loot_message(&mut self, item: LootMessage) {
4642 self.new_loot_messages.push_back(item);
4643 }
4644
4645 pub fn dialogue(
4646 &mut self,
4647 sender: EcsEntity,
4648 player_pos: Vec3<f32>,
4649 dialogue: rtsim::Dialogue<true>,
4650 ) {
4651 match dialogue.kind {
4652 rtsim::DialogueKind::Marker(marker) => {
4653 self.extra_markers.retain(|em| !em.marker.is_same(&marker));
4655 self.extra_markers.push(map::ExtraMarker {
4656 recv_pos: player_pos.xy(),
4657 marker,
4658 });
4659 },
4660 rtsim::DialogueKind::End => {
4661 if self
4662 .current_dialogue
4663 .take_if(|(old_sender, _, _)| *old_sender == sender)
4664 .is_some()
4665 {
4666 self.show.quest(false);
4667 }
4668 },
4669 _ => {
4670 if !self.show.quest
4671 || self
4672 .current_dialogue
4673 .as_ref()
4674 .is_none_or(|(old_sender, _, _)| *old_sender == sender)
4675 {
4676 self.show.quest(true);
4677 self.current_dialogue = Some((sender, Instant::now(), dialogue));
4678 }
4679 },
4680 }
4681 }
4682
4683 pub fn new_message(&mut self, msg: comp::ChatMsg) { self.new_messages.push_back(msg); }
4684
4685 pub fn new_notification(&mut self, msg: UserNotification) {
4686 self.new_notifications.push_back(msg);
4687 }
4688
4689 pub fn set_scaling_mode(&mut self, scale_mode: ScaleMode) {
4690 self.ui.set_scaling_mode(scale_mode);
4691 }
4692
4693 pub fn scale_change(&mut self, scale_change: ScaleChange) -> ScaleMode {
4694 let scale_mode = match scale_change {
4695 ScaleChange::Adjust(scale) => ScaleMode::Absolute(scale),
4696 ScaleChange::ToAbsolute => self.ui.scale().scaling_mode_as_absolute(),
4697 ScaleChange::ToRelative => self.ui.scale().scaling_mode_as_relative(),
4698 };
4699 self.ui.set_scaling_mode(scale_mode);
4700 scale_mode
4701 }
4702
4703 fn typing(&self) -> bool { Hud::is_captured::<widget::TextEdit>(&self.ui.ui) }
4705
4706 fn is_captured<W: Widget>(ui: &conrod_core::Ui) -> bool {
4708 if let Some(id) = ui.global_input().current.widget_capturing_keyboard {
4709 ui.widget_graph()
4710 .widget(id)
4711 .filter(|c| c.type_id == std::any::TypeId::of::<<W as Widget>::State>())
4712 .is_some()
4713 } else {
4714 false
4715 }
4716 }
4717
4718 pub fn handle_event(
4719 &mut self,
4720 event: WinEvent,
4721 global_state: &mut GlobalState,
4722 client_inventory: Option<&comp::Inventory>,
4723 ) -> bool {
4724 fn handle_slot(
4726 slot: hotbar::Slot,
4727 state: bool,
4728 events: &mut Vec<Event>,
4729 slot_manager: &mut slots::SlotManager,
4730 hotbar: &mut hotbar::State,
4731 client_inventory: Option<&comp::Inventory>,
4732 ) {
4733 use slots::InventorySlot;
4734 if let Some(slots::SlotKind::Inventory(InventorySlot {
4735 slot: Slot::Inventory(i),
4736 ours: true,
4737 ..
4738 })) = slot_manager.selected()
4739 {
4740 if let Some(item) = client_inventory.and_then(|inv| inv.get(i)) {
4741 hotbar.add_inventory_link(slot, item);
4742 events.push(Event::ChangeHotbarState(Box::new(hotbar.to_owned())));
4743 slot_manager.idle();
4744 }
4745 } else {
4746 let just_pressed = hotbar.process_input(slot, state);
4747 hotbar.get(slot).map(|s| match s {
4748 hotbar::SlotContents::Inventory(i, _) => {
4749 if just_pressed && let Some(inv) = client_inventory {
4750 if inv
4755 .equipped(comp::slot::EquipSlot::InactiveMainhand)
4756 .is_some_and(|item| item.item_hash() == i)
4757 {
4758 events.push(Event::SwapEquippedWeapons);
4759 } else if let Some(slot) = inv.get_slot_from_hash(i) {
4760 events.push(Event::UseSlot {
4761 slot: comp::slot::Slot::Inventory(slot),
4762 bypass_dialog: false,
4763 });
4764 }
4765 }
4766 },
4767 hotbar::SlotContents::Ability(idx) => {
4768 events.push(Event::Ability { idx, state })
4769 },
4770 });
4771 }
4772 }
4773
4774 #[instrument(skip(show, global_state))]
4775 fn handle_map_zoom(
4776 factor: f64,
4777 world_size: Vec2<u32>,
4778 show: &Show,
4779 global_state: &mut GlobalState,
4780 ) -> bool {
4781 trace!("Handling map Zoom");
4782
4783 let max_zoom = world_size.reduce_partial_max() as f64;
4784
4785 if show.map {
4786 let new_zoom_lvl = (global_state.settings.interface.map_zoom * factor)
4787 .clamped(1.25, max_zoom / 64.0);
4788 global_state.settings.interface.map_zoom = new_zoom_lvl;
4789 } else if global_state.settings.interface.minimap_show {
4790 let min_zoom = 1.0;
4796 let max_zoom = world_size
4797 .reduce_partial_max() as f64;
4798
4799 let new_zoom_lvl = (global_state.settings.interface.minimap_zoom * factor)
4800 .clamped(min_zoom, max_zoom);
4801 global_state.settings.interface.minimap_zoom = new_zoom_lvl;
4802 }
4803
4804 show.map && global_state.settings.interface.minimap_show
4805 }
4806
4807 let cursor_grabbed = global_state.window.is_cursor_grabbed();
4808 let handled = match event {
4809 WinEvent::Ui(event) => {
4810 if (self.typing() && event.is_keyboard() && self.show.ui)
4811 || !(cursor_grabbed && event.is_keyboard_or_mouse())
4812 {
4813 self.ui.handle_event(event);
4814 }
4815 true
4816 },
4817 WinEvent::ScaleFactorChanged(scale_factor) => {
4818 self.ui.scale_factor_changed(scale_factor);
4819 false
4820 },
4821 WinEvent::InputUpdate(GameInput::ToggleInterface, true) if !self.typing() => {
4822 self.show.toggle_ui();
4823 true
4824 },
4825 WinEvent::InputUpdate(GameInput::ToggleCursor, true) if !self.typing() => {
4826 self.force_ungrab = !self.force_ungrab;
4827 true
4828 },
4829 WinEvent::InputUpdate(GameInput::AcceptGroupInvite, true) if !self.typing() => {
4830 if let Some(prompt_dialog) = &mut self.show.prompt_dialog {
4831 prompt_dialog.set_outcome_via_keypress(true);
4832 true
4833 } else {
4834 false
4835 }
4836 },
4837 WinEvent::InputUpdate(GameInput::DeclineGroupInvite, true) if !self.typing() => {
4838 if let Some(prompt_dialog) = &mut self.show.prompt_dialog {
4839 prompt_dialog.set_outcome_via_keypress(false);
4840 true
4841 } else {
4842 false
4843 }
4844 },
4845
4846 WinEvent::InputUpdate(key, state) if !self.show.ui => {
4849 if let Some(slot) = try_hotbar_slot_from_input(key) {
4850 handle_slot(
4851 slot,
4852 state,
4853 &mut self.events,
4854 &mut self.slot_manager,
4855 &mut self.hotbar,
4856 client_inventory,
4857 );
4858 true
4859 } else {
4860 false
4861 }
4862 },
4863
4864 WinEvent::Zoom(_) => !cursor_grabbed && !self.ui.no_widget_capturing_mouse(),
4865
4866 WinEvent::InputUpdate(GameInput::Chat, true) => {
4867 self.ui.focus_widget(if self.typing() {
4868 None
4869 } else {
4870 self.force_chat = true;
4871 Some(self.ids.chat)
4872 });
4873 true
4874 },
4875 WinEvent::InputUpdate(GameInput::Escape, true) => {
4876 if self.typing() {
4877 self.ui.focus_widget(None);
4878 self.force_chat = false;
4879 } else if self.show.trade {
4880 self.events.push(Event::TradeAction(TradeAction::Decline));
4881 } else {
4882 if self.show.bag {
4884 self.slot_manager.idle();
4885 }
4886 self.show.toggle_windows(global_state);
4887 }
4888 true
4889 },
4890
4891 WinEvent::InputUpdate(key, state) if !self.typing() => {
4893 let gs_audio = &global_state.settings.audio;
4894 let mut toggle_mute = |audio: Audio| {
4895 self.events
4896 .push(Event::SettingsChange(SettingsChange::Audio(audio)));
4897 true
4898 };
4899
4900 match key {
4901 GameInput::Command if state => {
4902 self.force_chat_input = Some("/".to_owned());
4903 self.force_chat_cursor = Some(Index { line: 0, char: 1 });
4904 self.force_chat = true;
4905 self.ui.focus_widget(Some(self.ids.chat));
4906 true
4907 },
4908 GameInput::Map if state => {
4909 self.show.toggle_map();
4910 true
4911 },
4912 GameInput::Inventory if state => {
4913 let state = !self.show.bag;
4914 Self::show_bag(&mut self.slot_manager, &mut self.show, state);
4915 true
4916 },
4917 GameInput::Social if state => {
4918 self.show.toggle_social();
4919 true
4920 },
4921 GameInput::Crafting if state => {
4922 self.show.toggle_crafting();
4923 true
4924 },
4925 GameInput::Diary if state => {
4926 self.show.toggle_diary();
4927 true
4928 },
4929 GameInput::Settings if state => {
4930 self.show.toggle_settings(global_state);
4931 true
4932 },
4933 GameInput::Controls if state => {
4934 self.show.toggle_settings(global_state);
4935 self.show.settings_tab = SettingsTab::Controls;
4936 true
4937 },
4938 GameInput::ToggleDebug if state => {
4939 global_state.settings.interface.toggle_debug =
4940 !global_state.settings.interface.toggle_debug;
4941 true
4942 },
4943 #[cfg(feature = "egui-ui")]
4944 GameInput::ToggleEguiDebug if state => {
4945 global_state.settings.interface.toggle_egui_debug =
4946 !global_state.settings.interface.toggle_egui_debug;
4947 true
4948 },
4949 GameInput::ToggleChat if state => {
4950 global_state.settings.interface.toggle_chat =
4951 !global_state.settings.interface.toggle_chat;
4952 true
4953 },
4954 GameInput::ToggleIngameUi if state => {
4955 self.show.ingame = !self.show.ingame;
4956 true
4957 },
4958 GameInput::MapZoomIn if state => {
4959 handle_map_zoom(2.0, self.world_map.1, &self.show, global_state)
4960 },
4961 GameInput::MapZoomOut if state => {
4962 handle_map_zoom(0.5, self.world_map.1, &self.show, global_state)
4963 },
4964 GameInput::MuteMaster if state => {
4965 toggle_mute(Audio::MuteMasterVolume(!gs_audio.master_volume.muted))
4966 },
4967 GameInput::MuteInactiveMaster if state => {
4968 toggle_mute(Audio::MuteInactiveMasterVolume(
4969 !gs_audio.inactive_master_volume_perc.muted,
4970 ))
4971 },
4972 GameInput::MuteMusic if state => {
4973 toggle_mute(Audio::MuteMusicVolume(!gs_audio.music_volume.muted))
4974 },
4975 GameInput::MuteSfx if state => {
4976 toggle_mute(Audio::MuteSfxVolume(!gs_audio.sfx_volume.muted))
4977 },
4978 GameInput::MuteAmbience if state => {
4979 toggle_mute(Audio::MuteAmbienceVolume(!gs_audio.ambience_volume.muted))
4980 },
4981 GameInput::Interact if state => {
4982 if let Some((sender, _, dialogue)) = &self.current_dialogue
4984 && let rtsim::DialogueKind::Statement { tag, .. } = dialogue.kind
4985 {
4986 self.events.push(Event::Dialogue(*sender, rtsim::Dialogue {
4987 id: dialogue.id,
4988 kind: rtsim::DialogueKind::Ack { tag },
4989 }));
4990 true
4991 } else {
4992 false
4993 }
4994 },
4995 input => {
4997 if let Some(slot) = try_hotbar_slot_from_input(input) {
4998 handle_slot(
4999 slot,
5000 state,
5001 &mut self.events,
5002 &mut self.slot_manager,
5003 &mut self.hotbar,
5004 client_inventory,
5005 );
5006 true
5007 } else {
5008 false
5009 }
5010 },
5011 }
5012 },
5013 WinEvent::InputUpdate(_key, _) => self.typing(),
5015 WinEvent::Focused(state) => {
5016 self.force_ungrab = !state;
5017 true
5018 },
5019 WinEvent::Moved(_) => {
5020 self.show.want_grab = false;
5026 true
5027 },
5028 _ => false,
5029 };
5030 global_state
5032 .window
5033 .grab_cursor(!self.force_ungrab && self.show.want_grab);
5034
5035 handled
5036 }
5037
5038 pub fn maintain(
5039 &mut self,
5040 client: &Client,
5041 global_state: &mut GlobalState,
5042 debug_info: &Option<DebugInfo>,
5043 camera: &Camera,
5044 dt: Duration,
5045 info: HudInfo,
5046 interactable_map: (
5047 HashMap<specs::Entity, Vec<interactable::EntityInteraction>>,
5048 HashMap<VolumePos, (Block, Vec<&interactable::BlockInteraction>)>,
5049 ),
5050 ) -> Vec<Event> {
5051 span!(_guard, "maintain", "Hud::maintain");
5052
5053 if let Some(pos) = client.position() {
5055 self.extra_markers.retain(|em| {
5056 const EXTRA_DISTANCE: f32 = 100.0;
5057 em.marker.wpos.distance(pos.xy())
5058 < em.recv_pos.distance(em.marker.wpos) + EXTRA_DISTANCE
5059 });
5060 }
5061
5062 if self.ui.ui.global_input().events().any(|event| {
5064 use conrod_core::{event, input};
5065 matches!(
5066 event,
5067 event::Event::Ui(event::Ui::Press(_, event::Press {
5070 button: event::Button::Keyboard(input::Key::Tab),
5071 ..
5072 },))
5073 )
5074 }) {
5075 self.ui
5076 .ui
5077 .handle_event(conrod_core::event::Input::Text("\t".to_string()));
5078 }
5079
5080 self.show.crafting_fields.craft_sprite =
5083 self.show
5084 .crafting_fields
5085 .craft_sprite
5086 .filter(|(pos, sprite)| {
5087 self.show.crafting
5088 && if let Some(player_pos) = client.position() {
5089 pos.get_block_and_transform(
5090 &client.state().terrain(),
5091 &client.state().ecs().read_resource(),
5092 |e| {
5093 client
5094 .state()
5095 .read_storage::<vcomp::Interpolated>()
5096 .get(e)
5097 .map(|interpolated| {
5098 (comp::Pos(interpolated.pos), interpolated.ori)
5099 })
5100 },
5101 &client.state().read_storage(),
5102 )
5103 .is_some_and(|(mat, block)| {
5104 block.get_sprite() == Some(*sprite)
5105 && mat.mul_point(Vec3::broadcast(0.5)).distance(player_pos)
5106 < MAX_PICKUP_RANGE
5107 })
5108 } else {
5109 false
5110 }
5111 });
5112
5113 if !self.show.ui {
5115 return std::mem::take(&mut self.events);
5116 }
5117
5118 if let Some(maybe_id) = self.to_focus.take() {
5119 self.ui.focus_widget(maybe_id);
5120 }
5121 let events = self.update_layout(
5122 client,
5123 global_state,
5124 debug_info,
5125 dt,
5126 info,
5127 camera,
5128 interactable_map,
5129 );
5130 let camera::Dependents {
5131 view_mat, proj_mat, ..
5132 } = camera.dependents();
5133 let focus_off = camera.get_focus_pos().map(f32::trunc);
5134
5135 self.item_imgs.reload_if_changed(&mut self.ui);
5137 let _pool = client.state().ecs().read_resource::<SlowJobPool>();
5141 self.ui.maintain(
5142 global_state.window.renderer_mut(),
5143 None,
5144 Some(proj_mat * view_mat * Mat4::translation_3d(-focus_off)),
5146 );
5147
5148 events
5149 }
5150
5151 #[inline]
5152 pub fn clear_cursor(&mut self) { self.slot_manager.idle(); }
5153
5154 pub fn render<'a>(&'a self, drawer: &mut UiDrawer<'_, 'a>) {
5155 span!(_guard, "render", "Hud::render");
5156 if self.show.ui {
5158 self.ui.render(drawer);
5159 }
5160 }
5161
5162 pub fn free_look(&mut self, free_look: bool) { self.show.free_look = free_look; }
5163
5164 pub fn auto_walk(&mut self, auto_walk: bool) { self.show.auto_walk = auto_walk; }
5165
5166 pub fn camera_clamp(&mut self, camera_clamp: bool) { self.show.camera_clamp = camera_clamp; }
5167
5168 pub fn zoom_lock_reminder(&mut self) {
5171 if self.show.zoom_lock.reason.is_none() {
5172 self.show.zoom_lock = ChangeNotification::from_reason(NotificationReason::Remind);
5173 }
5174 }
5175
5176 pub fn zoom_lock_toggle(&mut self, state: bool) {
5179 self.show.zoom_lock = ChangeNotification::from_state(state);
5180 }
5181
5182 pub fn show_content_bubble(&mut self, pos: Vec3<f32>, content: comp::Content) {
5183 self.content_bubbles.push((
5184 pos,
5185 comp::SpeechBubble::new(content, comp::SpeechBubbleType::None),
5186 ));
5187 }
5188
5189 pub fn handle_outcome(
5190 &mut self,
5191 outcome: &Outcome,
5192 scene_data: &SceneData,
5193 global_state: &GlobalState,
5194 ) {
5195 let client = scene_data.client;
5196 let interface = &global_state.settings.interface;
5197 match outcome {
5198 Outcome::ExpChange { uid, exp, xp_pools } => {
5199 let ecs = client.state().ecs();
5200 let uids = ecs.read_storage::<Uid>();
5201 let me = scene_data.viewpoint_entity;
5202
5203 if uids.get(me).is_some_and(|me| *me == *uid) {
5204 match self.floaters.exp_floaters.last_mut() {
5205 Some(floater)
5206 if floater.timer
5207 > (EXP_FLOATER_LIFETIME - EXP_ACCUMULATION_DURATION)
5208 && global_state.settings.interface.accum_experience
5209 && floater.owner == *uid =>
5210 {
5211 floater.jump_timer = 0.0;
5212 floater.exp_change += *exp;
5213 },
5214 _ => self.floaters.exp_floaters.push(ExpFloater {
5215 owner: *uid,
5217 exp_change: *exp,
5218 timer: EXP_FLOATER_LIFETIME,
5219 jump_timer: 0.0,
5220 rand_offset: rand::rng().random::<(f32, f32)>(),
5221 xp_pools: xp_pools.clone(),
5222 }),
5223 }
5224 }
5225 },
5226 Outcome::SkillPointGain {
5227 uid,
5228 skill_tree,
5229 total_points,
5230 ..
5231 } => {
5232 let ecs = client.state().ecs();
5233 let uids = ecs.read_storage::<Uid>();
5234 let me = scene_data.viewpoint_entity;
5235
5236 if uids.get(me).is_some_and(|me| *me == *uid) {
5237 self.floaters.skill_point_displays.push(SkillPointGain {
5238 skill_tree: *skill_tree,
5239 total_points: *total_points,
5240 timer: 5.0,
5241 });
5242 }
5243 },
5244 Outcome::ComboChange { uid, combo } => {
5245 let ecs = client.state().ecs();
5246 let uids = ecs.read_storage::<Uid>();
5247 let me = scene_data.viewpoint_entity;
5248
5249 if uids.get(me).is_some_and(|me| *me == *uid) {
5250 self.floaters.combo_floater = Some(ComboFloater {
5251 combo: *combo,
5252 timer: comp::combo::COMBO_DECAY_START,
5253 });
5254 }
5255 },
5256 Outcome::Block { uid, parry, .. } if *parry => {
5257 let ecs = client.state().ecs();
5258 let uids = ecs.read_storage::<Uid>();
5259 let me = scene_data.viewpoint_entity;
5260
5261 if uids.get(me).is_some_and(|me| *me == *uid) {
5262 self.floaters
5263 .block_floaters
5264 .push(BlockFloater { timer: 1.0 });
5265 }
5266 },
5267 Outcome::HealthChange { info, .. } => {
5268 let ecs = client.state().ecs();
5269 let mut hp_floater_lists = ecs.write_storage::<HpFloaterList>();
5270 let uids = ecs.read_storage::<Uid>();
5271 let me = scene_data.viewpoint_entity;
5272 let my_uid = uids.get(me);
5273
5274 if let Some(entity) = ecs.entity_from_uid(info.target)
5275 && let Some(floater_list) = hp_floater_lists.get_mut(entity)
5276 {
5277 let hit_me = my_uid.is_some_and(|&uid| {
5278 (info.target == uid) && global_state.settings.interface.sct_inc_dmg
5279 });
5280 if match info.by {
5281 Some(by) => {
5282 let by_me = my_uid.is_some_and(|&uid| by.uid() == uid);
5283 if by_me {
5285 floater_list.time_since_last_dmg_by_me = Some(0.0);
5286 }
5287 hit_me || by_me
5288 },
5289 None => hit_me,
5290 } {
5291 for floater in floater_list.floaters.iter_mut().rev() {
5293 if floater.timer > 0.0 {
5294 break;
5295 }
5296 if floater.info.instance == info.instance
5297 && (hit_me
5299 || floater.info.precise
5300 == info.precise)
5301 {
5302 floater.info.amount += info.amount;
5303 if info.precise {
5304 floater.info.precise = info.precise
5305 }
5306 return;
5307 }
5308 }
5309
5310 let last_floater = if !info.precise || hit_me {
5313 floater_list.floaters.iter_mut().rev().find(|f| {
5314 (if info.amount < 0.0 {
5315 f.info.amount < 0.0
5316 } else {
5317 f.info.amount > 0.0
5318 }) && f.timer
5319 < if hit_me {
5320 interface.sct_inc_dmg_accum_duration
5321 } else {
5322 interface.sct_dmg_accum_duration
5323 }
5324 && (hit_me || !f.info.precise)
5326 })
5327 } else {
5328 None
5329 };
5330
5331 match last_floater {
5332 Some(f) => {
5333 f.jump_timer = 0.0;
5334 f.info.amount += info.amount;
5335 f.info.precise = info.precise;
5336 },
5337 _ => {
5338 floater_list.floaters.push(HpFloater {
5339 timer: 0.0,
5340 jump_timer: 0.0,
5341 info: *info,
5342 rand: rand::random(),
5343 });
5344 },
5345 }
5346 }
5347 }
5348 },
5349
5350 _ => {},
5351 }
5352 }
5353}
5354pub fn get_quality_col(quality: Quality) -> Color {
5356 match quality {
5357 Quality::Low => QUALITY_LOW,
5358 Quality::Common => QUALITY_COMMON,
5359 Quality::Moderate => QUALITY_MODERATE,
5360 Quality::High => QUALITY_HIGH,
5361 Quality::Epic => QUALITY_EPIC,
5362 Quality::Legendary => QUALITY_LEGENDARY,
5363 Quality::Artifact => QUALITY_ARTIFACT,
5364 Quality::Debug => QUALITY_DEBUG,
5365 }
5366}
5367
5368fn try_hotbar_slot_from_input(input: GameInput) -> Option<hotbar::Slot> {
5369 Some(match input {
5370 GameInput::Slot1 => hotbar::Slot::One,
5371 GameInput::Slot2 => hotbar::Slot::Two,
5372 GameInput::Slot3 => hotbar::Slot::Three,
5373 GameInput::Slot4 => hotbar::Slot::Four,
5374 GameInput::Slot5 => hotbar::Slot::Five,
5375 GameInput::Slot6 => hotbar::Slot::Six,
5376 GameInput::Slot7 => hotbar::Slot::Seven,
5377 GameInput::Slot8 => hotbar::Slot::Eight,
5378 GameInput::Slot9 => hotbar::Slot::Nine,
5379 GameInput::Slot10 => hotbar::Slot::Ten,
5380 _ => return None,
5381 })
5382}
5383
5384pub fn cr_color(combat_rating: f32) -> Color {
5385 let common = 2.0;
5386 let moderate = 3.5;
5387 let high = 6.5;
5388 let epic = 8.5;
5389 let legendary = 10.4;
5390 let artifact = 122.0;
5391 let debug = 200.0;
5392
5393 match combat_rating {
5394 x if (0.0..common).contains(&x) => QUALITY_LOW,
5395 x if (common..moderate).contains(&x) => QUALITY_COMMON,
5396 x if (moderate..high).contains(&x) => QUALITY_MODERATE,
5397 x if (high..epic).contains(&x) => QUALITY_HIGH,
5398 x if (epic..legendary).contains(&x) => QUALITY_EPIC,
5399 x if (legendary..artifact).contains(&x) => QUALITY_LEGENDARY,
5400 x if (artifact..debug).contains(&x) => QUALITY_ARTIFACT,
5401 x if x >= debug => QUALITY_DEBUG,
5402 _ => XP_COLOR,
5403 }
5404}
5405
5406pub fn get_buff_image(buff: BuffKind, imgs: &Imgs) -> conrod_core::image::Id {
5407 match buff {
5408 BuffKind::Regeneration => imgs.buff_plus_0,
5410 BuffKind::Saturation => imgs.buff_saturation_0,
5411 BuffKind::Potion => imgs.buff_potion_0,
5412 BuffKind::Agility => imgs.buff_haste_0,
5414 BuffKind::RestingHeal => imgs.buff_resting_heal_0,
5415 BuffKind::EnergyRegen => imgs.buff_energyplus_0,
5416 BuffKind::ComboGeneration => imgs.buff_fury,
5417 BuffKind::IncreaseMaxEnergy => imgs.buff_energyplus_0,
5418 BuffKind::IncreaseMaxHealth => imgs.buff_healthplus_0,
5419 BuffKind::Invulnerability => imgs.buff_invincibility_0,
5420 BuffKind::ProtectingWard => imgs.buff_dmg_red_0,
5421 BuffKind::Frenzied => imgs.buff_frenzy_0,
5422 BuffKind::Hastened => imgs.buff_haste_0,
5423 BuffKind::Fortitude => imgs.buff_fortitude_0,
5424 BuffKind::Reckless => imgs.buff_reckless,
5425 BuffKind::Flame => imgs.buff_flame,
5426 BuffKind::Frigid => imgs.buff_frigid,
5427 BuffKind::Lifesteal => imgs.buff_lifesteal,
5428 BuffKind::Resilience => imgs.buff_resilience,
5429 BuffKind::ImminentCritical => imgs.buff_imminentcritical,
5432 BuffKind::Fury => imgs.buff_fury,
5433 BuffKind::Sunderer => imgs.buff_sunderer,
5434 BuffKind::Defiance => imgs.buff_defiance,
5435 BuffKind::Bloodfeast => imgs.buff_plus_0,
5436 BuffKind::Berserk => imgs.buff_reckless,
5437 BuffKind::ScornfulTaunt => imgs.buff_scornfultaunt,
5438 BuffKind::Tenacity => imgs.buff_tenacity,
5439 BuffKind::Bleeding => imgs.debuff_bleed_0,
5441 BuffKind::Cursed => imgs.debuff_cursed_0,
5442 BuffKind::Burning => imgs.debuff_burning_0,
5443 BuffKind::Crippled => imgs.debuff_crippled_0,
5444 BuffKind::Frozen => imgs.debuff_frozen_0,
5445 BuffKind::Wet => imgs.debuff_wet_0,
5446 BuffKind::Ensnared => imgs.debuff_ensnared_0,
5447 BuffKind::Poisoned => imgs.debuff_poisoned_0,
5448 BuffKind::Parried => imgs.debuff_parried_0,
5449 BuffKind::PotionSickness => imgs.debuff_potionsickness_0,
5450 BuffKind::Polymorphed => imgs.debuff_polymorphed_0,
5451 BuffKind::Heatstroke => imgs.debuff_heatstroke_0,
5452 BuffKind::Rooted => imgs.debuff_rooted_0,
5453 BuffKind::Winded => imgs.debuff_winded_0,
5454 BuffKind::Amnesia => imgs.debuff_amnesia_0,
5455 BuffKind::OffBalance => imgs.debuff_offbalance_0,
5456 }
5457}
5458
5459pub fn get_sprite_desc(
5460 sprite: SpriteKind,
5461 localized_strings: &Localization,
5462) -> Option<Cow<'_, str>> {
5463 let i18n_key = match sprite {
5464 SpriteKind::Empty | SpriteKind::GlassBarrier => return None,
5465 SpriteKind::Anvil => "hud-crafting-anvil",
5466 SpriteKind::Cauldron => "hud-crafting-cauldron",
5467 SpriteKind::CookingPot => "hud-crafting-cooking_pot",
5468 SpriteKind::RepairBench => "hud-crafting-repair_bench",
5469 SpriteKind::CraftingBench => "hud-crafting-crafting_bench",
5470 SpriteKind::Forge => "hud-crafting-forge",
5471 SpriteKind::Loom => "hud-crafting-loom",
5472 SpriteKind::SpinningWheel => "hud-crafting-spinning_wheel",
5473 SpriteKind::TanningRack => "hud-crafting-tanning_rack",
5474 SpriteKind::DismantlingBench => "hud-crafting-salvaging_station",
5475 SpriteKind::ChestBuried
5476 | SpriteKind::Chest
5477 | SpriteKind::CommonLockedChest
5478 | SpriteKind::CoralChest
5479 | SpriteKind::DungeonChest0
5480 | SpriteKind::DungeonChest1
5481 | SpriteKind::DungeonChest2
5482 | SpriteKind::DungeonChest3
5483 | SpriteKind::DungeonChest4
5484 | SpriteKind::DungeonChest5
5485 | SpriteKind::SahaginChest
5486 | SpriteKind::TerracottaChest => "common-sprite-chest",
5487 SpriteKind::Mud => "common-sprite-mud",
5488 SpriteKind::Grave => "common-sprite-grave",
5489 SpriteKind::Crate => "common-sprite-crate",
5490 _ => return None,
5491 };
5492 Some(localized_strings.get_msg(i18n_key))
5493}
5494
5495pub fn angle_of_attack_text(
5496 fluid: Option<comp::Fluid>,
5497 velocity: Option<comp::Vel>,
5498 character_state: Option<&comp::CharacterState>,
5499) -> String {
5500 use comp::CharacterState;
5501
5502 let glider_ori = if let Some(CharacterState::Glide(data)) = character_state {
5503 data.ori
5504 } else {
5505 return "Angle of Attack: Not gliding".to_owned();
5506 };
5507
5508 let fluid = if let Some(fluid) = fluid {
5509 fluid
5510 } else {
5511 return "Angle of Attack: Not in fluid".to_owned();
5512 };
5513
5514 let velocity = if let Some(velocity) = velocity {
5515 velocity
5516 } else {
5517 return "Angle of Attack: Player has no vel component".to_owned();
5518 };
5519 let rel_flow = fluid.relative_flow(&velocity).0;
5520 let v_sq = rel_flow.magnitude_squared();
5521
5522 if v_sq.abs() > 0.0001 {
5523 let rel_flow_dir = Dir::new(rel_flow / v_sq.sqrt());
5524 let aoe = fluid_dynamics::angle_of_attack(&glider_ori, &rel_flow_dir);
5525 let (rel_x, rel_y, rel_z) = (rel_flow.x, rel_flow.y, rel_flow.z);
5526 format!(
5527 "Angle of Attack: {:.1} ({:.1},{:.1},{:.1})",
5528 aoe.to_degrees(),
5529 rel_x,
5530 rel_y,
5531 rel_z
5532 )
5533 } else {
5534 "Angle of Attack: Not moving".to_owned()
5535 }
5536}
5537
5538fn air_velocity(fluid: Option<comp::Fluid>) -> String {
5539 if let Some(comp::Fluid::Air { vel: air_vel, .. }) = fluid {
5540 format!(
5541 "Air Velocity: ({:.1}, {:.1}, {:.1})",
5542 air_vel.0.x, air_vel.0.y, air_vel.0.z
5543 )
5544 } else {
5545 "Air Velocity: Not in Air".to_owned()
5546 }
5547}
5548
5549pub fn multiplier_to_percentage(value: f32) -> f32 { value * 100.0 - 100.0 }