veloren_client/
lib.rs

1#![deny(unsafe_code)]
2#![deny(clippy::clone_on_ref_ptr)]
3
4pub mod addr;
5pub mod error;
6
7// Reexports
8pub use crate::error::Error;
9pub use authc::AuthClientError;
10pub use common_net::msg::ServerInfo;
11pub use specs::{
12    Builder, DispatcherBuilder, Entity as EcsEntity, Join, LendJoin, ReadStorage, World, WorldExt,
13};
14
15use crate::addr::ConnectionArgs;
16use byteorder::{ByteOrder, LittleEndian};
17use common::{
18    character::{CharacterId, CharacterItem},
19    comp::{
20        self, AdminRole, CharacterState, ChatMode, ControlAction, ControlEvent, Controller,
21        ControllerInputs, GroupManip, Hardcore, InputKind, InventoryAction, InventoryEvent,
22        InventoryUpdateEvent, MapMarkerChange, PresenceKind, UtteranceKind,
23        chat::KillSource,
24        controller::CraftEvent,
25        gizmos::Gizmos,
26        group,
27        inventory::{
28            InventorySortOrder,
29            item::{ItemKind, modular, tool},
30        },
31        invite::{InviteKind, InviteResponse},
32        skills::Skill,
33        slot::{EquipSlot, InvSlotId, Slot},
34    },
35    event::{EventBus, LocalEvent, PluginHash, UpdateCharacterMetadata},
36    grid::Grid,
37    link::Is,
38    lod,
39    map::Marker,
40    mounting::{Rider, VolumePos, VolumeRider},
41    outcome::Outcome,
42    recipe::{ComponentRecipeBook, RecipeBookManifest, RepairRecipeBook},
43    resources::{BattleMode, GameMode, PlayerEntity, Time, TimeOfDay},
44    rtsim,
45    shared_server_config::ServerConstants,
46    spiral::Spiral2d,
47    terrain::{
48        BiomeKind, CoordinateConversions, SiteKindMeta, SpriteKind, TerrainChunk, TerrainChunkSize,
49        TerrainGrid, block::Block, map::MapConfig, neighbors,
50    },
51    trade::{PendingTrade, SitePrices, TradeAction, TradeId, TradeResult},
52    uid::{IdMaps, Uid},
53    vol::RectVolSize,
54    weather::{CompressedWeather, SharedWeatherGrid, Weather, WeatherGrid},
55};
56#[cfg(feature = "tracy")] use common_base::plot;
57use common_base::{prof_span, span};
58use common_i18n::Content;
59use common_net::{
60    msg::{
61        ChatTypeContext, ClientGeneral, ClientMsg, ClientRegister, DisconnectReason, InviteAnswer,
62        Notification, PingMsg, PlayerInfo, PlayerListUpdate, RegisterError, ServerGeneral,
63        ServerInit, ServerRegisterAnswer,
64        server::ServerDescription,
65        world_msg::{EconomyInfo, PoiInfo, SiteId},
66    },
67    sync::WorldSyncExt,
68};
69
70pub use common_net::msg::ClientType;
71use common_state::State;
72#[cfg(feature = "plugins")]
73use common_state::plugin::PluginMgr;
74use common_systems::add_local_systems;
75use comp::BuffKind;
76use hashbrown::{HashMap, HashSet};
77use hickory_resolver::{Resolver, config::ResolverConfig, name_server::TokioConnectionProvider};
78use image::DynamicImage;
79use network::{ConnectAddr, Network, Participant, Pid, Stream};
80use num::traits::FloatConst;
81use rayon::prelude::*;
82use rustls::client::danger::ServerCertVerified;
83use specs::Component;
84use std::{
85    collections::{BTreeMap, VecDeque},
86    fmt::Debug,
87    mem,
88    path::PathBuf,
89    sync::Arc,
90    time::{Duration, Instant},
91};
92use tokio::runtime::Runtime;
93use tracing::{debug, error, trace, warn};
94use vek::*;
95
96pub const MAX_SELECTABLE_VIEW_DISTANCE: u32 = 65;
97
98const PING_ROLLING_AVERAGE_SECS: usize = 10;
99
100/// Client frontend events.
101///
102/// These events are returned to the frontend that ticks the client.
103#[derive(Debug)]
104pub enum Event {
105    Chat(comp::ChatMsg),
106    GroupInventoryUpdate(comp::FrontendItem, Uid),
107    InviteComplete {
108        target: Uid,
109        answer: InviteAnswer,
110        kind: InviteKind,
111    },
112    TradeComplete {
113        result: TradeResult,
114        trade: PendingTrade,
115    },
116    Disconnect,
117    DisconnectionNotification(u64),
118    InventoryUpdated(Vec<InventoryUpdateEvent>),
119    Notification(UserNotification),
120    SetViewDistance(u32),
121    Outcome(Outcome),
122    CharacterCreated(CharacterId),
123    CharacterEdited(CharacterId),
124    CharacterJoined(UpdateCharacterMetadata),
125    CharacterError(String),
126    MapMarker(comp::MapMarkerUpdate),
127    StartSpectate(Vec3<f32>),
128    SpectatePosition(Vec3<f32>),
129    PluginDataReceived(Vec<u8>),
130    Dialogue(Uid, rtsim::Dialogue<true>),
131    Gizmos(Vec<Gizmos>),
132}
133
134/// A message for the user to be displayed through the UI.
135///
136/// This type mirrors the [`common_net::msg::Notification`] type, but does not
137/// include any data that the UI does not need.
138#[derive(Debug)]
139pub enum UserNotification {
140    WaypointUpdated,
141}
142
143#[derive(Debug)]
144pub enum ClientInitStage {
145    /// A connection to the server is being created
146    ConnectionEstablish,
147    /// Waiting for server version
148    WatingForServerVersion,
149    /// We're currently authenticating with the server
150    Authentication,
151    /// Loading map data, site information, recipe information and other
152    /// initialization data
153    LoadingInitData,
154    /// Prepare data received by the server to be used by the client (insert
155    /// data into the ECS, render map)
156    StartingClient,
157}
158
159pub struct WorldData {
160    /// Just the "base" layer for LOD; currently includes colors and nothing
161    /// else. In the future we'll add more layers, like shadows, rivers, and
162    /// probably foliage, cities, roads, and other structures.
163    pub lod_base: Grid<u32>,
164    /// The "height" layer for LOD; currently includes only land altitudes, but
165    /// in the future should also water depth, and probably other
166    /// information as well.
167    pub lod_alt: Grid<u32>,
168    /// The "shadow" layer for LOD.  Includes east and west horizon angles and
169    /// an approximate max occluder height, which we use to try to
170    /// approximate soft and volumetric shadows.
171    pub lod_horizon: Grid<u32>,
172    /// A fully rendered map image for use with the map and minimap; note that
173    /// this can be constructed dynamically by combining the layers of world
174    /// map data (e.g. with shadow map data or river data), but at present
175    /// we opt not to do this.
176    ///
177    /// The first two elements of the tuple are the regular and topographic maps
178    /// respectively. The third element of the tuple is the world size (as a 2D
179    /// grid, in chunks), and the fourth element holds the minimum height for
180    /// any land chunk (i.e. the sea level) in its x coordinate, and the maximum
181    /// land height above this height (i.e. the max height) in its y coordinate.
182    map: (Vec<Arc<DynamicImage>>, Vec2<u16>, Vec2<f32>),
183}
184
185impl WorldData {
186    pub fn chunk_size(&self) -> Vec2<u16> { self.map.1 }
187
188    pub fn map_layers(&self) -> &Vec<Arc<DynamicImage>> { &self.map.0 }
189
190    pub fn map_image(&self) -> &Arc<DynamicImage> { &self.map.0[0] }
191
192    pub fn topo_map_image(&self) -> &Arc<DynamicImage> { &self.map.0[1] }
193
194    pub fn min_chunk_alt(&self) -> f32 { self.map.2.x }
195
196    pub fn max_chunk_alt(&self) -> f32 { self.map.2.y }
197}
198
199pub struct SiteMarker {
200    pub marker: Marker,
201    pub economy: Option<EconomyInfo>,
202}
203
204struct WeatherLerp {
205    old: (SharedWeatherGrid, Instant),
206    new: (SharedWeatherGrid, Instant),
207    old_local_wind: (Vec2<f32>, Instant),
208    new_local_wind: (Vec2<f32>, Instant),
209    local_wind: Vec2<f32>,
210}
211
212impl WeatherLerp {
213    fn local_wind_update(&mut self, wind: Vec2<f32>) {
214        self.old_local_wind = mem::replace(&mut self.new_local_wind, (wind, Instant::now()));
215    }
216
217    fn update_local_wind(&mut self) {
218        // Assumes updates are regular
219        let t = (self.new_local_wind.1.elapsed().as_secs_f32()
220            / self
221                .new_local_wind
222                .1
223                .duration_since(self.old_local_wind.1)
224                .as_secs_f32())
225        .clamp(0.0, 1.0);
226
227        self.local_wind = Vec2::lerp_unclamped(self.old_local_wind.0, self.new_local_wind.0, t);
228    }
229
230    fn weather_update(&mut self, weather: SharedWeatherGrid) {
231        self.old = mem::replace(&mut self.new, (weather, Instant::now()));
232    }
233
234    // TODO: Make improvements to this interpolation, it's main issue is assuming
235    // that updates come at regular intervals.
236    fn update(&mut self, to_update: &mut WeatherGrid) {
237        prof_span!("WeatherLerp::update");
238        self.update_local_wind();
239        let old = &self.old.0;
240        let new = &self.new.0;
241        if new.size() == Vec2::zero() {
242            return;
243        }
244        if to_update.size() != new.size() {
245            *to_update = WeatherGrid::from(new);
246        }
247        if old.size() == new.size() {
248            // Assumes updates are regular
249            let t = (self.new.1.elapsed().as_secs_f32()
250                / self.new.1.duration_since(self.old.1).as_secs_f32())
251            .clamp(0.0, 1.0);
252
253            to_update
254                .iter_mut()
255                .zip(old.iter().zip(new.iter()))
256                .for_each(|((_, current), ((_, old), (_, new)))| {
257                    *current = CompressedWeather::lerp_unclamped(old, new, t);
258                    // `local_wind` is set for all weather cells on the client,
259                    // which will still be inaccurate outside the "local" area
260                    current.wind = self.local_wind;
261                });
262        }
263    }
264}
265
266impl Default for WeatherLerp {
267    fn default() -> Self {
268        let old = Instant::now();
269        let new = Instant::now();
270        Self {
271            old: (SharedWeatherGrid::new(Vec2::zero()), old),
272            new: (SharedWeatherGrid::new(Vec2::zero()), new),
273            old_local_wind: (Vec2::zero(), old),
274            new_local_wind: (Vec2::zero(), new),
275            local_wind: Vec2::zero(),
276        }
277    }
278}
279
280pub struct Client {
281    client_type: ClientType,
282    registered: bool,
283    presence: Option<PresenceKind>,
284    runtime: Arc<Runtime>,
285    server_info: ServerInfo,
286    /// Localized server motd and rules
287    server_description: ServerDescription,
288    world_data: WorldData,
289    weather: WeatherLerp,
290    player_list: HashMap<Uid, PlayerInfo>,
291    character_list: CharacterList,
292    character_being_deleted: Option<CharacterId>,
293    sites: HashMap<SiteId, SiteMarker>,
294    extra_markers: Vec<Marker>,
295    possible_starting_sites: Vec<SiteId>,
296    pois: Vec<PoiInfo>,
297    pub chat_mode: ChatMode,
298    component_recipe_book: ComponentRecipeBook,
299    repair_recipe_book: RepairRecipeBook,
300    available_recipes: HashMap<String, Option<SpriteKind>>,
301    lod_zones: HashMap<Vec2<i32>, lod::Zone>,
302    lod_last_requested: Option<Instant>,
303    lod_pos_fallback: Option<Vec2<f32>>,
304    force_update_counter: u64,
305
306    role: Option<AdminRole>,
307    max_group_size: u32,
308    // Client has received an invite (inviter uid, time out instant)
309    invite: Option<(Uid, Instant, Duration, InviteKind)>,
310    group_leader: Option<Uid>,
311    // Note: potentially representable as a client only component
312    group_members: HashMap<Uid, group::Role>,
313    // Pending invites that this client has sent out
314    pending_invites: HashSet<Uid>,
315    // The pending trade the client is involved in, and it's id
316    pending_trade: Option<(TradeId, PendingTrade, Option<SitePrices>)>,
317    waypoint: Option<String>,
318
319    network: Option<Network>,
320    participant: Option<Participant>,
321    general_stream: Stream,
322    ping_stream: Stream,
323    register_stream: Stream,
324    character_screen_stream: Stream,
325    in_game_stream: Stream,
326    terrain_stream: Stream,
327
328    client_timeout: Duration,
329    last_server_ping: f64,
330    last_server_pong: f64,
331    last_ping_delta: f64,
332    ping_deltas: VecDeque<f64>,
333
334    tick: u64,
335    state: State,
336
337    flashing_lights_enabled: bool,
338
339    /// Terrrain view distance
340    server_view_distance_limit: Option<u32>,
341    view_distance: Option<u32>,
342    lod_distance: f32,
343    // TODO: move into voxygen
344    loaded_distance: f32,
345
346    pending_chunks: HashMap<Vec2<i32>, Instant>,
347    target_time_of_day: Option<TimeOfDay>,
348    dt_adjustment: f64,
349
350    connected_server_constants: ServerConstants,
351    /// Requested but not yet received plugins
352    missing_plugins: HashSet<PluginHash>,
353    /// Locally cached plugins needed by the server
354    local_plugins: Vec<PathBuf>,
355}
356
357/// Holds data related to the current players characters, as well as some
358/// additional state to handle UI.
359#[derive(Debug, Default)]
360pub struct CharacterList {
361    pub characters: Vec<CharacterItem>,
362    pub loading: bool,
363}
364
365async fn connect_quic(
366    network: &Network,
367    hostname: String,
368    override_port: Option<u16>,
369    prefer_ipv6: bool,
370    validate_tls: bool,
371) -> Result<network::Participant, crate::error::Error> {
372    let config = if validate_tls {
373        quinn::ClientConfig::try_with_platform_verifier()?
374    } else {
375        warn!(
376            "skipping validation of server identity. There is no guarantee that the server you're \
377             connected to is the one you expect to be connecting to."
378        );
379        #[derive(Debug)]
380        struct Verifier;
381        impl rustls::client::danger::ServerCertVerifier for Verifier {
382            fn verify_server_cert(
383                &self,
384                _end_entity: &rustls::pki_types::CertificateDer<'_>,
385                _intermediates: &[rustls::pki_types::CertificateDer<'_>],
386                _server_name: &rustls::pki_types::ServerName<'_>,
387                _ocsp_response: &[u8],
388                _now: rustls::pki_types::UnixTime,
389            ) -> Result<ServerCertVerified, rustls::Error> {
390                Ok(ServerCertVerified::assertion())
391            }
392
393            fn verify_tls12_signature(
394                &self,
395                _message: &[u8],
396                _cert: &rustls::pki_types::CertificateDer<'_>,
397                _dss: &rustls::DigitallySignedStruct,
398            ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error>
399            {
400                Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
401            }
402
403            fn verify_tls13_signature(
404                &self,
405                _message: &[u8],
406                _cert: &rustls::pki_types::CertificateDer<'_>,
407                _dss: &rustls::DigitallySignedStruct,
408            ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error>
409            {
410                Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
411            }
412
413            fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
414                vec![
415                    rustls::SignatureScheme::RSA_PKCS1_SHA1,
416                    rustls::SignatureScheme::ECDSA_SHA1_Legacy,
417                    rustls::SignatureScheme::RSA_PKCS1_SHA256,
418                    rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
419                    rustls::SignatureScheme::RSA_PKCS1_SHA384,
420                    rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
421                    rustls::SignatureScheme::RSA_PKCS1_SHA512,
422                    rustls::SignatureScheme::ECDSA_NISTP521_SHA512,
423                    rustls::SignatureScheme::RSA_PSS_SHA256,
424                    rustls::SignatureScheme::RSA_PSS_SHA384,
425                    rustls::SignatureScheme::RSA_PSS_SHA512,
426                    rustls::SignatureScheme::ED25519,
427                    rustls::SignatureScheme::ED448,
428                ]
429            }
430        }
431
432        let mut cfg = rustls::ClientConfig::builder()
433            .dangerous()
434            .with_custom_certificate_verifier(Arc::new(Verifier))
435            .with_no_client_auth();
436        cfg.enable_early_data = true;
437
438        quinn::ClientConfig::new(Arc::new(
439            quinn::crypto::rustls::QuicClientConfig::try_from(cfg).unwrap(),
440        ))
441    };
442
443    addr::try_connect(network, &hostname, override_port, prefer_ipv6, |a| {
444        ConnectAddr::Quic(a, config.clone(), hostname.clone())
445    })
446    .await
447}
448
449impl Client {
450    pub async fn new(
451        addr: ConnectionArgs,
452        runtime: Arc<Runtime>,
453        // TODO: refactor to avoid needing to use this out parameter
454        mismatched_server_info: &mut Option<ServerInfo>,
455        username: &str,
456        password: &str,
457        locale: Option<String>,
458        auth_trusted: impl FnMut(&str) -> bool,
459        init_stage_update: &(dyn Fn(ClientInitStage) + Send + Sync),
460        add_foreign_systems: impl Fn(&mut DispatcherBuilder) + Send + 'static,
461        #[cfg_attr(not(feature = "plugins"), expect(unused_variables))] config_dir: PathBuf,
462        client_type: ClientType,
463    ) -> Result<Self, Error> {
464        let _ = rustls::crypto::ring::default_provider().install_default(); // needs to be initialized before usage
465        let network = Network::new(Pid::new(), &runtime);
466
467        init_stage_update(ClientInitStage::ConnectionEstablish);
468
469        let mut participant = match addr {
470            ConnectionArgs::Srv {
471                hostname,
472                prefer_ipv6,
473                validate_tls,
474                use_quic,
475            } => {
476                // Try to create a resolver backed by /etc/resolv.conf or the Windows Registry
477                // first. If that fails, create a resolver being hard-coded to
478                // Google's 8.8.8.8 public resolver.
479                let resolver = Resolver::builder_tokio()
480                    .unwrap_or_else(|error| {
481                        error!(
482                            "Failed to create DNS resolver using system configuration: {error:?}"
483                        );
484                        warn!("Falling back to a default configured resolver.");
485                        Resolver::builder_with_config(
486                            ResolverConfig::default(),
487                            TokioConnectionProvider::default(),
488                        )
489                    })
490                    .build();
491
492                let quic_service_host = format!("_veloren._udp.{hostname}");
493                let quic_lookup_future = resolver.srv_lookup(quic_service_host);
494                let tcp_service_host = format!("_veloren._tcp.{hostname}");
495                let tcp_lookup_future = resolver.srv_lookup(tcp_service_host);
496                let (quic_rr, tcp_rr) = tokio::join!(quic_lookup_future, tcp_lookup_future);
497
498                #[derive(Eq, PartialEq)]
499                enum ConnMode {
500                    Quic,
501                    Tcp,
502                }
503
504                // Push the results of both futures into `srv_rr`. This uses map_or_else purely
505                // for side effects.
506                let mut srv_rr = Vec::new();
507                let () = quic_rr.map_or_else(
508                    |error| {
509                        warn!("QUIC SRV lookup failed: {error:?}");
510                    },
511                    |srv_lookup| {
512                        srv_rr.extend(srv_lookup.iter().cloned().map(|srv| (ConnMode::Quic, srv)))
513                    },
514                );
515                let () = tcp_rr.map_or_else(
516                    |error| {
517                        warn!("TCP SRV lookup failed: {error:?}");
518                    },
519                    |srv_lookup| {
520                        srv_rr.extend(srv_lookup.iter().cloned().map(|srv| (ConnMode::Tcp, srv)))
521                    },
522                );
523
524                // SRV records have a priority; lowest priority hosts MUST be contacted first.
525                let srv_rr_slice = srv_rr.as_mut_slice();
526                srv_rr_slice.sort_by_key(|(_, srv)| srv.priority());
527
528                let mut iter = srv_rr_slice.iter();
529
530                // This loops exits as soon as the above iter over `srv_rr_slice` is exhausted
531                loop {
532                    if let Some((conn_mode, srv_rr)) = iter.next() {
533                        let hostname = format!("{}", srv_rr.target());
534                        let port = Some(srv_rr.port());
535                        let conn_result = match conn_mode {
536                            ConnMode::Quic => {
537                                connect_quic(&network, hostname, port, prefer_ipv6, validate_tls)
538                                    .await
539                            },
540                            ConnMode::Tcp => {
541                                addr::try_connect(
542                                    &network,
543                                    &hostname,
544                                    port,
545                                    prefer_ipv6,
546                                    ConnectAddr::Tcp,
547                                )
548                                .await
549                            },
550                        };
551                        match conn_result {
552                            Ok(c) => break c,
553                            Err(error) => {
554                                warn!("Failed to connect to host {}: {error:?}", srv_rr.target())
555                            },
556                        }
557                    } else {
558                        warn!(
559                            "No SRV hosts succeeded connection, falling back to direct connection"
560                        );
561                        // This case is also hit if no SRV host was returned from the query, so we
562                        // check for QUIC/TCP preference.
563                        let c = if use_quic {
564                            connect_quic(&network, hostname, None, prefer_ipv6, validate_tls)
565                                .await?
566                        } else {
567                            match addr::try_connect(
568                                &network,
569                                &hostname,
570                                None,
571                                prefer_ipv6,
572                                ConnectAddr::Tcp,
573                            )
574                            .await
575                            {
576                                Ok(c) => c,
577                                Err(error) => return Err(error),
578                            }
579                        };
580                        break c;
581                    }
582                }
583            },
584            ConnectionArgs::Tcp {
585                hostname,
586                prefer_ipv6,
587            } => {
588                addr::try_connect(&network, &hostname, None, prefer_ipv6, ConnectAddr::Tcp).await?
589            },
590            ConnectionArgs::Quic {
591                hostname,
592                prefer_ipv6,
593                validate_tls,
594            } => {
595                warn!(
596                    "QUIC is enabled. This is experimental and you won't be able to connect to \
597                     TCP servers unless deactivated"
598                );
599
600                connect_quic(&network, hostname, None, prefer_ipv6, validate_tls).await?
601            },
602            ConnectionArgs::Mpsc(id) => network.connect(ConnectAddr::Mpsc(id)).await?,
603        };
604
605        let stream = participant.opened().await?;
606        let ping_stream = participant.opened().await?;
607        let mut register_stream = participant.opened().await?;
608        let character_screen_stream = participant.opened().await?;
609        let in_game_stream = participant.opened().await?;
610        let terrain_stream = participant.opened().await?;
611
612        init_stage_update(ClientInitStage::WatingForServerVersion);
613        register_stream.send(client_type)?;
614        let server_info: ServerInfo = register_stream.recv().await?;
615        if server_info.git_hash != *common::util::GIT_HASH {
616            warn!(
617                "Server is running {}[{}], you are running {}[{}], versions might be incompatible!",
618                server_info.git_hash,
619                server_info.git_date,
620                common::util::GIT_HASH.to_string(),
621                *common::util::GIT_DATE,
622            );
623        }
624        // Pass the server info back to the caller to ensure they can access it even
625        // if this function errors.
626        *mismatched_server_info = Some(server_info.clone());
627        debug!("Auth Server: {:?}", server_info.auth_provider);
628
629        ping_stream.send(PingMsg::Ping)?;
630
631        init_stage_update(ClientInitStage::Authentication);
632        // Register client
633        Self::register(
634            username,
635            password,
636            locale,
637            auth_trusted,
638            &server_info,
639            &mut register_stream,
640        )
641        .await?;
642
643        init_stage_update(ClientInitStage::LoadingInitData);
644        // Wait for initial sync
645        let mut ping_interval = tokio::time::interval(Duration::from_secs(1));
646        let ServerInit::GameSync {
647            entity_package,
648            time_of_day,
649            max_group_size,
650            client_timeout,
651            world_map,
652            recipe_book,
653            component_recipe_book,
654            material_stats,
655            ability_map,
656            server_constants,
657            repair_recipe_book,
658            description,
659            active_plugins: _active_plugins,
660            role,
661        } = loop {
662            tokio::select! {
663                // Spawn in a blocking thread (leaving the network thread free).  This is mostly
664                // useful for bots.
665                res = register_stream.recv() => break res?,
666                _ = ping_interval.tick() => ping_stream.send(PingMsg::Ping)?,
667            }
668        };
669
670        init_stage_update(ClientInitStage::StartingClient);
671        // Spawn in a blocking thread (leaving the network thread free).  This is mostly
672        // useful for bots.
673        let mut task = tokio::task::spawn_blocking(move || {
674            let map_size_lg =
675                common::terrain::MapSizeLg::new(world_map.dimensions_lg).map_err(|_| {
676                    Error::Other(format!(
677                        "Server sent bad world map dimensions: {:?}",
678                        world_map.dimensions_lg,
679                    ))
680                })?;
681            let sea_level = world_map.default_chunk.get_min_z() as f32;
682
683            // Initialize `State`
684            let pools = State::pools(GameMode::Client);
685            let mut state = State::client(
686                pools,
687                map_size_lg,
688                world_map.default_chunk,
689                // TODO: Add frontend systems
690                |dispatch_builder| {
691                    add_local_systems(dispatch_builder);
692                    add_foreign_systems(dispatch_builder);
693                },
694                #[cfg(feature = "plugins")]
695                common_state::plugin::PluginMgr::from_asset_or_default(),
696            );
697
698            #[cfg_attr(not(feature = "plugins"), expect(unused_mut))]
699            let mut missing_plugins: Vec<PluginHash> = Vec::new();
700            #[cfg_attr(not(feature = "plugins"), expect(unused_mut))]
701            let mut local_plugins: Vec<PathBuf> = Vec::new();
702            #[cfg(feature = "plugins")]
703            {
704                let already_present = state.ecs().read_resource::<PluginMgr>().plugin_list();
705                for hash in _active_plugins.iter() {
706                    if !already_present.contains(hash) {
707                        // look in config_dir first (cache)
708                        if let Ok(local_path) = common_state::plugin::find_cached(&config_dir, hash)
709                        {
710                            local_plugins.push(local_path);
711                        } else {
712                            //tracing::info!("cache not found {local_path:?}");
713                            tracing::info!("Server requires plugin {hash:x?}");
714                            missing_plugins.push(*hash);
715                        }
716                    }
717                }
718            }
719            // Client-only components
720            state.ecs_mut().register::<comp::Last<CharacterState>>();
721            let entity = state.ecs_mut().apply_entity_package(entity_package);
722            *state.ecs_mut().write_resource() = time_of_day;
723            *state.ecs_mut().write_resource() = PlayerEntity(Some(entity));
724            state.ecs_mut().insert(material_stats);
725            state.ecs_mut().insert(ability_map);
726            state.ecs_mut().insert(recipe_book);
727
728            let map_size = map_size_lg.chunks();
729            let max_height = world_map.max_height;
730            let rgba = world_map.rgba;
731            let alt = world_map.alt;
732            if rgba.size() != map_size.map(|e| e as i32) {
733                return Err(Error::Other("Server sent a bad world map image".into()));
734            }
735            if alt.size() != map_size.map(|e| e as i32) {
736                return Err(Error::Other("Server sent a bad altitude map.".into()));
737            }
738            let [west, east] = world_map.horizons;
739            let scale_angle = |a: u8| (a as f32 / 255.0 * <f32 as FloatConst>::FRAC_PI_2()).tan();
740            let scale_height = |h: u8| h as f32 / 255.0 * max_height;
741            let scale_height_big = |h: u32| (h >> 3) as f32 / 8191.0 * max_height;
742
743            debug!("Preparing image...");
744            let unzip_horizons = |(angles, heights): &(Vec<_>, Vec<_>)| {
745                (
746                    angles.iter().copied().map(scale_angle).collect::<Vec<_>>(),
747                    heights
748                        .iter()
749                        .copied()
750                        .map(scale_height)
751                        .collect::<Vec<_>>(),
752                )
753            };
754            let horizons = [unzip_horizons(&west), unzip_horizons(&east)];
755
756            // Redraw map (with shadows this time).
757            let mut world_map_rgba = vec![0u32; rgba.size().product() as usize];
758            let mut world_map_topo = vec![0u32; rgba.size().product() as usize];
759            let mut map_config = common::terrain::map::MapConfig::orthographic(
760                map_size_lg,
761                core::ops::RangeInclusive::new(0.0, max_height),
762            );
763            map_config.horizons = Some(&horizons);
764            let rescale_height = |h: f32| h / max_height;
765            let bounds_check = |pos: Vec2<i32>| {
766                pos.reduce_partial_min() >= 0
767                    && pos.x < map_size.x as i32
768                    && pos.y < map_size.y as i32
769            };
770            fn sample_pos(
771                map_config: &MapConfig,
772                pos: Vec2<i32>,
773                alt: &Grid<u32>,
774                rgba: &Grid<u32>,
775                map_size: &Vec2<u16>,
776                map_size_lg: &common::terrain::MapSizeLg,
777                max_height: f32,
778            ) -> common::terrain::map::MapSample {
779                let rescale_height = |h: f32| h / max_height;
780                let scale_height_big = |h: u32| (h >> 3) as f32 / 8191.0 * max_height;
781                let bounds_check = |pos: Vec2<i32>| {
782                    pos.reduce_partial_min() >= 0
783                        && pos.x < map_size.x as i32
784                        && pos.y < map_size.y as i32
785                };
786                let MapConfig {
787                    gain,
788                    is_contours,
789                    is_height_map,
790                    is_stylized_topo,
791                    ..
792                } = *map_config;
793                let mut is_contour_line = false;
794                let mut is_border = false;
795                let (rgb, alt, downhill_wpos) = if bounds_check(pos) {
796                    let posi = pos.y as usize * map_size.x as usize + pos.x as usize;
797                    let [r, g, b, _a] = rgba[pos].to_le_bytes();
798                    let is_water = r == 0 && b > 102 && g < 77;
799                    let alti = alt[pos];
800                    // Compute contours (chunks are assigned in the river code below)
801                    let altj = rescale_height(scale_height_big(alti));
802                    let contour_interval = 150.0;
803                    let chunk_contour = (altj * gain / contour_interval) as u32;
804
805                    // Compute downhill.
806                    let downhill = {
807                        let mut best = -1;
808                        let mut besth = alti;
809                        for nposi in neighbors(*map_size_lg, posi) {
810                            let nbh = alt.raw()[nposi];
811                            let nalt = rescale_height(scale_height_big(nbh));
812                            let nchunk_contour = (nalt * gain / contour_interval) as u32;
813                            if !is_contour_line && chunk_contour > nchunk_contour {
814                                is_contour_line = true;
815                            }
816                            let [nr, ng, nb, _na] = rgba.raw()[nposi].to_le_bytes();
817                            let n_is_water = nr == 0 && nb > 102 && ng < 77;
818
819                            if !is_border && is_water && !n_is_water {
820                                is_border = true;
821                            }
822
823                            if nbh < besth {
824                                besth = nbh;
825                                best = nposi as isize;
826                            }
827                        }
828                        best
829                    };
830                    let downhill_wpos = if downhill < 0 {
831                        None
832                    } else {
833                        Some(
834                            Vec2::new(
835                                (downhill as usize % map_size.x as usize) as i32,
836                                (downhill as usize / map_size.x as usize) as i32,
837                            ) * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
838                        )
839                    };
840                    (Rgb::new(r, g, b), alti, downhill_wpos)
841                } else {
842                    (Rgb::zero(), 0, None)
843                };
844                let alt = f64::from(rescale_height(scale_height_big(alt)));
845                let wpos = pos * TerrainChunkSize::RECT_SIZE.map(|e| e as i32);
846                let downhill_wpos =
847                    downhill_wpos.unwrap_or(wpos + TerrainChunkSize::RECT_SIZE.map(|e| e as i32));
848                let is_path = rgb.r == 0x37 && rgb.g == 0x29 && rgb.b == 0x23;
849                let rgb = rgb.map(|e: u8| e as f64 / 255.0);
850                let is_water = rgb.r == 0.0 && rgb.b > 0.4 && rgb.g < 0.3;
851
852                let rgb = if is_height_map {
853                    if is_path {
854                        // Path color is Rgb::new(0x37, 0x29, 0x23)
855                        Rgb::new(0.9, 0.9, 0.63)
856                    } else if is_water {
857                        Rgb::new(0.23, 0.47, 0.53)
858                    } else if is_contours && is_contour_line {
859                        // Color contour lines
860                        Rgb::new(0.15, 0.15, 0.15)
861                    } else {
862                        // Color hill shading
863                        let lightness = (alt + 0.2).min(1.0);
864                        Rgb::new(lightness, 0.9 * lightness, 0.5 * lightness)
865                    }
866                } else if is_stylized_topo {
867                    if is_path {
868                        Rgb::new(0.9, 0.9, 0.63)
869                    } else if is_water {
870                        if is_border {
871                            Rgb::new(0.10, 0.34, 0.50)
872                        } else {
873                            Rgb::new(0.23, 0.47, 0.63)
874                        }
875                    } else if is_contour_line {
876                        Rgb::new(0.25, 0.25, 0.25)
877                    } else {
878                        // Stylized colors
879                        Rgb::new(
880                            (rgb.r + 0.25).min(1.0),
881                            (rgb.g + 0.23).min(1.0),
882                            (rgb.b + 0.10).min(1.0),
883                        )
884                    }
885                } else {
886                    Rgb::new(rgb.r, rgb.g, rgb.b)
887                }
888                .map(|e| (e * 255.0) as u8);
889                common::terrain::map::MapSample {
890                    rgb,
891                    alt,
892                    downhill_wpos,
893                    connections: None,
894                }
895            }
896            // Generate standard shaded map
897            map_config.is_shaded = true;
898            map_config.generate(
899                |pos| {
900                    sample_pos(
901                        &map_config,
902                        pos,
903                        &alt,
904                        &rgba,
905                        &map_size,
906                        &map_size_lg,
907                        max_height,
908                    )
909                },
910                |wpos| {
911                    let pos = wpos.wpos_to_cpos();
912                    rescale_height(if bounds_check(pos) {
913                        scale_height_big(alt[pos])
914                    } else {
915                        0.0
916                    })
917                },
918                |pos, (r, g, b, a)| {
919                    world_map_rgba[pos.y * map_size.x as usize + pos.x] =
920                        u32::from_le_bytes([r, g, b, a]);
921                },
922            );
923            // Generate map with topographical lines and stylized colors
924            map_config.is_contours = true;
925            map_config.is_stylized_topo = true;
926            map_config.generate(
927                |pos| {
928                    sample_pos(
929                        &map_config,
930                        pos,
931                        &alt,
932                        &rgba,
933                        &map_size,
934                        &map_size_lg,
935                        max_height,
936                    )
937                },
938                |wpos| {
939                    let pos = wpos.wpos_to_cpos();
940                    rescale_height(if bounds_check(pos) {
941                        scale_height_big(alt[pos])
942                    } else {
943                        0.0
944                    })
945                },
946                |pos, (r, g, b, a)| {
947                    world_map_topo[pos.y * map_size.x as usize + pos.x] =
948                        u32::from_le_bytes([r, g, b, a]);
949                },
950            );
951            let make_raw = |rgb| -> Result<_, Error> {
952                let mut raw = vec![0u8; 4 * world_map_rgba.len()];
953                LittleEndian::write_u32_into(rgb, &mut raw);
954                Ok(Arc::new(
955                    DynamicImage::ImageRgba8({
956                        // Should not fail if the dimensions are correct.
957                        let map =
958                            image::ImageBuffer::from_raw(u32::from(map_size.x), u32::from(map_size.y), raw);
959                        map.ok_or_else(|| Error::Other("Server sent a bad world map image".into()))?
960                    })
961                    // Flip the image, since Voxygen uses an orientation where rotation from
962                    // positive x axis to positive y axis is counterclockwise around the z axis.
963                    .flipv(),
964                ))
965            };
966            let lod_base = rgba;
967            let lod_alt = alt;
968            let world_map_rgb_img = make_raw(&world_map_rgba)?;
969            let world_map_topo_img = make_raw(&world_map_topo)?;
970            let world_map_layers = vec![world_map_rgb_img, world_map_topo_img];
971            let horizons = (west.0, west.1, east.0, east.1)
972                .into_par_iter()
973                .map(|(wa, wh, ea, eh)| u32::from_le_bytes([wa, wh, ea, eh]))
974                .collect::<Vec<_>>();
975            let lod_horizon = horizons;
976            let map_bounds = Vec2::new(sea_level, max_height);
977            debug!("Done preparing image...");
978
979            Ok((
980                state,
981                lod_base,
982                lod_alt,
983                Grid::from_raw(map_size.map(|e| e as i32), lod_horizon),
984                (world_map_layers, map_size, map_bounds),
985                world_map.sites,
986                world_map.possible_starting_sites,
987                world_map.pois,
988                component_recipe_book,
989                repair_recipe_book,
990                max_group_size,
991                client_timeout,
992                missing_plugins,
993                local_plugins,
994                role,
995            ))
996        });
997
998        let (
999            state,
1000            lod_base,
1001            lod_alt,
1002            lod_horizon,
1003            world_map,
1004            sites,
1005            possible_starting_sites,
1006            pois,
1007            component_recipe_book,
1008            repair_recipe_book,
1009            max_group_size,
1010            client_timeout,
1011            missing_plugins,
1012            local_plugins,
1013            role,
1014        ) = loop {
1015            tokio::select! {
1016                res = &mut task => break res.expect("Client thread should not panic")?,
1017                _ = ping_interval.tick() => ping_stream.send(PingMsg::Ping)?,
1018            }
1019        };
1020        let missing_plugins_set = missing_plugins.iter().cloned().collect();
1021        if !missing_plugins.is_empty() {
1022            stream.send(ClientGeneral::RequestPlugins(missing_plugins))?;
1023        }
1024        ping_stream.send(PingMsg::Ping)?;
1025
1026        debug!("Initial sync done");
1027
1028        Ok(Self {
1029            client_type,
1030            registered: true,
1031            presence: None,
1032            runtime,
1033            server_info,
1034            server_description: description,
1035            world_data: WorldData {
1036                lod_base,
1037                lod_alt,
1038                lod_horizon,
1039                map: world_map,
1040            },
1041            weather: WeatherLerp::default(),
1042            player_list: HashMap::new(),
1043            character_list: CharacterList::default(),
1044            character_being_deleted: None,
1045            sites: sites
1046                .iter()
1047                .filter_map(|m| {
1048                    Some((m.site?, SiteMarker {
1049                        marker: m.clone(),
1050                        economy: None,
1051                    }))
1052                })
1053                .collect(),
1054            extra_markers: sites.iter().filter(|m| m.site.is_none()).cloned().collect(),
1055            possible_starting_sites,
1056            pois,
1057            component_recipe_book,
1058            repair_recipe_book,
1059            available_recipes: HashMap::default(),
1060            chat_mode: ChatMode::default(),
1061
1062            lod_zones: HashMap::new(),
1063            lod_last_requested: None,
1064            lod_pos_fallback: None,
1065
1066            force_update_counter: 0,
1067
1068            role,
1069            max_group_size,
1070            invite: None,
1071            group_leader: None,
1072            group_members: HashMap::new(),
1073            pending_invites: HashSet::new(),
1074            pending_trade: None,
1075            waypoint: None,
1076
1077            network: Some(network),
1078            participant: Some(participant),
1079            general_stream: stream,
1080            ping_stream,
1081            register_stream,
1082            character_screen_stream,
1083            in_game_stream,
1084            terrain_stream,
1085
1086            client_timeout,
1087
1088            last_server_ping: 0.0,
1089            last_server_pong: 0.0,
1090            last_ping_delta: 0.0,
1091            ping_deltas: VecDeque::new(),
1092
1093            tick: 0,
1094            state,
1095
1096            flashing_lights_enabled: true,
1097
1098            server_view_distance_limit: None,
1099            view_distance: None,
1100            lod_distance: 4.0,
1101            loaded_distance: 0.0,
1102
1103            pending_chunks: HashMap::new(),
1104            target_time_of_day: None,
1105            dt_adjustment: 1.0,
1106
1107            connected_server_constants: server_constants,
1108            missing_plugins: missing_plugins_set,
1109            local_plugins,
1110        })
1111    }
1112
1113    /// Request a state transition to `ClientState::Registered`.
1114    async fn register(
1115        username: &str,
1116        password: &str,
1117        locale: Option<String>,
1118        mut auth_trusted: impl FnMut(&str) -> bool,
1119        server_info: &ServerInfo,
1120        register_stream: &mut Stream,
1121    ) -> Result<(), Error> {
1122        // Authentication
1123        let token_or_username = match &server_info.auth_provider {
1124            Some(addr) => {
1125                // Query whether this is a trusted auth server
1126                if auth_trusted(addr) {
1127                    let (scheme, authority) = match addr.split_once("://") {
1128                        Some((s, a)) => (s, a),
1129                        None => return Err(Error::AuthServerUrlInvalid(addr.to_string())),
1130                    };
1131
1132                    let scheme = match scheme.parse::<authc::Scheme>() {
1133                        Ok(s) => s,
1134                        Err(_) => return Err(Error::AuthServerUrlInvalid(addr.to_string())),
1135                    };
1136
1137                    let authority = match authority.parse::<authc::Authority>() {
1138                        Ok(a) => a,
1139                        Err(_) => return Err(Error::AuthServerUrlInvalid(addr.to_string())),
1140                    };
1141
1142                    Ok(authc::AuthClient::new(scheme, authority)?
1143                        .sign_in(username, password)
1144                        .await?
1145                        .serialize())
1146                } else {
1147                    Err(Error::AuthServerNotTrusted)
1148                }
1149            },
1150            None => Ok(username.to_owned()),
1151        }?;
1152
1153        debug!("Registering client...");
1154
1155        register_stream.send(ClientRegister {
1156            token_or_username,
1157            locale,
1158        })?;
1159
1160        match register_stream.recv::<ServerRegisterAnswer>().await? {
1161            Err(RegisterError::AuthError(err)) => Err(Error::AuthErr(err)),
1162            Err(RegisterError::InvalidCharacter) => Err(Error::InvalidCharacter),
1163            Err(RegisterError::NotOnWhitelist) => Err(Error::NotOnWhitelist),
1164            Err(RegisterError::Kicked(err)) => Err(Error::Kicked(err)),
1165            Err(RegisterError::Banned(info)) => Err(Error::Banned(info)),
1166            Err(RegisterError::TooManyPlayers) => Err(Error::TooManyPlayers),
1167            Ok(()) => {
1168                debug!("Client registered successfully.");
1169                Ok(())
1170            },
1171        }
1172    }
1173
1174    fn send_msg_err<S>(&mut self, msg: S) -> Result<(), network::StreamError>
1175    where
1176        S: Into<ClientMsg>,
1177    {
1178        prof_span!("send_msg_err");
1179        let msg: ClientMsg = msg.into();
1180        #[cfg(debug_assertions)]
1181        {
1182            const C_TYPE: ClientType = ClientType::Game;
1183            let verified = msg.verify(C_TYPE, self.registered, self.presence);
1184
1185            // Due to the fact that character loading is performed asynchronously after
1186            // initial connect it is possible to receive messages after a character load
1187            // error while in the wrong state.
1188            if !verified {
1189                warn!(
1190                    "Received ClientType::Game message when not in game (Registered: {} Presence: \
1191                     {:?}), dropping message: {:?} ",
1192                    self.registered, self.presence, msg
1193                );
1194                return Ok(());
1195            }
1196        }
1197        match msg {
1198            ClientMsg::Type(msg) => self.register_stream.send(msg),
1199            ClientMsg::Register(msg) => self.register_stream.send(msg),
1200            ClientMsg::General(msg) => {
1201                #[cfg(feature = "tracy")]
1202                let (mut ingame, mut terrain) = (0.0, 0.0);
1203                let stream = match msg {
1204                    ClientGeneral::RequestCharacterList
1205                    | ClientGeneral::CreateCharacter { .. }
1206                    | ClientGeneral::EditCharacter { .. }
1207                    | ClientGeneral::DeleteCharacter(_)
1208                    | ClientGeneral::Character(_, _)
1209                    | ClientGeneral::Spectate(_) => &mut self.character_screen_stream,
1210                    // Only in game
1211                    ClientGeneral::ControllerInputs(_)
1212                    | ClientGeneral::ControlEvent(_)
1213                    | ClientGeneral::ControlAction(_)
1214                    | ClientGeneral::SetViewDistance(_)
1215                    | ClientGeneral::BreakBlock(_)
1216                    | ClientGeneral::PlaceBlock(_, _)
1217                    | ClientGeneral::ExitInGame
1218                    | ClientGeneral::PlayerPhysics { .. }
1219                    | ClientGeneral::UnlockSkill(_)
1220                    | ClientGeneral::RequestSiteInfo(_)
1221                    | ClientGeneral::RequestPlayerPhysics { .. }
1222                    | ClientGeneral::RequestLossyTerrainCompression { .. }
1223                    | ClientGeneral::UpdateMapMarker(_)
1224                    | ClientGeneral::SpectatePosition(_)
1225                    | ClientGeneral::SpectateEntity(_)
1226                    | ClientGeneral::SetBattleMode(_) => {
1227                        #[cfg(feature = "tracy")]
1228                        {
1229                            ingame = 1.0;
1230                        }
1231                        &mut self.in_game_stream
1232                    },
1233                    // Terrain
1234                    ClientGeneral::TerrainChunkRequest { .. }
1235                    | ClientGeneral::LodZoneRequest { .. } => {
1236                        #[cfg(feature = "tracy")]
1237                        {
1238                            terrain = 1.0;
1239                        }
1240                        &mut self.terrain_stream
1241                    },
1242                    // Always possible
1243                    ClientGeneral::ChatMsg(_)
1244                    | ClientGeneral::Command(_, _)
1245                    | ClientGeneral::Terminate
1246                    | ClientGeneral::RequestPlugins(_) => &mut self.general_stream,
1247                };
1248                #[cfg(feature = "tracy")]
1249                {
1250                    plot!("ingame_sends", ingame);
1251                    plot!("terrain_sends", terrain);
1252                }
1253                stream.send(msg)
1254            },
1255            ClientMsg::Ping(msg) => self.ping_stream.send(msg),
1256        }
1257    }
1258
1259    pub fn request_player_physics(&mut self, server_authoritative: bool) {
1260        self.send_msg(ClientGeneral::RequestPlayerPhysics {
1261            server_authoritative,
1262        })
1263    }
1264
1265    pub fn request_lossy_terrain_compression(&mut self, lossy_terrain_compression: bool) {
1266        self.send_msg(ClientGeneral::RequestLossyTerrainCompression {
1267            lossy_terrain_compression,
1268        })
1269    }
1270
1271    fn send_msg<S>(&mut self, msg: S)
1272    where
1273        S: Into<ClientMsg>,
1274    {
1275        let res = self.send_msg_err(msg);
1276        if let Err(e) = res {
1277            warn!(
1278                ?e,
1279                "connection to server no longer possible, couldn't send msg"
1280            );
1281        }
1282    }
1283
1284    /// Request a state transition to `ClientState::Character`.
1285    pub fn request_character(
1286        &mut self,
1287        character_id: CharacterId,
1288        view_distances: common::ViewDistances,
1289    ) {
1290        let view_distances = self.set_view_distances_local(view_distances);
1291        self.send_msg(ClientGeneral::Character(character_id, view_distances));
1292
1293        if let Some(character) = self
1294            .character_list
1295            .characters
1296            .iter()
1297            .find(|x| x.character.id == Some(character_id))
1298        {
1299            self.waypoint = character.location.clone();
1300        }
1301
1302        // Assume we are in_game unless server tells us otherwise
1303        self.presence = Some(PresenceKind::Character(character_id));
1304    }
1305
1306    /// Request a state transition to `ClientState::Spectate`.
1307    pub fn request_spectate(&mut self, view_distances: common::ViewDistances) {
1308        let view_distances = self.set_view_distances_local(view_distances);
1309        self.send_msg(ClientGeneral::Spectate(view_distances));
1310
1311        self.presence = Some(PresenceKind::Spectator);
1312    }
1313
1314    /// Load the current players character list
1315    pub fn load_character_list(&mut self) {
1316        self.character_list.loading = true;
1317        self.send_msg(ClientGeneral::RequestCharacterList);
1318    }
1319
1320    /// New character creation
1321    pub fn create_character(
1322        &mut self,
1323        alias: String,
1324        mainhand: Option<String>,
1325        offhand: Option<String>,
1326        body: comp::Body,
1327        hardcore: bool,
1328        start_site: Option<SiteId>,
1329    ) {
1330        self.character_list.loading = true;
1331        self.send_msg(ClientGeneral::CreateCharacter {
1332            alias,
1333            mainhand,
1334            offhand,
1335            body,
1336            hardcore,
1337            start_site,
1338        });
1339    }
1340
1341    pub fn edit_character(&mut self, alias: String, id: CharacterId, body: comp::Body) {
1342        self.character_list.loading = true;
1343        self.send_msg(ClientGeneral::EditCharacter { alias, id, body });
1344    }
1345
1346    /// Character deletion
1347    pub fn delete_character(&mut self, character_id: CharacterId) {
1348        // Pre-emptively remove the character to be deleted from the character list as
1349        // character deletes are processed asynchronously by the server so we can't rely
1350        // on a timely response to update the character list
1351        if let Some(pos) = self
1352            .character_list
1353            .characters
1354            .iter()
1355            .position(|x| x.character.id == Some(character_id))
1356        {
1357            self.character_list.characters.remove(pos);
1358        }
1359        self.send_msg(ClientGeneral::DeleteCharacter(character_id));
1360    }
1361
1362    /// Send disconnect message to the server
1363    pub fn logout(&mut self) {
1364        debug!("Sending logout from server");
1365        self.send_msg(ClientGeneral::Terminate);
1366        self.registered = false;
1367        self.presence = None;
1368    }
1369
1370    /// Request a state transition to `ClientState::Registered` from an ingame
1371    /// state.
1372    pub fn request_remove_character(&mut self) {
1373        self.chat_mode = ChatMode::World;
1374        self.send_msg(ClientGeneral::ExitInGame);
1375    }
1376
1377    pub fn set_view_distances(&mut self, view_distances: common::ViewDistances) {
1378        let view_distances = self.set_view_distances_local(view_distances);
1379        self.send_msg(ClientGeneral::SetViewDistance(view_distances));
1380    }
1381
1382    /// Clamps provided view distances, locally sets the terrain view distance
1383    /// in the client's properties and returns the clamped values for the
1384    /// caller to send to the server.
1385    fn set_view_distances_local(
1386        &mut self,
1387        view_distances: common::ViewDistances,
1388    ) -> common::ViewDistances {
1389        let view_distances = common::ViewDistances {
1390            terrain: view_distances
1391                .terrain
1392                .clamp(1, MAX_SELECTABLE_VIEW_DISTANCE),
1393            entity: view_distances.entity.max(1),
1394        };
1395        self.view_distance = Some(view_distances.terrain);
1396        view_distances
1397    }
1398
1399    pub fn set_lod_distance(&mut self, lod_distance: u32) {
1400        let lod_distance = lod_distance.clamp(0, 1000) as f32 / lod::ZONE_SIZE as f32;
1401        self.lod_distance = lod_distance;
1402    }
1403
1404    pub fn set_flashing_lights_enabled(&mut self, flashing_lights_enabled: bool) {
1405        self.flashing_lights_enabled = flashing_lights_enabled;
1406    }
1407
1408    pub fn use_slot(&mut self, slot: Slot) {
1409        self.control_action(ControlAction::InventoryAction(InventoryAction::Use(slot)))
1410    }
1411
1412    pub fn swap_slots(&mut self, a: Slot, b: Slot) {
1413        match (a, b) {
1414            (Slot::Overflow(o), Slot::Inventory(inv))
1415            | (Slot::Inventory(inv), Slot::Overflow(o)) => {
1416                self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1417                    InventoryEvent::OverflowMove(o, inv),
1418                )));
1419            },
1420            (Slot::Overflow(_), _) | (_, Slot::Overflow(_)) => {},
1421            (Slot::Equip(equip), slot) | (slot, Slot::Equip(equip)) => self.control_action(
1422                ControlAction::InventoryAction(InventoryAction::Swap(equip, slot)),
1423            ),
1424            (Slot::Inventory(inv1), Slot::Inventory(inv2)) => {
1425                self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1426                    InventoryEvent::Swap(inv1, inv2),
1427                )))
1428            },
1429        }
1430    }
1431
1432    pub fn drop_slot(&mut self, slot: Slot) {
1433        match slot {
1434            Slot::Equip(equip) => {
1435                self.control_action(ControlAction::InventoryAction(InventoryAction::Drop(equip)))
1436            },
1437            Slot::Inventory(inv) => self.send_msg(ClientGeneral::ControlEvent(
1438                ControlEvent::InventoryEvent(InventoryEvent::Drop(inv)),
1439            )),
1440            Slot::Overflow(o) => self.send_msg(ClientGeneral::ControlEvent(
1441                ControlEvent::InventoryEvent(InventoryEvent::OverflowDrop(o)),
1442            )),
1443        }
1444    }
1445
1446    pub fn sort_inventory(&mut self, sort_order: InventorySortOrder) {
1447        self.control_action(ControlAction::InventoryAction(InventoryAction::Sort(
1448            sort_order,
1449        )));
1450    }
1451
1452    pub fn perform_trade_action(&mut self, action: TradeAction) {
1453        if let Some((id, _, _)) = self.pending_trade {
1454            if let TradeAction::Decline = action {
1455                self.pending_trade.take();
1456            }
1457            self.send_msg(ClientGeneral::ControlEvent(
1458                ControlEvent::PerformTradeAction(id, action),
1459            ));
1460        }
1461    }
1462
1463    pub fn is_dead(&self) -> bool { self.current::<comp::Health>().is_some_and(|h| h.is_dead) }
1464
1465    pub fn is_gliding(&self) -> bool {
1466        self.current::<CharacterState>()
1467            .is_some_and(|cs| matches!(cs, CharacterState::Glide(_)))
1468    }
1469
1470    pub fn split_swap_slots(&mut self, a: Slot, b: Slot) {
1471        match (a, b) {
1472            (Slot::Overflow(_), _) | (_, Slot::Overflow(_)) => {},
1473            (Slot::Equip(equip), slot) | (slot, Slot::Equip(equip)) => self.control_action(
1474                ControlAction::InventoryAction(InventoryAction::Swap(equip, slot)),
1475            ),
1476            (Slot::Inventory(inv1), Slot::Inventory(inv2)) => {
1477                self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1478                    InventoryEvent::SplitSwap(inv1, inv2),
1479                )))
1480            },
1481        }
1482    }
1483
1484    pub fn split_drop_slot(&mut self, slot: Slot) {
1485        match slot {
1486            Slot::Equip(equip) => {
1487                self.control_action(ControlAction::InventoryAction(InventoryAction::Drop(equip)))
1488            },
1489            Slot::Inventory(inv) => self.send_msg(ClientGeneral::ControlEvent(
1490                ControlEvent::InventoryEvent(InventoryEvent::SplitDrop(inv)),
1491            )),
1492            Slot::Overflow(o) => self.send_msg(ClientGeneral::ControlEvent(
1493                ControlEvent::InventoryEvent(InventoryEvent::OverflowSplitDrop(o)),
1494            )),
1495        }
1496    }
1497
1498    pub fn pick_up(&mut self, entity: EcsEntity) {
1499        // Get the health component from the entity
1500
1501        if let Some(uid) = self.state.read_component_copied(entity) {
1502            // If we're dead, exit before sending the message
1503            if self.is_dead() {
1504                return;
1505            }
1506
1507            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1508                InventoryEvent::Pickup(uid),
1509            )));
1510        }
1511    }
1512
1513    pub fn do_pet(&mut self, target_entity: EcsEntity) {
1514        if self.is_dead() {
1515            return;
1516        }
1517
1518        if let Some(target_uid) = self.state.read_component_copied(target_entity) {
1519            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InteractWith {
1520                target: target_uid,
1521                kind: common::interaction::InteractionKind::Pet,
1522            }))
1523        }
1524    }
1525
1526    pub fn npc_interact(&mut self, npc_entity: EcsEntity) {
1527        // If we're dead, exit before sending message
1528        if self.is_dead() {
1529            return;
1530        }
1531
1532        if let Some(uid) = self.state.read_component_copied(npc_entity) {
1533            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::Interact(uid)));
1534        }
1535    }
1536
1537    pub fn player_list(&self) -> &HashMap<Uid, PlayerInfo> { &self.player_list }
1538
1539    pub fn character_list(&self) -> &CharacterList { &self.character_list }
1540
1541    pub fn server_info(&self) -> &ServerInfo { &self.server_info }
1542
1543    pub fn server_description(&self) -> &ServerDescription { &self.server_description }
1544
1545    pub fn world_data(&self) -> &WorldData { &self.world_data }
1546
1547    pub fn component_recipe_book(&self) -> &ComponentRecipeBook { &self.component_recipe_book }
1548
1549    pub fn repair_recipe_book(&self) -> &RepairRecipeBook { &self.repair_recipe_book }
1550
1551    pub fn client_type(&self) -> &ClientType { &self.client_type }
1552
1553    pub fn available_recipes(&self) -> &HashMap<String, Option<SpriteKind>> {
1554        &self.available_recipes
1555    }
1556
1557    pub fn lod_zones(&self) -> &HashMap<Vec2<i32>, lod::Zone> { &self.lod_zones }
1558
1559    /// Set the fallback position used for loading LoD zones when the client
1560    /// entity does not have a position.
1561    pub fn set_lod_pos_fallback(&mut self, pos: Vec2<f32>) { self.lod_pos_fallback = Some(pos); }
1562
1563    pub fn craft_recipe(
1564        &mut self,
1565        recipe: &str,
1566        slots: Vec<(u32, InvSlotId)>,
1567        craft_sprite: Option<(VolumePos, SpriteKind)>,
1568        amount: u32,
1569    ) -> bool {
1570        let (can_craft, has_sprite) = if let Some(inventory) = self
1571            .state
1572            .ecs()
1573            .read_storage::<comp::Inventory>()
1574            .get(self.entity())
1575        {
1576            let rbm = self.state.ecs().read_resource::<RecipeBookManifest>();
1577            let (can_craft, required_sprite) = inventory.can_craft_recipe(recipe, 1, &rbm);
1578            let has_sprite =
1579                required_sprite.is_none_or(|s| Some(s) == craft_sprite.map(|(_, s)| s));
1580            (can_craft, has_sprite)
1581        } else {
1582            (false, false)
1583        };
1584        if can_craft && has_sprite {
1585            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1586                InventoryEvent::CraftRecipe {
1587                    craft_event: CraftEvent::Simple {
1588                        recipe: recipe.to_string(),
1589                        slots,
1590                        amount,
1591                    },
1592                    craft_sprite: craft_sprite.map(|(pos, _)| pos),
1593                },
1594            )));
1595            true
1596        } else {
1597            false
1598        }
1599    }
1600
1601    /// Checks if the item in the given slot can be salvaged.
1602    pub fn can_salvage_item(&self, slot: InvSlotId) -> bool {
1603        self.inventories()
1604            .get(self.entity())
1605            .and_then(|inv| inv.get(slot))
1606            .is_some_and(|item| item.is_salvageable())
1607    }
1608
1609    /// Salvage the item in the given inventory slot. `salvage_pos` should be
1610    /// the location of a relevant crafting station within range of the player.
1611    pub fn salvage_item(&mut self, slot: InvSlotId, salvage_pos: VolumePos) -> bool {
1612        let is_salvageable = self.can_salvage_item(slot);
1613        if is_salvageable {
1614            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1615                InventoryEvent::CraftRecipe {
1616                    craft_event: CraftEvent::Salvage(slot),
1617                    craft_sprite: Some(salvage_pos),
1618                },
1619            )));
1620        }
1621        is_salvageable
1622    }
1623
1624    /// Crafts modular weapon from components in the provided slots.
1625    /// `sprite_pos` should be the location of the necessary crafting station in
1626    /// range of the player.
1627    /// Returns whether or not the networking event was sent (which is based on
1628    /// whether the player has two modular components in the provided slots)
1629    pub fn craft_modular_weapon(
1630        &mut self,
1631        primary_component: InvSlotId,
1632        secondary_component: InvSlotId,
1633        sprite_pos: Option<VolumePos>,
1634    ) -> bool {
1635        let inventories = self.inventories();
1636        let inventory = inventories.get(self.entity());
1637
1638        enum ModKind {
1639            Primary,
1640            Secondary,
1641        }
1642
1643        // Closure to get inner modular component info from item in a given slot
1644        let mod_kind = |slot| match inventory
1645            .and_then(|inv| inv.get(slot).map(|item| item.kind()))
1646            .as_deref()
1647        {
1648            Some(ItemKind::ModularComponent(modular::ModularComponent::ToolPrimaryComponent {
1649                ..
1650            })) => Some(ModKind::Primary),
1651            Some(ItemKind::ModularComponent(
1652                modular::ModularComponent::ToolSecondaryComponent { .. },
1653            )) => Some(ModKind::Secondary),
1654            _ => None,
1655        };
1656
1657        if let (Some(ModKind::Primary), Some(ModKind::Secondary)) =
1658            (mod_kind(primary_component), mod_kind(secondary_component))
1659        {
1660            drop(inventories);
1661            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1662                InventoryEvent::CraftRecipe {
1663                    craft_event: CraftEvent::ModularWeapon {
1664                        primary_component,
1665                        secondary_component,
1666                    },
1667                    craft_sprite: sprite_pos,
1668                },
1669            )));
1670            true
1671        } else {
1672            false
1673        }
1674    }
1675
1676    pub fn craft_modular_weapon_component(
1677        &mut self,
1678        toolkind: tool::ToolKind,
1679        material: InvSlotId,
1680        modifier: Option<InvSlotId>,
1681        slots: Vec<(u32, InvSlotId)>,
1682        sprite_pos: Option<VolumePos>,
1683    ) {
1684        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1685            InventoryEvent::CraftRecipe {
1686                craft_event: CraftEvent::ModularWeaponPrimaryComponent {
1687                    toolkind,
1688                    material,
1689                    modifier,
1690                    slots,
1691                },
1692                craft_sprite: sprite_pos,
1693            },
1694        )));
1695    }
1696
1697    /// Repairs the item in the given inventory slot. `sprite_pos` should be
1698    /// the location of a relevant crafting station within range of the player.
1699    pub fn repair_item(
1700        &mut self,
1701        item: Slot,
1702        slots: Vec<(u32, InvSlotId)>,
1703        sprite_pos: VolumePos,
1704    ) -> bool {
1705        let is_repairable = {
1706            let inventories = self.inventories();
1707            let inventory = inventories.get(self.entity());
1708            inventory.is_some_and(|inv| {
1709                if let Some(item) = match item {
1710                    Slot::Equip(equip_slot) => inv.equipped(equip_slot),
1711                    Slot::Inventory(invslot) => inv.get(invslot),
1712                    Slot::Overflow(_) => None,
1713                } {
1714                    item.has_durability()
1715                } else {
1716                    false
1717                }
1718            })
1719        };
1720        if is_repairable {
1721            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InventoryEvent(
1722                InventoryEvent::CraftRecipe {
1723                    craft_event: CraftEvent::Repair { item, slots },
1724                    craft_sprite: Some(sprite_pos),
1725                },
1726            )));
1727        }
1728        is_repairable
1729    }
1730
1731    fn update_available_recipes(&mut self) {
1732        let rbm = self.state.ecs().read_resource::<RecipeBookManifest>();
1733        let inventories = self.state.ecs().read_storage::<comp::Inventory>();
1734        if let Some(inventory) = inventories.get(self.entity()) {
1735            self.available_recipes = inventory
1736                .recipes_iter()
1737                .cloned()
1738                .filter_map(|name| {
1739                    let (can_craft, required_sprite) = inventory.can_craft_recipe(&name, 1, &rbm);
1740                    if can_craft {
1741                        Some((name, required_sprite))
1742                    } else {
1743                        None
1744                    }
1745                })
1746                .collect();
1747        }
1748    }
1749
1750    /// Unstable, likely to be removed in a future release
1751    pub fn sites(&self) -> &HashMap<SiteId, SiteMarker> { &self.sites }
1752
1753    pub fn markers(&self) -> impl Iterator<Item = &Marker> {
1754        self.sites
1755            .values()
1756            .map(|s| &s.marker)
1757            .chain(self.extra_markers.iter())
1758    }
1759
1760    pub fn possible_starting_sites(&self) -> &[SiteId] { &self.possible_starting_sites }
1761
1762    /// Unstable, likely to be removed in a future release
1763    pub fn pois(&self) -> &Vec<PoiInfo> { &self.pois }
1764
1765    pub fn enable_lantern(&mut self) {
1766        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::EnableLantern));
1767    }
1768
1769    pub fn disable_lantern(&mut self) {
1770        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::DisableLantern));
1771    }
1772
1773    pub fn toggle_sprite_light(&mut self, pos: VolumePos, enable: bool) {
1774        self.control_action(ControlAction::InventoryAction(
1775            InventoryAction::ToggleSpriteLight(pos, enable),
1776        ));
1777    }
1778
1779    pub fn help_downed(&mut self, target_entity: EcsEntity) {
1780        if self.is_dead() {
1781            return;
1782        }
1783
1784        if let Some(target_uid) = self.state.read_component_copied(target_entity) {
1785            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InteractWith {
1786                target: target_uid,
1787                kind: common::interaction::InteractionKind::HelpDowned,
1788            }))
1789        }
1790    }
1791
1792    pub fn remove_buff(&mut self, buff_id: BuffKind) {
1793        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::RemoveBuff(
1794            buff_id,
1795        )));
1796    }
1797
1798    pub fn leave_stance(&mut self) {
1799        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::LeaveStance));
1800    }
1801
1802    pub fn unlock_skill(&mut self, skill: Skill) {
1803        self.send_msg(ClientGeneral::UnlockSkill(skill));
1804    }
1805
1806    pub fn max_group_size(&self) -> u32 { self.max_group_size }
1807
1808    pub fn invite(&self) -> Option<(Uid, Instant, Duration, InviteKind)> { self.invite }
1809
1810    pub fn group_info(&self) -> Option<(String, Uid)> {
1811        self.group_leader.map(|l| ("Group".into(), l)) // TODO
1812    }
1813
1814    pub fn group_members(&self) -> &HashMap<Uid, group::Role> { &self.group_members }
1815
1816    pub fn pending_invites(&self) -> &HashSet<Uid> { &self.pending_invites }
1817
1818    pub fn pending_trade(&self) -> &Option<(TradeId, PendingTrade, Option<SitePrices>)> {
1819        &self.pending_trade
1820    }
1821
1822    pub fn is_trading(&self) -> bool { self.pending_trade.is_some() }
1823
1824    pub fn send_invite(&mut self, invitee: Uid, kind: InviteKind) {
1825        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InitiateInvite(
1826            invitee, kind,
1827        )))
1828    }
1829
1830    pub fn accept_invite(&mut self) {
1831        // Clear invite
1832        self.invite.take();
1833        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InviteResponse(
1834            InviteResponse::Accept,
1835        )));
1836    }
1837
1838    pub fn decline_invite(&mut self) {
1839        // Clear invite
1840        self.invite.take();
1841        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::InviteResponse(
1842            InviteResponse::Decline,
1843        )));
1844    }
1845
1846    pub fn leave_group(&mut self) {
1847        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::GroupManip(
1848            GroupManip::Leave,
1849        )));
1850    }
1851
1852    pub fn kick_from_group(&mut self, uid: Uid) {
1853        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::GroupManip(
1854            GroupManip::Kick(uid),
1855        )));
1856    }
1857
1858    pub fn assign_group_leader(&mut self, uid: Uid) {
1859        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::GroupManip(
1860            GroupManip::AssignLeader(uid),
1861        )));
1862    }
1863
1864    pub fn is_riding(&self) -> bool {
1865        self.state
1866            .ecs()
1867            .read_storage::<Is<Rider>>()
1868            .get(self.entity())
1869            .is_some()
1870            || self
1871                .state
1872                .ecs()
1873                .read_storage::<Is<VolumeRider>>()
1874                .get(self.entity())
1875                .is_some()
1876    }
1877
1878    pub fn is_lantern_enabled(&self) -> bool {
1879        self.state
1880            .ecs()
1881            .read_storage::<comp::LightEmitter>()
1882            .get(self.entity())
1883            .is_some()
1884    }
1885
1886    pub fn mount(&mut self, entity: EcsEntity) {
1887        if let Some(uid) = self.state.read_component_copied(entity) {
1888            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::Mount(uid)));
1889        }
1890    }
1891
1892    /// Mount a block at a `VolumePos`.
1893    pub fn mount_volume(&mut self, volume_pos: VolumePos) {
1894        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::MountVolume(
1895            volume_pos,
1896        )));
1897    }
1898
1899    pub fn unmount(&mut self) { self.send_msg(ClientGeneral::ControlEvent(ControlEvent::Unmount)); }
1900
1901    pub fn set_pet_stay(&mut self, entity: EcsEntity, stay: bool) {
1902        if let Some(uid) = self.state.read_component_copied(entity) {
1903            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::SetPetStay(
1904                uid, stay,
1905            )));
1906        }
1907    }
1908
1909    pub fn give_up(&mut self) {
1910        if comp::is_downed(self.current().as_ref(), self.current().as_ref()) {
1911            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::GiveUp));
1912        }
1913    }
1914
1915    pub fn respawn(&mut self) {
1916        if self.current::<comp::Health>().is_some_and(|h| h.is_dead) {
1917            // Hardcore characters cannot respawn, kick them to character selection
1918            if self.current::<Hardcore>().is_some() {
1919                self.request_remove_character();
1920            } else {
1921                self.send_msg(ClientGeneral::ControlEvent(ControlEvent::Respawn));
1922            }
1923        }
1924    }
1925
1926    pub fn map_marker_event(&mut self, event: MapMarkerChange) {
1927        self.send_msg(ClientGeneral::UpdateMapMarker(event));
1928    }
1929
1930    /// Set the current position to spectate, returns true if the client's
1931    /// player has a Pos component to write to.
1932    pub fn spectate_position(&mut self, pos: Vec3<f32>) -> bool {
1933        let write = if let Some(position) = self
1934            .state
1935            .ecs()
1936            .write_storage::<comp::Pos>()
1937            .get_mut(self.entity())
1938        {
1939            position.0 = pos;
1940            true
1941        } else {
1942            false
1943        };
1944        if write {
1945            self.send_msg(ClientGeneral::SpectatePosition(pos));
1946        }
1947        write
1948    }
1949
1950    pub fn start_spectate_entity(&mut self, entity: EcsEntity) {
1951        if let Some(uid) = self.state.read_component_copied(entity) {
1952            self.send_msg(ClientGeneral::SpectateEntity(Some(uid)));
1953        } else {
1954            warn!("Spectating entity without a `Uid` component");
1955        }
1956    }
1957
1958    pub fn stop_spectate_entity(&mut self) { self.send_msg(ClientGeneral::SpectateEntity(None)); }
1959
1960    /// Checks whether a player can swap their weapon+ability `Loadout` settings
1961    /// and sends the `ControlAction` event that signals to do the swap.
1962    pub fn swap_loadout(&mut self) { self.control_action(ControlAction::SwapEquippedWeapons) }
1963
1964    /// Determine whether the player is wielding, if they're even capable of
1965    /// being in a wield state.
1966    pub fn is_wielding(&self) -> Option<bool> {
1967        self.state
1968            .ecs()
1969            .read_storage::<CharacterState>()
1970            .get(self.entity())
1971            .map(|cs| cs.is_wield())
1972    }
1973
1974    pub fn toggle_wield(&mut self) {
1975        match self.is_wielding() {
1976            Some(true) => self.control_action(ControlAction::Unwield),
1977            Some(false) => self.control_action(ControlAction::Wield),
1978            None => warn!("Can't toggle wield, client entity doesn't have a `CharacterState`"),
1979        }
1980    }
1981
1982    pub fn toggle_sit(&mut self) {
1983        let is_sitting = self
1984            .state
1985            .ecs()
1986            .read_storage::<CharacterState>()
1987            .get(self.entity())
1988            .map(|cs| matches!(cs, CharacterState::Sit));
1989
1990        match is_sitting {
1991            Some(true) => self.control_action(ControlAction::Stand),
1992            Some(false) => self.control_action(ControlAction::Sit),
1993            None => warn!("Can't toggle sit, client entity doesn't have a `CharacterState`"),
1994        }
1995    }
1996
1997    pub fn toggle_crawl(&mut self) {
1998        let is_crawling = self
1999            .state
2000            .ecs()
2001            .read_storage::<CharacterState>()
2002            .get(self.entity())
2003            .map(|cs| matches!(cs, CharacterState::Crawl));
2004
2005        match is_crawling {
2006            Some(true) => self.control_action(ControlAction::Stand),
2007            Some(false) => self.control_action(ControlAction::Crawl),
2008            None => warn!("Can't toggle crawl, client entity doesn't have a `CharacterState`"),
2009        }
2010    }
2011
2012    pub fn toggle_dance(&mut self) {
2013        let is_dancing = self
2014            .state
2015            .ecs()
2016            .read_storage::<CharacterState>()
2017            .get(self.entity())
2018            .map(|cs| matches!(cs, CharacterState::Dance));
2019
2020        match is_dancing {
2021            Some(true) => self.control_action(ControlAction::Stand),
2022            Some(false) => self.control_action(ControlAction::Dance),
2023            None => warn!("Can't toggle dance, client entity doesn't have a `CharacterState`"),
2024        }
2025    }
2026
2027    pub fn utter(&mut self, kind: UtteranceKind) {
2028        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::Utterance(kind)));
2029    }
2030
2031    pub fn toggle_sneak(&mut self) {
2032        let is_sneaking = self
2033            .state
2034            .ecs()
2035            .read_storage::<CharacterState>()
2036            .get(self.entity())
2037            .map(CharacterState::is_stealthy);
2038
2039        match is_sneaking {
2040            Some(true) => self.control_action(ControlAction::Stand),
2041            Some(false) => self.control_action(ControlAction::Sneak),
2042            None => warn!("Can't toggle sneak, client entity doesn't have a `CharacterState`"),
2043        }
2044    }
2045
2046    pub fn toggle_glide(&mut self) {
2047        let using_glider = self
2048            .state
2049            .ecs()
2050            .read_storage::<CharacterState>()
2051            .get(self.entity())
2052            .map(|cs| matches!(cs, CharacterState::GlideWield(_) | CharacterState::Glide(_)));
2053
2054        match using_glider {
2055            Some(true) => self.control_action(ControlAction::Unwield),
2056            Some(false) => self.control_action(ControlAction::GlideWield),
2057            None => warn!("Can't toggle glide, client entity doesn't have a `CharacterState`"),
2058        }
2059    }
2060
2061    pub fn cancel_climb(&mut self) {
2062        let is_climbing = self
2063            .state
2064            .ecs()
2065            .read_storage::<CharacterState>()
2066            .get(self.entity())
2067            .map(|cs| matches!(cs, CharacterState::Climb(_)));
2068
2069        match is_climbing {
2070            Some(true) => self.control_action(ControlAction::Stand),
2071            Some(false) => {},
2072            None => warn!("Can't stop climbing, client entity doesn't have a `CharacterState`"),
2073        }
2074    }
2075
2076    pub fn handle_input(
2077        &mut self,
2078        input: InputKind,
2079        pressed: bool,
2080        select_pos: Option<Vec3<f32>>,
2081        target_entity: Option<EcsEntity>,
2082    ) {
2083        if pressed {
2084            self.control_action(ControlAction::StartInput {
2085                input,
2086                target_entity: target_entity.and_then(|e| self.state.read_component_copied(e)),
2087                select_pos,
2088            });
2089        } else {
2090            self.control_action(ControlAction::CancelInput { input });
2091        }
2092    }
2093
2094    pub fn activate_portal(&mut self, portal: EcsEntity) {
2095        if let Some(portal_uid) = self.state.read_component_copied(portal) {
2096            self.send_msg(ClientGeneral::ControlEvent(ControlEvent::ActivatePortal(
2097                portal_uid,
2098            )));
2099        }
2100    }
2101
2102    fn control_action(&mut self, control_action: ControlAction) {
2103        if let Some(controller) = self
2104            .state
2105            .ecs()
2106            .write_storage::<Controller>()
2107            .get_mut(self.entity())
2108        {
2109            controller.push_action(control_action);
2110        }
2111        self.send_msg(ClientGeneral::ControlAction(control_action));
2112    }
2113
2114    fn control_event(&mut self, control_event: ControlEvent) {
2115        if let Some(controller) = self
2116            .state
2117            .ecs()
2118            .write_storage::<Controller>()
2119            .get_mut(self.entity())
2120        {
2121            controller.push_event(control_event.clone());
2122        }
2123        self.send_msg(ClientGeneral::ControlEvent(control_event));
2124    }
2125
2126    pub fn view_distance(&self) -> Option<u32> { self.view_distance }
2127
2128    pub fn server_view_distance_limit(&self) -> Option<u32> { self.server_view_distance_limit }
2129
2130    pub fn loaded_distance(&self) -> f32 { self.loaded_distance }
2131
2132    pub fn position(&self) -> Option<Vec3<f32>> {
2133        self.state
2134            .read_storage::<comp::Pos>()
2135            .get(self.entity())
2136            .map(|v| v.0)
2137    }
2138
2139    /// Returns Weather::default if no player position exists.
2140    pub fn weather_at_player(&self) -> Weather {
2141        self.position()
2142            .map(|p| {
2143                let mut weather = self.state.weather_at(p.xy());
2144                weather.wind = self.weather.local_wind;
2145                weather
2146            })
2147            .unwrap_or_default()
2148    }
2149
2150    pub fn current_chunk(&self) -> Option<Arc<TerrainChunk>> {
2151        let chunk_pos = Vec2::from(self.position()?)
2152            .map2(TerrainChunkSize::RECT_SIZE, |e: f32, sz| {
2153                (e as u32).div_euclid(sz) as i32
2154            });
2155
2156        self.state.terrain().get_key_arc(chunk_pos).cloned()
2157    }
2158
2159    pub fn current<C>(&self) -> Option<C>
2160    where
2161        C: Component + Clone,
2162    {
2163        self.state.read_storage::<C>().get(self.entity()).cloned()
2164    }
2165
2166    pub fn current_biome(&self) -> BiomeKind {
2167        match self.current_chunk() {
2168            Some(chunk) => chunk.meta().biome(),
2169            _ => BiomeKind::Void,
2170        }
2171    }
2172
2173    pub fn current_site(&self) -> SiteKindMeta {
2174        let mut player_alt = 0.0;
2175        if let Some(position) = self.current::<comp::Pos>() {
2176            player_alt = position.0.z;
2177        }
2178        let mut terrain_alt = 0.0;
2179        let mut site = None;
2180        if let Some(chunk) = self.current_chunk() {
2181            terrain_alt = chunk.meta().alt();
2182            site = chunk.meta().site();
2183        }
2184        if player_alt < terrain_alt - 40.0 {
2185            if let Some(SiteKindMeta::Dungeon(dungeon)) = site {
2186                SiteKindMeta::Dungeon(dungeon)
2187            } else {
2188                SiteKindMeta::Cave
2189            }
2190        } else {
2191            site.unwrap_or_default()
2192        }
2193    }
2194
2195    pub fn request_site_economy(&mut self, id: SiteId) {
2196        self.send_msg(ClientGeneral::RequestSiteInfo(id))
2197    }
2198
2199    pub fn inventories(&self) -> ReadStorage<'_, comp::Inventory> { self.state.read_storage() }
2200
2201    /// Send a chat message to the server.
2202    pub fn send_chat(&mut self, message: String) {
2203        self.send_msg(ClientGeneral::ChatMsg(comp::Content::Plain(message)));
2204    }
2205
2206    /// Send a command to the server.
2207    pub fn send_command(&mut self, name: String, args: Vec<String>) {
2208        self.send_msg(ClientGeneral::Command(name, args));
2209    }
2210
2211    /// Remove all cached terrain
2212    pub fn clear_terrain(&mut self) {
2213        self.state.clear_terrain();
2214        self.pending_chunks.clear();
2215    }
2216
2217    pub fn place_block(&mut self, pos: Vec3<i32>, block: Block) {
2218        self.send_msg(ClientGeneral::PlaceBlock(pos, block));
2219    }
2220
2221    pub fn remove_block(&mut self, pos: Vec3<i32>) {
2222        self.send_msg(ClientGeneral::BreakBlock(pos));
2223    }
2224
2225    pub fn collect_block(&mut self, pos: Vec3<i32>) {
2226        self.control_action(ControlAction::InventoryAction(InventoryAction::Collect(
2227            pos,
2228        )));
2229    }
2230
2231    pub fn perform_dialogue(&mut self, target: EcsEntity, dialogue: rtsim::Dialogue) {
2232        if let Some(target_uid) = self.state.read_component_copied(target) {
2233            // TODO: Add a way to do send-only chat
2234            // if let Some(msg) = dialogue.message().cloned() {
2235            //     self.send_msg(ClientGeneral::ChatMsg(msg));
2236            // }
2237            self.control_event(ControlEvent::Dialogue(target_uid, dialogue));
2238        }
2239    }
2240
2241    pub fn do_talk(&mut self, tgt: Option<EcsEntity>) {
2242        if let Some(controller) = self
2243            .state
2244            .ecs()
2245            .write_storage::<comp::Controller>()
2246            .get_mut(self.entity())
2247        {
2248            controller.push_action(ControlAction::Talk(
2249                tgt.and_then(|tgt| self.state.read_component_copied(tgt)),
2250            ));
2251        }
2252    }
2253
2254    pub fn change_ability(&mut self, slot: usize, new_ability: comp::ability::AuxiliaryAbility) {
2255        let auxiliary_key = self
2256            .inventories()
2257            .get(self.entity())
2258            .map_or((None, None), |inv| {
2259                let tool_kind = |slot| {
2260                    inv.equipped(slot).and_then(|item| match &*item.kind() {
2261                        ItemKind::Tool(tool) => Some(tool.kind),
2262                        _ => None,
2263                    })
2264                };
2265
2266                (
2267                    tool_kind(EquipSlot::ActiveMainhand),
2268                    tool_kind(EquipSlot::ActiveOffhand),
2269                )
2270            });
2271
2272        self.send_msg(ClientGeneral::ControlEvent(ControlEvent::ChangeAbility {
2273            slot,
2274            auxiliary_key,
2275            new_ability,
2276        }))
2277    }
2278
2279    pub fn waypoint(&self) -> &Option<String> { &self.waypoint }
2280
2281    pub fn set_battle_mode(&mut self, battle_mode: BattleMode) {
2282        self.send_msg(ClientGeneral::SetBattleMode(battle_mode));
2283    }
2284
2285    pub fn get_battle_mode(&self) -> BattleMode {
2286        let Some(uid) = self.uid() else {
2287            error!("Client entity does not have a Uid component");
2288
2289            return BattleMode::PvP;
2290        };
2291
2292        let Some(player_info) = self.player_list.get(&uid) else {
2293            error!("Client does not have PlayerInfo for its Uid");
2294
2295            return BattleMode::PvP;
2296        };
2297
2298        let Some(ref character_info) = player_info.character else {
2299            error!("Client does not have CharacterInfo for its PlayerInfo");
2300
2301            return BattleMode::PvP;
2302        };
2303
2304        character_info.battle_mode
2305    }
2306
2307    /// Execute a single client tick, handle input and update the game state by
2308    /// the given duration.
2309    pub fn tick(&mut self, inputs: ControllerInputs, dt: Duration) -> Result<Vec<Event>, Error> {
2310        span!(_guard, "tick", "Client::tick");
2311        // This tick function is the centre of the Veloren universe. Most client-side
2312        // things are managed from here, and as such it's important that it
2313        // stays organised. Please consult the core developers before making
2314        // significant changes to this code. Here is the approximate order of
2315        // things. Please update it as this code changes.
2316        //
2317        // 1) Collect input from the frontend, apply input effects to the state of the
2318        //    game
2319        // 2) Handle messages from the server
2320        // 3) Go through any events (timer-driven or otherwise) that need handling and
2321        //    apply them to the state of the game
2322        // 4) Perform a single LocalState tick (i.e: update the world and entities in
2323        //    the world)
2324        // 5) Go through the terrain update queue and apply all changes to the terrain
2325        // 6) Sync information to the server
2326        // 7) Finish the tick, passing actions of the main thread back to the frontend
2327
2328        // 1) Handle input from frontend.
2329        // Pass character actions from frontend input to the player's entity.
2330        if self.presence.is_some() {
2331            prof_span!("handle and send inputs");
2332            if let Err(e) = self
2333                .state
2334                .ecs()
2335                .write_storage::<Controller>()
2336                .entry(self.entity())
2337                .map(|entry| {
2338                    entry
2339                        .or_insert_with(|| Controller {
2340                            inputs: inputs.clone(),
2341                            queued_inputs: BTreeMap::new(),
2342                            events: Vec::new(),
2343                            actions: Vec::new(),
2344                        })
2345                        .inputs = inputs.clone();
2346                })
2347            {
2348                let entry = self.entity();
2349                error!(
2350                    ?e,
2351                    ?entry,
2352                    "Couldn't access controller component on client entity"
2353                );
2354            }
2355            self.send_msg_err(ClientGeneral::ControllerInputs(Box::new(inputs)))?;
2356        }
2357
2358        // 2) Build up a list of events for this frame, to be passed to the frontend.
2359        let mut frontend_events = Vec::new();
2360
2361        // Prepare for new events
2362        {
2363            prof_span!("Last<CharacterState> comps update");
2364            let ecs = self.state.ecs();
2365            let mut last_character_states = ecs.write_storage::<comp::Last<CharacterState>>();
2366            for (entity, _, character_state) in (
2367                &ecs.entities(),
2368                &ecs.read_storage::<comp::Body>(),
2369                &ecs.read_storage::<CharacterState>(),
2370            )
2371                .join()
2372            {
2373                if let Some(l) = last_character_states
2374                    .entry(entity)
2375                    .ok()
2376                    .map(|l| l.or_insert_with(|| comp::Last(character_state.clone())))
2377                    // TODO: since this just updates when the variant changes we should
2378                    // just store the variant to avoid the clone overhead
2379                    .filter(|l| !character_state.same_variant(&l.0))
2380                {
2381                    *l = comp::Last(character_state.clone());
2382                }
2383            }
2384        }
2385
2386        // Handle new messages from the server.
2387        frontend_events.append(&mut self.handle_new_messages()?);
2388
2389        // 3) Update client local data
2390        // Check if the invite has timed out and remove if so
2391        if self
2392            .invite
2393            .is_some_and(|(_, timeout, dur, _)| timeout.elapsed() > dur)
2394        {
2395            self.invite = None;
2396        }
2397
2398        // Lerp the clientside weather.
2399        self.weather.update(&mut self.state.weather_grid_mut());
2400
2401        if let Some(target_tod) = self.target_time_of_day {
2402            let mut tod = self.state.ecs_mut().write_resource::<TimeOfDay>();
2403            tod.0 = target_tod.0;
2404            self.target_time_of_day = None;
2405        }
2406
2407        // Save dead hardcore character ids to avoid displaying in the character list
2408        // while the server is still in the process of deleting the character
2409        if self.current::<Hardcore>().is_some()
2410            && self.is_dead()
2411            && let Some(PresenceKind::Character(character_id)) = self.presence
2412        {
2413            self.character_being_deleted = Some(character_id);
2414        }
2415
2416        // 4) Tick the client's LocalState
2417        self.state.tick(
2418            Duration::from_secs_f64(dt.as_secs_f64() * self.dt_adjustment),
2419            true,
2420            None,
2421            &self.connected_server_constants,
2422            |_, _| {},
2423        );
2424
2425        // TODO: avoid emitting these in the first place OR actually use outcomes
2426        // generated locally on the client (if they can be deduplicated from
2427        // ones that the server generates or if the client can reliably generate
2428        // them (e.g. syncing skipping character states past certain
2429        // stages might skip points where outcomes are generated, however we might not
2430        // care about this?) and the server doesn't need to send them)
2431        let _ = self.state.ecs().fetch::<EventBus<Outcome>>().recv_all();
2432
2433        // 5) Terrain
2434        self.tick_terrain()?;
2435
2436        // Send a ping to the server once every second
2437        if self.state.get_program_time() - self.last_server_ping > 1. {
2438            self.send_msg_err(PingMsg::Ping)?;
2439            self.last_server_ping = self.state.get_program_time();
2440        }
2441
2442        // 6) Update the server about the player's physics attributes.
2443        if self.presence.is_some()
2444            && let (Some(pos), Some(vel), Some(ori)) = (
2445                self.state.read_storage().get(self.entity()).cloned(),
2446                self.state.read_storage().get(self.entity()).cloned(),
2447                self.state.read_storage().get(self.entity()).cloned(),
2448            )
2449        {
2450            self.in_game_stream.send(ClientGeneral::PlayerPhysics {
2451                pos,
2452                vel,
2453                ori,
2454                force_counter: self.force_update_counter,
2455            })?;
2456        }
2457
2458        /*
2459        // Output debug metrics
2460        if log_enabled!(Level::Info) && self.tick % 600 == 0 {
2461            let metrics = self
2462                .state
2463                .terrain()
2464                .iter()
2465                .fold(ChonkMetrics::default(), |a, (_, c)| a + c.get_metrics());
2466            info!("{:?}", metrics);
2467        }
2468        */
2469
2470        // 7) Finish the tick, pass control back to the frontend.
2471        self.tick += 1;
2472        Ok(frontend_events)
2473    }
2474
2475    /// Clean up the client after a tick.
2476    pub fn cleanup(&mut self) {
2477        // Cleanup the local state
2478        self.state.cleanup();
2479    }
2480
2481    /// Handles terrain addition and removal.
2482    ///
2483    /// Removes old terrain chunks outside the view distance.
2484    /// Sends requests for missing chunks within the view distance.
2485    fn tick_terrain(&mut self) -> Result<(), Error> {
2486        let pos = self
2487            .state
2488            .read_storage::<comp::Pos>()
2489            .get(self.entity())
2490            .cloned();
2491        if let (Some(pos), Some(view_distance)) = (pos, self.view_distance) {
2492            prof_span!("terrain");
2493            let chunk_pos = self.state.terrain().pos_key(pos.0.map(|e| e as i32));
2494
2495            // Remove chunks that are too far from the player.
2496            let mut chunks_to_remove = Vec::new();
2497            self.state.terrain().iter().for_each(|(key, _)| {
2498                // Subtract 2 from the offset before computing squared magnitude
2499                // 1 for the chunks needed bordering other chunks for meshing
2500                // 1 as a buffer so that if the player moves back in that direction the chunks
2501                //   don't need to be reloaded
2502                // Take the minimum of the adjusted difference vs the view_distance + 1 to
2503                //   prevent magnitude_squared from overflowing
2504
2505                if (chunk_pos - key)
2506                    .map(|e: i32| (e.unsigned_abs()).saturating_sub(2).min(view_distance + 1))
2507                    .magnitude_squared()
2508                    > view_distance.pow(2)
2509                {
2510                    chunks_to_remove.push(key);
2511                }
2512            });
2513            for key in chunks_to_remove {
2514                self.state.remove_chunk(key);
2515            }
2516
2517            let mut current_tick_send_chunk_requests = 0;
2518            // Request chunks from the server.
2519            self.loaded_distance = ((view_distance * TerrainChunkSize::RECT_SIZE.x) as f32).powi(2);
2520            // +1 so we can find a chunk that's outside the vd for better fog
2521            for dist in 0..view_distance as i32 + 1 {
2522                // Only iterate through chunks that need to be loaded for circular vd
2523                // The (dist - 2) explained:
2524                // -0.5 because a chunk is visible if its corner is within the view distance
2525                // -0.5 for being able to move to the corner of the current chunk
2526                // -1 because chunks are not meshed if they don't have all their neighbors
2527                //     (notice also that view_distance is decreased by 1)
2528                //     (this subtraction on vd is omitted elsewhere in order to provide
2529                //     a buffer layer of loaded chunks)
2530                let top = if 2 * (dist - 2).max(0).pow(2) > (view_distance - 1).pow(2) as i32 {
2531                    ((view_distance - 1).pow(2) as f32 - (dist - 2).pow(2) as f32)
2532                        .sqrt()
2533                        .round() as i32
2534                        + 1
2535                } else {
2536                    dist
2537                };
2538
2539                let mut skip_mode = false;
2540                for i in -top..top + 1 {
2541                    let keys = [
2542                        chunk_pos + Vec2::new(dist, i),
2543                        chunk_pos + Vec2::new(i, dist),
2544                        chunk_pos + Vec2::new(-dist, i),
2545                        chunk_pos + Vec2::new(i, -dist),
2546                    ];
2547
2548                    for key in keys.iter() {
2549                        let dist_to_player = (TerrainGrid::key_chunk(*key).map(|x| x as f32)
2550                            + TerrainChunkSize::RECT_SIZE.map(|x| x as f32) / 2.0)
2551                            .distance_squared(pos.0.into());
2552
2553                        let terrain = self.state.terrain();
2554                        if let Some(chunk) = terrain.get_key_arc(*key) {
2555                            if !skip_mode && !terrain.contains_key_real(*key) {
2556                                let chunk = Arc::clone(chunk);
2557                                drop(terrain);
2558                                self.state.insert_chunk(*key, chunk);
2559                            }
2560                        } else {
2561                            drop(terrain);
2562                            if !skip_mode && !self.pending_chunks.contains_key(key) {
2563                                const TOTAL_PENDING_CHUNKS_LIMIT: usize = 12;
2564                                const CURRENT_TICK_PENDING_CHUNKS_LIMIT: usize = 2;
2565                                if self.pending_chunks.len() < TOTAL_PENDING_CHUNKS_LIMIT
2566                                    && current_tick_send_chunk_requests
2567                                        < CURRENT_TICK_PENDING_CHUNKS_LIMIT
2568                                {
2569                                    self.send_msg_err(ClientGeneral::TerrainChunkRequest {
2570                                        key: *key,
2571                                    })?;
2572                                    current_tick_send_chunk_requests += 1;
2573                                    self.pending_chunks.insert(*key, Instant::now());
2574                                } else {
2575                                    skip_mode = true;
2576                                }
2577                            }
2578
2579                            if dist_to_player < self.loaded_distance {
2580                                self.loaded_distance = dist_to_player;
2581                            }
2582                        }
2583                    }
2584                }
2585            }
2586            self.loaded_distance = self.loaded_distance.sqrt()
2587                - ((TerrainChunkSize::RECT_SIZE.x as f32 / 2.0).powi(2)
2588                    + (TerrainChunkSize::RECT_SIZE.y as f32 / 2.0).powi(2))
2589                .sqrt();
2590
2591            // If chunks are taking too long, assume they're no longer pending.
2592            let now = Instant::now();
2593            self.pending_chunks
2594                .retain(|_, created| now.duration_since(*created) < Duration::from_secs(3));
2595        }
2596
2597        if let Some(lod_pos) = pos.map(|p| p.0.xy()).or(self.lod_pos_fallback) {
2598            // Manage LoD zones
2599            let lod_zone = lod_pos.map(|e| lod::from_wpos(e as i32));
2600
2601            // Request LoD zones that are in range
2602            if self
2603                .lod_last_requested
2604                .is_none_or(|i| i.elapsed() > Duration::from_secs(5))
2605                && let Some(rpos) = Spiral2d::new()
2606                    .take((1 + self.lod_distance.ceil() as i32 * 2).pow(2) as usize)
2607                    .filter(|rpos| !self.lod_zones.contains_key(&(lod_zone + *rpos)))
2608                    .min_by_key(|rpos| rpos.magnitude_squared())
2609                    .filter(|rpos| {
2610                        rpos.map(|e| e as f32).magnitude() < (self.lod_distance - 0.5).max(0.0)
2611                    })
2612            {
2613                self.send_msg_err(ClientGeneral::LodZoneRequest {
2614                    key: lod_zone + rpos,
2615                })?;
2616                self.lod_last_requested = Some(Instant::now());
2617            }
2618
2619            // Cull LoD zones out of range
2620            self.lod_zones.retain(|p, _| {
2621                (*p - lod_zone).map(|e| e as f32).magnitude_squared() < self.lod_distance.powi(2)
2622            });
2623        }
2624
2625        Ok(())
2626    }
2627
2628    fn handle_server_msg(
2629        &mut self,
2630        frontend_events: &mut Vec<Event>,
2631        msg: ServerGeneral,
2632    ) -> Result<(), Error> {
2633        prof_span!("handle_server_msg");
2634        match msg {
2635            ServerGeneral::Disconnect(reason) => match reason {
2636                DisconnectReason::Shutdown => return Err(Error::ServerShutdown),
2637                DisconnectReason::Kicked(reason) => return Err(Error::Kicked(reason)),
2638                DisconnectReason::Banned(info) => return Err(Error::Banned(info)),
2639            },
2640            ServerGeneral::PlayerListUpdate(PlayerListUpdate::Init(list)) => {
2641                self.player_list = list
2642            },
2643            ServerGeneral::PlayerListUpdate(PlayerListUpdate::Add(uid, player_info)) => {
2644                if let Some(old_player_info) = self.player_list.insert(uid, player_info.clone()) {
2645                    warn!(
2646                        "Received msg to insert {} with uid {} into the player list but there was \
2647                         already an entry for {} with the same uid that was overwritten!",
2648                        player_info.player_alias, uid, old_player_info.player_alias
2649                    );
2650                }
2651            },
2652            ServerGeneral::PlayerListUpdate(PlayerListUpdate::Moderator(uid, moderator)) => {
2653                if let Some(player_info) = self.player_list.get_mut(&uid) {
2654                    player_info.is_moderator = moderator;
2655                } else {
2656                    warn!(
2657                        "Received msg to update admin status of uid {}, but they were not in the \
2658                         list.",
2659                        uid
2660                    );
2661                }
2662            },
2663            ServerGeneral::PlayerListUpdate(PlayerListUpdate::SelectedCharacter(
2664                uid,
2665                char_info,
2666            )) => {
2667                if let Some(player_info) = self.player_list.get_mut(&uid) {
2668                    player_info.character = Some(char_info);
2669                } else {
2670                    warn!(
2671                        "Received msg to update character info for uid {}, but they were not in \
2672                         the list.",
2673                        uid
2674                    );
2675                }
2676            },
2677            ServerGeneral::PlayerListUpdate(PlayerListUpdate::ExitCharacter(uid)) => {
2678                if let Some(player_info) = self.player_list.get_mut(&uid) {
2679                    if player_info.character.is_none() {
2680                        debug!(?player_info.player_alias, ?uid, "Received PlayerListUpdate::ExitCharacter for a player who wasnt ingame");
2681                    }
2682                    player_info.character = None;
2683                } else {
2684                    debug!(
2685                        ?uid,
2686                        "Received PlayerListUpdate::ExitCharacter for a nonexitent player"
2687                    );
2688                }
2689            },
2690            ServerGeneral::PlayerListUpdate(PlayerListUpdate::Remove(uid)) => {
2691                // Instead of removing players, mark them as offline because we need to
2692                // remember the names of disconnected players in chat.
2693                //
2694                // TODO: consider alternatives since this leads to an ever growing list as
2695                // players log out and in. Keep in mind we might only want to
2696                // keep only so many messages in chat the history. We could
2697                // potentially use an ID that's more persistent than the Uid.
2698                // One of the reasons we don't just store the string of the player name
2699                // into the message is to make alias changes reflected in older messages.
2700
2701                if let Some(player_info) = self.player_list.get_mut(&uid) {
2702                    if player_info.is_online {
2703                        player_info.is_online = false;
2704                    } else {
2705                        warn!(
2706                            "Received msg to remove uid {} from the player list by they were \
2707                             already marked offline",
2708                            uid
2709                        );
2710                    }
2711                } else {
2712                    warn!(
2713                        "Received msg to remove uid {} from the player list by they weren't in \
2714                         the list!",
2715                        uid
2716                    );
2717                }
2718            },
2719            ServerGeneral::PlayerListUpdate(PlayerListUpdate::Alias(uid, new_name)) => {
2720                if let Some(player_info) = self.player_list.get_mut(&uid) {
2721                    player_info.player_alias = new_name;
2722                } else {
2723                    warn!(
2724                        "Received msg to alias player with uid {} to {} but this uid is not in \
2725                         the player list",
2726                        uid, new_name
2727                    );
2728                }
2729            },
2730            ServerGeneral::PlayerListUpdate(PlayerListUpdate::UpdateBattleMode(
2731                uid,
2732                battle_mode,
2733            )) => {
2734                if let Some(player_info) = self.player_list.get_mut(&uid) {
2735                    if let Some(ref mut character_info) = player_info.character {
2736                        character_info.battle_mode = battle_mode;
2737                    } else {
2738                        warn!(
2739                            "Received msg to update battle mode of uid {} to {:?} but this player \
2740                             does not have a character",
2741                            uid, battle_mode
2742                        );
2743                    }
2744                } else {
2745                    warn!(
2746                        "Received msg to update battle mode of uid {} to {:?} but this uid is not \
2747                         in the player list",
2748                        uid, battle_mode
2749                    );
2750                }
2751            },
2752            ServerGeneral::ChatMsg(m) => frontend_events.push(Event::Chat(m)),
2753            ServerGeneral::ChatMode(m) => {
2754                self.chat_mode = m;
2755            },
2756            ServerGeneral::SetPlayerEntity(uid) => {
2757                if let Some(entity) = self.state.ecs().entity_from_uid(uid) {
2758                    let old_player_entity = mem::replace(
2759                        &mut *self.state.ecs_mut().write_resource(),
2760                        PlayerEntity(Some(entity)),
2761                    );
2762                    if let Some(old_entity) = old_player_entity.0 {
2763                        // Transfer controller to the new entity.
2764                        let mut controllers = self.state.ecs().write_storage::<Controller>();
2765                        if let Some(controller) = controllers.remove(old_entity)
2766                            && let Err(e) = controllers.insert(entity, controller)
2767                        {
2768                            error!(
2769                                ?e,
2770                                "Failed to insert controller when setting new player entity!"
2771                            );
2772                        }
2773                    }
2774                    if let Some(presence) = self.presence {
2775                        self.presence = Some(match presence {
2776                            PresenceKind::Spectator => PresenceKind::Spectator,
2777                            PresenceKind::LoadingCharacter(_) => PresenceKind::Possessor,
2778                            PresenceKind::Character(_) => PresenceKind::Possessor,
2779                            PresenceKind::Possessor => PresenceKind::Possessor,
2780                        });
2781                    }
2782                    // Clear pending trade
2783                    self.pending_trade = None;
2784                } else {
2785                    return Err(Error::Other("Failed to find entity from uid.".into()));
2786                }
2787            },
2788            ServerGeneral::TimeOfDay(time_of_day, calendar, new_time, time_scale) => {
2789                self.target_time_of_day = Some(time_of_day);
2790                *self.state.ecs_mut().write_resource() = calendar;
2791                *self.state.ecs_mut().write_resource() = time_scale;
2792                let mut time = self.state.ecs_mut().write_resource::<Time>();
2793                // Avoid side-eye from Einstein
2794                // If new time from server is at least 5 seconds ahead, replace client time.
2795                // Otherwise try to slightly twean client time (by 1%) to keep it in line with
2796                // server time.
2797                self.dt_adjustment = if new_time.0 > time.0 + 5.0 {
2798                    *time = new_time;
2799                    1.0
2800                } else if new_time.0 > time.0 {
2801                    1.01
2802                } else {
2803                    0.99
2804                };
2805            },
2806            ServerGeneral::EntitySync(entity_sync_package) => {
2807                let uid = self.uid();
2808                self.state
2809                    .ecs_mut()
2810                    .apply_entity_sync_package(entity_sync_package, uid);
2811            },
2812            ServerGeneral::CompSync(comp_sync_package, force_counter) => {
2813                self.force_update_counter = force_counter;
2814                self.state
2815                    .ecs_mut()
2816                    .apply_comp_sync_package(comp_sync_package);
2817            },
2818            ServerGeneral::CreateEntity(entity_package) => {
2819                self.state.ecs_mut().apply_entity_package(entity_package);
2820            },
2821            ServerGeneral::DeleteEntity(entity_uid) => {
2822                if self.uid() != Some(entity_uid) {
2823                    self.state
2824                        .ecs_mut()
2825                        .delete_entity_and_clear_uid_mapping(entity_uid);
2826                }
2827            },
2828            ServerGeneral::Notification(n) => {
2829                let Notification::WaypointSaved { location_name } = n.clone();
2830                self.waypoint = Some(location_name);
2831
2832                frontend_events.push(Event::Notification(UserNotification::WaypointUpdated));
2833            },
2834            ServerGeneral::PluginData(d) => {
2835                let plugin_len = d.len();
2836                tracing::info!(?plugin_len, "plugin data");
2837                frontend_events.push(Event::PluginDataReceived(d));
2838            },
2839            ServerGeneral::SetPlayerRole(role) => {
2840                debug!(?role, "Updating client role");
2841                self.role = role;
2842            },
2843            _ => unreachable!("Not a general msg"),
2844        }
2845        Ok(())
2846    }
2847
2848    fn handle_server_in_game_msg(
2849        &mut self,
2850        frontend_events: &mut Vec<Event>,
2851        msg: ServerGeneral,
2852    ) -> Result<(), Error> {
2853        prof_span!("handle_server_in_game_msg");
2854        match msg {
2855            ServerGeneral::GroupUpdate(change_notification) => {
2856                use comp::group::ChangeNotification::*;
2857                // Note: we use a hashmap since this would not work with entities outside
2858                // the view distance
2859                match change_notification {
2860                    Added(uid, role) => {
2861                        // Check if this is a newly formed group by looking for absence of
2862                        // other non pet group members
2863                        if !matches!(role, group::Role::Pet)
2864                            && !self
2865                                .group_members
2866                                .values()
2867                                .any(|r| !matches!(r, group::Role::Pet))
2868                        {
2869                            frontend_events
2870                                // TODO: localise
2871                                .push(Event::Chat(comp::ChatType::Meta.into_plain_msg(
2872                                    "Type /g or /group to chat with your group members",
2873                                )));
2874                        }
2875                        if let Some(player_info) = self.player_list.get(&uid) {
2876                            frontend_events.push(Event::Chat(
2877                                // TODO: localise, uses deprecated personalize_alias
2878                                #[expect(deprecated, reason = "i18n alias")]
2879                                comp::ChatType::GroupMeta("Group".into()).into_plain_msg(format!(
2880                                    "[{}] joined group",
2881                                    self.personalize_alias(uid, player_info.player_alias.clone())
2882                                )),
2883                            ));
2884                        }
2885                        if self.group_members.insert(uid, role) == Some(role) {
2886                            warn!(
2887                                "Received msg to add uid {} to the group members but they were \
2888                                 already there",
2889                                uid
2890                            );
2891                        }
2892                    },
2893                    Removed(uid) => {
2894                        if let Some(player_info) = self.player_list.get(&uid) {
2895                            frontend_events.push(Event::Chat(
2896                                // TODO: localise, uses deprecated personalize_alias
2897                                #[expect(deprecated, reason = "i18n alias")]
2898                                comp::ChatType::GroupMeta("Group".into()).into_plain_msg(format!(
2899                                    "[{}] left group",
2900                                    self.personalize_alias(uid, player_info.player_alias.clone())
2901                                )),
2902                            ));
2903                            frontend_events.push(Event::MapMarker(
2904                                comp::MapMarkerUpdate::GroupMember(uid, MapMarkerChange::Remove),
2905                            ));
2906                        }
2907                        if self.group_members.remove(&uid).is_none() {
2908                            warn!(
2909                                "Received msg to remove uid {} from group members but by they \
2910                                 weren't in there!",
2911                                uid
2912                            );
2913                        }
2914                    },
2915                    NewLeader(leader) => {
2916                        self.group_leader = Some(leader);
2917                    },
2918                    NewGroup { leader, members } => {
2919                        self.group_leader = Some(leader);
2920                        self.group_members = members.into_iter().collect();
2921                        // Currently add/remove messages treat client as an implicit member
2922                        // of the group whereas this message explicitly includes them so to
2923                        // be consistent for now we will remove the client from the
2924                        // received hashset
2925                        if let Some(uid) = self.uid() {
2926                            self.group_members.remove(&uid);
2927                        }
2928                        frontend_events.push(Event::MapMarker(comp::MapMarkerUpdate::ClearGroup));
2929                    },
2930                    NoGroup => {
2931                        self.group_leader = None;
2932                        self.group_members = HashMap::new();
2933                        frontend_events.push(Event::MapMarker(comp::MapMarkerUpdate::ClearGroup));
2934                    },
2935                }
2936            },
2937            ServerGeneral::Invite {
2938                inviter,
2939                timeout,
2940                kind,
2941            } => {
2942                self.invite = Some((inviter, Instant::now(), timeout, kind));
2943            },
2944            ServerGeneral::InvitePending(uid) => {
2945                if !self.pending_invites.insert(uid) {
2946                    warn!("Received message about pending invite that was already pending");
2947                }
2948            },
2949            ServerGeneral::InviteComplete {
2950                target,
2951                answer,
2952                kind,
2953            } => {
2954                if !self.pending_invites.remove(&target) {
2955                    warn!(
2956                        "Received completed invite message for invite that was not in the list of \
2957                         pending invites"
2958                    )
2959                }
2960                frontend_events.push(Event::InviteComplete {
2961                    target,
2962                    answer,
2963                    kind,
2964                });
2965            },
2966            ServerGeneral::GroupInventoryUpdate(item, uid) => {
2967                frontend_events.push(Event::GroupInventoryUpdate(item, uid));
2968            },
2969            // Cleanup for when the client goes back to the `presence = None`
2970            ServerGeneral::ExitInGameSuccess => {
2971                self.presence = None;
2972                self.clean_state();
2973            },
2974            ServerGeneral::InventoryUpdate(inventory, events) => {
2975                let mut update_inventory = false;
2976                for event in events.iter() {
2977                    match event {
2978                        InventoryUpdateEvent::BlockCollectFailed { .. } => {},
2979                        InventoryUpdateEvent::EntityCollectFailed { .. } => {},
2980                        _ => update_inventory = true,
2981                    }
2982                }
2983                if update_inventory {
2984                    // Push the updated inventory component to the client
2985                    // FIXME: Figure out whether this error can happen under normal gameplay,
2986                    // if not find a better way to handle it, if so maybe consider kicking the
2987                    // client back to login?
2988                    let entity = self.entity();
2989                    if let Err(e) = self
2990                        .state
2991                        .ecs_mut()
2992                        .write_storage()
2993                        .insert(entity, inventory)
2994                    {
2995                        warn!(
2996                            ?e,
2997                            "Received an inventory update event for client entity, but this \
2998                             entity was not found... this may be a bug."
2999                        );
3000                    }
3001                }
3002
3003                self.update_available_recipes();
3004
3005                frontend_events.push(Event::InventoryUpdated(events));
3006            },
3007            ServerGeneral::Dialogue(sender, dialogue) => {
3008                frontend_events.push(Event::Dialogue(sender, dialogue));
3009            },
3010            ServerGeneral::SetViewDistance(vd) => {
3011                self.view_distance = Some(vd);
3012                frontend_events.push(Event::SetViewDistance(vd));
3013                // If the server is correcting client vd selection we assume this is the max
3014                // allowed view distance.
3015                self.server_view_distance_limit = Some(vd);
3016            },
3017            ServerGeneral::Outcomes(outcomes) => {
3018                frontend_events.extend(outcomes.into_iter().map(Event::Outcome))
3019            },
3020            ServerGeneral::Knockback(impulse) => {
3021                self.state
3022                    .ecs()
3023                    .read_resource::<EventBus<LocalEvent>>()
3024                    .emit_now(LocalEvent::ApplyImpulse {
3025                        entity: self.entity(),
3026                        impulse,
3027                    });
3028            },
3029            ServerGeneral::UpdatePendingTrade(id, trade, pricing) => {
3030                trace!("UpdatePendingTrade {:?} {:?}", id, trade);
3031                self.pending_trade = Some((id, trade, pricing));
3032            },
3033            ServerGeneral::FinishedTrade(result) => {
3034                if let Some((_, trade, _)) = self.pending_trade.take() {
3035                    self.update_available_recipes();
3036                    frontend_events.push(Event::TradeComplete { result, trade })
3037                }
3038            },
3039            ServerGeneral::SiteEconomy(economy) => {
3040                if let Some(rich) = self.sites.get_mut(&economy.id) {
3041                    rich.economy = Some(economy);
3042                }
3043            },
3044            ServerGeneral::MapMarker(event) => {
3045                frontend_events.push(Event::MapMarker(event));
3046            },
3047            ServerGeneral::WeatherUpdate(weather) => {
3048                self.weather.weather_update(weather);
3049            },
3050            ServerGeneral::LocalWindUpdate(wind) => {
3051                self.weather.local_wind_update(wind);
3052            },
3053            ServerGeneral::SpectatePosition(pos) => {
3054                frontend_events.push(Event::SpectatePosition(pos));
3055            },
3056            ServerGeneral::UpdateRecipes => {
3057                self.update_available_recipes();
3058            },
3059            ServerGeneral::Gizmos(gizmos) => frontend_events.push(Event::Gizmos(gizmos)),
3060            _ => unreachable!("Not a in_game message"),
3061        }
3062        Ok(())
3063    }
3064
3065    fn handle_server_terrain_msg(&mut self, msg: ServerGeneral) -> Result<(), Error> {
3066        prof_span!("handle_server_terrain_mgs");
3067        match msg {
3068            ServerGeneral::TerrainChunkUpdate { key, chunk } => {
3069                if let Some(chunk) = chunk.ok().and_then(|c| c.to_chunk()) {
3070                    self.state.insert_chunk(key, Arc::new(chunk));
3071                }
3072                self.pending_chunks.remove(&key);
3073            },
3074            ServerGeneral::LodZoneUpdate { key, zone } => {
3075                self.lod_zones.insert(key, zone);
3076                self.lod_last_requested = None;
3077            },
3078            ServerGeneral::TerrainBlockUpdates(blocks) => {
3079                if let Some(mut blocks) = blocks.decompress() {
3080                    blocks.drain().for_each(|(pos, block)| {
3081                        self.state.set_block(pos, block);
3082                    });
3083                }
3084            },
3085            _ => unreachable!("Not a terrain message"),
3086        }
3087        Ok(())
3088    }
3089
3090    fn handle_server_character_screen_msg(
3091        &mut self,
3092        events: &mut Vec<Event>,
3093        msg: ServerGeneral,
3094    ) -> Result<(), Error> {
3095        prof_span!("handle_server_character_screen_msg");
3096        match msg {
3097            ServerGeneral::CharacterListUpdate(character_list) => {
3098                self.character_list.characters = character_list;
3099                if self.character_being_deleted.is_some() {
3100                    if let Some(pos) = self
3101                        .character_list
3102                        .characters
3103                        .iter()
3104                        .position(|x| x.character.id == self.character_being_deleted)
3105                    {
3106                        self.character_list.characters.remove(pos);
3107                    } else {
3108                        self.character_being_deleted = None;
3109                    }
3110                }
3111                self.character_list.loading = false;
3112            },
3113            ServerGeneral::CharacterActionError(error) => {
3114                warn!("CharacterActionError: {:?}.", error);
3115                events.push(Event::CharacterError(error));
3116            },
3117            ServerGeneral::CharacterDataLoadResult(Ok(metadata)) => {
3118                trace!("Handling join result by server");
3119                events.push(Event::CharacterJoined(metadata));
3120            },
3121            ServerGeneral::CharacterDataLoadResult(Err(error)) => {
3122                trace!("Handling join error by server");
3123                self.presence = None;
3124                self.clean_state();
3125                events.push(Event::CharacterError(error));
3126            },
3127            ServerGeneral::CharacterCreated(character_id) => {
3128                events.push(Event::CharacterCreated(character_id));
3129            },
3130            ServerGeneral::CharacterEdited(character_id) => {
3131                events.push(Event::CharacterEdited(character_id));
3132            },
3133            ServerGeneral::CharacterSuccess => debug!("client is now in ingame state on server"),
3134            ServerGeneral::SpectatorSuccess(spawn_point) => {
3135                events.push(Event::StartSpectate(spawn_point));
3136                debug!("client is now in ingame state on server");
3137            },
3138            _ => unreachable!("Not a character_screen msg"),
3139        }
3140        Ok(())
3141    }
3142
3143    fn handle_ping_msg(&mut self, msg: PingMsg) -> Result<(), Error> {
3144        prof_span!("handle_ping_msg");
3145        match msg {
3146            PingMsg::Ping => {
3147                self.send_msg_err(PingMsg::Pong)?;
3148            },
3149            PingMsg::Pong => {
3150                self.last_server_pong = self.state.get_program_time();
3151                self.last_ping_delta = self.state.get_program_time() - self.last_server_ping;
3152
3153                // Maintain the correct number of deltas for calculating the rolling average
3154                // ping. The client sends a ping to the server every second so we should be
3155                // receiving a pong reply roughly every second.
3156                while self.ping_deltas.len() > PING_ROLLING_AVERAGE_SECS - 1 {
3157                    self.ping_deltas.pop_front();
3158                }
3159                self.ping_deltas.push_back(self.last_ping_delta);
3160            },
3161        }
3162        Ok(())
3163    }
3164
3165    fn handle_messages(&mut self, frontend_events: &mut Vec<Event>) -> Result<u64, Error> {
3166        let mut cnt = 0;
3167        #[cfg(feature = "tracy")]
3168        let (mut terrain_cnt, mut ingame_cnt) = (0, 0);
3169        loop {
3170            let cnt_start = cnt;
3171
3172            while let Some(msg) = self.general_stream.try_recv()? {
3173                cnt += 1;
3174                self.handle_server_msg(frontend_events, msg)?;
3175            }
3176            while let Some(msg) = self.ping_stream.try_recv()? {
3177                cnt += 1;
3178                self.handle_ping_msg(msg)?;
3179            }
3180            while let Some(msg) = self.character_screen_stream.try_recv()? {
3181                cnt += 1;
3182                self.handle_server_character_screen_msg(frontend_events, msg)?;
3183            }
3184            while let Some(msg) = self.in_game_stream.try_recv()? {
3185                cnt += 1;
3186                #[cfg(feature = "tracy")]
3187                {
3188                    ingame_cnt += 1;
3189                }
3190                self.handle_server_in_game_msg(frontend_events, msg)?;
3191            }
3192            while let Some(msg) = self.terrain_stream.try_recv()? {
3193                cnt += 1;
3194                #[cfg(feature = "tracy")]
3195                {
3196                    if let ServerGeneral::TerrainChunkUpdate { chunk, .. } = &msg {
3197                        terrain_cnt += chunk.as_ref().map(|x| x.approx_len()).unwrap_or(0);
3198                    }
3199                }
3200                self.handle_server_terrain_msg(msg)?;
3201            }
3202
3203            if cnt_start == cnt {
3204                #[cfg(feature = "tracy")]
3205                {
3206                    plot!("terrain_recvs", terrain_cnt as f64);
3207                    plot!("ingame_recvs", ingame_cnt as f64);
3208                }
3209                return Ok(cnt);
3210            }
3211        }
3212    }
3213
3214    /// Handle new server messages.
3215    fn handle_new_messages(&mut self) -> Result<Vec<Event>, Error> {
3216        prof_span!("handle_new_messages");
3217        let mut frontend_events = Vec::new();
3218
3219        // Check that we have an valid connection.
3220        // Use the last ping time as a 1s rate limiter, we only notify the user once per
3221        // second
3222        if self.state.get_program_time() - self.last_server_ping > 1. {
3223            let duration_since_last_pong = self.state.get_program_time() - self.last_server_pong;
3224
3225            // Dispatch a notification to the HUD warning they will be kicked in {n} seconds
3226            const KICK_WARNING_AFTER_REL_TO_TIMEOUT_FRACTION: f64 = 0.75;
3227            if duration_since_last_pong
3228                >= (self.client_timeout.as_secs() as f64
3229                    * KICK_WARNING_AFTER_REL_TO_TIMEOUT_FRACTION)
3230                && self.state.get_program_time() - duration_since_last_pong > 0.
3231            {
3232                frontend_events.push(Event::DisconnectionNotification(
3233                    (self.state.get_program_time() - duration_since_last_pong).round() as u64,
3234                ));
3235            }
3236        }
3237
3238        let msg_count = self.handle_messages(&mut frontend_events)?;
3239
3240        if msg_count == 0
3241            && self.state.get_program_time() - self.last_server_pong
3242                > self.client_timeout.as_secs() as f64
3243        {
3244            return Err(Error::ServerTimeout);
3245        }
3246
3247        // ignore network events
3248        while let Some(res) = self
3249            .participant
3250            .as_mut()
3251            .and_then(|p| p.try_fetch_event().transpose())
3252        {
3253            let event = res?;
3254            trace!(?event, "received network event");
3255        }
3256
3257        Ok(frontend_events)
3258    }
3259
3260    pub fn entity(&self) -> EcsEntity {
3261        self.state
3262            .ecs()
3263            .read_resource::<PlayerEntity>()
3264            .0
3265            .expect("Client::entity should always have PlayerEntity be Some")
3266    }
3267
3268    pub fn uid(&self) -> Option<Uid> { self.state.read_component_copied(self.entity()) }
3269
3270    pub fn presence(&self) -> Option<PresenceKind> { self.presence }
3271
3272    pub fn registered(&self) -> bool { self.registered }
3273
3274    pub fn get_tick(&self) -> u64 { self.tick }
3275
3276    pub fn get_ping_ms(&self) -> f64 { self.last_ping_delta * 1000.0 }
3277
3278    pub fn get_ping_ms_rolling_avg(&self) -> f64 {
3279        let mut total_weight = 0.;
3280        let pings = self.ping_deltas.len() as f64;
3281        (self
3282            .ping_deltas
3283            .iter()
3284            .enumerate()
3285            .fold(0., |acc, (i, ping)| {
3286                let weight = i as f64 + 1. / pings;
3287                total_weight += weight;
3288                acc + (weight * ping)
3289            })
3290            / total_weight)
3291            * 1000.0
3292    }
3293
3294    /// Get a reference to the client's runtime thread pool. This pool should be
3295    /// used for any computationally expensive operations that run outside
3296    /// of the main thread (i.e., threads that block on I/O operations are
3297    /// exempt).
3298    pub fn runtime(&self) -> &Arc<Runtime> { &self.runtime }
3299
3300    /// Get a reference to the client's game state.
3301    pub fn state(&self) -> &State { &self.state }
3302
3303    /// Get a mutable reference to the client's game state.
3304    pub fn state_mut(&mut self) -> &mut State { &mut self.state }
3305
3306    /// Returns an iterator over the aliases of all the online players on the
3307    /// server
3308    pub fn players(&self) -> impl Iterator<Item = &str> {
3309        self.player_list()
3310            .values()
3311            .filter_map(|player_info| player_info.is_online.then_some(&*player_info.player_alias))
3312    }
3313
3314    /// Return true if this client is a moderator on the server
3315    pub fn is_moderator(&self) -> bool { self.role.is_some() }
3316
3317    pub fn role(&self) -> &Option<AdminRole> { &self.role }
3318
3319    /// Clean client ECS state
3320    fn clean_state(&mut self) {
3321        // Clear pending trade
3322        self.pending_trade = None;
3323
3324        let client_uid = self.uid().expect("Client doesn't have a Uid!!!");
3325
3326        // Clear ecs of all entities
3327        self.state.ecs_mut().delete_all();
3328        self.state.ecs_mut().maintain();
3329        self.state.ecs_mut().insert(IdMaps::default());
3330
3331        // Recreate client entity with Uid
3332        let entity_builder = self.state.ecs_mut().create_entity();
3333        entity_builder
3334            .world
3335            .write_resource::<IdMaps>()
3336            .add_entity(client_uid, entity_builder.entity);
3337
3338        let entity = entity_builder.with(client_uid).build();
3339        self.state.ecs().write_resource::<PlayerEntity>().0 = Some(entity);
3340    }
3341
3342    /// Change player alias to "You" if client belongs to matching player
3343    // TODO: move this to voxygen or i18n-helpers and properly localize there
3344    // or what's better, just remove completely, it won't properly work with
3345    // localization anyway.
3346    #[deprecated = "this function doesn't localize"]
3347    fn personalize_alias(&self, uid: Uid, alias: String) -> String {
3348        let client_uid = self.uid().expect("Client doesn't have a Uid!!!");
3349        if client_uid == uid {
3350            "You".to_string()
3351        } else {
3352            alias
3353        }
3354    }
3355
3356    /// Get important information from client that is necessary for message
3357    /// localisation
3358    pub fn lookup_msg_context(&self, msg: &comp::ChatMsg) -> ChatTypeContext {
3359        let mut result = ChatTypeContext {
3360            you: self.uid().expect("Client doesn't have a Uid!!!"),
3361            player_info: HashMap::new(),
3362            entity_name: HashMap::new(),
3363        };
3364
3365        let name_of_uid = |uid| {
3366            let ecs = self.state().ecs();
3367            let id_maps = ecs.read_resource::<common::uid::IdMaps>();
3368            id_maps.uid_entity(uid).and_then(|e| {
3369                ecs.read_storage::<comp::Stats>()
3370                    .get(e)
3371                    .map(|s| s.name.clone())
3372            })
3373        };
3374
3375        let mut add_data_of = |uid| {
3376            match self.player_list.get(uid) {
3377                Some(player_info) => {
3378                    result.player_info.insert(*uid, player_info.clone());
3379                },
3380                None => {
3381                    result.entity_name.insert(
3382                        *uid,
3383                        name_of_uid(*uid).unwrap_or_else(|| Content::Plain("<?>".to_string())),
3384                    );
3385                },
3386            };
3387        };
3388
3389        match &msg.chat_type {
3390            comp::ChatType::Online(uid) | comp::ChatType::Offline(uid) => add_data_of(uid),
3391            comp::ChatType::Kill(kill_source, victim) => {
3392                add_data_of(victim);
3393
3394                match kill_source {
3395                    KillSource::Player(attacker_uid, _) => {
3396                        add_data_of(attacker_uid);
3397                    },
3398                    KillSource::NonPlayer(_, _)
3399                    | KillSource::FallDamage
3400                    | KillSource::Suicide
3401                    | KillSource::NonExistent(_)
3402                    | KillSource::Other => (),
3403                };
3404            },
3405            comp::ChatType::Tell(from, to) | comp::ChatType::NpcTell(from, to) => {
3406                add_data_of(from);
3407                add_data_of(to);
3408            },
3409            comp::ChatType::Say(uid)
3410            | comp::ChatType::Region(uid)
3411            | comp::ChatType::World(uid)
3412            | comp::ChatType::NpcSay(uid)
3413            | comp::ChatType::Group(uid, _)
3414            | comp::ChatType::Faction(uid, _)
3415            | comp::ChatType::Npc(uid) => add_data_of(uid),
3416            comp::ChatType::CommandError
3417            | comp::ChatType::CommandInfo
3418            | comp::ChatType::FactionMeta(_)
3419            | comp::ChatType::GroupMeta(_)
3420            | comp::ChatType::Meta => (),
3421        };
3422        result
3423    }
3424
3425    /// Execute a single client tick:
3426    /// - handles messages from the server
3427    /// - sends physics update
3428    /// - requests chunks
3429    ///
3430    /// The game state is purposefully not simulated to reduce the overhead of
3431    /// running the client. This method is for use in testing a server with
3432    /// many clients connected.
3433    #[cfg(feature = "tick_network")]
3434    #[expect(clippy::needless_collect)] // False positive
3435    pub fn tick_network(&mut self, dt: Duration) -> Result<(), Error> {
3436        span!(_guard, "tick_network", "Client::tick_network");
3437        // Advance state time manually since we aren't calling `State::tick`
3438        self.state
3439            .ecs()
3440            .write_resource::<common::resources::ProgramTime>()
3441            .0 += dt.as_secs_f64();
3442
3443        let time_scale = *self
3444            .state
3445            .ecs()
3446            .read_resource::<common::resources::TimeScale>();
3447        self.state
3448            .ecs()
3449            .write_resource::<common::resources::Time>()
3450            .0 += dt.as_secs_f64() * time_scale.0;
3451
3452        // Handle new messages from the server.
3453        self.handle_new_messages()?;
3454
3455        // 5) Terrain
3456        self.tick_terrain()?;
3457        let empty = Arc::new(TerrainChunk::new(
3458            0,
3459            Block::empty(),
3460            Block::empty(),
3461            common::terrain::TerrainChunkMeta::void(),
3462        ));
3463        let mut terrain = self.state.terrain_mut();
3464        // Replace chunks with empty chunks to save memory
3465        let to_clear = terrain
3466            .iter()
3467            .filter_map(|(key, chunk)| (chunk.sub_chunks_len() != 0).then(|| key))
3468            .collect::<Vec<_>>();
3469        to_clear.into_iter().for_each(|key| {
3470            terrain.insert(key, Arc::clone(&empty));
3471        });
3472        drop(terrain);
3473
3474        // Send a ping to the server once every second
3475        if self.state.get_program_time() - self.last_server_ping > 1. {
3476            self.send_msg_err(PingMsg::Ping)?;
3477            self.last_server_ping = self.state.get_program_time();
3478        }
3479
3480        // 6) Update the server about the player's physics attributes.
3481        if self.presence.is_some() {
3482            if let (Some(pos), Some(vel), Some(ori)) = (
3483                self.state.read_storage().get(self.entity()).cloned(),
3484                self.state.read_storage().get(self.entity()).cloned(),
3485                self.state.read_storage().get(self.entity()).cloned(),
3486            ) {
3487                self.in_game_stream.send(ClientGeneral::PlayerPhysics {
3488                    pos,
3489                    vel,
3490                    ori,
3491                    force_counter: self.force_update_counter,
3492                })?;
3493            }
3494        }
3495
3496        // 7) Finish the tick, pass control back to the frontend.
3497        self.tick += 1;
3498
3499        Ok(())
3500    }
3501
3502    /// another plugin data received, is this the last one
3503    pub fn plugin_received(&mut self, hash: PluginHash) -> usize {
3504        if !self.missing_plugins.remove(&hash) {
3505            tracing::warn!(?hash, "received unrequested plugin");
3506        }
3507        self.missing_plugins.len()
3508    }
3509
3510    /// true if missing_plugins is not empty
3511    pub fn are_plugins_missing(&self) -> bool { !self.missing_plugins.is_empty() }
3512
3513    /// extract list of locally cached plugins to load
3514    pub fn take_local_plugins(&mut self) -> Vec<PathBuf> { std::mem::take(&mut self.local_plugins) }
3515}
3516
3517impl Drop for Client {
3518    fn drop(&mut self) {
3519        trace!("Dropping client");
3520        if self.registered {
3521            if let Err(e) = self.send_msg_err(ClientGeneral::Terminate) {
3522                warn!(
3523                    ?e,
3524                    "Error during drop of client, couldn't send disconnect package, is the \
3525                     connection already closed?",
3526                );
3527            }
3528        } else {
3529            trace!("no disconnect msg necessary as client wasn't registered")
3530        }
3531
3532        tokio::task::block_in_place(|| {
3533            if let Err(e) = self
3534                .runtime
3535                .block_on(self.participant.take().unwrap().disconnect())
3536            {
3537                warn!(?e, "error when disconnecting, couldn't send all data");
3538            }
3539        });
3540        //explicitly drop the network here while the runtime is still existing
3541        drop(self.network.take());
3542    }
3543}
3544
3545#[cfg(test)]
3546mod tests {
3547    use super::*;
3548    use client_i18n::LocalizationHandle;
3549
3550    #[test]
3551    /// THIS TEST VERIFIES THE CONSTANT API.
3552    /// CHANGING IT WILL BREAK 3rd PARTY APPLICATIONS (please extend) which
3553    /// needs to be informed (or fixed)
3554    ///  - torvus: https://gitlab.com/veloren/torvus
3555    ///
3556    /// CONTACT @Core Developer BEFORE MERGING CHANGES TO THIS TEST
3557    fn constant_api_test() {
3558        use common::clock::Clock;
3559        use voxygen_i18n_helpers::localize_chat_message;
3560
3561        const SPT: f64 = 1.0 / 60.0;
3562
3563        let runtime = Arc::new(Runtime::new().unwrap());
3564        let runtime2 = Arc::clone(&runtime);
3565        let username = "Foo";
3566        let password = "Bar";
3567        let auth_server = "auth.veloren.net";
3568        let veloren_client: Result<Client, Error> = runtime.block_on(Client::new(
3569            ConnectionArgs::Tcp {
3570                hostname: "127.0.0.1:9000".to_owned(),
3571                prefer_ipv6: false,
3572            },
3573            runtime2,
3574            &mut None,
3575            username,
3576            password,
3577            None,
3578            |suggestion: &str| suggestion == auth_server,
3579            &|_| {},
3580            |_| {},
3581            PathBuf::default(),
3582            ClientType::ChatOnly,
3583        ));
3584        let localisation = LocalizationHandle::load_expect("en");
3585
3586        let _ = veloren_client.map(|mut client| {
3587            //clock
3588            let mut clock = Clock::new(Duration::from_secs_f64(SPT));
3589
3590            //tick
3591            let events_result: Result<Vec<Event>, Error> =
3592                client.tick(ControllerInputs::default(), clock.dt());
3593
3594            //chat functionality
3595            client.send_chat("foobar".to_string());
3596
3597            let _ = events_result.map(|mut events| {
3598                // event handling
3599                if let Some(event) = events.pop() {
3600                    match event {
3601                        Event::Chat(msg) => {
3602                            let msg: comp::ChatMsg = msg;
3603                            let _s: String = localize_chat_message(
3604                                &msg,
3605                                &client.lookup_msg_context(&msg),
3606                                &localisation.read(),
3607                                true,
3608                            )
3609                            .1;
3610                        },
3611                        Event::Disconnect => {},
3612                        Event::DisconnectionNotification(_) => {
3613                            debug!("Will be disconnected soon! :/")
3614                        },
3615                        Event::Notification(notification) => {
3616                            let notification: UserNotification = notification;
3617                            debug!("Notification: {:?}", notification);
3618                        },
3619                        _ => {},
3620                    }
3621                };
3622            });
3623
3624            client.cleanup();
3625            clock.tick();
3626        });
3627    }
3628}