veloren/server/src/sys/msg/in_game.rs

402 lines
17 KiB
Rust
Raw Normal View History

#[cfg(feature = "persistent_world")]
use crate::TerrainPersistence;
use crate::{client::Client, presence::Presence, Settings};
use common::{
comp::{
2021-11-11 22:55:14 +00:00
Admin, CanBuild, ControlEvent, Controller, ForceUpdate, Health, Ori, Player, Pos, SkillSet,
Vel,
},
event::{EventBus, ServerEvent},
2022-01-17 09:47:29 +00:00
link::Is,
mounting::Rider,
resources::PlayerPhysicsSettings,
terrain::TerrainGrid,
vol::ReadVol,
};
use common_ecs::{Job, Origin, Phase, System};
use common_net::msg::{ClientGeneral, PresenceKind, ServerGeneral};
2021-04-06 15:47:03 +00:00
use common_state::{BlockChange, BuildAreas};
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, Write, WriteStorage};
2021-04-14 21:55:19 +00:00
use tracing::{debug, trace, warn};
2021-04-30 13:06:07 +00:00
use vek::*;
#[cfg(feature = "persistent_world")]
pub type TerrainPersistenceData<'a> = Option<Write<'a, TerrainPersistence>>;
#[cfg(not(feature = "persistent_world"))]
pub type TerrainPersistenceData<'a> = ();
impl Sys {
#[allow(clippy::too_many_arguments)]
fn handle_client_in_game_msg(
server_emitter: &mut common::event::Emitter<'_, ServerEvent>,
entity: specs::Entity,
client: &Client,
maybe_presence: &mut Option<&mut Presence>,
terrain: &ReadExpect<'_, TerrainGrid>,
can_build: &ReadStorage<'_, CanBuild>,
2022-01-17 09:47:29 +00:00
is_rider: &ReadStorage<'_, Is<Rider>>,
force_updates: &ReadStorage<'_, ForceUpdate>,
skill_sets: &mut WriteStorage<'_, SkillSet>,
healths: &ReadStorage<'_, Health>,
block_changes: &mut Write<'_, BlockChange>,
positions: &mut WriteStorage<'_, Pos>,
velocities: &mut WriteStorage<'_, Vel>,
orientations: &mut WriteStorage<'_, Ori>,
controllers: &mut WriteStorage<'_, Controller>,
settings: &Read<'_, Settings>,
build_areas: &Read<'_, BuildAreas>,
player_physics_settings: &mut Write<'_, PlayerPhysicsSettings>,
_terrain_persistence: &mut TerrainPersistenceData<'_>,
maybe_player: &Option<&Player>,
maybe_admin: &Option<&Admin>,
msg: ClientGeneral,
) -> Result<(), crate::error::Error> {
let presence = match maybe_presence {
Some(g) => g,
None => {
debug!(?entity, "client is not in_game, ignoring msg");
trace!(?msg, "ignored msg content");
return Ok(());
},
};
match msg {
// Go back to registered state (char selection screen)
ClientGeneral::ExitInGame => {
server_emitter.emit(ServerEvent::ExitIngame { entity });
client.send(ServerGeneral::ExitInGameSuccess)?;
*maybe_presence = None;
},
ClientGeneral::SetViewDistance(view_distance) => {
presence.view_distance = settings
.max_view_distance
.map(|max| view_distance.min(max))
.unwrap_or(view_distance);
//correct client if its VD is to high
if settings
.max_view_distance
.map(|max| view_distance > max)
.unwrap_or(false)
{
client.send(ServerGeneral::SetViewDistance(
settings.max_view_distance.unwrap_or(0),
))?;
}
},
ClientGeneral::ControllerInputs(inputs) => {
if matches!(presence.kind, PresenceKind::Character(_)) {
if let Some(controller) = controllers.get_mut(entity) {
controller.inputs.update_with_new(*inputs);
}
}
},
ClientGeneral::ControlEvent(event) => {
if matches!(presence.kind, PresenceKind::Character(_)) {
// Skip respawn if client entity is alive
if let ControlEvent::Respawn = event {
if healths.get(entity).map_or(true, |h| !h.is_dead) {
//Todo: comment why return!
return Ok(());
}
}
if let Some(controller) = controllers.get_mut(entity) {
controller.push_event(event);
}
}
},
ClientGeneral::ControlAction(event) => {
if matches!(presence.kind, PresenceKind::Character(_)) {
if let Some(controller) = controllers.get_mut(entity) {
2022-01-26 18:52:19 +00:00
controller.push_action(event);
}
}
},
ClientGeneral::PlayerPhysics { pos, vel, ori } => {
2021-04-15 18:24:20 +00:00
let player_physics_setting = maybe_player.map(|p| {
player_physics_settings
.settings
.entry(p.uuid())
.or_default()
});
if matches!(presence.kind, PresenceKind::Character(_))
&& force_updates.get(entity).is_none()
&& healths.get(entity).map_or(true, |h| !h.is_dead)
2022-01-17 09:47:29 +00:00
&& is_rider.get(entity).is_none()
2021-04-14 21:55:19 +00:00
&& player_physics_setting
.as_ref()
.map_or(true, |s| s.client_authoritative())
{
2021-04-30 13:06:07 +00:00
enum Rejection {
TooFar { old: Vec3<f32>, new: Vec3<f32> },
TooFast { vel: Vec3<f32> },
}
let rejection = if maybe_admin.is_some() {
None
} else if let Some(mut setting) = player_physics_setting {
2021-04-14 21:55:19 +00:00
// If we detect any thresholds being exceeded, force server-authoritative
// physics for that player. This doesn't detect subtle hacks, but it
// prevents blatant ones and forces people to not debug physics hacks on the
2021-04-14 21:55:19 +00:00
// live server (and also mitigates some floating-point overflow crashes)
2021-04-30 13:06:07 +00:00
let rejection = None
// Check position
.or_else(|| {
if let Some(prev_pos) = positions.get(entity) {
if prev_pos.0.distance_squared(pos.0) > (500.0f32).powf(2.0) {
Some(Rejection::TooFar { old: prev_pos.0, new: pos.0 })
} else {
None
}
} else {
None
}
})
// Check velocity
.or_else(|| {
if vel.0.magnitude_squared() > (500.0f32).powf(2.0) {
Some(Rejection::TooFast { vel: vel.0 })
} else {
None
}
});
2021-04-14 21:55:19 +00:00
2021-04-30 13:06:07 +00:00
// Force a client-side physics update if rejectable physics data is
// received.
if rejection.is_some() {
// We skip this for `TooFar` because false positives can occur when
// using server-side teleportation commands
// that the client doesn't know about (leading to the client sending
// physics state that disagree with the server). In the future,
// client-authoritative physics will be gone
// and this will no longer be necessary.
setting.server_force =
!matches!(rejection, Some(Rejection::TooFar { .. })); // true;
2021-04-14 21:55:19 +00:00
}
2021-04-30 13:06:07 +00:00
rejection
2021-04-14 21:55:19 +00:00
} else {
2021-04-30 13:06:07 +00:00
None
};
match rejection {
Some(Rejection::TooFar { old, new }) => warn!(
"Rejected player physics update (new position {:?} is too far from \
old position {:?})",
new, old
),
Some(Rejection::TooFast { vel }) => warn!(
"Rejected player physics update (new velocity {:?} is too fast)",
vel
),
None => {
// Don't insert unless the component already exists
let _ = positions.get_mut(entity).map(|p| *p = pos);
let _ = velocities.get_mut(entity).map(|v| *v = vel);
let _ = orientations.get_mut(entity).map(|o| *o = ori);
},
2021-04-14 21:55:19 +00:00
}
}
},
ClientGeneral::BreakBlock(pos) => {
if let Some(comp_can_build) = can_build.get(entity) {
if comp_can_build.enabled {
for area in comp_can_build.build_areas.iter() {
2021-07-23 12:04:16 +00:00
if let Some(old_block) = build_areas
.areas()
.get(*area)
// TODO: Make this an exclusive check on the upper bound of the AABB
// Vek defaults to inclusive which is not optimal
.filter(|aabb| aabb.contains_point(pos))
.and_then(|_| terrain.get(pos).ok())
{
2021-07-23 12:04:16 +00:00
let new_block = old_block.into_vacant();
let _was_set = block_changes.try_set(pos, new_block).is_some();
#[cfg(feature = "persistent_world")]
if _was_set {
if let Some(terrain_persistence) = _terrain_persistence.as_mut()
2021-07-23 12:04:16 +00:00
{
terrain_persistence.set_block(pos, new_block);
}
}
}
}
}
}
},
2021-07-23 12:04:16 +00:00
ClientGeneral::PlaceBlock(pos, new_block) => {
if let Some(comp_can_build) = can_build.get(entity) {
if comp_can_build.enabled {
for area in comp_can_build.build_areas.iter() {
if build_areas
.areas()
.get(*area)
// TODO: Make this an exclusive check on the upper bound of the AABB
// Vek defaults to inclusive which is not optimal
.filter(|aabb| aabb.contains_point(pos))
.is_some()
{
let _was_set = block_changes.try_set(pos, new_block).is_some();
#[cfg(feature = "persistent_world")]
if _was_set {
if let Some(terrain_persistence) = _terrain_persistence.as_mut()
2021-07-23 12:04:16 +00:00
{
terrain_persistence.set_block(pos, new_block);
}
}
}
}
}
}
},
ClientGeneral::UnlockSkill(skill) => {
skill_sets
.get_mut(entity)
.map(|mut skill_set| skill_set.unlock_skill(skill));
},
ClientGeneral::UnlockSkillGroup(skill_group_kind) => {
skill_sets
.get_mut(entity)
.map(|mut skill_set| skill_set.unlock_skill_group(skill_group_kind));
},
Implement /price_list (work in progress), stub for /buy and /sell remove outdated economic simulation code remove old values, document add natural resources to economy Remove NaturalResources from Place (now in Economy) find closest site to each chunk implement natural resources (the distance scale is wrong) cargo fmt working distance calculation this collection of natural resources seem to make sense, too much Wheat though use natural resources and controlled area to replenish goods increase the amount of chunks controlled by one guard to 50 add new professions and goods to the list implement multiple products per worker remove the old code and rename the new code to the previous name correctly determine which goods guards will give you access to correctly estimate the amount of natural resources controlled adapt to new server API instrument tooltips Now I just need to figure out how to store a (reference to) a closure closures for tooltip content generation pass site/cave id to the client Add economic information to the client structure (not yet exchanged with the server) Send SiteId to the client, prepare messages for economy request Make client::sites a HashMap Specialize the Crafter into Brewer,Bladesmith and Blacksmith working server request for economic info from within tooltip fully operational economic tooltips I need to fix the id clash between caves and towns though fix overlapping ids between caves and sites display stock amount correctly handle invalid (cave) ids in the request some initial balancing, turn off most info logging less intrusive way of implementing the dynamic tool tips in map further tooltip cleanup further cleanup, dynamic tooltip not fully working as intended correctly working tooltip visibility logic cleanup, display labor value separate economy info request in a separate translation unit display values as well nicer display format for economy add last_exports and coin to the new economy do not allocate natural resources to Dungeons (making town so much larger) balancing attempt print town size statistics cargo fmt (dead code) resource tweaks, csv debugging output a more interesting town (and then all sites) fix the labor value logic (now we have meaningful prices) load professions from ron (WIP) use assets manager in economy loading professions works use professions from ron file fix Labor debug logic count chunks per type separately (preparing for better resource control) better structured resource data traders, more professions (WIP) fix exception when starting the simulation fix replenish function TODO: - use area_ratio for resource usage (chunks should be added to stock, ratio on usage?) - fix trading documentation clean up fix merge artifact Revise trader mechanic start Coin with a reasonable default remove the outdated economy code preserve documentation from removed old structure output neighboring sites (preparation) pass list of neighbors to economy add trade structures trading stub Description of purpose by zesterer on Discord remember prices (needed for planning) avoid growing the order vector unboundedly into_iter doesn't clear the Vec, so clear it manually use drain to process Vecs, avoid clone fix the test server implement a test stub (I need to get it faster than 30 seconds to be more useful) enable info output in test debug missing and extra goods use the same logging extension as water, activate feature update dependencies determine good prices, good exchange goods a working set of revisions a cozy world which economy tests in 2s first order planning version fun with package version buy according to value/priority, not missing amount introduce min price constant, fix order priority in depth debugging with a correct sign the trading plans start to make sense move the trade planning to a separate function rename new function reorganize code into subroutines (much cleaner) each trading step now has its own function cut down the number of debugging output introduce RoadSecurity and Transportation transport capacity bookkeeping only plan to pay with valuable goods, you can no longer stockpile unused options (which interestingly shows a huge impact, to be investigated) Coin is now listed as a payment (although not used) proper transportation estimation (although 0) remove more left overs uncovered by viewing the code in a merge request use the old default values, handle non-pileable stocks directly before increasing it (as economy is based on last year's products) don't order the missing good multiple times also it uses coin to buy things! fix warnings and use the transportation from stock again cargo fmt prepare evaluation of trade don't count transportation multiple times fix merge artifact operational trade planning trade itself is still misleading make clippy happy clean up correct labor ratio of merchants (no need to multiply with amount produced) incomplete merchant labor_value computation correct last commit make economy of scale more explicit make clippy happy (and code cleaner) more merchant tweaks (more pop=better) beginning of real trading code revert the update of dependencies remove stale comments/unused code trading implementation complete (but untested) something is still strange ... fix sign in trading another sign fix some bugfixes and plenty of debugging code another bug fixed, more to go fix another invariant (rounding will lead to very small negative value) introduce Terrain and Territory fix merge mistakes
2021-03-14 03:18:32 +00:00
ClientGeneral::RequestSiteInfo(id) => {
server_emitter.emit(ServerEvent::RequestSiteInfo { entity, id });
},
ClientGeneral::RequestPlayerPhysics {
server_authoritative,
} => {
2021-04-15 18:24:20 +00:00
let player_physics_setting = maybe_player.map(|p| {
player_physics_settings
.settings
.entry(p.uuid())
.or_default()
});
if let Some(setting) = player_physics_setting {
setting.client_optin = server_authoritative;
}
},
ClientGeneral::RequestLossyTerrainCompression {
lossy_terrain_compression,
} => {
presence.lossy_terrain_compression = lossy_terrain_compression;
},
ClientGeneral::AcknowledgePersistenceLoadError => {
skill_sets
.get_mut(entity)
.map(|mut skill_set| skill_set.persistence_load_error = None);
},
ClientGeneral::RequestCharacterList
| ClientGeneral::CreateCharacter { .. }
2021-12-13 00:13:33 +00:00
| ClientGeneral::EditCharacter { .. }
| ClientGeneral::DeleteCharacter(_)
| ClientGeneral::Character(_)
| ClientGeneral::Spectate
| ClientGeneral::TerrainChunkRequest { .. }
| ClientGeneral::ChatMsg(_)
| ClientGeneral::Command(..)
| ClientGeneral::Terminate => tracing::error!("not a client_in_game msg"),
}
Ok(())
}
}
/// This system will handle new messages from clients
#[derive(Default)]
pub struct Sys;
2021-03-08 11:13:59 +00:00
impl<'a> System<'a> for Sys {
#[allow(clippy::type_complexity)]
type SystemData = (
Entities<'a>,
Read<'a, EventBus<ServerEvent>>,
ReadExpect<'a, TerrainGrid>,
ReadStorage<'a, CanBuild>,
ReadStorage<'a, ForceUpdate>,
2022-01-17 09:47:29 +00:00
ReadStorage<'a, Is<Rider>>,
WriteStorage<'a, SkillSet>,
ReadStorage<'a, Health>,
Write<'a, BlockChange>,
WriteStorage<'a, Pos>,
WriteStorage<'a, Vel>,
WriteStorage<'a, Ori>,
WriteStorage<'a, Presence>,
WriteStorage<'a, Client>,
WriteStorage<'a, Controller>,
Read<'a, Settings>,
Read<'a, BuildAreas>,
Write<'a, PlayerPhysicsSettings>,
TerrainPersistenceData<'a>,
ReadStorage<'a, Player>,
ReadStorage<'a, Admin>,
);
const NAME: &'static str = "msg::in_game";
const ORIGIN: Origin = Origin::Server;
const PHASE: Phase = Phase::Create;
fn run(
2021-03-08 11:13:59 +00:00
_job: &mut Job<Self>,
(
entities,
server_event_bus,
terrain,
can_build,
force_updates,
2022-01-17 09:47:29 +00:00
is_rider,
mut skill_sets,
healths,
mut block_changes,
mut positions,
mut velocities,
mut orientations,
mut presences,
mut clients,
mut controllers,
settings,
build_areas,
mut player_physics_settings,
2021-07-23 12:04:16 +00:00
mut terrain_persistence,
players,
admins,
): Self::SystemData,
) {
let mut server_emitter = server_event_bus.emitter();
for (entity, client, mut maybe_presence, player, maybe_admin) in (
&entities,
&mut clients,
(&mut presences).maybe(),
players.maybe(),
admins.maybe(),
)
.join()
{
let _ = super::try_recv_all(client, 2, |client, msg| {
Self::handle_client_in_game_msg(
&mut server_emitter,
entity,
client,
&mut maybe_presence.as_deref_mut(),
&terrain,
&can_build,
2022-01-17 09:47:29 +00:00
&is_rider,
&force_updates,
&mut skill_sets,
&healths,
&mut block_changes,
&mut positions,
&mut velocities,
&mut orientations,
&mut controllers,
&settings,
&build_areas,
&mut player_physics_settings,
2021-07-23 12:04:16 +00:00
&mut terrain_persistence,
&player,
&maybe_admin,
msg,
)
});
}
}
}