2019-08-19 12:39:23 +00:00
|
|
|
#![deny(unsafe_code)]
|
2019-09-06 05:16:11 +00:00
|
|
|
#![feature(label_break_value)]
|
2019-03-05 18:39:18 +00:00
|
|
|
|
2020-05-09 20:41:29 +00:00
|
|
|
pub mod cmd;
|
2019-03-03 22:02:38 +00:00
|
|
|
pub mod error;
|
|
|
|
|
|
|
|
// Reexports
|
2019-05-22 20:53:24 +00:00
|
|
|
pub use crate::error::Error;
|
2020-01-04 10:21:59 +00:00
|
|
|
pub use authc::AuthClientError;
|
2019-12-31 08:10:51 +00:00
|
|
|
pub use specs::{
|
|
|
|
join::Join,
|
|
|
|
saveload::{Marker, MarkerAllocator},
|
2020-01-10 00:33:38 +00:00
|
|
|
Builder, DispatcherBuilder, Entity as EcsEntity, ReadStorage, WorldExt,
|
2019-12-31 08:10:51 +00:00
|
|
|
};
|
2019-03-03 22:02:38 +00:00
|
|
|
|
2020-01-11 19:25:48 +00:00
|
|
|
use byteorder::{ByteOrder, LittleEndian};
|
2019-03-03 22:02:38 +00:00
|
|
|
use common::{
|
2020-05-09 15:41:25 +00:00
|
|
|
character::CharacterItem,
|
2020-03-11 10:30:59 +00:00
|
|
|
comp::{
|
2020-03-24 07:38:16 +00:00
|
|
|
self, ControlAction, ControlEvent, Controller, ControllerInputs, InventoryManip,
|
|
|
|
InventoryUpdateEvent,
|
2020-03-11 10:30:59 +00:00
|
|
|
},
|
2019-08-14 04:38:54 +00:00
|
|
|
msg::{
|
2020-05-14 16:56:10 +00:00
|
|
|
validate_chat_msg, ChatMsgValidationError, ClientMsg, ClientState, Notification,
|
2020-05-20 11:59:44 +00:00
|
|
|
PlayerInfo, PlayerListUpdate, RegisterError, RequestStateError, ServerInfo, ServerMsg,
|
2020-05-14 16:56:10 +00:00
|
|
|
MAX_BYTES_CHAT_MSG,
|
2019-08-14 04:38:54 +00:00
|
|
|
},
|
2019-11-24 20:12:03 +00:00
|
|
|
state::State,
|
2019-12-31 08:10:51 +00:00
|
|
|
sync::{Uid, UidAllocator, WorldSyncExt},
|
2019-09-06 13:23:38 +00:00
|
|
|
terrain::{block::Block, TerrainChunk, TerrainChunkSize},
|
common: Rework volume API
See the doc comments in `common/src/vol.rs` for more information on
the API itself.
The changes include:
* Consistent `Err`/`Error` naming.
* Types are named `...Error`.
* `enum` variants are named `...Err`.
* Rename `VolMap{2d, 3d}` -> `VolGrid{2d, 3d}`. This is in preparation
to an upcoming change where a “map” in the game related sense will
be added.
* Add volume iterators. There are two types of them:
* _Position_ iterators obtained from the trait `IntoPosIterator`
using the method
`fn pos_iter(self, lower_bound: Vec3<i32>, upper_bound: Vec3<i32>) -> ...`
which returns an iterator over `Vec3<i32>`.
* _Volume_ iterators obtained from the trait `IntoVolIterator`
using the method
`fn vol_iter(self, lower_bound: Vec3<i32>, upper_bound: Vec3<i32>) -> ...`
which returns an iterator over `(Vec3<i32>, &Self::Vox)`.
Those traits will usually be implemented by references to volume
types (i.e. `impl IntoVolIterator<'a> for &'a T` where `T` is some
type which usually implements several volume traits, such as `Chunk`).
* _Position_ iterators iterate over the positions valid for that
volume.
* _Volume_ iterators do the same but return not only the position
but also the voxel at that position, in each iteration.
* Introduce trait `RectSizedVol` for the use case which we have with
`Chonk`: A `Chonk` is sized only in x and y direction.
* Introduce traits `RasterableVol`, `RectRasterableVol`
* `RasterableVol` represents a volume that is compile-time sized and has
its lower bound at `(0, 0, 0)`. The name `RasterableVol` was chosen
because such a volume can be used with `VolGrid3d`.
* `RectRasterableVol` represents a volume that is compile-time sized at
least in x and y direction and has its lower bound at `(0, 0, z)`.
There's no requirement on he lower bound or size in z direction.
The name `RectRasterableVol` was chosen because such a volume can be
used with `VolGrid2d`.
2019-09-03 22:23:29 +00:00
|
|
|
vol::RectVolSize,
|
2019-03-03 22:02:38 +00:00
|
|
|
};
|
2020-07-01 09:51:37 +00:00
|
|
|
use futures_executor::block_on;
|
|
|
|
use futures_timer::Delay;
|
|
|
|
use futures_util::{select, FutureExt};
|
2019-08-11 19:54:20 +00:00
|
|
|
use hashbrown::HashMap;
|
2019-10-16 11:39:41 +00:00
|
|
|
use image::DynamicImage;
|
2020-07-09 11:42:38 +00:00
|
|
|
use network::{
|
|
|
|
Network, Participant, Pid, ProtocolAddr, Stream, PROMISES_CONSISTENCY, PROMISES_ORDERED,
|
|
|
|
};
|
2019-05-16 20:18:48 +00:00
|
|
|
use std::{
|
2020-07-10 20:25:45 +00:00
|
|
|
collections::VecDeque,
|
2019-05-16 20:18:48 +00:00
|
|
|
net::SocketAddr,
|
2019-06-11 18:39:25 +00:00
|
|
|
sync::Arc,
|
2019-06-15 10:36:26 +00:00
|
|
|
time::{Duration, Instant},
|
2019-05-16 20:18:48 +00:00
|
|
|
};
|
2020-07-05 23:29:28 +00:00
|
|
|
use tracing::{debug, error, trace, warn};
|
2019-07-12 18:51:22 +00:00
|
|
|
use uvth::{ThreadPool, ThreadPoolBuilder};
|
2019-04-23 09:53:45 +00:00
|
|
|
use vek::*;
|
2019-01-02 17:23:31 +00:00
|
|
|
|
2020-01-27 16:48:42 +00:00
|
|
|
// The duration of network inactivity until the player is kicked
|
|
|
|
// @TODO: in the future, this should be configurable on the server
|
|
|
|
// and be provided to the client
|
2020-03-01 22:18:22 +00:00
|
|
|
const SERVER_TIMEOUT: f64 = 20.0;
|
2019-03-05 18:39:18 +00:00
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
// After this duration has elapsed, the user will begin getting kick warnings in
|
|
|
|
// their chat window
|
2020-03-01 22:18:22 +00:00
|
|
|
const SERVER_TIMEOUT_GRACE_PERIOD: f64 = 14.0;
|
2020-07-10 20:25:45 +00:00
|
|
|
const PING_ROLLING_AVERAGE_SECS: usize = 10;
|
2019-10-17 04:09:01 +00:00
|
|
|
|
2019-03-03 22:02:38 +00:00
|
|
|
pub enum Event {
|
2020-06-02 02:42:26 +00:00
|
|
|
Chat(comp::ChatMsg),
|
2019-04-23 12:01:16 +00:00
|
|
|
Disconnect,
|
2019-10-17 04:09:01 +00:00
|
|
|
DisconnectionNotification(u64),
|
2020-06-28 15:21:12 +00:00
|
|
|
InventoryUpdated(InventoryUpdateEvent),
|
2020-05-14 16:56:10 +00:00
|
|
|
Notification(Notification),
|
2020-06-25 11:20:09 +00:00
|
|
|
SetViewDistance(u32),
|
2019-01-02 17:23:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Client {
|
2019-05-24 19:10:18 +00:00
|
|
|
client_state: ClientState,
|
2019-04-10 23:16:29 +00:00
|
|
|
thread_pool: ThreadPool,
|
2019-05-08 16:22:52 +00:00
|
|
|
pub server_info: ServerInfo,
|
2020-01-11 19:25:48 +00:00
|
|
|
pub world_map: (Arc<DynamicImage>, Vec2<u32>),
|
2020-06-02 06:11:47 +00:00
|
|
|
pub player_list: HashMap<Uid, PlayerInfo>,
|
2020-05-09 15:41:25 +00:00
|
|
|
pub character_list: CharacterList,
|
2020-06-16 13:55:37 +00:00
|
|
|
pub active_character_id: Option<i32>,
|
2019-01-02 17:23:31 +00:00
|
|
|
|
2020-07-01 07:30:38 +00:00
|
|
|
_network: Network,
|
2020-07-09 07:58:21 +00:00
|
|
|
participant: Option<Participant>,
|
2020-07-01 07:30:38 +00:00
|
|
|
singleton_stream: Stream,
|
2019-03-03 22:02:38 +00:00
|
|
|
|
2020-03-01 22:18:22 +00:00
|
|
|
last_server_ping: f64,
|
|
|
|
last_server_pong: f64,
|
2019-05-23 08:18:25 +00:00
|
|
|
last_ping_delta: f64,
|
2020-07-10 20:25:45 +00:00
|
|
|
ping_deltas: VecDeque<f64>,
|
2019-05-23 08:18:25 +00:00
|
|
|
|
2019-01-23 20:01:58 +00:00
|
|
|
tick: u64,
|
|
|
|
state: State,
|
2019-04-19 19:32:47 +00:00
|
|
|
entity: EcsEntity,
|
2019-06-23 19:49:15 +00:00
|
|
|
|
2019-05-19 00:45:02 +00:00
|
|
|
view_distance: Option<u32>,
|
2020-01-19 20:48:57 +00:00
|
|
|
// TODO: move into voxygen
|
2020-01-12 11:09:37 +00:00
|
|
|
loaded_distance: f32,
|
2019-04-11 22:26:43 +00:00
|
|
|
|
2019-05-17 17:44:30 +00:00
|
|
|
pending_chunks: HashMap<Vec2<i32>, Instant>,
|
2019-01-02 17:23:31 +00:00
|
|
|
}
|
|
|
|
|
2020-05-09 15:41:25 +00:00
|
|
|
/// Holds data related to the current players characters, as well as some
|
|
|
|
/// additional state to handle UI.
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct CharacterList {
|
|
|
|
pub characters: Vec<CharacterItem>,
|
|
|
|
pub loading: bool,
|
|
|
|
pub error: Option<String>,
|
|
|
|
}
|
|
|
|
|
2019-01-02 17:23:31 +00:00
|
|
|
impl Client {
|
2019-01-12 15:57:19 +00:00
|
|
|
/// Create a new `Client`.
|
2019-05-19 00:45:02 +00:00
|
|
|
pub fn new<A: Into<SocketAddr>>(addr: A, view_distance: Option<u32>) -> Result<Self, Error> {
|
2019-06-06 14:48:41 +00:00
|
|
|
let client_state = ClientState::Connected;
|
2020-07-01 07:30:38 +00:00
|
|
|
|
|
|
|
let mut thread_pool = ThreadPoolBuilder::new()
|
|
|
|
.name("veloren-worker".into())
|
|
|
|
.build();
|
|
|
|
// We reduce the thread count by 1 to keep rendering smooth
|
|
|
|
thread_pool.set_num_threads((num_cpus::get() - 1).max(1));
|
|
|
|
|
|
|
|
let (network, f) = Network::new(Pid::new(), None);
|
|
|
|
thread_pool.execute(f);
|
|
|
|
|
2020-07-09 11:42:38 +00:00
|
|
|
let participant = block_on(network.connect(ProtocolAddr::Tcp(addr.into())))?;
|
2020-07-01 07:30:38 +00:00
|
|
|
let mut stream = block_on(participant.open(10, PROMISES_ORDERED | PROMISES_CONSISTENCY))?;
|
2019-03-03 22:02:38 +00:00
|
|
|
|
2019-04-19 19:32:47 +00:00
|
|
|
// Wait for initial sync
|
2020-07-01 09:51:37 +00:00
|
|
|
let (state, entity, server_info, world_map) = block_on(async {
|
2020-07-01 07:30:38 +00:00
|
|
|
loop {
|
|
|
|
match stream.recv().await? {
|
|
|
|
ServerMsg::InitialSync {
|
|
|
|
entity_package,
|
|
|
|
server_info,
|
|
|
|
time_of_day,
|
|
|
|
world_map: (map_size, world_map),
|
|
|
|
} => {
|
|
|
|
// TODO: Display that versions don't match in Voxygen
|
|
|
|
if &server_info.git_hash != *common::util::GIT_HASH {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Server is running {}[{}], you are running {}[{}], versions might \
|
|
|
|
be incompatible!",
|
|
|
|
server_info.git_hash,
|
|
|
|
server_info.git_date,
|
|
|
|
common::util::GIT_HASH.to_string(),
|
|
|
|
common::util::GIT_DATE.to_string(),
|
|
|
|
);
|
2020-07-01 07:30:38 +00:00
|
|
|
}
|
2019-07-21 17:45:31 +00:00
|
|
|
|
2020-07-01 07:30:38 +00:00
|
|
|
debug!("Auth Server: {:?}", server_info.auth_provider);
|
2019-10-16 11:39:41 +00:00
|
|
|
|
2020-07-01 07:30:38 +00:00
|
|
|
// Initialize `State`
|
|
|
|
let mut state = State::default();
|
|
|
|
// Client-only components
|
|
|
|
state
|
|
|
|
.ecs_mut()
|
|
|
|
.register::<comp::Last<comp::CharacterState>>();
|
|
|
|
|
|
|
|
let entity = state.ecs_mut().apply_entity_package(entity_package);
|
|
|
|
*state.ecs_mut().write_resource() = time_of_day;
|
|
|
|
|
|
|
|
assert_eq!(world_map.len(), (map_size.x * map_size.y) as usize);
|
2020-07-01 09:51:37 +00:00
|
|
|
let mut world_map_raw =
|
|
|
|
vec![0u8; 4 * world_map.len()/*map_size.x * map_size.y*/];
|
2020-07-01 07:30:38 +00:00
|
|
|
LittleEndian::write_u32_into(&world_map, &mut world_map_raw);
|
|
|
|
debug!("Preparing image...");
|
|
|
|
let world_map = Arc::new(
|
|
|
|
image::DynamicImage::ImageRgba8({
|
|
|
|
// Should not fail if the dimensions are correct.
|
|
|
|
let world_map =
|
|
|
|
image::ImageBuffer::from_raw(map_size.x, map_size.y, world_map_raw);
|
|
|
|
world_map.ok_or_else(|| Error::Other("Server sent a bad world map image".into()))?
|
|
|
|
})
|
|
|
|
// Flip the image, since Voxygen uses an orientation where rotation from
|
|
|
|
// positive x axis to positive y axis is counterclockwise around the z axis.
|
|
|
|
.flipv(),
|
|
|
|
);
|
|
|
|
debug!("Done preparing image...");
|
2019-04-10 17:23:27 +00:00
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
break Ok((state, entity, server_info, (world_map, map_size)));
|
2020-07-01 07:30:38 +00:00
|
|
|
},
|
|
|
|
ServerMsg::TooManyPlayers => break Err(Error::TooManyPlayers),
|
|
|
|
err => {
|
|
|
|
warn!("whoops, server mad {:?}, ignoring", err);
|
|
|
|
},
|
2020-07-01 09:51:37 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-01 07:30:38 +00:00
|
|
|
})?;
|
|
|
|
|
|
|
|
stream.send(ClientMsg::Ping)?;
|
2019-04-24 07:59:42 +00:00
|
|
|
|
2019-07-12 18:51:22 +00:00
|
|
|
let mut thread_pool = ThreadPoolBuilder::new()
|
|
|
|
.name("veloren-worker".into())
|
2019-06-05 13:13:24 +00:00
|
|
|
.build();
|
|
|
|
// We reduce the thread count by 1 to keep rendering smooth
|
2019-07-12 17:35:11 +00:00
|
|
|
thread_pool.set_num_threads((num_cpus::get() - 1).max(1));
|
2019-06-05 13:13:24 +00:00
|
|
|
|
2019-03-03 22:02:38 +00:00
|
|
|
Ok(Self {
|
2019-04-19 19:32:47 +00:00
|
|
|
client_state,
|
2019-06-05 13:13:24 +00:00
|
|
|
thread_pool,
|
2019-05-08 16:22:52 +00:00
|
|
|
server_info,
|
2019-10-16 11:39:41 +00:00
|
|
|
world_map,
|
2019-12-23 06:02:00 +00:00
|
|
|
player_list: HashMap::new(),
|
2020-05-09 15:41:25 +00:00
|
|
|
character_list: CharacterList::default(),
|
2020-06-16 13:55:37 +00:00
|
|
|
active_character_id: None,
|
2019-01-15 15:13:11 +00:00
|
|
|
|
2020-07-01 07:30:38 +00:00
|
|
|
_network: network,
|
2020-07-09 07:58:21 +00:00
|
|
|
participant: Some(participant),
|
2020-07-01 07:30:38 +00:00
|
|
|
singleton_stream: stream,
|
2019-03-03 22:02:38 +00:00
|
|
|
|
2020-03-01 22:18:22 +00:00
|
|
|
last_server_ping: 0.0,
|
|
|
|
last_server_pong: 0.0,
|
2019-05-23 08:18:25 +00:00
|
|
|
last_ping_delta: 0.0,
|
2020-07-10 20:25:45 +00:00
|
|
|
ping_deltas: VecDeque::new(),
|
2019-05-23 08:18:25 +00:00
|
|
|
|
2019-01-23 20:01:58 +00:00
|
|
|
tick: 0,
|
2019-03-03 22:02:38 +00:00
|
|
|
state,
|
2019-04-22 00:38:29 +00:00
|
|
|
entity,
|
2019-04-10 23:16:29 +00:00
|
|
|
view_distance,
|
2020-01-12 11:09:37 +00:00
|
|
|
loaded_distance: 0.0,
|
2019-04-11 22:26:43 +00:00
|
|
|
|
2019-05-16 20:18:48 +00:00
|
|
|
pending_chunks: HashMap::new(),
|
2019-03-03 22:02:38 +00:00
|
|
|
})
|
2019-01-02 17:23:31 +00:00
|
|
|
}
|
|
|
|
|
2019-06-05 13:13:24 +00:00
|
|
|
pub fn with_thread_pool(mut self, thread_pool: ThreadPool) -> Self {
|
|
|
|
self.thread_pool = thread_pool;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-05-25 21:13:38 +00:00
|
|
|
/// Request a state transition to `ClientState::Registered`.
|
2020-01-02 08:43:45 +00:00
|
|
|
pub fn register(
|
|
|
|
&mut self,
|
2020-01-11 21:04:49 +00:00
|
|
|
username: String,
|
2020-01-02 08:43:45 +00:00
|
|
|
password: String,
|
|
|
|
mut auth_trusted: impl FnMut(&str) -> bool,
|
|
|
|
) -> Result<(), Error> {
|
|
|
|
// Authentication
|
2020-01-11 21:04:49 +00:00
|
|
|
let token_or_username = self.server_info.auth_provider.as_ref().map(|addr|
|
2020-01-02 08:43:45 +00:00
|
|
|
// Query whether this is a trusted auth server
|
|
|
|
if auth_trusted(&addr) {
|
2020-01-11 21:04:49 +00:00
|
|
|
Ok(authc::AuthClient::new(addr)
|
|
|
|
.sign_in(&username, &password)?
|
|
|
|
.serialize())
|
2020-01-02 08:43:45 +00:00
|
|
|
} else {
|
2020-01-11 21:04:49 +00:00
|
|
|
Err(Error::AuthServerNotTrusted)
|
2020-01-02 08:43:45 +00:00
|
|
|
}
|
2020-01-11 21:04:49 +00:00
|
|
|
).unwrap_or(Ok(username))?;
|
2020-01-02 08:43:45 +00:00
|
|
|
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream.send(ClientMsg::Register {
|
2020-01-11 21:04:49 +00:00
|
|
|
view_distance: self.view_distance,
|
2020-01-02 08:43:45 +00:00
|
|
|
token_or_username,
|
2020-07-01 07:30:38 +00:00
|
|
|
})?;
|
2019-08-08 16:01:15 +00:00
|
|
|
self.client_state = ClientState::Pending;
|
2020-01-02 08:43:45 +00:00
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
block_on(async {
|
|
|
|
loop {
|
|
|
|
match self.singleton_stream.recv().await? {
|
|
|
|
ServerMsg::StateAnswer(Err((
|
|
|
|
RequestStateError::RegisterDenied(err),
|
|
|
|
state,
|
|
|
|
))) => {
|
|
|
|
self.client_state = state;
|
|
|
|
break Err(match err {
|
|
|
|
RegisterError::AlreadyLoggedIn => Error::AlreadyLoggedIn,
|
|
|
|
RegisterError::AuthError(err) => Error::AuthErr(err),
|
|
|
|
RegisterError::InvalidCharacter => Error::InvalidCharacter,
|
|
|
|
RegisterError::NotOnWhitelist => Error::NotOnWhitelist,
|
|
|
|
});
|
|
|
|
},
|
|
|
|
ServerMsg::StateAnswer(Ok(ClientState::Registered)) => break Ok(()),
|
|
|
|
ignore => {
|
|
|
|
warn!(
|
|
|
|
"Ignoring what the server send till registered: {:? }",
|
|
|
|
ignore
|
|
|
|
);
|
|
|
|
//return Err(Error::ServerWentMad)
|
|
|
|
},
|
2020-07-01 07:30:38 +00:00
|
|
|
}
|
2019-08-08 15:23:58 +00:00
|
|
|
}
|
2020-07-01 09:51:37 +00:00
|
|
|
})
|
2019-04-21 18:12:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-25 21:13:38 +00:00
|
|
|
/// Request a state transition to `ClientState::Character`.
|
2020-06-16 01:00:32 +00:00
|
|
|
pub fn request_character(&mut self, character_id: i32) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::Character(character_id))
|
|
|
|
.unwrap();
|
2020-06-16 01:00:32 +00:00
|
|
|
|
2020-06-16 13:55:37 +00:00
|
|
|
self.active_character_id = Some(character_id);
|
2019-05-24 19:10:18 +00:00
|
|
|
self.client_state = ClientState::Pending;
|
2019-05-17 20:47:58 +00:00
|
|
|
}
|
|
|
|
|
2020-05-09 15:41:25 +00:00
|
|
|
/// Load the current players character list
|
2020-05-11 10:06:53 +00:00
|
|
|
pub fn load_character_list(&mut self) {
|
2020-05-09 15:41:25 +00:00
|
|
|
self.character_list.loading = true;
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::RequestCharacterList)
|
|
|
|
.unwrap();
|
2020-05-09 15:41:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// New character creation
|
|
|
|
pub fn create_character(&mut self, alias: String, tool: Option<String>, body: comp::Body) {
|
|
|
|
self.character_list.loading = true;
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::CreateCharacter { alias, tool, body })
|
|
|
|
.unwrap();
|
2020-05-09 15:41:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Character deletion
|
|
|
|
pub fn delete_character(&mut self, character_id: i32) {
|
|
|
|
self.character_list.loading = true;
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::DeleteCharacter(character_id))
|
|
|
|
.unwrap();
|
2020-05-09 15:41:25 +00:00
|
|
|
}
|
|
|
|
|
2019-12-31 08:10:51 +00:00
|
|
|
/// Send disconnect message to the server
|
2020-07-01 09:51:37 +00:00
|
|
|
pub fn request_logout(&mut self) {
|
2020-07-05 23:29:28 +00:00
|
|
|
debug!("Requesting logout from server");
|
2020-07-01 09:51:37 +00:00
|
|
|
if let Err(e) = self.singleton_stream.send(ClientMsg::Disconnect) {
|
|
|
|
error!(
|
|
|
|
?e,
|
2020-07-05 23:29:28 +00:00
|
|
|
"Couldn't send disconnect package to server, did server close already?"
|
2020-07-01 09:51:37 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2019-06-02 02:17:36 +00:00
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
/// Request a state transition to `ClientState::Registered` from an ingame
|
|
|
|
/// state.
|
2019-06-02 02:17:36 +00:00
|
|
|
pub fn request_remove_character(&mut self) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream.send(ClientMsg::ExitIngame).unwrap();
|
2019-06-02 02:17:36 +00:00
|
|
|
self.client_state = ClientState::Pending;
|
|
|
|
}
|
|
|
|
|
2019-05-19 00:45:02 +00:00
|
|
|
pub fn set_view_distance(&mut self, view_distance: u32) {
|
2019-10-16 11:39:41 +00:00
|
|
|
self.view_distance = Some(view_distance.max(1).min(65));
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::SetViewDistance(self.view_distance.unwrap()))
|
|
|
|
.unwrap();
|
2019-08-26 09:49:14 +00:00
|
|
|
// Can't fail
|
2019-05-19 00:45:02 +00:00
|
|
|
}
|
|
|
|
|
2020-04-10 02:36:35 +00:00
|
|
|
pub fn use_slot(&mut self, slot: comp::slot::Slot) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::InventoryManip(
|
2019-10-15 04:06:14 +00:00
|
|
|
InventoryManip::Use(slot),
|
2020-07-01 09:51:37 +00:00
|
|
|
)))
|
|
|
|
.unwrap();
|
2019-08-28 20:47:52 +00:00
|
|
|
}
|
|
|
|
|
2020-04-10 02:36:35 +00:00
|
|
|
pub fn swap_slots(&mut self, a: comp::slot::Slot, b: comp::slot::Slot) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::InventoryManip(
|
2019-10-15 04:06:14 +00:00
|
|
|
InventoryManip::Swap(a, b),
|
2020-07-01 09:51:37 +00:00
|
|
|
)))
|
|
|
|
.unwrap();
|
2019-07-25 22:52:28 +00:00
|
|
|
}
|
|
|
|
|
2020-04-10 02:36:35 +00:00
|
|
|
pub fn drop_slot(&mut self, slot: comp::slot::Slot) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::InventoryManip(
|
2019-10-15 04:06:14 +00:00
|
|
|
InventoryManip::Drop(slot),
|
2020-07-01 09:51:37 +00:00
|
|
|
)))
|
|
|
|
.unwrap();
|
2019-07-26 17:08:40 +00:00
|
|
|
}
|
|
|
|
|
2019-07-29 16:19:08 +00:00
|
|
|
pub fn pick_up(&mut self, entity: EcsEntity) {
|
|
|
|
if let Some(uid) = self.state.ecs().read_storage::<Uid>().get(entity).copied() {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::InventoryManip(
|
2019-10-15 04:06:14 +00:00
|
|
|
InventoryManip::Pickup(uid),
|
2020-07-01 09:51:37 +00:00
|
|
|
)))
|
|
|
|
.unwrap();
|
2019-07-29 16:19:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-04 15:15:31 +00:00
|
|
|
pub fn toggle_lantern(&mut self) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::ToggleLantern))
|
|
|
|
.unwrap();
|
2020-05-04 15:15:31 +00:00
|
|
|
}
|
|
|
|
|
2019-09-09 19:11:40 +00:00
|
|
|
pub fn is_mounted(&self) -> bool {
|
|
|
|
self.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::Mounting>()
|
|
|
|
.get(self.entity)
|
|
|
|
.is_some()
|
|
|
|
}
|
|
|
|
|
2019-10-15 04:06:14 +00:00
|
|
|
pub fn mount(&mut self, entity: EcsEntity) {
|
|
|
|
if let Some(uid) = self.state.ecs().read_storage::<Uid>().get(entity).copied() {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::Mount(uid)))
|
|
|
|
.unwrap();
|
2019-10-15 04:06:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn unmount(&mut self) {
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::Unmount))
|
|
|
|
.unwrap();
|
2019-10-15 04:06:14 +00:00
|
|
|
}
|
|
|
|
|
2020-03-24 07:38:16 +00:00
|
|
|
pub fn respawn(&mut self) {
|
|
|
|
if self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::Stats>()
|
|
|
|
.get(self.entity)
|
|
|
|
.map_or(false, |s| s.is_dead)
|
|
|
|
{
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::Respawn))
|
|
|
|
.unwrap();
|
2020-03-24 07:38:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-01 14:30:18 +00:00
|
|
|
/// Checks whether a player can swap their weapon+ability `Loadout` settings
|
|
|
|
/// and sends the `ControlAction` event that signals to do the swap.
|
2020-06-17 13:34:58 +00:00
|
|
|
pub fn swap_loadout(&mut self) { self.control_action(ControlAction::SwapLoadout) }
|
2020-03-24 07:38:16 +00:00
|
|
|
|
2020-03-26 15:05:17 +00:00
|
|
|
pub fn toggle_wield(&mut self) {
|
|
|
|
let is_wielding = self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::CharacterState>()
|
|
|
|
.get(self.entity)
|
|
|
|
.map(|cs| cs.is_wield());
|
2020-03-24 07:38:16 +00:00
|
|
|
|
2020-03-26 15:05:17 +00:00
|
|
|
match is_wielding {
|
|
|
|
Some(true) => self.control_action(ControlAction::Unwield),
|
|
|
|
Some(false) => self.control_action(ControlAction::Wield),
|
|
|
|
None => warn!("Can't toggle wield, client entity doesn't have a `CharacterState`"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn toggle_sit(&mut self) {
|
|
|
|
let is_sitting = self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::CharacterState>()
|
|
|
|
.get(self.entity)
|
|
|
|
.map(|cs| matches!(cs, comp::CharacterState::Sit));
|
|
|
|
|
|
|
|
match is_sitting {
|
|
|
|
Some(true) => self.control_action(ControlAction::Stand),
|
|
|
|
Some(false) => self.control_action(ControlAction::Sit),
|
|
|
|
None => warn!("Can't toggle sit, client entity doesn't have a `CharacterState`"),
|
|
|
|
}
|
|
|
|
}
|
2020-03-24 07:38:16 +00:00
|
|
|
|
2020-05-27 06:41:55 +00:00
|
|
|
pub fn toggle_dance(&mut self) {
|
|
|
|
let is_dancing = self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::CharacterState>()
|
|
|
|
.get(self.entity)
|
|
|
|
.map(|cs| matches!(cs, comp::CharacterState::Dance));
|
|
|
|
|
|
|
|
match is_dancing {
|
|
|
|
Some(true) => self.control_action(ControlAction::Stand),
|
|
|
|
Some(false) => self.control_action(ControlAction::Dance),
|
|
|
|
None => warn!("Can't toggle dance, client entity doesn't have a `CharacterState`"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-16 21:32:39 +00:00
|
|
|
pub fn toggle_glide(&mut self) {
|
|
|
|
let is_gliding = self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::CharacterState>()
|
|
|
|
.get(self.entity)
|
|
|
|
.map(|cs| {
|
|
|
|
matches!(
|
|
|
|
cs,
|
|
|
|
comp::CharacterState::GlideWield | comp::CharacterState::Glide
|
|
|
|
)
|
|
|
|
});
|
|
|
|
|
|
|
|
match is_gliding {
|
|
|
|
Some(true) => self.control_action(ControlAction::Unwield),
|
|
|
|
Some(false) => self.control_action(ControlAction::GlideWield),
|
|
|
|
None => warn!("Can't toggle glide, client entity doesn't have a `CharacterState`"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-24 07:38:16 +00:00
|
|
|
fn control_action(&mut self, control_action: ControlAction) {
|
|
|
|
if let Some(controller) = self
|
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.write_storage::<Controller>()
|
|
|
|
.get_mut(self.entity)
|
|
|
|
{
|
|
|
|
controller.actions.push(control_action);
|
|
|
|
}
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
2020-07-01 09:51:37 +00:00
|
|
|
.send(ClientMsg::ControlAction(control_action))
|
|
|
|
.unwrap();
|
2020-03-24 07:38:16 +00:00
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn view_distance(&self) -> Option<u32> { self.view_distance }
|
2019-05-27 17:01:00 +00:00
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn loaded_distance(&self) -> f32 { self.loaded_distance }
|
2019-06-05 16:32:33 +00:00
|
|
|
|
2019-06-11 18:39:25 +00:00
|
|
|
pub fn current_chunk(&self) -> Option<Arc<TerrainChunk>> {
|
2019-06-15 10:36:26 +00:00
|
|
|
let chunk_pos = Vec2::from(
|
|
|
|
self.state
|
2019-06-14 15:27:05 +00:00
|
|
|
.read_storage::<comp::Pos>()
|
2019-06-15 10:36:26 +00:00
|
|
|
.get(self.entity)
|
|
|
|
.cloned()?
|
|
|
|
.0,
|
|
|
|
)
|
common: Rework volume API
See the doc comments in `common/src/vol.rs` for more information on
the API itself.
The changes include:
* Consistent `Err`/`Error` naming.
* Types are named `...Error`.
* `enum` variants are named `...Err`.
* Rename `VolMap{2d, 3d}` -> `VolGrid{2d, 3d}`. This is in preparation
to an upcoming change where a “map” in the game related sense will
be added.
* Add volume iterators. There are two types of them:
* _Position_ iterators obtained from the trait `IntoPosIterator`
using the method
`fn pos_iter(self, lower_bound: Vec3<i32>, upper_bound: Vec3<i32>) -> ...`
which returns an iterator over `Vec3<i32>`.
* _Volume_ iterators obtained from the trait `IntoVolIterator`
using the method
`fn vol_iter(self, lower_bound: Vec3<i32>, upper_bound: Vec3<i32>) -> ...`
which returns an iterator over `(Vec3<i32>, &Self::Vox)`.
Those traits will usually be implemented by references to volume
types (i.e. `impl IntoVolIterator<'a> for &'a T` where `T` is some
type which usually implements several volume traits, such as `Chunk`).
* _Position_ iterators iterate over the positions valid for that
volume.
* _Volume_ iterators do the same but return not only the position
but also the voxel at that position, in each iteration.
* Introduce trait `RectSizedVol` for the use case which we have with
`Chonk`: A `Chonk` is sized only in x and y direction.
* Introduce traits `RasterableVol`, `RectRasterableVol`
* `RasterableVol` represents a volume that is compile-time sized and has
its lower bound at `(0, 0, 0)`. The name `RasterableVol` was chosen
because such a volume can be used with `VolGrid3d`.
* `RectRasterableVol` represents a volume that is compile-time sized at
least in x and y direction and has its lower bound at `(0, 0, z)`.
There's no requirement on he lower bound or size in z direction.
The name `RectRasterableVol` was chosen because such a volume can be
used with `VolGrid2d`.
2019-09-03 22:23:29 +00:00
|
|
|
.map2(TerrainChunkSize::RECT_SIZE, |e: f32, sz| {
|
2019-06-15 10:36:26 +00:00
|
|
|
(e as u32).div_euclid(sz) as i32
|
|
|
|
});
|
2019-06-11 18:39:25 +00:00
|
|
|
|
|
|
|
self.state.terrain().get_key_arc(chunk_pos).cloned()
|
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn inventories(&self) -> ReadStorage<comp::Inventory> { self.state.read_storage() }
|
2019-07-25 17:41:06 +00:00
|
|
|
|
2020-04-04 17:51:41 +00:00
|
|
|
pub fn loadouts(&self) -> ReadStorage<comp::Loadout> { self.state.read_storage() }
|
|
|
|
|
2019-05-25 21:13:38 +00:00
|
|
|
/// Send a chat message to the server.
|
2019-12-31 08:10:51 +00:00
|
|
|
pub fn send_chat(&mut self, message: String) {
|
|
|
|
match validate_chat_msg(&message) {
|
2020-07-01 09:51:37 +00:00
|
|
|
Ok(()) => self
|
|
|
|
.singleton_stream
|
|
|
|
.send(ClientMsg::ChatMsg(message))
|
|
|
|
.unwrap(),
|
2020-06-02 02:42:26 +00:00
|
|
|
Err(ChatMsgValidationError::TooLong) => tracing::warn!(
|
2019-08-14 04:38:54 +00:00
|
|
|
"Attempted to send a message that's too long (Over {} bytes)",
|
|
|
|
MAX_BYTES_CHAT_MSG
|
|
|
|
),
|
|
|
|
}
|
2019-05-20 19:24:47 +00:00
|
|
|
}
|
|
|
|
|
2019-05-25 21:13:38 +00:00
|
|
|
/// Remove all cached terrain
|
|
|
|
pub fn clear_terrain(&mut self) {
|
|
|
|
self.state.clear_terrain();
|
|
|
|
self.pending_chunks.clear();
|
2019-05-23 08:18:25 +00:00
|
|
|
}
|
|
|
|
|
2019-07-02 18:19:16 +00:00
|
|
|
pub fn place_block(&mut self, pos: Vec3<i32>, block: Block) {
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::PlaceBlock(pos, block))
|
|
|
|
.unwrap();
|
2019-07-02 18:19:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn remove_block(&mut self, pos: Vec3<i32>) {
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::BreakBlock(pos))
|
|
|
|
.unwrap();
|
2019-07-02 18:19:16 +00:00
|
|
|
}
|
|
|
|
|
2019-09-25 21:17:43 +00:00
|
|
|
pub fn collect_block(&mut self, pos: Vec3<i32>) {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::ControlEvent(ControlEvent::InventoryManip(
|
2019-10-15 04:06:14 +00:00
|
|
|
InventoryManip::Collect(pos),
|
2020-07-01 09:51:37 +00:00
|
|
|
)))
|
|
|
|
.unwrap();
|
2019-09-25 21:17:43 +00:00
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
/// Execute a single client tick, handle input and update the game state by
|
|
|
|
/// the given duration.
|
2020-01-10 00:33:38 +00:00
|
|
|
pub fn tick(
|
|
|
|
&mut self,
|
|
|
|
inputs: ControllerInputs,
|
|
|
|
dt: Duration,
|
|
|
|
add_foreign_systems: impl Fn(&mut DispatcherBuilder),
|
|
|
|
) -> Result<Vec<Event>, Error> {
|
2020-02-01 20:39:39 +00:00
|
|
|
// This tick function is the centre of the Veloren universe. Most client-side
|
|
|
|
// things are managed from here, and as such it's important that it
|
|
|
|
// stays organised. Please consult the core developers before making
|
|
|
|
// significant changes to this code. Here is the approximate order of
|
|
|
|
// things. Please update it as this code changes.
|
2019-01-02 17:23:31 +00:00
|
|
|
//
|
2020-01-27 16:48:42 +00:00
|
|
|
// 1) Collect input from the frontend, apply input effects to the state
|
|
|
|
// of the game
|
2019-05-17 20:47:58 +00:00
|
|
|
// 2) Handle messages from the server
|
2020-01-27 16:48:42 +00:00
|
|
|
// 3) Go through any events (timer-driven or otherwise) that need handling
|
|
|
|
// and apply them to the state of the game
|
|
|
|
// 4) Perform a single LocalState tick (i.e: update the world and entities
|
|
|
|
// in the world)
|
|
|
|
// 5) Go through the terrain update queue and apply all changes
|
|
|
|
// to the terrain
|
2019-05-17 20:47:58 +00:00
|
|
|
// 6) Sync information to the server
|
2020-01-27 16:48:42 +00:00
|
|
|
// 7) Finish the tick, passing actions of the main thread back
|
|
|
|
// to the frontend
|
2019-05-17 20:47:58 +00:00
|
|
|
|
|
|
|
// 1) Handle input from frontend.
|
2019-05-22 20:53:24 +00:00
|
|
|
// Pass character actions from frontend input to the player's entity.
|
2019-12-31 08:10:51 +00:00
|
|
|
if let ClientState::Character = self.client_state {
|
2020-06-21 21:47:49 +00:00
|
|
|
if let Err(e) = self
|
2020-03-24 07:38:16 +00:00
|
|
|
.state
|
|
|
|
.ecs()
|
|
|
|
.write_storage::<Controller>()
|
|
|
|
.entry(self.entity)
|
|
|
|
.map(|entry| {
|
|
|
|
entry
|
|
|
|
.or_insert_with(|| Controller {
|
|
|
|
inputs: inputs.clone(),
|
|
|
|
events: Vec::new(),
|
|
|
|
actions: Vec::new(),
|
|
|
|
})
|
|
|
|
.inputs = inputs.clone();
|
|
|
|
})
|
|
|
|
{
|
2020-06-21 21:47:49 +00:00
|
|
|
let entry = self.entity;
|
2020-03-24 07:38:16 +00:00
|
|
|
error!(
|
2020-06-21 21:47:49 +00:00
|
|
|
?e,
|
|
|
|
?entry,
|
|
|
|
"Couldn't access controller component on client entity"
|
2020-03-24 07:38:16 +00:00
|
|
|
);
|
|
|
|
}
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
2020-07-11 14:08:25 +00:00
|
|
|
.send(ClientMsg::ControllerInputs(inputs))?;
|
2019-06-17 17:52:06 +00:00
|
|
|
}
|
2019-03-02 03:48:30 +00:00
|
|
|
|
2019-05-17 20:47:58 +00:00
|
|
|
// 2) Build up a list of events for this frame, to be passed to the frontend.
|
|
|
|
let mut frontend_events = Vec::new();
|
2019-01-02 17:23:31 +00:00
|
|
|
|
2019-08-28 13:55:35 +00:00
|
|
|
// Prepare for new events
|
2019-08-25 22:22:43 +00:00
|
|
|
{
|
2019-10-15 04:06:14 +00:00
|
|
|
let ecs = self.state.ecs();
|
2019-08-25 22:22:43 +00:00
|
|
|
for (entity, _) in (&ecs.entities(), &ecs.read_storage::<comp::Body>()).join() {
|
2019-08-28 12:46:20 +00:00
|
|
|
let mut last_character_states =
|
2019-08-25 22:22:43 +00:00
|
|
|
ecs.write_storage::<comp::Last<comp::CharacterState>>();
|
|
|
|
if let Some(client_character_state) =
|
|
|
|
ecs.read_storage::<comp::CharacterState>().get(entity)
|
|
|
|
{
|
2019-08-28 12:46:20 +00:00
|
|
|
if last_character_states
|
2019-08-25 22:22:43 +00:00
|
|
|
.get(entity)
|
2020-03-22 12:46:09 +00:00
|
|
|
.map(|l| !client_character_state.same_variant(&l.0))
|
2019-08-25 22:22:43 +00:00
|
|
|
.unwrap_or(true)
|
|
|
|
{
|
2019-08-28 12:46:20 +00:00
|
|
|
let _ = last_character_states
|
2020-03-16 11:32:57 +00:00
|
|
|
.insert(entity, comp::Last(client_character_state.clone()));
|
2019-08-25 22:22:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-03-04 10:09:48 +00:00
|
|
|
|
2019-08-28 13:55:35 +00:00
|
|
|
// Handle new messages from the server.
|
|
|
|
frontend_events.append(&mut self.handle_new_messages()?);
|
|
|
|
|
|
|
|
// 3) Update client local data
|
2019-05-17 20:47:58 +00:00
|
|
|
|
|
|
|
// 4) Tick the client's LocalState
|
2020-03-09 03:32:34 +00:00
|
|
|
self.state.tick(dt, add_foreign_systems, true);
|
2019-04-16 14:29:44 +00:00
|
|
|
|
2019-05-17 20:47:58 +00:00
|
|
|
// 5) Terrain
|
2019-04-25 19:08:26 +00:00
|
|
|
let pos = self
|
2019-04-23 09:53:45 +00:00
|
|
|
.state
|
2019-06-14 15:27:05 +00:00
|
|
|
.read_storage::<comp::Pos>()
|
2019-04-23 09:53:45 +00:00
|
|
|
.get(self.entity)
|
2019-04-25 19:08:26 +00:00
|
|
|
.cloned();
|
2019-05-19 00:45:02 +00:00
|
|
|
if let (Some(pos), Some(view_distance)) = (pos, self.view_distance) {
|
2019-04-14 20:30:27 +00:00
|
|
|
let chunk_pos = self.state.terrain().pos_key(pos.0.map(|e| e as i32));
|
|
|
|
|
2019-05-17 09:22:32 +00:00
|
|
|
// Remove chunks that are too far from the player.
|
2019-04-25 19:08:26 +00:00
|
|
|
let mut chunks_to_remove = Vec::new();
|
2019-04-25 19:25:22 +00:00
|
|
|
self.state.terrain().iter().for_each(|(key, _)| {
|
2019-12-23 06:02:00 +00:00
|
|
|
// Subtract 2 from the offset before computing squared magnitude
|
|
|
|
// 1 for the chunks needed bordering other chunks for meshing
|
|
|
|
// 1 as a buffer so that if the player moves back in that direction the chunks
|
|
|
|
// don't need to be reloaded
|
2019-07-02 19:00:57 +00:00
|
|
|
if (chunk_pos - key)
|
2020-06-30 14:56:49 +00:00
|
|
|
.map(|e: i32| (e.abs() as u32).saturating_sub(2))
|
2019-06-23 19:49:15 +00:00
|
|
|
.magnitude_squared()
|
|
|
|
> view_distance.pow(2)
|
2019-05-09 17:58:16 +00:00
|
|
|
{
|
2019-04-25 19:25:22 +00:00
|
|
|
chunks_to_remove.push(key);
|
2019-04-25 19:08:26 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
for key in chunks_to_remove {
|
|
|
|
self.state.remove_chunk(key);
|
|
|
|
}
|
|
|
|
|
2019-05-17 09:22:32 +00:00
|
|
|
// Request chunks from the server.
|
2020-01-12 11:09:37 +00:00
|
|
|
self.loaded_distance = ((view_distance * TerrainChunkSize::RECT_SIZE.x) as f32).powi(2);
|
|
|
|
// +1 so we can find a chunk that's outside the vd for better fog
|
|
|
|
for dist in 0..view_distance as i32 + 1 {
|
2019-06-23 19:49:15 +00:00
|
|
|
// Only iterate through chunks that need to be loaded for circular vd
|
|
|
|
// The (dist - 2) explained:
|
|
|
|
// -0.5 because a chunk is visible if its corner is within the view distance
|
|
|
|
// -0.5 for being able to move to the corner of the current chunk
|
|
|
|
// -1 because chunks are not meshed if they don't have all their neighbors
|
|
|
|
// (notice also that view_distance is decreased by 1)
|
2020-01-27 16:48:42 +00:00
|
|
|
// (this subtraction on vd is ommitted elsewhere in order to provide
|
|
|
|
// a buffer layer of loaded chunks)
|
2019-06-23 19:49:15 +00:00
|
|
|
let top = if 2 * (dist - 2).max(0).pow(2) > (view_distance - 1).pow(2) as i32 {
|
|
|
|
((view_distance - 1).pow(2) as f32 - (dist - 2).pow(2) as f32)
|
|
|
|
.sqrt()
|
|
|
|
.round() as i32
|
|
|
|
+ 1
|
|
|
|
} else {
|
|
|
|
dist
|
|
|
|
};
|
|
|
|
|
2020-01-12 11:09:37 +00:00
|
|
|
let mut skip_mode = false;
|
2020-01-12 14:45:20 +00:00
|
|
|
for i in -top..top + 1 {
|
2019-06-23 19:49:15 +00:00
|
|
|
let keys = [
|
|
|
|
chunk_pos + Vec2::new(dist, i),
|
|
|
|
chunk_pos + Vec2::new(i, dist),
|
|
|
|
chunk_pos + Vec2::new(-dist, i),
|
|
|
|
chunk_pos + Vec2::new(i, -dist),
|
|
|
|
];
|
|
|
|
|
|
|
|
for key in keys.iter() {
|
|
|
|
if self.state.terrain().get_key(*key).is_none() {
|
2020-01-12 11:09:37 +00:00
|
|
|
if !skip_mode && !self.pending_chunks.contains_key(key) {
|
2019-06-05 16:32:33 +00:00
|
|
|
if self.pending_chunks.len() < 4 {
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::TerrainChunkRequest { key: *key })?;
|
2019-06-23 19:49:15 +00:00
|
|
|
self.pending_chunks.insert(*key, Instant::now());
|
2019-06-05 16:32:33 +00:00
|
|
|
} else {
|
2020-01-12 11:09:37 +00:00
|
|
|
skip_mode = true;
|
2019-06-05 16:32:33 +00:00
|
|
|
}
|
2019-05-13 12:08:17 +00:00
|
|
|
}
|
2019-06-05 16:32:33 +00:00
|
|
|
|
2020-01-12 11:09:37 +00:00
|
|
|
let dist_to_player =
|
|
|
|
(self.state.terrain().key_pos(*key).map(|x| x as f32)
|
|
|
|
+ TerrainChunkSize::RECT_SIZE.map(|x| x as f32) / 2.0)
|
|
|
|
.distance_squared(pos.0.into());
|
|
|
|
|
|
|
|
if dist_to_player < self.loaded_distance {
|
|
|
|
self.loaded_distance = dist_to_player;
|
|
|
|
}
|
2019-04-11 22:26:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-01-12 11:09:37 +00:00
|
|
|
self.loaded_distance = self.loaded_distance.sqrt()
|
|
|
|
- ((TerrainChunkSize::RECT_SIZE.x as f32 / 2.0).powi(2)
|
|
|
|
+ (TerrainChunkSize::RECT_SIZE.y as f32 / 2.0).powi(2))
|
|
|
|
.sqrt();
|
2019-05-16 20:18:48 +00:00
|
|
|
|
2019-05-17 09:22:32 +00:00
|
|
|
// If chunks are taking too long, assume they're no longer pending.
|
2019-05-16 20:18:48 +00:00
|
|
|
let now = Instant::now();
|
2019-05-16 21:04:16 +00:00
|
|
|
self.pending_chunks
|
2019-06-05 18:00:17 +00:00
|
|
|
.retain(|_, created| now.duration_since(*created) < Duration::from_secs(3));
|
2019-04-11 22:26:43 +00:00
|
|
|
}
|
|
|
|
|
2019-05-17 20:47:58 +00:00
|
|
|
// Send a ping to the server once every second
|
2020-03-01 22:18:22 +00:00
|
|
|
if self.state.get_time() - self.last_server_ping > 1. {
|
2020-07-01 07:30:38 +00:00
|
|
|
self.singleton_stream.send(ClientMsg::Ping)?;
|
2020-03-01 22:18:22 +00:00
|
|
|
self.last_server_ping = self.state.get_time();
|
2019-05-23 08:18:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-17 20:47:58 +00:00
|
|
|
// 6) Update the server about the player's physics attributes.
|
2019-06-29 20:40:40 +00:00
|
|
|
if let ClientState::Character = self.client_state {
|
2019-07-02 19:00:57 +00:00
|
|
|
if let (Some(pos), Some(vel), Some(ori)) = (
|
2019-06-29 20:40:40 +00:00
|
|
|
self.state.read_storage().get(self.entity).cloned(),
|
|
|
|
self.state.read_storage().get(self.entity).cloned(),
|
|
|
|
self.state.read_storage().get(self.entity).cloned(),
|
|
|
|
) {
|
2020-07-01 09:51:37 +00:00
|
|
|
self.singleton_stream
|
|
|
|
.send(ClientMsg::PlayerPhysics { pos, vel, ori })?;
|
2019-05-17 20:47:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-06 13:23:38 +00:00
|
|
|
/*
|
2019-06-04 12:45:41 +00:00
|
|
|
// Output debug metrics
|
2020-06-21 14:26:06 +00:00
|
|
|
if log_enabled!(Level::Info) && self.tick % 600 == 0 {
|
2019-06-04 12:49:57 +00:00
|
|
|
let metrics = self
|
|
|
|
.state
|
2019-06-04 12:45:41 +00:00
|
|
|
.terrain()
|
|
|
|
.iter()
|
|
|
|
.fold(ChonkMetrics::default(), |a, (_, c)| a + c.get_metrics());
|
|
|
|
info!("{:?}", metrics);
|
|
|
|
}
|
2019-09-06 13:23:38 +00:00
|
|
|
*/
|
2019-06-04 12:45:41 +00:00
|
|
|
|
2019-05-17 20:47:58 +00:00
|
|
|
// 7) Finish the tick, pass control back to the frontend.
|
2019-01-23 20:01:58 +00:00
|
|
|
self.tick += 1;
|
2019-03-03 22:02:38 +00:00
|
|
|
Ok(frontend_events)
|
2019-01-02 17:23:31 +00:00
|
|
|
}
|
2019-01-23 20:01:58 +00:00
|
|
|
|
2019-05-17 09:22:32 +00:00
|
|
|
/// Clean up the client after a tick.
|
2019-01-23 20:01:58 +00:00
|
|
|
pub fn cleanup(&mut self) {
|
|
|
|
// Cleanup the local state
|
|
|
|
self.state.cleanup();
|
|
|
|
}
|
2019-03-03 22:02:38 +00:00
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
async fn handle_message(
|
|
|
|
&mut self,
|
|
|
|
frontend_events: &mut Vec<Event>,
|
|
|
|
cnt: &mut u64,
|
|
|
|
) -> Result<(), Error> {
|
2020-07-01 09:45:39 +00:00
|
|
|
loop {
|
2020-07-01 09:51:37 +00:00
|
|
|
let msg = self.singleton_stream.recv().await?;
|
2020-07-01 09:45:39 +00:00
|
|
|
*cnt += 1;
|
|
|
|
match msg {
|
|
|
|
ServerMsg::TooManyPlayers => {
|
|
|
|
return Err(Error::ServerWentMad);
|
|
|
|
},
|
|
|
|
ServerMsg::Shutdown => return Err(Error::ServerShutdown),
|
|
|
|
ServerMsg::InitialSync { .. } => return Err(Error::ServerWentMad),
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::Init(list)) => {
|
|
|
|
self.player_list = list
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::Add(uid, player_info)) => {
|
2020-07-01 09:51:37 +00:00
|
|
|
if let Some(old_player_info) = self.player_list.insert(uid, player_info.clone())
|
2020-07-01 09:45:39 +00:00
|
|
|
{
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to insert {} with uid {} into the player list but there \
|
|
|
|
was already an entry for {} with the same uid that was overwritten!",
|
2020-07-01 09:45:39 +00:00
|
|
|
player_info.player_alias, uid, old_player_info.player_alias
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::Admin(uid, admin)) => {
|
|
|
|
if let Some(player_info) = self.player_list.get_mut(&uid) {
|
|
|
|
player_info.is_admin = admin;
|
|
|
|
} else {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to update admin status of uid {}, but they were not in \
|
|
|
|
the list.",
|
2020-07-01 09:45:39 +00:00
|
|
|
uid
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::SelectedCharacter(
|
2020-07-01 09:51:37 +00:00
|
|
|
uid,
|
|
|
|
char_info,
|
|
|
|
)) => {
|
2020-07-01 09:45:39 +00:00
|
|
|
if let Some(player_info) = self.player_list.get_mut(&uid) {
|
|
|
|
player_info.character = Some(char_info);
|
|
|
|
} else {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to update character info for uid {}, but they were not \
|
|
|
|
in the list.",
|
2020-07-01 09:45:39 +00:00
|
|
|
uid
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::LevelChange(uid, next_level)) => {
|
|
|
|
if let Some(player_info) = self.player_list.get_mut(&uid) {
|
|
|
|
player_info.character = match &player_info.character {
|
|
|
|
Some(character) => Some(common::msg::CharacterInfo {
|
|
|
|
name: character.name.to_string(),
|
|
|
|
level: next_level,
|
|
|
|
}),
|
|
|
|
None => {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to update character level info to {} for uid \
|
|
|
|
{}, but this player's character is None.",
|
2020-07-01 09:45:39 +00:00
|
|
|
next_level, uid
|
|
|
|
);
|
|
|
|
|
|
|
|
None
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::Remove(uid)) => {
|
|
|
|
// Instead of removing players, mark them as offline because we need to
|
|
|
|
// remember the names of disconnected players in chat.
|
|
|
|
//
|
|
|
|
// TODO the server should re-use uids of players that log out and log back
|
|
|
|
// in.
|
|
|
|
|
|
|
|
if let Some(player_info) = self.player_list.get_mut(&uid) {
|
|
|
|
if player_info.is_online {
|
|
|
|
player_info.is_online = false;
|
|
|
|
} else {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to remove uid {} from the player list by they were \
|
|
|
|
already marked offline",
|
2020-07-01 09:45:39 +00:00
|
|
|
uid
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to remove uid {} from the player list by they weren't \
|
|
|
|
in the list!",
|
2020-07-01 09:45:39 +00:00
|
|
|
uid
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::PlayerListUpdate(PlayerListUpdate::Alias(uid, new_name)) => {
|
|
|
|
if let Some(player_info) = self.player_list.get_mut(&uid) {
|
|
|
|
player_info.player_alias = new_name;
|
|
|
|
} else {
|
|
|
|
warn!(
|
2020-07-01 09:51:37 +00:00
|
|
|
"Received msg to alias player with uid {} to {} but this uid is not \
|
|
|
|
in the player list",
|
2020-07-01 09:45:39 +00:00
|
|
|
uid, new_name
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
ServerMsg::Ping => {
|
|
|
|
self.singleton_stream.send(ClientMsg::Pong)?;
|
|
|
|
},
|
2020-07-01 09:45:39 +00:00
|
|
|
ServerMsg::Pong => {
|
|
|
|
self.last_server_pong = self.state.get_time();
|
2020-07-10 20:25:45 +00:00
|
|
|
self.last_ping_delta = self.state.get_time() - self.last_server_ping;
|
2020-07-01 09:45:39 +00:00
|
|
|
|
2020-07-10 20:25:45 +00:00
|
|
|
// Maintain the correct number of deltas for calculating the rolling average
|
|
|
|
// ping. The client sends a ping to the server every second so we should be
|
|
|
|
// receiving a pong reply roughly every second.
|
|
|
|
while self.ping_deltas.len() > PING_ROLLING_AVERAGE_SECS - 1 {
|
|
|
|
self.ping_deltas.pop_front();
|
|
|
|
}
|
|
|
|
self.ping_deltas.push_back(self.last_ping_delta);
|
2020-07-01 09:45:39 +00:00
|
|
|
},
|
|
|
|
ServerMsg::ChatMsg(m) => frontend_events.push(Event::Chat(m)),
|
|
|
|
ServerMsg::SetPlayerEntity(uid) => {
|
|
|
|
if let Some(entity) = self.state.ecs().entity_from_uid(uid.0) {
|
|
|
|
self.entity = entity;
|
|
|
|
} else {
|
|
|
|
return Err(Error::Other("Failed to find entity from uid.".to_owned()));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
ServerMsg::TimeOfDay(time_of_day) => {
|
|
|
|
*self.state.ecs_mut().write_resource() = time_of_day;
|
|
|
|
},
|
|
|
|
ServerMsg::EntitySync(entity_sync_package) => {
|
|
|
|
self.state
|
|
|
|
.ecs_mut()
|
|
|
|
.apply_entity_sync_package(entity_sync_package);
|
|
|
|
},
|
|
|
|
ServerMsg::CompSync(comp_sync_package) => {
|
|
|
|
self.state
|
|
|
|
.ecs_mut()
|
|
|
|
.apply_comp_sync_package(comp_sync_package);
|
|
|
|
},
|
|
|
|
ServerMsg::CreateEntity(entity_package) => {
|
|
|
|
self.state.ecs_mut().apply_entity_package(entity_package);
|
|
|
|
},
|
|
|
|
ServerMsg::DeleteEntity(entity) => {
|
|
|
|
if self.state.read_component_cloned::<Uid>(self.entity) != Some(entity) {
|
|
|
|
self.state
|
|
|
|
.ecs_mut()
|
|
|
|
.delete_entity_and_clear_from_uid_allocator(entity.0);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
// Cleanup for when the client goes back to the `Registered` state
|
|
|
|
ServerMsg::ExitIngameCleanup => {
|
|
|
|
self.clean_state();
|
|
|
|
},
|
|
|
|
ServerMsg::InventoryUpdate(inventory, event) => {
|
|
|
|
match event {
|
|
|
|
InventoryUpdateEvent::CollectFailed => {},
|
|
|
|
_ => {
|
|
|
|
// Push the updated inventory component to the client
|
|
|
|
self.state.write_component(self.entity, inventory);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
frontend_events.push(Event::InventoryUpdated(event));
|
|
|
|
},
|
|
|
|
ServerMsg::TerrainChunkUpdate { key, chunk } => {
|
|
|
|
if let Ok(chunk) = chunk {
|
|
|
|
self.state.insert_chunk(key, *chunk);
|
|
|
|
}
|
|
|
|
self.pending_chunks.remove(&key);
|
|
|
|
},
|
|
|
|
ServerMsg::TerrainBlockUpdates(mut blocks) => {
|
|
|
|
blocks.drain().for_each(|(pos, block)| {
|
|
|
|
self.state.set_block(pos, block);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
ServerMsg::StateAnswer(Ok(state)) => {
|
|
|
|
self.client_state = state;
|
|
|
|
},
|
|
|
|
ServerMsg::StateAnswer(Err((error, state))) => {
|
|
|
|
warn!(
|
|
|
|
"StateAnswer: {:?}. Server thinks client is in state {:?}.",
|
|
|
|
error, state
|
|
|
|
);
|
|
|
|
},
|
|
|
|
ServerMsg::Disconnect => {
|
|
|
|
frontend_events.push(Event::Disconnect);
|
|
|
|
self.singleton_stream.send(ClientMsg::Terminate)?;
|
|
|
|
},
|
|
|
|
ServerMsg::CharacterListUpdate(character_list) => {
|
|
|
|
self.character_list.characters = character_list;
|
|
|
|
self.character_list.loading = false;
|
|
|
|
},
|
|
|
|
ServerMsg::CharacterActionError(error) => {
|
|
|
|
warn!("CharacterActionError: {:?}.", error);
|
|
|
|
self.character_list.error = Some(error);
|
|
|
|
},
|
|
|
|
ServerMsg::Notification(n) => {
|
|
|
|
frontend_events.push(Event::Notification(n));
|
|
|
|
},
|
|
|
|
ServerMsg::CharacterDataLoadError(error) => {
|
|
|
|
self.clean_state();
|
|
|
|
self.character_list.error = Some(error);
|
|
|
|
},
|
|
|
|
ServerMsg::SetViewDistance(vd) => {
|
|
|
|
self.view_distance = Some(vd);
|
|
|
|
frontend_events.push(Event::SetViewDistance(vd));
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-11 17:06:11 +00:00
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
/// Handle new server messages.
|
2019-03-03 22:02:38 +00:00
|
|
|
fn handle_new_messages(&mut self) -> Result<Vec<Event>, Error> {
|
|
|
|
let mut frontend_events = Vec::new();
|
|
|
|
|
2019-10-17 04:09:01 +00:00
|
|
|
// Check that we have an valid connection.
|
2020-02-01 20:39:39 +00:00
|
|
|
// Use the last ping time as a 1s rate limiter, we only notify the user once per
|
|
|
|
// second
|
2020-03-01 22:18:22 +00:00
|
|
|
if self.state.get_time() - self.last_server_ping > 1. {
|
|
|
|
let duration_since_last_pong = self.state.get_time() - self.last_server_pong;
|
2019-10-17 04:09:01 +00:00
|
|
|
|
|
|
|
// Dispatch a notification to the HUD warning they will be kicked in {n} seconds
|
2020-06-11 17:06:11 +00:00
|
|
|
if duration_since_last_pong >= SERVER_TIMEOUT_GRACE_PERIOD
|
|
|
|
&& self.state.get_time() - duration_since_last_pong > 0.
|
|
|
|
{
|
|
|
|
frontend_events.push(Event::DisconnectionNotification(
|
|
|
|
(self.state.get_time() - duration_since_last_pong).round() as u64,
|
|
|
|
));
|
2019-10-17 04:09:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
let mut handles_msg = 0;
|
2019-10-17 04:09:01 +00:00
|
|
|
|
2020-07-01 09:51:37 +00:00
|
|
|
block_on(async {
|
2020-07-01 09:45:39 +00:00
|
|
|
//TIMEOUT 0.01 ms for msg handling
|
|
|
|
select!(
|
|
|
|
_ = Delay::new(std::time::Duration::from_micros(10)).fuse() => Ok(()),
|
|
|
|
err = self.handle_message(&mut frontend_events, &mut handles_msg).fuse() => err,
|
|
|
|
)
|
|
|
|
})?;
|
2020-06-28 15:21:12 +00:00
|
|
|
|
2020-07-01 09:45:39 +00:00
|
|
|
if handles_msg == 0 && self.state.get_time() - self.last_server_pong > SERVER_TIMEOUT {
|
2019-03-05 18:39:18 +00:00
|
|
|
return Err(Error::ServerTimeout);
|
2019-03-03 22:02:38 +00:00
|
|
|
}
|
2020-07-01 09:45:39 +00:00
|
|
|
|
2019-03-03 22:02:38 +00:00
|
|
|
Ok(frontend_events)
|
|
|
|
}
|
2019-05-25 21:13:38 +00:00
|
|
|
|
|
|
|
/// Get the player's entity.
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn entity(&self) -> EcsEntity { self.entity }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
|
|
|
/// Get the client state
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn get_client_state(&self) -> ClientState { self.client_state }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
|
|
|
/// Get the current tick number.
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn get_tick(&self) -> u64 { self.tick }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn get_ping_ms(&self) -> f64 { self.last_ping_delta * 1000.0 }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
2020-07-10 20:25:45 +00:00
|
|
|
pub fn get_ping_ms_rolling_avg(&self) -> f64 {
|
|
|
|
let mut total_weight = 0.;
|
|
|
|
let pings = self.ping_deltas.len() as f64;
|
|
|
|
(self
|
|
|
|
.ping_deltas
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.fold(0., |acc, (i, ping)| {
|
|
|
|
let weight = i as f64 + 1. / pings;
|
|
|
|
total_weight += weight;
|
|
|
|
acc + (weight * ping)
|
|
|
|
})
|
|
|
|
/ total_weight)
|
|
|
|
* 1000.0
|
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
/// Get a reference to the client's worker thread pool. This pool should be
|
|
|
|
/// used for any computationally expensive operations that run outside
|
|
|
|
/// of the main thread (i.e., threads that block on I/O operations are
|
|
|
|
/// exempt).
|
|
|
|
pub fn thread_pool(&self) -> &ThreadPool { &self.thread_pool }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
|
|
|
/// Get a reference to the client's game state.
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn state(&self) -> &State { &self.state }
|
2019-05-25 21:13:38 +00:00
|
|
|
|
|
|
|
/// Get a mutable reference to the client's game state.
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn state_mut(&mut self) -> &mut State { &mut self.state }
|
2019-04-24 07:59:42 +00:00
|
|
|
|
|
|
|
/// Get a vector of all the players on the server
|
2019-06-02 14:35:21 +00:00
|
|
|
pub fn get_players(&mut self) -> Vec<comp::Player> {
|
|
|
|
// TODO: Don't clone players.
|
|
|
|
self.state
|
|
|
|
.ecs()
|
|
|
|
.read_storage::<comp::Player>()
|
2019-04-24 07:59:42 +00:00
|
|
|
.join()
|
2019-07-02 19:00:57 +00:00
|
|
|
.cloned()
|
2019-04-24 07:59:42 +00:00
|
|
|
.collect()
|
|
|
|
}
|
2020-06-16 01:00:32 +00:00
|
|
|
|
2020-07-09 21:01:48 +00:00
|
|
|
/// Return true if this client is an admin on the server
|
|
|
|
pub fn is_admin(&self) -> bool {
|
|
|
|
let client_uid = self
|
|
|
|
.state
|
|
|
|
.read_component_cloned::<Uid>(self.entity)
|
|
|
|
.expect("Client doesn't have a Uid!!!");
|
|
|
|
|
|
|
|
self.player_list
|
|
|
|
.get(&client_uid)
|
|
|
|
.map_or(false, |info| info.is_admin)
|
|
|
|
}
|
|
|
|
|
2020-06-16 01:00:32 +00:00
|
|
|
/// Clean client ECS state
|
|
|
|
fn clean_state(&mut self) {
|
|
|
|
let client_uid = self
|
|
|
|
.state
|
|
|
|
.read_component_cloned::<Uid>(self.entity)
|
|
|
|
.map(|u| u.into())
|
|
|
|
.expect("Client doesn't have a Uid!!!");
|
|
|
|
|
|
|
|
// Clear ecs of all entities
|
|
|
|
self.state.ecs_mut().delete_all();
|
|
|
|
self.state.ecs_mut().maintain();
|
|
|
|
self.state.ecs_mut().insert(UidAllocator::default());
|
|
|
|
|
|
|
|
// Recreate client entity with Uid
|
|
|
|
let entity_builder = self.state.ecs_mut().create_entity();
|
|
|
|
let uid = entity_builder
|
|
|
|
.world
|
|
|
|
.write_resource::<UidAllocator>()
|
|
|
|
.allocate(entity_builder.entity, Some(client_uid));
|
|
|
|
|
|
|
|
self.entity = entity_builder.with(uid).build();
|
|
|
|
}
|
2020-06-27 23:12:12 +00:00
|
|
|
|
2020-06-10 04:21:56 +00:00
|
|
|
/// Format a message for the client (voxygen chat box or chat-cli)
|
2020-06-24 05:46:29 +00:00
|
|
|
pub fn format_message(&self, msg: &comp::ChatMsg, character_name: bool) -> String {
|
|
|
|
let comp::ChatMsg { chat_type, message } = &msg;
|
2020-06-10 04:21:56 +00:00
|
|
|
let alias_of_uid = |uid| {
|
|
|
|
self.player_list
|
|
|
|
.get(uid)
|
|
|
|
.map_or("<?>".to_string(), |player_info| {
|
|
|
|
if player_info.is_admin {
|
|
|
|
format!("ADMIN - {}", player_info.player_alias)
|
|
|
|
} else {
|
|
|
|
player_info.player_alias.to_string()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
};
|
2020-06-24 05:46:29 +00:00
|
|
|
let name_of_uid = |uid| {
|
|
|
|
let ecs = self.state.ecs();
|
2020-06-24 06:29:39 +00:00
|
|
|
(
|
|
|
|
&ecs.read_storage::<comp::Stats>(),
|
|
|
|
&ecs.read_storage::<Uid>(),
|
|
|
|
)
|
|
|
|
.join()
|
|
|
|
.find(|(_, u)| u == &uid)
|
|
|
|
.map(|(c, _)| c.name.clone())
|
2020-06-24 05:46:29 +00:00
|
|
|
};
|
2020-06-10 04:21:56 +00:00
|
|
|
let message_format = |uid, message, group| {
|
2020-06-24 05:46:29 +00:00
|
|
|
let alias = alias_of_uid(uid);
|
2020-06-24 06:29:39 +00:00
|
|
|
let name = if character_name {
|
|
|
|
name_of_uid(uid)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2020-06-24 05:46:29 +00:00
|
|
|
match (group, name) {
|
|
|
|
(Some(group), None) => format!("({}) [{}]: {}", group, alias, message),
|
|
|
|
(None, None) => format!("[{}]: {}", alias, message),
|
2020-06-24 06:29:39 +00:00
|
|
|
(Some(group), Some(name)) => {
|
|
|
|
format!("({}) [{}] {}: {}", group, alias, name, message)
|
|
|
|
},
|
2020-06-24 05:46:29 +00:00
|
|
|
(None, Some(name)) => format!("[{}] {}: {}", alias, name, message),
|
2020-06-10 04:21:56 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
match chat_type {
|
2020-06-12 07:43:20 +00:00
|
|
|
comp::ChatType::Online => message.to_string(),
|
|
|
|
comp::ChatType::Offline => message.to_string(),
|
|
|
|
comp::ChatType::CommandError => message.to_string(),
|
|
|
|
comp::ChatType::CommandInfo => message.to_string(),
|
2020-07-01 19:05:44 +00:00
|
|
|
comp::ChatType::Loot => message.to_string(),
|
2020-06-12 17:44:29 +00:00
|
|
|
comp::ChatType::FactionMeta(_) => message.to_string(),
|
|
|
|
comp::ChatType::GroupMeta(_) => message.to_string(),
|
2020-06-10 04:21:56 +00:00
|
|
|
comp::ChatType::Kill => message.to_string(),
|
|
|
|
comp::ChatType::Tell(from, to) => {
|
|
|
|
let from_alias = alias_of_uid(from);
|
|
|
|
let to_alias = alias_of_uid(to);
|
|
|
|
if Some(from) == self.state.ecs().read_storage::<Uid>().get(self.entity) {
|
|
|
|
format!("To [{}]: {}", to_alias, message)
|
|
|
|
} else {
|
|
|
|
format!("From [{}]: {}", from_alias, message)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
comp::ChatType::Say(uid) => message_format(uid, message, None),
|
|
|
|
comp::ChatType::Group(uid, s) => message_format(uid, message, Some(s)),
|
|
|
|
comp::ChatType::Faction(uid, s) => message_format(uid, message, Some(s)),
|
|
|
|
comp::ChatType::Region(uid) => message_format(uid, message, None),
|
|
|
|
comp::ChatType::World(uid) => message_format(uid, message, None),
|
|
|
|
// NPCs can't talk. Should be filtered by hud/mod.rs for voxygen and should be filtered
|
2020-06-12 07:43:20 +00:00
|
|
|
// by server (due to not having a Pos) for chat-cli
|
2020-06-10 04:21:56 +00:00
|
|
|
comp::ChatType::Npc(_uid, _r) => "".to_string(),
|
2020-06-28 17:10:01 +00:00
|
|
|
comp::ChatType::Meta => message.to_string(),
|
2020-06-10 04:21:56 +00:00
|
|
|
}
|
|
|
|
}
|
2019-03-03 22:02:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for Client {
|
2020-07-01 09:51:37 +00:00
|
|
|
fn drop(&mut self) {
|
2020-07-05 23:29:28 +00:00
|
|
|
trace!("Dropping client");
|
2020-07-01 09:51:37 +00:00
|
|
|
if let Err(e) = self.singleton_stream.send(ClientMsg::Disconnect) {
|
|
|
|
warn!(
|
2020-07-05 23:29:28 +00:00
|
|
|
?e,
|
|
|
|
"Error during drop of client, couldn't send disconnect package, is the connection \
|
|
|
|
already closed?",
|
2020-07-01 09:51:37 +00:00
|
|
|
);
|
|
|
|
}
|
2020-07-09 07:58:21 +00:00
|
|
|
if let Err(e) = block_on(self.participant.take().unwrap().disconnect()) {
|
|
|
|
warn!(?e, "error when disconnecting, couldn't send all data");
|
|
|
|
}
|
2020-07-01 09:51:37 +00:00
|
|
|
}
|
2019-01-02 17:23:31 +00:00
|
|
|
}
|