mirror of
https://gitlab.com/veloren/veloren.git
synced 2024-08-30 18:12:32 +00:00
Remove unnecessarily qualified paths
This commit is contained in:
parent
61573a7800
commit
5e5698249b
@ -55,7 +55,7 @@ pub(crate) async fn try_connect<F>(
|
|||||||
f: F,
|
f: F,
|
||||||
) -> Result<network::Participant, crate::error::Error>
|
) -> Result<network::Participant, crate::error::Error>
|
||||||
where
|
where
|
||||||
F: Fn(std::net::SocketAddr) -> network::ConnectAddr,
|
F: Fn(SocketAddr) -> network::ConnectAddr,
|
||||||
{
|
{
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
let mut participant = None;
|
let mut participant = None;
|
||||||
@ -77,7 +77,7 @@ where
|
|||||||
fn sort_ipv6(s: impl Iterator<Item = SocketAddr>, prefer_ipv6: bool) -> Vec<SocketAddr> {
|
fn sort_ipv6(s: impl Iterator<Item = SocketAddr>, prefer_ipv6: bool) -> Vec<SocketAddr> {
|
||||||
let (mut first_addrs, mut second_addrs) =
|
let (mut first_addrs, mut second_addrs) =
|
||||||
s.partition::<Vec<_>, _>(|a| a.is_ipv6() == prefer_ipv6);
|
s.partition::<Vec<_>, _>(|a| a.is_ipv6() == prefer_ipv6);
|
||||||
std::iter::Iterator::chain(first_addrs.drain(..), second_addrs.drain(..)).collect::<Vec<_>>()
|
Iterator::chain(first_addrs.drain(..), second_addrs.drain(..)).collect::<Vec<_>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
@ -183,7 +183,7 @@ impl BotClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_default_body() -> Body {
|
fn create_default_body() -> Body {
|
||||||
comp::body::humanoid::Body {
|
Body {
|
||||||
species: comp::body::humanoid::Species::Human,
|
species: comp::body::humanoid::Species::Human,
|
||||||
body_type: comp::body::humanoid::BodyType::Male,
|
body_type: comp::body::humanoid::BodyType::Male,
|
||||||
hair_style: 0,
|
hair_style: 0,
|
||||||
@ -208,14 +208,14 @@ impl BotClient {
|
|||||||
let client = match self.bot_clients.get_mut(&cred.username) {
|
let client = match self.bot_clients.get_mut(&cred.username) {
|
||||||
Some(c) => c,
|
Some(c) => c,
|
||||||
None => {
|
None => {
|
||||||
tracing::trace!(?cred.username, "skip not logged in client");
|
trace!(?cred.username, "skip not logged in client");
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let list = client.character_list();
|
let list = client.character_list();
|
||||||
if list.loading || list.characters.is_empty() {
|
if list.loading || list.characters.is_empty() {
|
||||||
tracing::trace!(?cred.username, "skip client as it has no character");
|
trace!(?cred.username, "skip client as it has no character");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -36,7 +36,7 @@ impl Settings {
|
|||||||
let mut new_path = path.to_owned();
|
let mut new_path = path.to_owned();
|
||||||
new_path.pop();
|
new_path.pop();
|
||||||
new_path.push("settings.invalid.ron");
|
new_path.push("settings.invalid.ron");
|
||||||
if let Err(e) = std::fs::rename(&path, &new_path) {
|
if let Err(e) = fs::rename(&path, &new_path) {
|
||||||
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
|
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -217,8 +217,8 @@ fn run_client(
|
|||||||
let entity = client.entity();
|
let entity = client.entity();
|
||||||
// Move or stay still depending on specified options
|
// Move or stay still depending on specified options
|
||||||
// TODO: make sure server cheat protections aren't triggering
|
// TODO: make sure server cheat protections aren't triggering
|
||||||
let pos = common::comp::Pos(position(index, opt) + world_center);
|
let pos = comp::Pos(position(index, opt) + world_center);
|
||||||
let vel = common::comp::Vel(Default::default());
|
let vel = comp::Vel(Default::default());
|
||||||
client
|
client
|
||||||
.state_mut()
|
.state_mut()
|
||||||
.write_component_ignore_entity_dead(entity, pos);
|
.write_component_ignore_entity_dead(entity, pos);
|
||||||
|
@ -321,7 +321,7 @@ impl Client {
|
|||||||
ping_stream.send(PingMsg::Ping)?;
|
ping_stream.send(PingMsg::Ping)?;
|
||||||
|
|
||||||
// Wait for initial sync
|
// Wait for initial sync
|
||||||
let mut ping_interval = tokio::time::interval(core::time::Duration::from_secs(1));
|
let mut ping_interval = tokio::time::interval(Duration::from_secs(1));
|
||||||
let (
|
let (
|
||||||
state,
|
state,
|
||||||
lod_base,
|
lod_base,
|
||||||
@ -601,7 +601,7 @@ impl Client {
|
|||||||
let mut raw = vec![0u8; 4 * world_map_rgba.len()];
|
let mut raw = vec![0u8; 4 * world_map_rgba.len()];
|
||||||
LittleEndian::write_u32_into(rgb, &mut raw);
|
LittleEndian::write_u32_into(rgb, &mut raw);
|
||||||
Ok(Arc::new(
|
Ok(Arc::new(
|
||||||
image::DynamicImage::ImageRgba8({
|
DynamicImage::ImageRgba8({
|
||||||
// Should not fail if the dimensions are correct.
|
// Should not fail if the dimensions are correct.
|
||||||
let map =
|
let map =
|
||||||
image::ImageBuffer::from_raw(u32::from(map_size.x), u32::from(map_size.y), raw);
|
image::ImageBuffer::from_raw(u32::from(map_size.x), u32::from(map_size.y), raw);
|
||||||
@ -991,7 +991,7 @@ impl Client {
|
|||||||
.map_or(false, |cs| matches!(cs, CharacterState::Glide(_)))
|
.map_or(false, |cs| matches!(cs, CharacterState::Glide(_)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn split_swap_slots(&mut self, a: comp::slot::Slot, b: comp::slot::Slot) {
|
pub fn split_swap_slots(&mut self, a: Slot, b: Slot) {
|
||||||
match (a, b) {
|
match (a, b) {
|
||||||
(Slot::Equip(equip), slot) | (slot, Slot::Equip(equip)) => self.control_action(
|
(Slot::Equip(equip), slot) | (slot, Slot::Equip(equip)) => self.control_action(
|
||||||
ControlAction::InventoryAction(InventoryAction::Swap(equip, slot)),
|
ControlAction::InventoryAction(InventoryAction::Swap(equip, slot)),
|
||||||
@ -1004,7 +1004,7 @@ impl Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn split_drop_slot(&mut self, slot: comp::slot::Slot) {
|
pub fn split_drop_slot(&mut self, slot: Slot) {
|
||||||
match slot {
|
match slot {
|
||||||
Slot::Equip(equip) => {
|
Slot::Equip(equip) => {
|
||||||
self.control_action(ControlAction::InventoryAction(InventoryAction::Drop(equip)))
|
self.control_action(ControlAction::InventoryAction(InventoryAction::Drop(equip)))
|
||||||
@ -1238,9 +1238,7 @@ impl Client {
|
|||||||
|
|
||||||
pub fn max_group_size(&self) -> u32 { self.max_group_size }
|
pub fn max_group_size(&self) -> u32 { self.max_group_size }
|
||||||
|
|
||||||
pub fn invite(&self) -> Option<(Uid, std::time::Instant, std::time::Duration, InviteKind)> {
|
pub fn invite(&self) -> Option<(Uid, Instant, Duration, InviteKind)> { self.invite }
|
||||||
self.invite
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn group_info(&self) -> Option<(String, Uid)> {
|
pub fn group_info(&self) -> Option<(String, Uid)> {
|
||||||
self.group_leader.map(|l| ("Group".into(), l)) // TODO
|
self.group_leader.map(|l| ("Group".into(), l)) // TODO
|
||||||
@ -1529,7 +1527,7 @@ impl Client {
|
|||||||
pub fn send_chat(&mut self, message: String) {
|
pub fn send_chat(&mut self, message: String) {
|
||||||
match validate_chat_msg(&message) {
|
match validate_chat_msg(&message) {
|
||||||
Ok(()) => self.send_msg(ClientGeneral::ChatMsg(message)),
|
Ok(()) => self.send_msg(ClientGeneral::ChatMsg(message)),
|
||||||
Err(ChatMsgValidationError::TooLong) => tracing::warn!(
|
Err(ChatMsgValidationError::TooLong) => warn!(
|
||||||
"Attempted to send a message that's too long (Over {} bytes)",
|
"Attempted to send a message that's too long (Over {} bytes)",
|
||||||
MAX_BYTES_CHAT_MSG
|
MAX_BYTES_CHAT_MSG
|
||||||
),
|
),
|
||||||
@ -1568,7 +1566,7 @@ impl Client {
|
|||||||
.map_or((None, None), |inv| {
|
.map_or((None, None), |inv| {
|
||||||
let tool_kind = |slot| {
|
let tool_kind = |slot| {
|
||||||
inv.equipped(slot).and_then(|item| match &*item.kind() {
|
inv.equipped(slot).and_then(|item| match &*item.kind() {
|
||||||
comp::item::ItemKind::Tool(tool) => Some(tool.kind),
|
ItemKind::Tool(tool) => Some(tool.kind),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
@ -2013,7 +2011,7 @@ impl Client {
|
|||||||
},
|
},
|
||||||
ServerGeneral::SetPlayerEntity(uid) => {
|
ServerGeneral::SetPlayerEntity(uid) => {
|
||||||
if let Some(entity) = self.state.ecs().entity_from_uid(uid.0) {
|
if let Some(entity) = self.state.ecs().entity_from_uid(uid.0) {
|
||||||
let old_player_entity = core::mem::replace(
|
let old_player_entity = mem::replace(
|
||||||
&mut *self.state.ecs_mut().write_resource(),
|
&mut *self.state.ecs_mut().write_resource(),
|
||||||
PlayerEntity(Some(entity)),
|
PlayerEntity(Some(entity)),
|
||||||
);
|
);
|
||||||
@ -2161,7 +2159,7 @@ impl Client {
|
|||||||
timeout,
|
timeout,
|
||||||
kind,
|
kind,
|
||||||
} => {
|
} => {
|
||||||
self.invite = Some((inviter, std::time::Instant::now(), timeout, kind));
|
self.invite = Some((inviter, Instant::now(), timeout, kind));
|
||||||
},
|
},
|
||||||
ServerGeneral::InvitePending(uid) => {
|
ServerGeneral::InvitePending(uid) => {
|
||||||
if !self.pending_invites.insert(uid) {
|
if !self.pending_invites.insert(uid) {
|
||||||
@ -2236,7 +2234,7 @@ impl Client {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
ServerGeneral::UpdatePendingTrade(id, trade, pricing) => {
|
ServerGeneral::UpdatePendingTrade(id, trade, pricing) => {
|
||||||
tracing::trace!("UpdatePendingTrade {:?} {:?}", id, trade);
|
trace!("UpdatePendingTrade {:?} {:?}", id, trade);
|
||||||
self.pending_trade = Some((id, trade, pricing));
|
self.pending_trade = Some((id, trade, pricing));
|
||||||
},
|
},
|
||||||
ServerGeneral::FinishedTrade(result) => {
|
ServerGeneral::FinishedTrade(result) => {
|
||||||
@ -2871,7 +2869,7 @@ mod tests {
|
|||||||
|
|
||||||
//tick
|
//tick
|
||||||
let events_result: Result<Vec<Event>, Error> =
|
let events_result: Result<Vec<Event>, Error> =
|
||||||
client.tick(comp::ControllerInputs::default(), clock.dt(), |_| {});
|
client.tick(ControllerInputs::default(), clock.dt(), |_| {});
|
||||||
|
|
||||||
//chat functionality
|
//chat functionality
|
||||||
client.send_chat("foobar".to_string());
|
client.send_chat("foobar".to_string());
|
||||||
@ -2886,11 +2884,11 @@ mod tests {
|
|||||||
},
|
},
|
||||||
Event::Disconnect => {},
|
Event::Disconnect => {},
|
||||||
Event::DisconnectionNotification(_) => {
|
Event::DisconnectionNotification(_) => {
|
||||||
tracing::debug!("Will be disconnected soon! :/")
|
debug!("Will be disconnected soon! :/")
|
||||||
},
|
},
|
||||||
Event::Notification(notification) => {
|
Event::Notification(notification) => {
|
||||||
let notification: Notification = notification;
|
let notification: Notification = notification;
|
||||||
tracing::debug!("Notification: {:?}", notification);
|
debug!("Notification: {:?}", notification);
|
||||||
},
|
},
|
||||||
_ => {},
|
_ => {},
|
||||||
}
|
}
|
||||||
|
@ -179,7 +179,7 @@ pub struct DotVoxAsset(pub DotVoxData);
|
|||||||
|
|
||||||
pub struct DotVoxLoader;
|
pub struct DotVoxLoader;
|
||||||
impl Loader<DotVoxAsset> for DotVoxLoader {
|
impl Loader<DotVoxAsset> for DotVoxLoader {
|
||||||
fn load(content: std::borrow::Cow<[u8]>, _: &str) -> Result<DotVoxAsset, BoxedError> {
|
fn load(content: Cow<[u8]>, _: &str) -> Result<DotVoxAsset, BoxedError> {
|
||||||
let data = dot_vox::load_bytes(&content).map_err(|err| err.to_owned())?;
|
let data = dot_vox::load_bytes(&content).map_err(|err| err.to_owned())?;
|
||||||
Ok(DotVoxAsset(data))
|
Ok(DotVoxAsset(data))
|
||||||
}
|
}
|
||||||
@ -201,7 +201,7 @@ impl Asset for ObjAsset {
|
|||||||
|
|
||||||
pub struct ObjAssetLoader;
|
pub struct ObjAssetLoader;
|
||||||
impl Loader<ObjAsset> for ObjAssetLoader {
|
impl Loader<ObjAsset> for ObjAssetLoader {
|
||||||
fn load(content: std::borrow::Cow<[u8]>, _: &str) -> Result<ObjAsset, BoxedError> {
|
fn load(content: Cow<[u8]>, _: &str) -> Result<ObjAsset, BoxedError> {
|
||||||
let data = wavefront::Obj::from_reader(&*content)?;
|
let data = wavefront::Obj::from_reader(&*content)?;
|
||||||
Ok(ObjAsset(data))
|
Ok(ObjAsset(data))
|
||||||
}
|
}
|
||||||
@ -407,7 +407,7 @@ pub mod asset_tweak {
|
|||||||
/// assert_eq!(y1, 10);
|
/// assert_eq!(y1, 10);
|
||||||
///
|
///
|
||||||
/// // you may want to remove this file later
|
/// // you may want to remove this file later
|
||||||
/// std::fs::remove_file(tweak_path);
|
/// fs::remove_file(tweak_path);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn tweak_expect<T>(specifier: Specifier) -> T
|
pub fn tweak_expect<T>(specifier: Specifier) -> T
|
||||||
where
|
where
|
||||||
|
@ -54,7 +54,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if git-lfs is working
|
// Check if git-lfs is working
|
||||||
if std::env::var("DISABLE_GIT_LFS_CHECK").is_err() && cfg!(not(feature = "no-assets")) {
|
if env::var("DISABLE_GIT_LFS_CHECK").is_err() && cfg!(not(feature = "no-assets")) {
|
||||||
let asset_path: PathBuf = ["..", "assets", "voxygen", "background", "bg_main.jpg"]
|
let asset_path: PathBuf = ["..", "assets", "voxygen", "background", "bg_main.jpg"]
|
||||||
.iter()
|
.iter()
|
||||||
.collect();
|
.collect();
|
||||||
|
@ -141,23 +141,23 @@ pub enum ServerGeneral {
|
|||||||
CharacterEdited(character::CharacterId),
|
CharacterEdited(character::CharacterId),
|
||||||
CharacterSuccess,
|
CharacterSuccess,
|
||||||
//Ingame related
|
//Ingame related
|
||||||
GroupUpdate(comp::group::ChangeNotification<sync::Uid>),
|
GroupUpdate(comp::group::ChangeNotification<Uid>),
|
||||||
/// Indicate to the client that they are invited to join a group
|
/// Indicate to the client that they are invited to join a group
|
||||||
Invite {
|
Invite {
|
||||||
inviter: sync::Uid,
|
inviter: Uid,
|
||||||
timeout: std::time::Duration,
|
timeout: Duration,
|
||||||
kind: InviteKind,
|
kind: InviteKind,
|
||||||
},
|
},
|
||||||
/// Indicate to the client that their sent invite was not invalid and is
|
/// Indicate to the client that their sent invite was not invalid and is
|
||||||
/// currently pending
|
/// currently pending
|
||||||
InvitePending(sync::Uid),
|
InvitePending(Uid),
|
||||||
/// Note: this could potentially include all the failure cases such as
|
/// Note: this could potentially include all the failure cases such as
|
||||||
/// inviting yourself in which case the `InvitePending` message could be
|
/// inviting yourself in which case the `InvitePending` message could be
|
||||||
/// removed and the client could consider their invite pending until
|
/// removed and the client could consider their invite pending until
|
||||||
/// they receive this message Indicate to the client the result of their
|
/// they receive this message Indicate to the client the result of their
|
||||||
/// invite
|
/// invite
|
||||||
InviteComplete {
|
InviteComplete {
|
||||||
target: sync::Uid,
|
target: Uid,
|
||||||
answer: InviteAnswer,
|
answer: InviteAnswer,
|
||||||
kind: InviteKind,
|
kind: InviteKind,
|
||||||
},
|
},
|
||||||
|
@ -56,7 +56,7 @@ impl WorldSyncExt for specs::World {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_entity_synced(&mut self) -> specs::EntityBuilder {
|
fn create_entity_synced(&mut self) -> specs::EntityBuilder {
|
||||||
self.create_entity().marked::<super::Uid>()
|
self.create_entity().marked::<Uid>()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn delete_entity_and_clear_from_uid_allocator(&mut self, uid: u64) {
|
fn delete_entity_and_clear_from_uid_allocator(&mut self, uid: u64) {
|
||||||
|
@ -33,7 +33,7 @@ where
|
|||||||
|
|
||||||
pub fn removed(&self) -> &BitSet { &self.removed }
|
pub fn removed(&self) -> &BitSet { &self.removed }
|
||||||
|
|
||||||
pub fn record_changes<'a>(&mut self, storage: &specs::ReadStorage<'a, C>) {
|
pub fn record_changes<'a>(&mut self, storage: &ReadStorage<'a, C>) {
|
||||||
self.inserted.clear();
|
self.inserted.clear();
|
||||||
self.modified.clear();
|
self.modified.clear();
|
||||||
self.removed.clear();
|
self.removed.clear();
|
||||||
@ -86,8 +86,8 @@ impl<C: Component + Clone + Send + Sync> UpdateTracker<C> {
|
|||||||
|
|
||||||
pub fn get_updates_for<'a, P>(
|
pub fn get_updates_for<'a, P>(
|
||||||
&self,
|
&self,
|
||||||
uids: &specs::ReadStorage<'a, Uid>,
|
uids: &ReadStorage<'a, Uid>,
|
||||||
storage: &specs::ReadStorage<'a, C>,
|
storage: &ReadStorage<'a, C>,
|
||||||
entity_filter: impl Join + Copy,
|
entity_filter: impl Join + Copy,
|
||||||
buf: &mut Vec<(u64, CompUpdateKind<P>)>,
|
buf: &mut Vec<(u64, CompUpdateKind<P>)>,
|
||||||
) where
|
) where
|
||||||
@ -127,7 +127,7 @@ impl<C: Component + Clone + Send + Sync> UpdateTracker<C> {
|
|||||||
/// entity.
|
/// entity.
|
||||||
pub fn get_update<'a, P>(
|
pub fn get_update<'a, P>(
|
||||||
&self,
|
&self,
|
||||||
storage: &specs::ReadStorage<'a, C>,
|
storage: &ReadStorage<'a, C>,
|
||||||
entity: Entity,
|
entity: Entity,
|
||||||
) -> Option<CompUpdateKind<P>>
|
) -> Option<CompUpdateKind<P>>
|
||||||
where
|
where
|
||||||
|
@ -50,7 +50,7 @@ fn walk_tree(dir: &Path, root: &Path) -> io::Result<Vec<Walk>> {
|
|||||||
Ok(buff)
|
Ok(buff)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk_with_migrate<OldV, NewV>(tree: Walk, from: &Path, to: &Path) -> std::io::Result<()>
|
fn walk_with_migrate<OldV, NewV>(tree: Walk, from: &Path, to: &Path) -> io::Result<()>
|
||||||
where
|
where
|
||||||
NewV: From<OldV>,
|
NewV: From<OldV>,
|
||||||
OldV: DeserializeOwned,
|
OldV: DeserializeOwned,
|
||||||
|
@ -46,7 +46,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
"Description",
|
"Description",
|
||||||
])?;
|
])?;
|
||||||
|
|
||||||
for item in comp::item::Item::new_from_asset_glob("common.items.armor.*")
|
for item in Item::new_from_asset_glob("common.items.armor.*")
|
||||||
.expect("Failed to iterate over item folders!")
|
.expect("Failed to iterate over item folders!")
|
||||||
{
|
{
|
||||||
match &*item.kind() {
|
match &*item.kind() {
|
||||||
@ -118,8 +118,8 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
// Does all items even outside weapon folder since we check if itemkind was a
|
// Does all items even outside weapon folder since we check if itemkind was a
|
||||||
// tool anyways
|
// tool anyways
|
||||||
let items: Vec<comp::Item> = comp::Item::new_from_asset_glob("common.items.*")
|
let items: Vec<Item> =
|
||||||
.expect("Failed to iterate over item folders!");
|
Item::new_from_asset_glob("common.items.*").expect("Failed to iterate over item folders!");
|
||||||
|
|
||||||
for item in items.iter() {
|
for item in items.iter() {
|
||||||
if let comp::item::ItemKind::Tool(tool) = &*item.kind() {
|
if let comp::item::ItemKind::Tool(tool) = &*item.kind() {
|
||||||
@ -207,8 +207,8 @@ fn all_items() -> Result<(), Box<dyn Error>> {
|
|||||||
let mut wtr = csv::Writer::from_path("items.csv")?;
|
let mut wtr = csv::Writer::from_path("items.csv")?;
|
||||||
wtr.write_record(&["Path", "Name"])?;
|
wtr.write_record(&["Path", "Name"])?;
|
||||||
|
|
||||||
for item in comp::item::Item::new_from_asset_glob("common.items.*")
|
for item in
|
||||||
.expect("Failed to iterate over item folders!")
|
Item::new_from_asset_glob("common.items.*").expect("Failed to iterate over item folders!")
|
||||||
{
|
{
|
||||||
wtr.write_record(&[
|
wtr.write_record(&[
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
@ -305,7 +305,7 @@ fn entity_drops(entity_config: &str) -> Result<(), Box<dyn Error>> {
|
|||||||
"Quantity",
|
"Quantity",
|
||||||
])?;
|
])?;
|
||||||
|
|
||||||
fn write_entity_loot<W: std::io::Write>(
|
fn write_entity_loot<W: Write>(
|
||||||
wtr: &mut csv::Writer<W>,
|
wtr: &mut csv::Writer<W>,
|
||||||
asset_path: &str,
|
asset_path: &str,
|
||||||
) -> Result<(), Box<dyn Error>> {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
@ -72,7 +72,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
.expect("Failed to iterate over item folders!")
|
.expect("Failed to iterate over item folders!")
|
||||||
{
|
{
|
||||||
match &*item.kind() {
|
match &*item.kind() {
|
||||||
comp::item::ItemKind::Armor(armor) => {
|
ItemKind::Armor(armor) => {
|
||||||
if let ArmorKind::Bag = armor.kind {
|
if let ArmorKind::Bag = armor.kind {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -190,20 +190,20 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
let quality = if let Some(quality_raw) = record.get(headers["Quality"])
|
let quality = if let Some(quality_raw) = record.get(headers["Quality"])
|
||||||
{
|
{
|
||||||
match quality_raw {
|
match quality_raw {
|
||||||
"Low" => comp::item::Quality::Low,
|
"Low" => Quality::Low,
|
||||||
"Common" => comp::item::Quality::Common,
|
"Common" => Quality::Common,
|
||||||
"Moderate" => comp::item::Quality::Moderate,
|
"Moderate" => Quality::Moderate,
|
||||||
"High" => comp::item::Quality::High,
|
"High" => Quality::High,
|
||||||
"Epic" => comp::item::Quality::Epic,
|
"Epic" => Quality::Epic,
|
||||||
"Legendary" => comp::item::Quality::Legendary,
|
"Legendary" => Quality::Legendary,
|
||||||
"Artifact" => comp::item::Quality::Artifact,
|
"Artifact" => Quality::Artifact,
|
||||||
"Debug" => comp::item::Quality::Debug,
|
"Debug" => Quality::Debug,
|
||||||
_ => {
|
_ => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Unknown quality variant for {:?}",
|
"Unknown quality variant for {:?}",
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
);
|
);
|
||||||
comp::item::Quality::Debug
|
Quality::Debug
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -211,7 +211,7 @@ fn armor_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
"Could not unwrap quality for {:?}",
|
"Could not unwrap quality for {:?}",
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
);
|
);
|
||||||
comp::item::Quality::Debug
|
Quality::Debug
|
||||||
};
|
};
|
||||||
|
|
||||||
let description = record
|
let description = record
|
||||||
@ -284,7 +284,7 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
.expect("Failed to iterate over item folders!");
|
.expect("Failed to iterate over item folders!");
|
||||||
|
|
||||||
for item in items.iter() {
|
for item in items.iter() {
|
||||||
if let comp::item::ItemKind::Tool(tool) = &*item.kind() {
|
if let ItemKind::Tool(tool) = &*item.kind() {
|
||||||
if let Ok(ref record) = record {
|
if let Ok(ref record) = record {
|
||||||
if item.item_definition_id()
|
if item.item_definition_id()
|
||||||
== ItemDefinitionId::Simple(
|
== ItemDefinitionId::Simple(
|
||||||
@ -328,19 +328,19 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
let hands = if let Some(hands_raw) = record.get(headers["Hands"]) {
|
let hands = if let Some(hands_raw) = record.get(headers["Hands"]) {
|
||||||
match hands_raw {
|
match hands_raw {
|
||||||
"One" | "1" | "1h" => comp::item::tool::Hands::One,
|
"One" | "1" | "1h" => Hands::One,
|
||||||
"Two" | "2" | "2h" => comp::item::tool::Hands::Two,
|
"Two" | "2" | "2h" => Hands::Two,
|
||||||
_ => {
|
_ => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Unknown hand variant for {:?}",
|
"Unknown hand variant for {:?}",
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
);
|
);
|
||||||
comp::item::tool::Hands::Two
|
Hands::Two
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!("Could not unwrap hand for {:?}", item.item_definition_id());
|
eprintln!("Could not unwrap hand for {:?}", item.item_definition_id());
|
||||||
comp::item::tool::Hands::Two
|
Hands::Two
|
||||||
};
|
};
|
||||||
|
|
||||||
let crit_chance: f32 = record
|
let crit_chance: f32 = record
|
||||||
@ -392,20 +392,20 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
let quality = if let Some(quality_raw) = record.get(headers["Quality"]) {
|
let quality = if let Some(quality_raw) = record.get(headers["Quality"]) {
|
||||||
match quality_raw {
|
match quality_raw {
|
||||||
"Low" => comp::item::Quality::Low,
|
"Low" => Quality::Low,
|
||||||
"Common" => comp::item::Quality::Common,
|
"Common" => Quality::Common,
|
||||||
"Moderate" => comp::item::Quality::Moderate,
|
"Moderate" => Quality::Moderate,
|
||||||
"High" => comp::item::Quality::High,
|
"High" => Quality::High,
|
||||||
"Epic" => comp::item::Quality::Epic,
|
"Epic" => Quality::Epic,
|
||||||
"Legendary" => comp::item::Quality::Legendary,
|
"Legendary" => Quality::Legendary,
|
||||||
"Artifact" => comp::item::Quality::Artifact,
|
"Artifact" => Quality::Artifact,
|
||||||
"Debug" => comp::item::Quality::Debug,
|
"Debug" => Quality::Debug,
|
||||||
_ => {
|
_ => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Unknown quality variant for {:?}",
|
"Unknown quality variant for {:?}",
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
);
|
);
|
||||||
comp::item::Quality::Debug
|
Quality::Debug
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -413,7 +413,7 @@ fn weapon_stats() -> Result<(), Box<dyn Error>> {
|
|||||||
"Could not unwrap quality for {:?}",
|
"Could not unwrap quality for {:?}",
|
||||||
item.item_definition_id()
|
item.item_definition_id()
|
||||||
);
|
);
|
||||||
comp::item::Quality::Debug
|
Quality::Debug
|
||||||
};
|
};
|
||||||
|
|
||||||
let description = record.get(headers["Description"]).expect(&format!(
|
let description = record.get(headers["Description"]).expect(&format!(
|
||||||
|
@ -804,7 +804,7 @@ impl ServerChatCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Produce an iterator over all the available commands
|
/// Produce an iterator over all the available commands
|
||||||
pub fn iter() -> impl Iterator<Item = Self> { <Self as strum::IntoEnumIterator>::iter() }
|
pub fn iter() -> impl Iterator<Item = Self> { <Self as IntoEnumIterator>::iter() }
|
||||||
|
|
||||||
/// A message that explains what the command does
|
/// A message that explains what the command does
|
||||||
pub fn help_string(&self) -> String {
|
pub fn help_string(&self) -> String {
|
||||||
|
@ -300,18 +300,14 @@ impl CharacterState {
|
|||||||
pub fn behavior(&self, j: &JoinData, output_events: &mut OutputEvents) -> StateUpdate {
|
pub fn behavior(&self, j: &JoinData, output_events: &mut OutputEvents) -> StateUpdate {
|
||||||
match &self {
|
match &self {
|
||||||
CharacterState::Idle(data) => data.behavior(j, output_events),
|
CharacterState::Idle(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Talk => states::talk::Data.behavior(j, output_events),
|
CharacterState::Talk => talk::Data.behavior(j, output_events),
|
||||||
CharacterState::Climb(data) => data.behavior(j, output_events),
|
CharacterState::Climb(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Wallrun(data) => data.behavior(j, output_events),
|
CharacterState::Wallrun(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Glide(data) => data.behavior(j, output_events),
|
CharacterState::Glide(data) => data.behavior(j, output_events),
|
||||||
CharacterState::GlideWield(data) => data.behavior(j, output_events),
|
CharacterState::GlideWield(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Stunned(data) => data.behavior(j, output_events),
|
CharacterState::Stunned(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Sit => {
|
CharacterState::Sit => sit::Data::behavior(&sit::Data, j, output_events),
|
||||||
states::sit::Data::behavior(&states::sit::Data, j, output_events)
|
CharacterState::Dance => dance::Data::behavior(&dance::Data, j, output_events),
|
||||||
},
|
|
||||||
CharacterState::Dance => {
|
|
||||||
states::dance::Data::behavior(&states::dance::Data, j, output_events)
|
|
||||||
},
|
|
||||||
CharacterState::BasicBlock(data) => data.behavior(j, output_events),
|
CharacterState::BasicBlock(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Roll(data) => data.behavior(j, output_events),
|
CharacterState::Roll(data) => data.behavior(j, output_events),
|
||||||
CharacterState::Wielding(data) => data.behavior(j, output_events),
|
CharacterState::Wielding(data) => data.behavior(j, output_events),
|
||||||
@ -347,17 +343,17 @@ impl CharacterState {
|
|||||||
) -> StateUpdate {
|
) -> StateUpdate {
|
||||||
match &self {
|
match &self {
|
||||||
CharacterState::Idle(data) => data.handle_event(j, output_events, action),
|
CharacterState::Idle(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Talk => states::talk::Data.handle_event(j, output_events, action),
|
CharacterState::Talk => talk::Data.handle_event(j, output_events, action),
|
||||||
CharacterState::Climb(data) => data.handle_event(j, output_events, action),
|
CharacterState::Climb(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Wallrun(data) => data.handle_event(j, output_events, action),
|
CharacterState::Wallrun(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Glide(data) => data.handle_event(j, output_events, action),
|
CharacterState::Glide(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::GlideWield(data) => data.handle_event(j, output_events, action),
|
CharacterState::GlideWield(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Stunned(data) => data.handle_event(j, output_events, action),
|
CharacterState::Stunned(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Sit => {
|
CharacterState::Sit => {
|
||||||
states::sit::Data::handle_event(&states::sit::Data, j, output_events, action)
|
states::sit::Data::handle_event(&sit::Data, j, output_events, action)
|
||||||
},
|
},
|
||||||
CharacterState::Dance => {
|
CharacterState::Dance => {
|
||||||
states::dance::Data::handle_event(&states::dance::Data, j, output_events, action)
|
states::dance::Data::handle_event(&dance::Data, j, output_events, action)
|
||||||
},
|
},
|
||||||
CharacterState::BasicBlock(data) => data.handle_event(j, output_events, action),
|
CharacterState::BasicBlock(data) => data.handle_event(j, output_events, action),
|
||||||
CharacterState::Roll(data) => data.handle_event(j, output_events, action),
|
CharacterState::Roll(data) => data.handle_event(j, output_events, action),
|
||||||
|
@ -263,8 +263,8 @@ impl TagExampleInfo for ItemTag {
|
|||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub enum ItemKind {
|
pub enum ItemKind {
|
||||||
/// Something wieldable
|
/// Something wieldable
|
||||||
Tool(tool::Tool),
|
Tool(Tool),
|
||||||
ModularComponent(modular::ModularComponent),
|
ModularComponent(ModularComponent),
|
||||||
Lantern(Lantern),
|
Lantern(Lantern),
|
||||||
Armor(armor::Armor),
|
Armor(armor::Armor),
|
||||||
Glider,
|
Glider,
|
||||||
@ -373,7 +373,7 @@ pub enum ItemName {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum ItemBase {
|
pub enum ItemBase {
|
||||||
Simple(Arc<ItemDef>),
|
Simple(Arc<ItemDef>),
|
||||||
Modular(modular::ModularBase),
|
Modular(ModularBase),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for ItemBase {
|
impl Serialize for ItemBase {
|
||||||
@ -1262,7 +1262,7 @@ mod tests {
|
|||||||
fn test_assets_items() {
|
fn test_assets_items() {
|
||||||
let ids = all_item_defs_expect();
|
let ids = all_item_defs_expect();
|
||||||
for item in ids.iter().map(|id| Item::new_from_asset_expect(id)) {
|
for item in ids.iter().map(|id| Item::new_from_asset_expect(id)) {
|
||||||
std::mem::drop(item)
|
drop(item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -41,8 +41,8 @@ impl MaterialStatManifest {
|
|||||||
/// needed for tests to load it without actual assets
|
/// needed for tests to load it without actual assets
|
||||||
pub fn with_empty() -> Self {
|
pub fn with_empty() -> Self {
|
||||||
Self {
|
Self {
|
||||||
tool_stats: hashbrown::HashMap::default(),
|
tool_stats: HashMap::default(),
|
||||||
armor_stats: hashbrown::HashMap::default(),
|
armor_stats: HashMap::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -84,7 +84,7 @@ impl ItemSpec {
|
|||||||
let mut rng = rand::thread_rng();
|
let mut rng = rand::thread_rng();
|
||||||
match self {
|
match self {
|
||||||
ItemSpec::Item(item_asset) => Item::new_from_asset(item_asset)
|
ItemSpec::Item(item_asset) => Item::new_from_asset(item_asset)
|
||||||
.map(std::mem::drop)
|
.map(drop)
|
||||||
.map_err(ValidationError::ItemAssetError),
|
.map_err(ValidationError::ItemAssetError),
|
||||||
ItemSpec::Choice(choices) => {
|
ItemSpec::Choice(choices) => {
|
||||||
// TODO: check for sanity of weigts?
|
// TODO: check for sanity of weigts?
|
||||||
@ -100,7 +100,7 @@ impl ItemSpec {
|
|||||||
material,
|
material,
|
||||||
hands,
|
hands,
|
||||||
} => item::modular::random_weapon(*tool, *material, *hands, &mut rng)
|
} => item::modular::random_weapon(*tool, *material, *hands, &mut rng)
|
||||||
.map(std::mem::drop)
|
.map(drop)
|
||||||
.map_err(ValidationError::ModularWeaponCreationError),
|
.map_err(ValidationError::ModularWeaponCreationError),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1219,7 +1219,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_loadout_presets() {
|
fn test_loadout_presets() {
|
||||||
for preset in Preset::iter() {
|
for preset in Preset::iter() {
|
||||||
std::mem::drop(LoadoutBuilder::empty().with_preset(preset));
|
drop(LoadoutBuilder::empty().with_preset(preset));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -269,7 +269,7 @@ impl Inventory {
|
|||||||
/// item or the same item again if that slot was not found.
|
/// item or the same item again if that slot was not found.
|
||||||
pub fn insert_at(&mut self, inv_slot_id: InvSlotId, item: Item) -> Result<Option<Item>, Item> {
|
pub fn insert_at(&mut self, inv_slot_id: InvSlotId, item: Item) -> Result<Option<Item>, Item> {
|
||||||
match self.slot_mut(inv_slot_id) {
|
match self.slot_mut(inv_slot_id) {
|
||||||
Some(slot) => Ok(core::mem::replace(slot, Some(item))),
|
Some(slot) => Ok(mem::replace(slot, Some(item))),
|
||||||
None => Err(item),
|
None => Err(item),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -319,7 +319,7 @@ impl Inventory {
|
|||||||
.err()
|
.err()
|
||||||
.and(Some(item))
|
.and(Some(item))
|
||||||
} else {
|
} else {
|
||||||
let old_item = core::mem::replace(slot_item, item);
|
let old_item = mem::replace(slot_item, item);
|
||||||
// No need to recount--we know the count is the same.
|
// No need to recount--we know the count is the same.
|
||||||
Some(old_item)
|
Some(old_item)
|
||||||
})
|
})
|
||||||
@ -808,8 +808,8 @@ impl Inventory {
|
|||||||
/// Used only when loading in persistence code.
|
/// Used only when loading in persistence code.
|
||||||
pub fn persistence_update_all_item_states(
|
pub fn persistence_update_all_item_states(
|
||||||
&mut self,
|
&mut self,
|
||||||
ability_map: &item::tool::AbilityMap,
|
ability_map: &AbilityMap,
|
||||||
msm: &item::MaterialStatManifest,
|
msm: &MaterialStatManifest,
|
||||||
) {
|
) {
|
||||||
self.slots_mut().for_each(|slot| {
|
self.slots_mut().for_each(|slot| {
|
||||||
if let Some(item) = slot {
|
if let Some(item) = slot {
|
||||||
|
@ -110,7 +110,7 @@ pub enum ArmorSlot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Slot {
|
impl Slot {
|
||||||
pub fn can_hold(self, item_kind: &item::ItemKind) -> bool {
|
pub fn can_hold(self, item_kind: &ItemKind) -> bool {
|
||||||
match (self, item_kind) {
|
match (self, item_kind) {
|
||||||
(Self::Inventory(_), _) => true,
|
(Self::Inventory(_), _) => true,
|
||||||
(Self::Equip(slot), item_kind) => slot.can_hold(item_kind),
|
(Self::Equip(slot), item_kind) => slot.can_hold(item_kind),
|
||||||
@ -119,7 +119,7 @@ impl Slot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EquipSlot {
|
impl EquipSlot {
|
||||||
pub fn can_hold(self, item_kind: &item::ItemKind) -> bool {
|
pub fn can_hold(self, item_kind: &ItemKind) -> bool {
|
||||||
match (self, item_kind) {
|
match (self, item_kind) {
|
||||||
(Self::Armor(slot), ItemKind::Armor(armor::Armor { kind, .. })) => slot.can_hold(kind),
|
(Self::Armor(slot), ItemKind::Armor(armor::Armor { kind, .. })) => slot.can_hold(kind),
|
||||||
(Self::ActiveMainhand, ItemKind::Tool(_)) => true,
|
(Self::ActiveMainhand, ItemKind::Tool(_)) => true,
|
||||||
@ -134,7 +134,7 @@ impl EquipSlot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ArmorSlot {
|
impl ArmorSlot {
|
||||||
fn can_hold(self, armor: &item::armor::ArmorKind) -> bool {
|
fn can_hold(self, armor: &ArmorKind) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
(self, armor),
|
(self, armor),
|
||||||
(Self::Head, ArmorKind::Head)
|
(Self::Head, ArmorKind::Head)
|
||||||
|
@ -519,12 +519,12 @@ fn get_scaling(contents: &AssetGuard<TradingPriceFile>, good: Good) -> f32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
impl std::cmp::PartialOrd for ItemDefinitionIdOwned {
|
impl PartialOrd for ItemDefinitionIdOwned {
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
impl std::cmp::Ord for ItemDefinitionIdOwned {
|
impl Ord for ItemDefinitionIdOwned {
|
||||||
fn cmp(&self, other: &Self) -> Ordering {
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
match self {
|
match self {
|
||||||
ItemDefinitionIdOwned::Simple(na) => match other {
|
ItemDefinitionIdOwned::Simple(na) => match other {
|
||||||
@ -781,7 +781,7 @@ impl TradePricing {
|
|||||||
for (_, recipe) in book.iter() {
|
for (_, recipe) in book.iter() {
|
||||||
let (ref asset_path, amount) = recipe.output;
|
let (ref asset_path, amount) = recipe.output;
|
||||||
if let ItemKind::ModularComponent(
|
if let ItemKind::ModularComponent(
|
||||||
crate::comp::inventory::item::modular::ModularComponent::ToolSecondaryComponent {
|
inventory::item::modular::ModularComponent::ToolSecondaryComponent {
|
||||||
toolkind,
|
toolkind,
|
||||||
stats: _,
|
stats: _,
|
||||||
hand_restriction: _,
|
hand_restriction: _,
|
||||||
|
@ -405,9 +405,7 @@ impl MeleeConstructor {
|
|||||||
if let Some(ref mut scaled) = &mut self.scaled {
|
if let Some(ref mut scaled) = &mut self.scaled {
|
||||||
*scaled = scaled.adjusted_by_stats(stats, regen);
|
*scaled = scaled.adjusted_by_stats(stats, regen);
|
||||||
}
|
}
|
||||||
if let Some(CombatEffect::Buff(combat::CombatBuff { strength, .. })) =
|
if let Some(CombatEffect::Buff(CombatBuff { strength, .. })) = &mut self.damage_effect {
|
||||||
&mut self.damage_effect
|
|
||||||
{
|
|
||||||
*strength *= stats.buff_strength;
|
*strength *= stats.buff_strength;
|
||||||
}
|
}
|
||||||
self
|
self
|
||||||
|
@ -126,7 +126,7 @@ pub enum ServerEvent {
|
|||||||
},
|
},
|
||||||
// TODO: to avoid breakage when adding new fields, perhaps have an `NpcBuilder` type?
|
// TODO: to avoid breakage when adding new fields, perhaps have an `NpcBuilder` type?
|
||||||
CreateNpc {
|
CreateNpc {
|
||||||
pos: comp::Pos,
|
pos: Pos,
|
||||||
stats: comp::Stats,
|
stats: comp::Stats,
|
||||||
skill_set: comp::SkillSet,
|
skill_set: comp::SkillSet,
|
||||||
health: Option<comp::Health>,
|
health: Option<comp::Health>,
|
||||||
@ -142,7 +142,7 @@ pub enum ServerEvent {
|
|||||||
projectile: Option<comp::Projectile>,
|
projectile: Option<comp::Projectile>,
|
||||||
},
|
},
|
||||||
CreateShip {
|
CreateShip {
|
||||||
pos: comp::Pos,
|
pos: Pos,
|
||||||
ship: comp::ship::Body,
|
ship: comp::ship::Body,
|
||||||
mountable: bool,
|
mountable: bool,
|
||||||
agent: Option<comp::Agent>,
|
agent: Option<comp::Agent>,
|
||||||
|
@ -167,7 +167,7 @@ pub struct EntityInfo {
|
|||||||
// Loadout
|
// Loadout
|
||||||
pub inventory: Vec<(u32, Item)>,
|
pub inventory: Vec<(u32, Item)>,
|
||||||
pub loadout: LoadoutBuilder,
|
pub loadout: LoadoutBuilder,
|
||||||
pub make_loadout: Option<fn(LoadoutBuilder, Option<&trade::SiteInformation>) -> LoadoutBuilder>,
|
pub make_loadout: Option<fn(LoadoutBuilder, Option<&SiteInformation>) -> LoadoutBuilder>,
|
||||||
// Skills
|
// Skills
|
||||||
pub skillset_asset: Option<String>,
|
pub skillset_asset: Option<String>,
|
||||||
|
|
||||||
@ -176,7 +176,7 @@ pub struct EntityInfo {
|
|||||||
|
|
||||||
// Economy
|
// Economy
|
||||||
// we can't use DHashMap, do we want to move that into common?
|
// we can't use DHashMap, do we want to move that into common?
|
||||||
pub trading_information: Option<trade::SiteInformation>,
|
pub trading_information: Option<SiteInformation>,
|
||||||
//Option<hashbrown::HashMap<crate::trade::Good, (f32, f32)>>, /* price and available amount */
|
//Option<hashbrown::HashMap<crate::trade::Good, (f32, f32)>>, /* price and available amount */
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -394,7 +394,7 @@ impl EntityInfo {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn with_lazy_loadout(
|
pub fn with_lazy_loadout(
|
||||||
mut self,
|
mut self,
|
||||||
creator: fn(LoadoutBuilder, Option<&trade::SiteInformation>) -> LoadoutBuilder,
|
creator: fn(LoadoutBuilder, Option<&SiteInformation>) -> LoadoutBuilder,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
self.make_loadout = Some(creator);
|
self.make_loadout = Some(creator);
|
||||||
self
|
self
|
||||||
@ -576,7 +576,7 @@ mod tests {
|
|||||||
|
|
||||||
match field {
|
match field {
|
||||||
Meta::SkillSetAsset(asset) => {
|
Meta::SkillSetAsset(asset) => {
|
||||||
std::mem::drop(SkillSetBuilder::from_asset_expect(&asset));
|
drop(SkillSetBuilder::from_asset_expect(&asset));
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -28,9 +28,7 @@ pub struct Is<R: Role> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Role> Is<R> {
|
impl<R: Role> Is<R> {
|
||||||
pub fn delete(&self, data: <R::Link as Link>::DeleteData<'_>) {
|
pub fn delete(&self, data: <R::Link as Link>::DeleteData<'_>) { Link::delete(&self.link, data) }
|
||||||
R::Link::delete(&self.link, data)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Role> Clone for Is<R> {
|
impl<R: Role> Clone for Is<R> {
|
||||||
|
@ -108,7 +108,7 @@ impl<T: AsRef<str>> LootSpec<T> {
|
|||||||
warn!(?e, "error while loading item: {}", item.as_ref());
|
warn!(?e, "error while loading item: {}", item.as_ref());
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
Option::Some,
|
Some,
|
||||||
),
|
),
|
||||||
Self::ItemQuantity(item, lower, upper) => {
|
Self::ItemQuantity(item, lower, upper) => {
|
||||||
let range = *lower..=*upper;
|
let range = *lower..=*upper;
|
||||||
@ -148,7 +148,7 @@ impl<T: AsRef<str>> LootSpec<T> {
|
|||||||
);
|
);
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
Option::Some,
|
Some,
|
||||||
),
|
),
|
||||||
Self::ModularWeaponPrimaryComponent {
|
Self::ModularWeaponPrimaryComponent {
|
||||||
tool,
|
tool,
|
||||||
|
@ -54,7 +54,7 @@ pub enum Outcome {
|
|||||||
},
|
},
|
||||||
SkillPointGain {
|
SkillPointGain {
|
||||||
uid: Uid,
|
uid: Uid,
|
||||||
skill_tree: comp::skillset::SkillGroupKind,
|
skill_tree: SkillGroupKind,
|
||||||
total_points: u16,
|
total_points: u16,
|
||||||
},
|
},
|
||||||
ComboChange {
|
ComboChange {
|
||||||
|
@ -167,7 +167,7 @@ mod tests {
|
|||||||
fn test_all_skillset_assets() {
|
fn test_all_skillset_assets() {
|
||||||
let skillsets = assets::read_expect_dir::<SkillSetTree>("common.skillset", true);
|
let skillsets = assets::read_expect_dir::<SkillSetTree>("common.skillset", true);
|
||||||
for skillset in skillsets {
|
for skillset in skillsets {
|
||||||
std::mem::drop({
|
drop({
|
||||||
let mut skillset_builder = SkillSetBuilder::default();
|
let mut skillset_builder = SkillSetBuilder::default();
|
||||||
let nodes = &*skillset.0;
|
let nodes = &*skillset.0;
|
||||||
let tree = skills_from_nodes(nodes);
|
let tree = skills_from_nodes(nodes);
|
||||||
|
@ -303,7 +303,7 @@ impl Body {
|
|||||||
|
|
||||||
/// set footwear in idle data and potential state change to Skate
|
/// set footwear in idle data and potential state change to Skate
|
||||||
pub fn handle_skating(data: &JoinData, update: &mut StateUpdate) {
|
pub fn handle_skating(data: &JoinData, update: &mut StateUpdate) {
|
||||||
if let Idle(crate::states::idle::Data {
|
if let Idle(idle::Data {
|
||||||
is_sneaking,
|
is_sneaking,
|
||||||
mut footwear,
|
mut footwear,
|
||||||
}) = data.character
|
}) = data.character
|
||||||
@ -313,19 +313,17 @@ pub fn handle_skating(data: &JoinData, update: &mut StateUpdate) {
|
|||||||
inv.equipped(EquipSlot::Armor(ArmorSlot::Feet))
|
inv.equipped(EquipSlot::Armor(ArmorSlot::Feet))
|
||||||
.map(|armor| match armor.kind().as_ref() {
|
.map(|armor| match armor.kind().as_ref() {
|
||||||
ItemKind::Armor(a) => a.stats(data.msm).ground_contact,
|
ItemKind::Armor(a) => a.stats(data.msm).ground_contact,
|
||||||
_ => crate::comp::inventory::item::armor::Friction::Normal,
|
_ => Friction::Normal,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
update.character = Idle(crate::states::idle::Data {
|
update.character = Idle(idle::Data {
|
||||||
is_sneaking: *is_sneaking,
|
is_sneaking: *is_sneaking,
|
||||||
footwear,
|
footwear,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if data.physics.skating_active {
|
if data.physics.skating_active {
|
||||||
update.character = CharacterState::Skate(crate::states::skate::Data::new(
|
update.character =
|
||||||
data,
|
CharacterState::Skate(skate::Data::new(data, footwear.unwrap_or(Friction::Normal)));
|
||||||
footwear.unwrap_or(Friction::Normal),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -687,7 +685,7 @@ pub fn attempt_talk(data: &JoinData<'_>, update: &mut StateUpdate) {
|
|||||||
|
|
||||||
pub fn attempt_sneak(data: &JoinData<'_>, update: &mut StateUpdate) {
|
pub fn attempt_sneak(data: &JoinData<'_>, update: &mut StateUpdate) {
|
||||||
if data.physics.on_ground.is_some() && data.body.is_humanoid() {
|
if data.physics.on_ground.is_some() && data.body.is_humanoid() {
|
||||||
update.character = CharacterState::Idle(idle::Data {
|
update.character = Idle(idle::Data {
|
||||||
is_sneaking: true,
|
is_sneaking: true,
|
||||||
footwear: data.character.footwear(),
|
footwear: data.character.footwear(),
|
||||||
});
|
});
|
||||||
|
@ -341,7 +341,7 @@ pub enum Good {
|
|||||||
|
|
||||||
impl Default for Good {
|
impl Default for Good {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Good::Terrain(crate::terrain::BiomeKind::Void) // Arbitrary
|
Good::Terrain(BiomeKind::Void) // Arbitrary
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -165,7 +165,7 @@ impl std::ops::Neg for Dir {
|
|||||||
/// Additionally, it avoids unnecessary calculations if they are near identical
|
/// Additionally, it avoids unnecessary calculations if they are near identical
|
||||||
/// Assumes `from` and `to` are normalized and returns a normalized vector
|
/// Assumes `from` and `to` are normalized and returns a normalized vector
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn slerp_normalized(from: vek::Vec3<f32>, to: vek::Vec3<f32>, factor: f32) -> vek::Vec3<f32> {
|
fn slerp_normalized(from: Vec3<f32>, to: Vec3<f32>, factor: f32) -> Vec3<f32> {
|
||||||
debug_assert!(!to.map(f32::is_nan).reduce_or());
|
debug_assert!(!to.map(f32::is_nan).reduce_or());
|
||||||
debug_assert!(!from.map(f32::is_nan).reduce_or());
|
debug_assert!(!from.map(f32::is_nan).reduce_or());
|
||||||
// Ensure from is normalized
|
// Ensure from is normalized
|
||||||
|
@ -277,9 +277,9 @@ impl<V, S: VolSize, M> Chunk<V, S, M> {
|
|||||||
{
|
{
|
||||||
if vox != self.default {
|
if vox != self.default {
|
||||||
let idx = self.force_idx_unchecked(pos);
|
let idx = self.force_idx_unchecked(pos);
|
||||||
core::mem::replace(&mut self.vox[idx], vox)
|
mem::replace(&mut self.vox[idx], vox)
|
||||||
} else if let Some(idx) = self.idx_unchecked(pos) {
|
} else if let Some(idx) = self.idx_unchecked(pos) {
|
||||||
core::mem::replace(&mut self.vox[idx], vox)
|
mem::replace(&mut self.vox[idx], vox)
|
||||||
} else {
|
} else {
|
||||||
self.default.clone()
|
self.default.clone()
|
||||||
}
|
}
|
||||||
|
@ -22,7 +22,7 @@ pub enum BuildAreaError {
|
|||||||
const RESERVED_BUILD_AREA_NAMES: &[&str] = &["world"];
|
const RESERVED_BUILD_AREA_NAMES: &[&str] = &["world"];
|
||||||
|
|
||||||
impl BuildAreas {
|
impl BuildAreas {
|
||||||
pub fn areas(&self) -> &Depot<geom::Aabb<i32>> { &self.areas }
|
pub fn areas(&self) -> &Depot<Aabb<i32>> { &self.areas }
|
||||||
|
|
||||||
pub fn area_names(&self) -> &HashMap<String, Id<Aabb<i32>>> { &self.area_names }
|
pub fn area_names(&self) -> &HashMap<String, Id<Aabb<i32>>> { &self.area_names }
|
||||||
|
|
||||||
|
@ -27,7 +27,7 @@ mod tests {
|
|||||||
state
|
state
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_entity(state: &mut State, ori: Ori) -> specs::Entity {
|
fn create_entity(state: &mut State, ori: Ori) -> Entity {
|
||||||
let body = common::comp::Body::Humanoid(common::comp::humanoid::Body::random_with(
|
let body = common::comp::Body::Humanoid(common::comp::humanoid::Body::random_with(
|
||||||
&mut thread_rng(),
|
&mut thread_rng(),
|
||||||
&common::comp::humanoid::Species::Human,
|
&common::comp::humanoid::Species::Human,
|
||||||
|
@ -36,14 +36,14 @@ fn dont_fall_outside_world() -> Result<(), Box<dyn Error>> {
|
|||||||
assert_relative_eq!(pos.0.x, 1000.0);
|
assert_relative_eq!(pos.0.x, 1000.0);
|
||||||
assert_relative_eq!(pos.0.y, 1000.0);
|
assert_relative_eq!(pos.0.y, 1000.0);
|
||||||
assert_relative_eq!(pos.0.z, 265.0);
|
assert_relative_eq!(pos.0.z, 265.0);
|
||||||
assert_eq!(vel.0, vek::Vec3::zero());
|
assert_eq!(vel.0, Vec3::zero());
|
||||||
|
|
||||||
utils::tick(&mut state, DT);
|
utils::tick(&mut state, DT);
|
||||||
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
||||||
assert_relative_eq!(pos.0.x, 1000.0);
|
assert_relative_eq!(pos.0.x, 1000.0);
|
||||||
assert_relative_eq!(pos.0.y, 1000.0);
|
assert_relative_eq!(pos.0.y, 1000.0);
|
||||||
assert_relative_eq!(pos.0.z, 265.0);
|
assert_relative_eq!(pos.0.z, 265.0);
|
||||||
assert_eq!(vel.0, vek::Vec3::zero());
|
assert_eq!(vel.0, Vec3::zero());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -56,7 +56,7 @@ fn fall_simple() -> Result<(), Box<dyn Error>> {
|
|||||||
assert_relative_eq!(pos.0.x, 16.0);
|
assert_relative_eq!(pos.0.x, 16.0);
|
||||||
assert_relative_eq!(pos.0.y, 16.0);
|
assert_relative_eq!(pos.0.y, 16.0);
|
||||||
assert_relative_eq!(pos.0.z, 265.0);
|
assert_relative_eq!(pos.0.z, 265.0);
|
||||||
assert_eq!(vel.0, vek::Vec3::zero());
|
assert_eq!(vel.0, Vec3::zero());
|
||||||
|
|
||||||
utils::tick(&mut state, DT);
|
utils::tick(&mut state, DT);
|
||||||
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
||||||
@ -145,7 +145,7 @@ fn walk_simple() -> Result<(), Box<dyn Error>> {
|
|||||||
}
|
}
|
||||||
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
let (pos, vel, _) = utils::get_transform(&state, p1)?;
|
||||||
assert_relative_eq!(pos.0.z, 257.0); // make sure it landed on ground
|
assert_relative_eq!(pos.0.z, 257.0); // make sure it landed on ground
|
||||||
assert_eq!(vel.0, vek::Vec3::zero());
|
assert_eq!(vel.0, Vec3::zero());
|
||||||
|
|
||||||
let mut actions = Controller::default();
|
let mut actions = Controller::default();
|
||||||
actions.inputs.move_dir = Vec2::new(1.0, 0.0);
|
actions.inputs.move_dir = Vec2::new(1.0, 0.0);
|
||||||
|
@ -62,7 +62,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn file_exists(file: &str) -> Result<(), String> {
|
fn file_exists(file: &str) -> Result<(), String> {
|
||||||
let file: std::path::PathBuf = shellexpand::tilde(file).parse().unwrap();
|
let file: PathBuf = shellexpand::tilde(file).parse().unwrap();
|
||||||
if file.exists() {
|
if file.exists() {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
|
@ -192,16 +192,16 @@ fn client(address: ConnectAddr, runtime: Arc<Runtime>) {
|
|||||||
}
|
}
|
||||||
if id > 2000000 {
|
if id > 2000000 {
|
||||||
println!("Stop");
|
println!("Stop");
|
||||||
std::thread::sleep(std::time::Duration::from_millis(2000));
|
thread::sleep(Duration::from_millis(2000));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
drop(s1);
|
drop(s1);
|
||||||
std::thread::sleep(std::time::Duration::from_millis(2000));
|
thread::sleep(Duration::from_millis(2000));
|
||||||
info!("Closing participant");
|
info!("Closing participant");
|
||||||
runtime.block_on(p1.disconnect()).unwrap();
|
runtime.block_on(p1.disconnect()).unwrap();
|
||||||
std::thread::sleep(std::time::Duration::from_millis(2000));
|
thread::sleep(Duration::from_millis(2000));
|
||||||
info!("DROPPING! client");
|
info!("DROPPING! client");
|
||||||
drop(client);
|
drop(client);
|
||||||
std::thread::sleep(std::time::Duration::from_millis(2000));
|
thread::sleep(Duration::from_millis(2000));
|
||||||
}
|
}
|
||||||
|
@ -192,8 +192,8 @@ mod utils {
|
|||||||
cap: usize,
|
cap: usize,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
|
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
@ -222,8 +222,8 @@ mod utils {
|
|||||||
cap: usize,
|
cap: usize,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
|
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
@ -252,8 +252,8 @@ mod utils {
|
|||||||
cap: usize,
|
cap: usize,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
|
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
|
@ -202,8 +202,8 @@ pub mod test_utils {
|
|||||||
cap: usize,
|
cap: usize,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
|
) -> [(MpscSendProtocol<ACDrain>, MpscRecvProtocol<ACSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("mpsc", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
|
@ -543,8 +543,8 @@ mod test_utils {
|
|||||||
drop_ratio: f32,
|
drop_ratio: f32,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
|
) -> [(QuicSendProtocol<QuicDrain>, QuicRecvProtocol<QuicSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
@ -804,8 +804,7 @@ mod tests {
|
|||||||
let sid = Sid::new(1);
|
let sid = Sid::new(1);
|
||||||
let (s, r) = async_channel::bounded(10);
|
let (s, r) = async_channel::bounded(10);
|
||||||
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
|
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
|
||||||
let mut r =
|
let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());
|
||||||
super::QuicRecvProtocol::new(super::test_utils::QuicSink { receiver: r }, m.clone());
|
|
||||||
|
|
||||||
const DATA1: &[u8; 69] =
|
const DATA1: &[u8; 69] =
|
||||||
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
|
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
|
||||||
@ -861,8 +860,7 @@ mod tests {
|
|||||||
let sid = Sid::new(1);
|
let sid = Sid::new(1);
|
||||||
let (s, r) = async_channel::bounded(10);
|
let (s, r) = async_channel::bounded(10);
|
||||||
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
|
let m = ProtocolMetricCache::new("quic", Arc::new(ProtocolMetrics::new().unwrap()));
|
||||||
let mut r =
|
let mut r = super::QuicRecvProtocol::new(QuicSink { receiver: r }, m.clone());
|
||||||
super::QuicRecvProtocol::new(super::test_utils::QuicSink { receiver: r }, m.clone());
|
|
||||||
|
|
||||||
let mut bytes = BytesMut::with_capacity(1500);
|
let mut bytes = BytesMut::with_capacity(1500);
|
||||||
OTFrame::OpenStream {
|
OTFrame::OpenStream {
|
||||||
|
@ -360,8 +360,8 @@ mod test_utils {
|
|||||||
cap: usize,
|
cap: usize,
|
||||||
metrics: Option<ProtocolMetricCache>,
|
metrics: Option<ProtocolMetricCache>,
|
||||||
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
|
) -> [(TcpSendProtocol<TcpDrain>, TcpRecvProtocol<TcpSink>); 2] {
|
||||||
let (s1, r1) = async_channel::bounded(cap);
|
let (s1, r1) = bounded(cap);
|
||||||
let (s2, r2) = async_channel::bounded(cap);
|
let (s2, r2) = bounded(cap);
|
||||||
let m = metrics.unwrap_or_else(|| {
|
let m = metrics.unwrap_or_else(|| {
|
||||||
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
|
ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()))
|
||||||
});
|
});
|
||||||
@ -603,8 +603,7 @@ mod tests {
|
|||||||
let sid = Sid::new(1);
|
let sid = Sid::new(1);
|
||||||
let (s, r) = async_channel::bounded(10);
|
let (s, r) = async_channel::bounded(10);
|
||||||
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
|
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
|
||||||
let mut r =
|
let mut r = super::TcpRecvProtocol::new(TcpSink { receiver: r }, m.clone());
|
||||||
super::TcpRecvProtocol::new(super::test_utils::TcpSink { receiver: r }, m.clone());
|
|
||||||
|
|
||||||
const DATA1: &[u8; 69] =
|
const DATA1: &[u8; 69] =
|
||||||
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
|
b"We need to make sure that its okay to send OPEN_STREAM and DATA_HEAD ";
|
||||||
@ -653,8 +652,7 @@ mod tests {
|
|||||||
let sid = Sid::new(1);
|
let sid = Sid::new(1);
|
||||||
let (s, r) = async_channel::bounded(10);
|
let (s, r) = async_channel::bounded(10);
|
||||||
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
|
let m = ProtocolMetricCache::new("tcp", Arc::new(ProtocolMetrics::new().unwrap()));
|
||||||
let mut r =
|
let mut r = super::TcpRecvProtocol::new(TcpSink { receiver: r }, m.clone());
|
||||||
super::TcpRecvProtocol::new(super::test_utils::TcpSink { receiver: r }, m.clone());
|
|
||||||
|
|
||||||
let mut bytes = BytesMut::with_capacity(1500);
|
let mut bytes = BytesMut::with_capacity(1500);
|
||||||
OTFrame::OpenStream {
|
OTFrame::OpenStream {
|
||||||
|
@ -107,7 +107,7 @@ pub struct Stream {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum NetworkError {
|
pub enum NetworkError {
|
||||||
NetworkClosed,
|
NetworkClosed,
|
||||||
ListenFailed(std::io::Error),
|
ListenFailed(io::Error),
|
||||||
ConnectFailed(NetworkConnectError),
|
ConnectFailed(NetworkConnectError),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,7 +117,7 @@ pub enum NetworkConnectError {
|
|||||||
/// Either a Pid UUID clash or you are trying to hijack a connection
|
/// Either a Pid UUID clash or you are trying to hijack a connection
|
||||||
InvalidSecret,
|
InvalidSecret,
|
||||||
Handshake(InitProtocolError<ProtocolsError>),
|
Handshake(InitProtocolError<ProtocolsError>),
|
||||||
Io(std::io::Error),
|
Io(io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Error type thrown by [`Participants`](Participant) methods
|
/// Error type thrown by [`Participants`](Participant) methods
|
||||||
@ -168,7 +168,7 @@ pub struct StreamParams {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, ConnectAddr, ListenAddr, Pid};
|
/// use veloren_network::{Network, ConnectAddr, ListenAddr, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on port `2999` to accept connections and connect to port `8080` to connect to a (pseudo) database Application
|
/// // Create a Network, listen on port `2999` to accept connections and connect to port `8080` to connect to a (pseudo) database Application
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -272,7 +272,7 @@ impl Network {
|
|||||||
#[cfg(feature = "metrics")] registry: Option<&Registry>,
|
#[cfg(feature = "metrics")] registry: Option<&Registry>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let p = participant_id;
|
let p = participant_id;
|
||||||
let span = tracing::info_span!("network", ?p);
|
let span = info_span!("network", ?p);
|
||||||
span.in_scope(|| trace!("Starting Network"));
|
span.in_scope(|| trace!("Starting Network"));
|
||||||
let (scheduler, listen_sender, connect_sender, connected_receiver, shutdown_sender) =
|
let (scheduler, listen_sender, connect_sender, connected_receiver, shutdown_sender) =
|
||||||
Scheduler::new(
|
Scheduler::new(
|
||||||
@ -295,7 +295,7 @@ impl Network {
|
|||||||
scheduler.run().await;
|
scheduler.run().await;
|
||||||
trace!("Stopping scheduler and his own thread");
|
trace!("Stopping scheduler and his own thread");
|
||||||
}
|
}
|
||||||
.instrument(tracing::info_span!("network", ?p)),
|
.instrument(info_span!("network", ?p)),
|
||||||
);
|
);
|
||||||
Self {
|
Self {
|
||||||
local_pid: participant_id,
|
local_pid: participant_id,
|
||||||
@ -340,7 +340,7 @@ impl Network {
|
|||||||
/// [`ListenAddr`]: crate::api::ListenAddr
|
/// [`ListenAddr`]: crate::api::ListenAddr
|
||||||
#[instrument(name="network", skip(self, address), fields(p = %self.local_pid))]
|
#[instrument(name="network", skip(self, address), fields(p = %self.local_pid))]
|
||||||
pub async fn listen(&self, address: ListenAddr) -> Result<(), NetworkError> {
|
pub async fn listen(&self, address: ListenAddr) -> Result<(), NetworkError> {
|
||||||
let (s2a_result_s, s2a_result_r) = oneshot::channel::<tokio::io::Result<()>>();
|
let (s2a_result_s, s2a_result_r) = oneshot::channel::<io::Result<()>>();
|
||||||
debug!(?address, "listening on address");
|
debug!(?address, "listening on address");
|
||||||
self.listen_sender
|
self.listen_sender
|
||||||
.lock()
|
.lock()
|
||||||
@ -428,7 +428,7 @@ impl Network {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid};
|
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on port `2020` TCP and opens returns their Pid
|
/// // Create a Network, listen on port `2020` TCP and opens returns their Pid
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -567,7 +567,7 @@ impl Participant {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
|
/// use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, connect on port 2100 and open a stream
|
/// // Create a Network, connect on port 2100 and open a stream
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -634,7 +634,7 @@ impl Participant {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises};
|
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, connect on port 2110 and wait for the other side to open a stream
|
/// // Create a Network, connect on port 2110 and wait for the other side to open a stream
|
||||||
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
|
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
@ -691,7 +691,7 @@ impl Participant {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr};
|
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on port `2030` TCP and opens returns their Pid and close connection.
|
/// // Create a Network, listen on port `2030` TCP and opens returns their Pid and close connection.
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -775,7 +775,7 @@ impl Participant {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises, ParticipantEvent};
|
/// use veloren_network::{Network, Pid, ListenAddr, ConnectAddr, Promises, ParticipantEvent};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, connect on port 2040 and wait for the other side to open a stream
|
/// // Create a Network, connect on port 2040 and wait for the other side to open a stream
|
||||||
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
|
/// // Note: It's quite unusual to actively connect, but then wait on a stream to be connected, usually the Application taking initiative want's to also create the first Stream.
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
@ -889,7 +889,7 @@ impl Stream {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on Port `2200` and wait for a Stream to be opened, then answer `Hello World`
|
/// // Create a Network, listen on Port `2200` and wait for a Stream to be opened, then answer `Hello World`
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -931,7 +931,7 @@ impl Stream {
|
|||||||
/// use bincode;
|
/// use bincode;
|
||||||
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid, Message};
|
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid, Message};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
/// # let remote1 = Network::new(Pid::new(), &runtime);
|
/// # let remote1 = Network::new(Pid::new(), &runtime);
|
||||||
@ -999,7 +999,7 @@ impl Stream {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on Port `2220` and wait for a Stream to be opened, then listen on it
|
/// // Create a Network, listen on Port `2220` and wait for a Stream to be opened, then listen on it
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -1033,7 +1033,7 @@ impl Stream {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on Port `2230` and wait for a Stream to be opened, then listen on it
|
/// // Create a Network, listen on Port `2230` and wait for a Stream to be opened, then listen on it
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -1089,7 +1089,7 @@ impl Stream {
|
|||||||
/// use tokio::runtime::Runtime;
|
/// use tokio::runtime::Runtime;
|
||||||
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
/// use veloren_network::{Network, ListenAddr, ConnectAddr, Pid};
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on Port `2240` and wait for a Stream to be opened, then listen on it
|
/// // Create a Network, listen on Port `2240` and wait for a Stream to be opened, then listen on it
|
||||||
/// let runtime = Runtime::new().unwrap();
|
/// let runtime = Runtime::new().unwrap();
|
||||||
/// let network = Network::new(Pid::new(), &runtime);
|
/// let network = Network::new(Pid::new(), &runtime);
|
||||||
@ -1141,7 +1141,7 @@ impl Stream {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl core::cmp::PartialEq for Participant {
|
impl PartialEq for Participant {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
//don't check local_pid, 2 Participant from different network should match if
|
//don't check local_pid, 2 Participant from different network should match if
|
||||||
// they are the "same"
|
// they are the "same"
|
||||||
@ -1293,8 +1293,8 @@ impl From<oneshot::error::RecvError> for NetworkError {
|
|||||||
fn from(_err: oneshot::error::RecvError) -> Self { NetworkError::NetworkClosed }
|
fn from(_err: oneshot::error::RecvError) -> Self { NetworkError::NetworkClosed }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<std::io::Error> for NetworkError {
|
impl From<io::Error> for NetworkError {
|
||||||
fn from(_err: std::io::Error) -> Self { NetworkError::NetworkClosed }
|
fn from(_err: io::Error) -> Self { NetworkError::NetworkClosed }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Box<bincode::ErrorKind>> for StreamError {
|
impl From<Box<bincode::ErrorKind>> for StreamError {
|
||||||
@ -1346,7 +1346,7 @@ impl core::fmt::Display for NetworkConnectError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// implementing PartialEq as it's super convenient in tests
|
/// implementing PartialEq as it's super convenient in tests
|
||||||
impl core::cmp::PartialEq for StreamError {
|
impl PartialEq for StreamError {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
StreamError::StreamClosed => match other {
|
StreamError::StreamClosed => match other {
|
||||||
|
@ -94,7 +94,7 @@ impl Protocols {
|
|||||||
metrics: Arc<ProtocolMetrics>,
|
metrics: Arc<ProtocolMetrics>,
|
||||||
s2s_stop_listening_r: oneshot::Receiver<()>,
|
s2s_stop_listening_r: oneshot::Receiver<()>,
|
||||||
c2s_protocol_s: mpsc::UnboundedSender<C2sProtocol>,
|
c2s_protocol_s: mpsc::UnboundedSender<C2sProtocol>,
|
||||||
) -> std::io::Result<()> {
|
) -> io::Result<()> {
|
||||||
use socket2::{Domain, Socket, Type};
|
use socket2::{Domain, Socket, Type};
|
||||||
let domain = Domain::for_address(addr);
|
let domain = Domain::for_address(addr);
|
||||||
let socket2_socket = Socket::new(domain, Type::STREAM, None)?;
|
let socket2_socket = Socket::new(domain, Type::STREAM, None)?;
|
||||||
@ -109,7 +109,7 @@ impl Protocols {
|
|||||||
socket2_socket.bind(&socket2_addr)?;
|
socket2_socket.bind(&socket2_addr)?;
|
||||||
socket2_socket.listen(1024)?;
|
socket2_socket.listen(1024)?;
|
||||||
let std_listener: std::net::TcpListener = socket2_socket.into();
|
let std_listener: std::net::TcpListener = socket2_socket.into();
|
||||||
let listener = tokio::net::TcpListener::from_std(std_listener)?;
|
let listener = net::TcpListener::from_std(std_listener)?;
|
||||||
trace!(?addr, "Tcp Listener bound");
|
trace!(?addr, "Tcp Listener bound");
|
||||||
let mut end_receiver = s2s_stop_listening_r.fuse();
|
let mut end_receiver = s2s_stop_listening_r.fuse();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@ -143,7 +143,7 @@ impl Protocols {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn new_tcp(stream: tokio::net::TcpStream, metrics: ProtocolMetricCache) -> Self {
|
pub(crate) fn new_tcp(stream: net::TcpStream, metrics: ProtocolMetricCache) -> Self {
|
||||||
let (r, w) = stream.into_split();
|
let (r, w) = stream.into_split();
|
||||||
let sp = TcpSendProtocol::new(TcpDrain { half: w }, metrics.clone());
|
let sp = TcpSendProtocol::new(TcpDrain { half: w }, metrics.clone());
|
||||||
let rp = TcpRecvProtocol::new(
|
let rp = TcpRecvProtocol::new(
|
||||||
@ -453,14 +453,14 @@ impl network_protocol::RecvProtocol for RecvProtocols {
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum MpscError {
|
pub enum MpscError {
|
||||||
Send(tokio::sync::mpsc::error::SendError<network_protocol::MpscMsg>),
|
Send(mpsc::error::SendError<MpscMsg>),
|
||||||
Recv,
|
Recv,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "quic")]
|
#[cfg(feature = "quic")]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum QuicError {
|
pub enum QuicError {
|
||||||
Send(std::io::Error),
|
Send(io::Error),
|
||||||
Connection(quinn::ConnectionError),
|
Connection(quinn::ConnectionError),
|
||||||
Write(quinn::WriteError),
|
Write(quinn::WriteError),
|
||||||
Read(quinn::ReadError),
|
Read(quinn::ReadError),
|
||||||
@ -470,8 +470,8 @@ pub enum QuicError {
|
|||||||
/// Error types for Protocols
|
/// Error types for Protocols
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ProtocolsError {
|
pub enum ProtocolsError {
|
||||||
Tcp(std::io::Error),
|
Tcp(io::Error),
|
||||||
Udp(std::io::Error),
|
Udp(io::Error),
|
||||||
#[cfg(feature = "quic")]
|
#[cfg(feature = "quic")]
|
||||||
Quic(QuicError),
|
Quic(QuicError),
|
||||||
Mpsc(MpscError),
|
Mpsc(MpscError),
|
||||||
@ -527,12 +527,12 @@ impl UnreliableSink for TcpSink {
|
|||||||
//// MPSC
|
//// MPSC
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MpscDrain {
|
pub struct MpscDrain {
|
||||||
sender: tokio::sync::mpsc::Sender<MpscMsg>,
|
sender: mpsc::Sender<MpscMsg>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MpscSink {
|
pub struct MpscSink {
|
||||||
receiver: tokio::sync::mpsc::Receiver<MpscMsg>,
|
receiver: mpsc::Receiver<MpscMsg>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@ -666,7 +666,7 @@ impl UnreliableSink for QuicSink {
|
|||||||
let (mut buffer, result, mut recvstream, id) = loop {
|
let (mut buffer, result, mut recvstream, id) = loop {
|
||||||
use futures_util::FutureExt;
|
use futures_util::FutureExt;
|
||||||
// first handle all bi streams!
|
// first handle all bi streams!
|
||||||
let (a, b) = tokio::select! {
|
let (a, b) = select! {
|
||||||
biased;
|
biased;
|
||||||
Some(n) = self.bi.next().fuse() => (Some(n), None),
|
Some(n) = self.bi.next().fuse() => (Some(n), None),
|
||||||
Some(n) = self.recvstreams_r.recv().fuse() => (None, Some(n)),
|
Some(n) = self.recvstreams_r.recv().fuse() => (None, Some(n)),
|
||||||
|
@ -44,7 +44,7 @@
|
|||||||
//! use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
|
//! use veloren_network::{ConnectAddr, ListenAddr, Network, Pid, Promises};
|
||||||
//!
|
//!
|
||||||
//! // Client
|
//! // Client
|
||||||
//! async fn client(runtime: &Runtime) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
//! async fn client(runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
//! sleep(std::time::Duration::from_secs(1)).await; // `connect` MUST be after `listen`
|
//! sleep(std::time::Duration::from_secs(1)).await; // `connect` MUST be after `listen`
|
||||||
//! let client_network = Network::new(Pid::new(), runtime);
|
//! let client_network = Network::new(Pid::new(), runtime);
|
||||||
//! let server = client_network
|
//! let server = client_network
|
||||||
@ -58,7 +58,7 @@
|
|||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! // Server
|
//! // Server
|
||||||
//! async fn server(runtime: &Runtime) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
//! async fn server(runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
//! let server_network = Network::new(Pid::new(), runtime);
|
//! let server_network = Network::new(Pid::new(), runtime);
|
||||||
//! server_network
|
//! server_network
|
||||||
//! .listen(ListenAddr::Tcp("127.0.0.1:12345".parse().unwrap()))
|
//! .listen(ListenAddr::Tcp("127.0.0.1:12345".parse().unwrap()))
|
||||||
@ -71,7 +71,7 @@
|
|||||||
//! Ok(())
|
//! Ok(())
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
//! let runtime = Runtime::new().unwrap();
|
//! let runtime = Runtime::new().unwrap();
|
||||||
//! runtime.block_on(async {
|
//! runtime.block_on(async {
|
||||||
//! let (result_c, result_s) = join!(client(&runtime), server(&runtime),);
|
//! let (result_c, result_s) = join!(client(&runtime), server(&runtime),);
|
||||||
|
@ -75,7 +75,7 @@ impl Message {
|
|||||||
/// # use tokio::runtime::Runtime;
|
/// # use tokio::runtime::Runtime;
|
||||||
/// # use std::sync::Arc;
|
/// # use std::sync::Arc;
|
||||||
///
|
///
|
||||||
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// // Create a Network, listen on Port `2300` and wait for a Stream to be opened, then listen on it
|
/// // Create a Network, listen on Port `2300` and wait for a Stream to be opened, then listen on it
|
||||||
/// # let runtime = Runtime::new().unwrap();
|
/// # let runtime = Runtime::new().unwrap();
|
||||||
/// # let network = Network::new(Pid::new(), &runtime);
|
/// # let network = Network::new(Pid::new(), &runtime);
|
||||||
|
@ -175,7 +175,7 @@ impl NetworkMetrics {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn connect_requests_cache(&self, protocol: &ListenAddr) -> prometheus::IntCounter {
|
pub(crate) fn connect_requests_cache(&self, protocol: &ListenAddr) -> IntCounter {
|
||||||
self.incoming_connections_total
|
self.incoming_connections_total
|
||||||
.with_label_values(&[protocollisten_name(protocol)])
|
.with_label_values(&[protocollisten_name(protocol)])
|
||||||
}
|
}
|
||||||
|
@ -474,7 +474,7 @@ impl BParticipant {
|
|||||||
recv_protocols.is_empty()
|
recv_protocols.is_empty()
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut defered_orphan = DeferredTracer::new(tracing::Level::WARN);
|
let mut defered_orphan = DeferredTracer::new(Level::WARN);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let (event, addp, remp) = select!(
|
let (event, addp, remp) = select!(
|
||||||
@ -705,7 +705,7 @@ impl BParticipant {
|
|||||||
.map(|(timeout_time, _)| *timeout_time)
|
.map(|(timeout_time, _)| *timeout_time)
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
);
|
);
|
||||||
let timeout = tokio::select! {
|
let timeout = select! {
|
||||||
_ = wait_for_manager() => false,
|
_ = wait_for_manager() => false,
|
||||||
_ = timeout => true,
|
_ = timeout => true,
|
||||||
};
|
};
|
||||||
@ -825,7 +825,7 @@ mod tests {
|
|||||||
watch::Receiver<f32>,
|
watch::Receiver<f32>,
|
||||||
JoinHandle<()>,
|
JoinHandle<()>,
|
||||||
) {
|
) {
|
||||||
let runtime = Arc::new(tokio::runtime::Runtime::new().unwrap());
|
let runtime = Arc::new(Runtime::new().unwrap());
|
||||||
let runtime_clone = Arc::clone(&runtime);
|
let runtime_clone = Arc::clone(&runtime);
|
||||||
|
|
||||||
let (b2s_prio_statistic_s, b2s_prio_statistic_r) =
|
let (b2s_prio_statistic_s, b2s_prio_statistic_r) =
|
||||||
|
@ -402,7 +402,7 @@ impl Scheduler {
|
|||||||
use network_protocol::InitProtocol;
|
use network_protocol::InitProtocol;
|
||||||
let init_result = protocol
|
let init_result = protocol
|
||||||
.initialize(send_handshake, local_pid, local_secret)
|
.initialize(send_handshake, local_pid, local_secret)
|
||||||
.instrument(tracing::info_span!("handshake", ?cid))
|
.instrument(info_span!("handshake", ?cid))
|
||||||
.await;
|
.await;
|
||||||
match init_result {
|
match init_result {
|
||||||
Ok((pid, sid, secret)) => {
|
Ok((pid, sid, secret)) => {
|
||||||
@ -447,7 +447,7 @@ impl Scheduler {
|
|||||||
tokio::spawn(
|
tokio::spawn(
|
||||||
bparticipant
|
bparticipant
|
||||||
.run(participant_channels.b2s_prio_statistic_s)
|
.run(participant_channels.b2s_prio_statistic_s)
|
||||||
.instrument(tracing::info_span!("remote", ?p)),
|
.instrument(info_span!("remote", ?p)),
|
||||||
);
|
);
|
||||||
//create a new channel within BParticipant and wait for it to run
|
//create a new channel within BParticipant and wait for it to run
|
||||||
let (b2s_create_channel_done_s, b2s_create_channel_done_r) =
|
let (b2s_create_channel_done_s, b2s_create_channel_done_r) =
|
||||||
@ -516,7 +516,7 @@ impl Scheduler {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.instrument(tracing::info_span!("")),
|
.instrument(info_span!("")),
|
||||||
); /*WORKAROUND FOR SPAN NOT TO GET LOST*/
|
); /*WORKAROUND FOR SPAN NOT TO GET LOST*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@ use veloren_network::{ConnectAddr, ListenAddr, Network, Participant, Pid, Promis
|
|||||||
|
|
||||||
// sleep time when only internal rust calculations are done
|
// sleep time when only internal rust calculations are done
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const SLEEP_INTERNAL: std::time::Duration = std::time::Duration::from_millis(3000);
|
pub const SLEEP_INTERNAL: Duration = Duration::from_millis(3000);
|
||||||
// sleep time when we interact with the system, e.g. actually send TCP/UDP
|
// sleep time when we interact with the system, e.g. actually send TCP/UDP
|
||||||
// package
|
// package
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const SLEEP_EXTERNAL: std::time::Duration = std::time::Duration::from_millis(5000);
|
pub const SLEEP_EXTERNAL: Duration = Duration::from_millis(5000);
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn setup(tracing: bool, sleep: u64) -> (u64, u64) {
|
pub fn setup(tracing: bool, sleep: u64) -> (u64, u64) {
|
||||||
|
@ -118,7 +118,7 @@ fn stream_simple_udp_3msg() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn tcp_and_udp_2_connections() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
fn tcp_and_udp_2_connections() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (_, _) = helper::setup(false, 0);
|
let (_, _) = helper::setup(false, 0);
|
||||||
let r = Arc::new(Runtime::new().unwrap());
|
let r = Arc::new(Runtime::new().unwrap());
|
||||||
let network = Network::new(Pid::new(), &r);
|
let network = Network::new(Pid::new(), &r);
|
||||||
@ -145,7 +145,7 @@ fn tcp_and_udp_2_connections() -> std::result::Result<(), Box<dyn std::error::Er
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn failed_listen_on_used_ports() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
fn failed_listen_on_used_ports() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (_, _) = helper::setup(false, 0);
|
let (_, _) = helper::setup(false, 0);
|
||||||
let r = Arc::new(Runtime::new().unwrap());
|
let r = Arc::new(Runtime::new().unwrap());
|
||||||
let network = Network::new(Pid::new(), &r);
|
let network = Network::new(Pid::new(), &r);
|
||||||
@ -176,7 +176,7 @@ fn failed_listen_on_used_ports() -> std::result::Result<(), Box<dyn std::error::
|
|||||||
/// So i rather put the same test into a unit test, these are now duplicate to
|
/// So i rather put the same test into a unit test, these are now duplicate to
|
||||||
/// the api, but are left here, just to be save!
|
/// the api, but are left here, just to be save!
|
||||||
#[test]
|
#[test]
|
||||||
fn api_stream_send_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
fn api_stream_send_main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (_, _) = helper::setup(false, 0);
|
let (_, _) = helper::setup(false, 0);
|
||||||
// Create a Network, listen on Port `1200` and wait for a Stream to be opened,
|
// Create a Network, listen on Port `1200` and wait for a Stream to be opened,
|
||||||
// then answer `Hello World`
|
// then answer `Hello World`
|
||||||
@ -205,7 +205,7 @@ fn api_stream_send_main() -> std::result::Result<(), Box<dyn std::error::Error>>
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn api_stream_recv_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
fn api_stream_recv_main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (_, _) = helper::setup(false, 0);
|
let (_, _) = helper::setup(false, 0);
|
||||||
// Create a Network, listen on Port `1220` and wait for a Stream to be opened,
|
// Create a Network, listen on Port `1220` and wait for a Stream to be opened,
|
||||||
// then listen on it
|
// then listen on it
|
||||||
|
@ -55,7 +55,7 @@ pub fn read_input<T>(ptr: i64, len: i64) -> Result<T, &'static str>
|
|||||||
where
|
where
|
||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
let slice = unsafe { ::std::slice::from_raw_parts(from_i64(ptr) as _, from_i64(len) as _) };
|
let slice = unsafe { std::slice::from_raw_parts(from_i64(ptr) as _, from_i64(len) as _) };
|
||||||
bincode::deserialize(slice).map_err(|_| "Failed to deserialize function input")
|
bincode::deserialize(slice).map_err(|_| "Failed to deserialize function input")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ impl Settings {
|
|||||||
let mut new_path = path.to_owned();
|
let mut new_path = path.to_owned();
|
||||||
new_path.pop();
|
new_path.pop();
|
||||||
new_path.push("settings.invalid.ron");
|
new_path.push("settings.invalid.ron");
|
||||||
if let Err(e) = std::fs::rename(&path, &new_path) {
|
if let Err(e) = fs::rename(&path, &new_path) {
|
||||||
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
|
warn!(?e, ?path, ?new_path, "Failed to rename settings file.");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -100,7 +100,7 @@ impl Tui {
|
|||||||
},
|
},
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
debug!(?line, "basic mode: command entered");
|
debug!(?line, "basic mode: command entered");
|
||||||
crate::cli::parse_command(line.trim(), &mut msg_s);
|
cli::parse_command(line.trim(), &mut msg_s);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -273,7 +273,7 @@ fn uuid(server: &Server, entity: EcsEntity, descriptor: &str) -> CmdResult<Uuid>
|
|||||||
.ok_or_else(|| format!("Cannot get player information for {:?}", descriptor))
|
.ok_or_else(|| format!("Cannot get player information for {:?}", descriptor))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn real_role(server: &Server, uuid: Uuid, descriptor: &str) -> CmdResult<comp::AdminRole> {
|
fn real_role(server: &Server, uuid: Uuid, descriptor: &str) -> CmdResult<AdminRole> {
|
||||||
server
|
server
|
||||||
.editable_settings()
|
.editable_settings()
|
||||||
.admins
|
.admins
|
||||||
@ -294,7 +294,7 @@ fn uid(server: &Server, target: EcsEntity, descriptor: &str) -> CmdResult<Uid> {
|
|||||||
.ok_or_else(|| format!("Cannot get uid for {:?}", descriptor))
|
.ok_or_else(|| format!("Cannot get uid for {:?}", descriptor))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn area(server: &mut Server, area_name: &str) -> CmdResult<depot::Id<vek::Aabb<i32>>> {
|
fn area(server: &mut Server, area_name: &str) -> CmdResult<depot::Id<Aabb<i32>>> {
|
||||||
server
|
server
|
||||||
.state
|
.state
|
||||||
.mut_resource::<BuildAreas>()
|
.mut_resource::<BuildAreas>()
|
||||||
@ -458,13 +458,13 @@ fn handle_drop_all(
|
|||||||
if let Some(mut inventory) = server
|
if let Some(mut inventory) = server
|
||||||
.state
|
.state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Inventory>()
|
.write_storage::<Inventory>()
|
||||||
.get_mut(target)
|
.get_mut(target)
|
||||||
{
|
{
|
||||||
items = inventory.drain().collect();
|
items = inventory.drain().collect();
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = thread_rng();
|
||||||
|
|
||||||
let item_to_place = items
|
let item_to_place = items
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@ -512,7 +512,7 @@ fn handle_give_item(
|
|||||||
server
|
server
|
||||||
.state
|
.state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Inventory>()
|
.write_storage::<Inventory>()
|
||||||
.get_mut(target)
|
.get_mut(target)
|
||||||
.map(|mut inv| {
|
.map(|mut inv| {
|
||||||
// NOTE: Deliberately ignores items that couldn't be pushed.
|
// NOTE: Deliberately ignores items that couldn't be pushed.
|
||||||
@ -530,7 +530,7 @@ fn handle_give_item(
|
|||||||
server
|
server
|
||||||
.state
|
.state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Inventory>()
|
.write_storage::<Inventory>()
|
||||||
.get_mut(target)
|
.get_mut(target)
|
||||||
.map(|mut inv| {
|
.map(|mut inv| {
|
||||||
for i in 0..give_amount {
|
for i in 0..give_amount {
|
||||||
@ -618,7 +618,7 @@ fn handle_make_npc(
|
|||||||
Err(_err) => return Err(format!("Failed to load entity config: {}", entity_config)),
|
Err(_err) => return Err(format!("Failed to load entity config: {}", entity_config)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut loadout_rng = rand::thread_rng();
|
let mut loadout_rng = thread_rng();
|
||||||
for _ in 0..number {
|
for _ in 0..number {
|
||||||
let comp::Pos(pos) = position(server, target, "target")?;
|
let comp::Pos(pos) = position(server, target, "target")?;
|
||||||
let entity_info = EntityInfo::at(pos).with_entity_config(
|
let entity_info = EntityInfo::at(pos).with_entity_config(
|
||||||
@ -861,7 +861,7 @@ fn handle_home(
|
|||||||
_action: &ServerChatCommand,
|
_action: &ServerChatCommand,
|
||||||
) -> CmdResult<()> {
|
) -> CmdResult<()> {
|
||||||
let home_pos = server.state.mut_resource::<SpawnPoint>().0;
|
let home_pos = server.state.mut_resource::<SpawnPoint>().0;
|
||||||
let time = *server.state.mut_resource::<common::resources::Time>();
|
let time = *server.state.mut_resource::<Time>();
|
||||||
|
|
||||||
position_mut(server, target, "target", |current_pos| {
|
position_mut(server, target, "target", |current_pos| {
|
||||||
current_pos.0 = home_pos
|
current_pos.0 = home_pos
|
||||||
@ -1170,8 +1170,8 @@ fn handle_spawn(
|
|||||||
|
|
||||||
for _ in 0..amount {
|
for _ in 0..amount {
|
||||||
let vel = Vec3::new(
|
let vel = Vec3::new(
|
||||||
rand::thread_rng().gen_range(-2.0..3.0),
|
thread_rng().gen_range(-2.0..3.0),
|
||||||
rand::thread_rng().gen_range(-2.0..3.0),
|
thread_rng().gen_range(-2.0..3.0),
|
||||||
10.0,
|
10.0,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -1208,10 +1208,10 @@ fn handle_spawn(
|
|||||||
pet_entity: new_entity,
|
pet_entity: new_entity,
|
||||||
});
|
});
|
||||||
} else if let Some(group) = match alignment {
|
} else if let Some(group) = match alignment {
|
||||||
comp::Alignment::Wild => None,
|
Alignment::Wild => None,
|
||||||
comp::Alignment::Passive => None,
|
Alignment::Passive => None,
|
||||||
comp::Alignment::Enemy => Some(comp::group::ENEMY),
|
Alignment::Enemy => Some(comp::group::ENEMY),
|
||||||
comp::Alignment::Npc | comp::Alignment::Tame => Some(comp::group::NPC),
|
Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
|
||||||
comp::Alignment::Owned(_) => unreachable!(),
|
comp::Alignment::Owned(_) => unreachable!(),
|
||||||
} {
|
} {
|
||||||
insert_or_replace_component(server, new_entity, group, "new entity")?;
|
insert_or_replace_component(server, new_entity, group, "new entity")?;
|
||||||
@ -1249,8 +1249,8 @@ fn handle_spawn_training_dummy(
|
|||||||
) -> CmdResult<()> {
|
) -> CmdResult<()> {
|
||||||
let pos = position(server, target, "target")?;
|
let pos = position(server, target, "target")?;
|
||||||
let vel = Vec3::new(
|
let vel = Vec3::new(
|
||||||
rand::thread_rng().gen_range(-2.0..3.0),
|
thread_rng().gen_range(-2.0..3.0),
|
||||||
rand::thread_rng().gen_range(-2.0..3.0),
|
thread_rng().gen_range(-2.0..3.0),
|
||||||
10.0,
|
10.0,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -1302,7 +1302,7 @@ fn handle_spawn_airship(
|
|||||||
200.0,
|
200.0,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = thread_rng();
|
||||||
let ship = comp::ship::Body::random_airship_with(&mut rng);
|
let ship = comp::ship::Body::random_airship_with(&mut rng);
|
||||||
let mut builder = server
|
let mut builder = server
|
||||||
.state
|
.state
|
||||||
@ -1350,7 +1350,7 @@ fn handle_spawn_ship(
|
|||||||
200.0,
|
200.0,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = thread_rng();
|
||||||
let ship = comp::ship::Body::random_ship_with(&mut rng);
|
let ship = comp::ship::Body::random_ship_with(&mut rng);
|
||||||
let mut builder = server
|
let mut builder = server
|
||||||
.state
|
.state
|
||||||
@ -1782,11 +1782,11 @@ fn handle_help(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_alignment(owner: Uid, alignment: &str) -> CmdResult<comp::Alignment> {
|
fn parse_alignment(owner: Uid, alignment: &str) -> CmdResult<Alignment> {
|
||||||
match alignment {
|
match alignment {
|
||||||
"wild" => Ok(comp::Alignment::Wild),
|
"wild" => Ok(Alignment::Wild),
|
||||||
"enemy" => Ok(comp::Alignment::Enemy),
|
"enemy" => Ok(Alignment::Enemy),
|
||||||
"npc" => Ok(comp::Alignment::Npc),
|
"npc" => Ok(Alignment::Npc),
|
||||||
"pet" => Ok(comp::Alignment::Owned(owner)),
|
"pet" => Ok(comp::Alignment::Owned(owner)),
|
||||||
_ => Err(format!("Invalid alignment: {:?}", alignment)),
|
_ => Err(format!("Invalid alignment: {:?}", alignment)),
|
||||||
}
|
}
|
||||||
@ -1808,7 +1808,7 @@ fn handle_kill_npcs(
|
|||||||
let ecs = server.state.ecs();
|
let ecs = server.state.ecs();
|
||||||
let mut healths = ecs.write_storage::<comp::Health>();
|
let mut healths = ecs.write_storage::<comp::Health>();
|
||||||
let players = ecs.read_storage::<comp::Player>();
|
let players = ecs.read_storage::<comp::Player>();
|
||||||
let alignments = ecs.read_storage::<comp::Alignment>();
|
let alignments = ecs.read_storage::<Alignment>();
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
|
|
||||||
for (mut health, (), alignment) in (&mut healths, !&players, alignments.maybe()).join() {
|
for (mut health, (), alignment) in (&mut healths, !&players, alignments.maybe()).join() {
|
||||||
@ -1907,7 +1907,7 @@ where
|
|||||||
server
|
server
|
||||||
.state()
|
.state()
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Inventory>()
|
.write_storage::<Inventory>()
|
||||||
.get_mut(target),
|
.get_mut(target),
|
||||||
server.state.ecs().write_storage::<comp::InventoryUpdate>(),
|
server.state.ecs().write_storage::<comp::InventoryUpdate>(),
|
||||||
) {
|
) {
|
||||||
@ -1918,7 +1918,7 @@ where
|
|||||||
let mut rng = thread_rng();
|
let mut rng = thread_rng();
|
||||||
for (item_id, quantity) in kit {
|
for (item_id, quantity) in kit {
|
||||||
let mut item = match &item_id {
|
let mut item = match &item_id {
|
||||||
KitSpec::Item(item_id) => comp::Item::new_from_asset(item_id)
|
KitSpec::Item(item_id) => Item::new_from_asset(item_id)
|
||||||
.map_err(|_| format!("Unknown item: {:#?}", item_id))?,
|
.map_err(|_| format!("Unknown item: {:#?}", item_id))?,
|
||||||
KitSpec::ModularWeapon { tool, material } => {
|
KitSpec::ModularWeapon { tool, material } => {
|
||||||
comp::item::modular::random_weapon(*tool, *material, None, &mut rng)
|
comp::item::modular::random_weapon(*tool, *material, None, &mut rng)
|
||||||
@ -2029,7 +2029,7 @@ fn handle_light(
|
|||||||
let (opt_r, opt_g, opt_b, opt_x, opt_y, opt_z, opt_s) =
|
let (opt_r, opt_g, opt_b, opt_x, opt_y, opt_z, opt_s) =
|
||||||
parse_cmd_args!(args, f32, f32, f32, f32, f32, f32, f32);
|
parse_cmd_args!(args, f32, f32, f32, f32, f32, f32, f32);
|
||||||
|
|
||||||
let mut light_emitter = comp::LightEmitter::default();
|
let mut light_emitter = LightEmitter::default();
|
||||||
let mut light_offset_opt = None;
|
let mut light_offset_opt = None;
|
||||||
|
|
||||||
if let (Some(r), Some(g), Some(b)) = (opt_r, opt_g, opt_b) {
|
if let (Some(r), Some(g), Some(b)) = (opt_r, opt_g, opt_b) {
|
||||||
@ -2083,7 +2083,7 @@ fn handle_lantern(
|
|||||||
if let Some(mut light) = server
|
if let Some(mut light) = server
|
||||||
.state
|
.state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::LightEmitter>()
|
.write_storage::<LightEmitter>()
|
||||||
.get_mut(target)
|
.get_mut(target)
|
||||||
{
|
{
|
||||||
light.strength = s.max(0.1).min(10.0);
|
light.strength = s.max(0.1).min(10.0);
|
||||||
@ -2181,7 +2181,7 @@ fn handle_waypoint(
|
|||||||
_action: &ServerChatCommand,
|
_action: &ServerChatCommand,
|
||||||
) -> CmdResult<()> {
|
) -> CmdResult<()> {
|
||||||
let pos = position(server, target, "target")?;
|
let pos = position(server, target, "target")?;
|
||||||
let time = *server.state.mut_resource::<common::resources::Time>();
|
let time = *server.state.mut_resource::<Time>();
|
||||||
insert_or_replace_component(
|
insert_or_replace_component(
|
||||||
server,
|
server,
|
||||||
target,
|
target,
|
||||||
@ -2897,8 +2897,8 @@ fn handle_remove_lights(
|
|||||||
for (entity, pos, _, _, _) in (
|
for (entity, pos, _, _, _) in (
|
||||||
&ecs.entities(),
|
&ecs.entities(),
|
||||||
&ecs.read_storage::<comp::Pos>(),
|
&ecs.read_storage::<comp::Pos>(),
|
||||||
&ecs.read_storage::<comp::LightEmitter>(),
|
&ecs.read_storage::<LightEmitter>(),
|
||||||
!&ecs.read_storage::<comp::WaypointArea>(),
|
!&ecs.read_storage::<WaypointArea>(),
|
||||||
!&ecs.read_storage::<comp::Player>(),
|
!&ecs.read_storage::<comp::Player>(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
@ -3072,7 +3072,7 @@ fn kick_player(
|
|||||||
.mut_resource::<EventBus<ServerEvent>>()
|
.mut_resource::<EventBus<ServerEvent>>()
|
||||||
.emit_now(ServerEvent::ClientDisconnect(
|
.emit_now(ServerEvent::ClientDisconnect(
|
||||||
target_player,
|
target_player,
|
||||||
common::comp::DisconnectReason::Kicked,
|
comp::DisconnectReason::Kicked,
|
||||||
));
|
));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -140,10 +140,10 @@ pub fn handle_create_npc(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if let Some(group) = match alignment {
|
} else if let Some(group) = match alignment {
|
||||||
comp::Alignment::Wild => None,
|
Alignment::Wild => None,
|
||||||
comp::Alignment::Passive => None,
|
Alignment::Passive => None,
|
||||||
comp::Alignment::Enemy => Some(comp::group::ENEMY),
|
Alignment::Enemy => Some(comp::group::ENEMY),
|
||||||
comp::Alignment::Npc | comp::Alignment::Tame => Some(comp::group::NPC),
|
Alignment::Npc | Alignment::Tame => Some(comp::group::NPC),
|
||||||
comp::Alignment::Owned(_) => unreachable!(),
|
comp::Alignment::Owned(_) => unreachable!(),
|
||||||
} {
|
} {
|
||||||
let _ = server.state.ecs().write_storage().insert(new_entity, group);
|
let _ = server.state.ecs().write_storage().insert(new_entity, group);
|
||||||
@ -152,7 +152,7 @@ pub fn handle_create_npc(
|
|||||||
|
|
||||||
pub fn handle_create_ship(
|
pub fn handle_create_ship(
|
||||||
server: &mut Server,
|
server: &mut Server,
|
||||||
pos: comp::Pos,
|
pos: Pos,
|
||||||
ship: comp::ship::Body,
|
ship: comp::ship::Body,
|
||||||
mountable: bool,
|
mountable: bool,
|
||||||
agent: Option<Agent>,
|
agent: Option<Agent>,
|
||||||
|
@ -172,7 +172,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
// one, we probably don't care about emitting death outcome)
|
// one, we probably don't care about emitting death outcome)
|
||||||
if state
|
if state
|
||||||
.ecs()
|
.ecs()
|
||||||
.read_storage::<comp::CharacterState>()
|
.read_storage::<CharacterState>()
|
||||||
.get(entity)
|
.get(entity)
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
@ -225,7 +225,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
let inventories = state.ecs().read_storage::<Inventory>();
|
let inventories = state.ecs().read_storage::<Inventory>();
|
||||||
let players = state.ecs().read_storage::<Player>();
|
let players = state.ecs().read_storage::<Player>();
|
||||||
let bodies = state.ecs().read_storage::<Body>();
|
let bodies = state.ecs().read_storage::<Body>();
|
||||||
let poises = state.ecs().read_storage::<comp::Poise>();
|
let poises = state.ecs().read_storage::<Poise>();
|
||||||
let positions = state.ecs().read_storage::<Pos>();
|
let positions = state.ecs().read_storage::<Pos>();
|
||||||
let groups = state.ecs().read_storage::<Group>();
|
let groups = state.ecs().read_storage::<Group>();
|
||||||
|
|
||||||
@ -307,7 +307,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
let alignments = state.ecs().read_storage::<Alignment>();
|
let alignments = state.ecs().read_storage::<Alignment>();
|
||||||
let uids = state.ecs().read_storage::<Uid>();
|
let uids = state.ecs().read_storage::<Uid>();
|
||||||
let mut outcomes = state.ecs().write_resource::<EventBus<Outcome>>();
|
let mut outcomes = state.ecs().write_resource::<EventBus<Outcome>>();
|
||||||
let inventories = state.ecs().read_storage::<comp::Inventory>();
|
let inventories = state.ecs().read_storage::<Inventory>();
|
||||||
|
|
||||||
let destroyed_group = groups.get(entity);
|
let destroyed_group = groups.get(entity);
|
||||||
|
|
||||||
@ -416,7 +416,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
.map(|e| error!(?e, ?entity, "Failed to insert ForceUpdate on dead client"));
|
.map(|e| error!(?e, ?entity, "Failed to insert ForceUpdate on dead client"));
|
||||||
state
|
state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Energy>()
|
.write_storage::<Energy>()
|
||||||
.get_mut(entity)
|
.get_mut(entity)
|
||||||
.map(|mut energy| {
|
.map(|mut energy| {
|
||||||
let energy = &mut *energy;
|
let energy = &mut *energy;
|
||||||
@ -424,11 +424,11 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
});
|
});
|
||||||
let _ = state
|
let _ = state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::CharacterState>()
|
.write_storage::<CharacterState>()
|
||||||
.insert(entity, comp::CharacterState::default());
|
.insert(entity, CharacterState::default());
|
||||||
|
|
||||||
false
|
false
|
||||||
} else if state.ecs().read_storage::<comp::Agent>().contains(entity)
|
} else if state.ecs().read_storage::<Agent>().contains(entity)
|
||||||
&& !matches!(
|
&& !matches!(
|
||||||
state.ecs().read_storage::<comp::Alignment>().get(entity),
|
state.ecs().read_storage::<comp::Alignment>().get(entity),
|
||||||
Some(comp::Alignment::Owned(_))
|
Some(comp::Alignment::Owned(_))
|
||||||
@ -445,7 +445,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(item) = item {
|
if let Some(item) = item {
|
||||||
let pos = state.ecs().read_storage::<comp::Pos>().get(entity).cloned();
|
let pos = state.ecs().read_storage::<Pos>().get(entity).cloned();
|
||||||
let vel = state.ecs().read_storage::<comp::Vel>().get(entity).cloned();
|
let vel = state.ecs().read_storage::<comp::Vel>().get(entity).cloned();
|
||||||
if let Some(pos) = pos {
|
if let Some(pos) = pos {
|
||||||
// Remove entries where zero exp was awarded - this happens because some
|
// Remove entries where zero exp was awarded - this happens because some
|
||||||
@ -471,7 +471,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
} else {
|
} else {
|
||||||
let uid = state
|
let uid = state
|
||||||
.ecs()
|
.ecs()
|
||||||
.read_storage::<comp::Body>()
|
.read_storage::<Body>()
|
||||||
.get(winner)
|
.get(winner)
|
||||||
.and_then(|body| {
|
.and_then(|body| {
|
||||||
// Only humanoids are awarded loot ownership - if the winner
|
// Only humanoids are awarded loot ownership - if the winner
|
||||||
@ -490,7 +490,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
};
|
};
|
||||||
|
|
||||||
let item_drop_entity = state
|
let item_drop_entity = state
|
||||||
.create_item_drop(comp::Pos(pos.0 + Vec3::unit_z() * 0.25), item)
|
.create_item_drop(Pos(pos.0 + Vec3::unit_z() * 0.25), item)
|
||||||
.maybe_with(vel)
|
.maybe_with(vel)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
@ -502,7 +502,7 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
|
|||||||
|
|
||||||
state
|
state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::LootOwner>()
|
.write_storage::<LootOwner>()
|
||||||
.insert(item_drop_entity, LootOwner::new(uid))
|
.insert(item_drop_entity, LootOwner::new(uid))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
@ -633,7 +633,7 @@ pub fn handle_respawn(server: &Server, entity: EcsEntity) {
|
|||||||
|
|
||||||
state
|
state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Health>()
|
.write_storage::<Health>()
|
||||||
.get_mut(entity)
|
.get_mut(entity)
|
||||||
.map(|mut health| health.revive());
|
.map(|mut health| health.revive());
|
||||||
state
|
state
|
||||||
@ -643,7 +643,7 @@ pub fn handle_respawn(server: &Server, entity: EcsEntity) {
|
|||||||
.map(|mut combo| combo.reset());
|
.map(|mut combo| combo.reset());
|
||||||
state
|
state
|
||||||
.ecs()
|
.ecs()
|
||||||
.write_storage::<comp::Pos>()
|
.write_storage::<Pos>()
|
||||||
.get_mut(entity)
|
.get_mut(entity)
|
||||||
.map(|pos| pos.0 = respawn_point);
|
.map(|pos| pos.0 = respawn_point);
|
||||||
state
|
state
|
||||||
@ -692,7 +692,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
|
|||||||
.any(|e| matches!(e, RadiusEffect::Attack(_))),
|
.any(|e| matches!(e, RadiusEffect::Attack(_))),
|
||||||
reagent: explosion.reagent,
|
reagent: explosion.reagent,
|
||||||
});
|
});
|
||||||
let groups = ecs.read_storage::<comp::Group>();
|
let groups = ecs.read_storage::<Group>();
|
||||||
|
|
||||||
// Used to get strength of explosion effects as they falloff over distance
|
// Used to get strength of explosion effects as they falloff over distance
|
||||||
fn cylinder_sphere_strength(
|
fn cylinder_sphere_strength(
|
||||||
@ -859,12 +859,12 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
RadiusEffect::Attack(attack) => {
|
RadiusEffect::Attack(attack) => {
|
||||||
let energies = &ecs.read_storage::<comp::Energy>();
|
let energies = &ecs.read_storage::<Energy>();
|
||||||
let combos = &ecs.read_storage::<comp::Combo>();
|
let combos = &ecs.read_storage::<comp::Combo>();
|
||||||
let inventories = &ecs.read_storage::<comp::Inventory>();
|
let inventories = &ecs.read_storage::<Inventory>();
|
||||||
let alignments = &ecs.read_storage::<Alignment>();
|
let alignments = &ecs.read_storage::<Alignment>();
|
||||||
let uid_allocator = &ecs.read_resource::<UidAllocator>();
|
let uid_allocator = &ecs.read_resource::<UidAllocator>();
|
||||||
let players = &ecs.read_storage::<comp::Player>();
|
let players = &ecs.read_storage::<Player>();
|
||||||
for (
|
for (
|
||||||
entity_b,
|
entity_b,
|
||||||
pos_b,
|
pos_b,
|
||||||
@ -872,13 +872,13 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
|
|||||||
(body_b_maybe, stats_b_maybe, ori_b_maybe, char_state_b_maybe, uid_b),
|
(body_b_maybe, stats_b_maybe, ori_b_maybe, char_state_b_maybe, uid_b),
|
||||||
) in (
|
) in (
|
||||||
&ecs.entities(),
|
&ecs.entities(),
|
||||||
&ecs.read_storage::<comp::Pos>(),
|
&ecs.read_storage::<Pos>(),
|
||||||
&ecs.read_storage::<comp::Health>(),
|
&ecs.read_storage::<Health>(),
|
||||||
(
|
(
|
||||||
ecs.read_storage::<comp::Body>().maybe(),
|
ecs.read_storage::<Body>().maybe(),
|
||||||
ecs.read_storage::<comp::Stats>().maybe(),
|
ecs.read_storage::<Stats>().maybe(),
|
||||||
ecs.read_storage::<comp::Ori>().maybe(),
|
ecs.read_storage::<comp::Ori>().maybe(),
|
||||||
ecs.read_storage::<comp::CharacterState>().maybe(),
|
ecs.read_storage::<CharacterState>().maybe(),
|
||||||
&ecs.read_storage::<Uid>(),
|
&ecs.read_storage::<Uid>(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@ -975,11 +975,11 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
|
|||||||
RadiusEffect::Entity(mut effect) => {
|
RadiusEffect::Entity(mut effect) => {
|
||||||
let alignments = &ecs.read_storage::<Alignment>();
|
let alignments = &ecs.read_storage::<Alignment>();
|
||||||
let uid_allocator = &ecs.read_resource::<UidAllocator>();
|
let uid_allocator = &ecs.read_resource::<UidAllocator>();
|
||||||
let players = &ecs.read_storage::<comp::Player>();
|
let players = &ecs.read_storage::<Player>();
|
||||||
for (entity_b, pos_b, body_b_maybe) in (
|
for (entity_b, pos_b, body_b_maybe) in (
|
||||||
&ecs.entities(),
|
&ecs.entities(),
|
||||||
&ecs.read_storage::<comp::Pos>(),
|
&ecs.read_storage::<Pos>(),
|
||||||
ecs.read_storage::<comp::Body>().maybe(),
|
ecs.read_storage::<Body>().maybe(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
{
|
{
|
||||||
@ -1011,7 +1011,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
|
|||||||
};
|
};
|
||||||
if strength > 0.0 {
|
if strength > 0.0 {
|
||||||
let is_alive = ecs
|
let is_alive = ecs
|
||||||
.read_storage::<comp::Health>()
|
.read_storage::<Health>()
|
||||||
.get(entity_b)
|
.get(entity_b)
|
||||||
.map_or(true, |h| !h.is_dead);
|
.map_or(true, |h| !h.is_dead);
|
||||||
|
|
||||||
@ -1056,7 +1056,7 @@ pub fn handle_bonk(server: &mut Server, pos: Vec3<f32>, owner: Option<Uid>, targ
|
|||||||
Some(SpriteKind::Bomb) => comp::object::Body::Bomb,
|
Some(SpriteKind::Bomb) => comp::object::Body::Bomb,
|
||||||
_ => comp::object::Body::Pouch,
|
_ => comp::object::Body::Pouch,
|
||||||
})
|
})
|
||||||
.with(comp::Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)))
|
.with(Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)))
|
||||||
.with(item)
|
.with(item)
|
||||||
.maybe_with(match block.get_sprite() {
|
.maybe_with(match block.get_sprite() {
|
||||||
Some(SpriteKind::Bomb) => Some(comp::Object::Bomb { owner }),
|
Some(SpriteKind::Bomb) => Some(comp::Object::Bomb { owner }),
|
||||||
@ -1071,7 +1071,7 @@ pub fn handle_bonk(server: &mut Server, pos: Vec3<f32>, owner: Option<Uid>, targ
|
|||||||
|
|
||||||
pub fn handle_aura(server: &mut Server, entity: EcsEntity, aura_change: aura::AuraChange) {
|
pub fn handle_aura(server: &mut Server, entity: EcsEntity, aura_change: aura::AuraChange) {
|
||||||
let ecs = &server.state.ecs();
|
let ecs = &server.state.ecs();
|
||||||
let mut auras_all = ecs.write_storage::<comp::Auras>();
|
let mut auras_all = ecs.write_storage::<Auras>();
|
||||||
if let Some(mut auras) = auras_all.get_mut(entity) {
|
if let Some(mut auras) = auras_all.get_mut(entity) {
|
||||||
use aura::AuraChange;
|
use aura::AuraChange;
|
||||||
match aura_change {
|
match aura_change {
|
||||||
@ -1090,7 +1090,7 @@ pub fn handle_aura(server: &mut Server, entity: EcsEntity, aura_change: aura::Au
|
|||||||
pub fn handle_buff(server: &mut Server, entity: EcsEntity, buff_change: buff::BuffChange) {
|
pub fn handle_buff(server: &mut Server, entity: EcsEntity, buff_change: buff::BuffChange) {
|
||||||
let ecs = &server.state.ecs();
|
let ecs = &server.state.ecs();
|
||||||
let mut buffs_all = ecs.write_storage::<comp::Buffs>();
|
let mut buffs_all = ecs.write_storage::<comp::Buffs>();
|
||||||
let bodies = ecs.read_storage::<comp::Body>();
|
let bodies = ecs.read_storage::<Body>();
|
||||||
if let Some(mut buffs) = buffs_all.get_mut(entity) {
|
if let Some(mut buffs) = buffs_all.get_mut(entity) {
|
||||||
use buff::BuffChange;
|
use buff::BuffChange;
|
||||||
match buff_change {
|
match buff_change {
|
||||||
@ -1238,7 +1238,7 @@ pub fn handle_combo_change(server: &Server, entity: EcsEntity, change: i32) {
|
|||||||
|
|
||||||
pub fn handle_parry(server: &Server, entity: EcsEntity, energy_cost: f32) {
|
pub fn handle_parry(server: &Server, entity: EcsEntity, energy_cost: f32) {
|
||||||
let ecs = &server.state.ecs();
|
let ecs = &server.state.ecs();
|
||||||
if let Some(mut character) = ecs.write_storage::<comp::CharacterState>().get_mut(entity) {
|
if let Some(mut character) = ecs.write_storage::<CharacterState>().get_mut(entity) {
|
||||||
*character =
|
*character =
|
||||||
CharacterState::Wielding(common::states::wielding::Data { is_sneaking: false });
|
CharacterState::Wielding(common::states::wielding::Data { is_sneaking: false });
|
||||||
};
|
};
|
||||||
@ -1316,11 +1316,11 @@ pub fn handle_entity_attacked_hook(server: &Server, entity: EcsEntity) {
|
|||||||
// Remove potion/saturation buff if attacked
|
// Remove potion/saturation buff if attacked
|
||||||
server_eventbus.emit_now(ServerEvent::Buff {
|
server_eventbus.emit_now(ServerEvent::Buff {
|
||||||
entity,
|
entity,
|
||||||
buff_change: buff::BuffChange::RemoveByKind(buff::BuffKind::Potion),
|
buff_change: buff::BuffChange::RemoveByKind(BuffKind::Potion),
|
||||||
});
|
});
|
||||||
server_eventbus.emit_now(ServerEvent::Buff {
|
server_eventbus.emit_now(ServerEvent::Buff {
|
||||||
entity,
|
entity,
|
||||||
buff_change: buff::BuffChange::RemoveByKind(buff::BuffKind::Saturation),
|
buff_change: buff::BuffChange::RemoveByKind(BuffKind::Saturation),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1332,8 +1332,8 @@ pub fn handle_change_ability(
|
|||||||
new_ability: ability::AuxiliaryAbility,
|
new_ability: ability::AuxiliaryAbility,
|
||||||
) {
|
) {
|
||||||
let ecs = &server.state.ecs();
|
let ecs = &server.state.ecs();
|
||||||
let inventories = ecs.read_storage::<comp::Inventory>();
|
let inventories = ecs.read_storage::<Inventory>();
|
||||||
let skill_sets = ecs.read_storage::<comp::SkillSet>();
|
let skill_sets = ecs.read_storage::<SkillSet>();
|
||||||
|
|
||||||
if let Some(mut active_abilities) = ecs.write_storage::<comp::ActiveAbilities>().get_mut(entity)
|
if let Some(mut active_abilities) = ecs.write_storage::<comp::ActiveAbilities>().get_mut(entity)
|
||||||
{
|
{
|
||||||
|
@ -113,7 +113,7 @@ pub fn update_map_markers<'a>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: turn chat messages into enums
|
// TODO: turn chat messages into enums
|
||||||
pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupManip) {
|
pub fn handle_group(server: &mut Server, entity: Entity, manip: GroupManip) {
|
||||||
match manip {
|
match manip {
|
||||||
GroupManip::Leave => {
|
GroupManip::Leave => {
|
||||||
let state = server.state_mut();
|
let state = server.state_mut();
|
||||||
@ -184,7 +184,7 @@ pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupMani
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut groups = state.ecs().write_storage::<group::Group>();
|
let mut groups = state.ecs().write_storage::<Group>();
|
||||||
let mut group_manager = state.ecs().write_resource::<GroupManager>();
|
let mut group_manager = state.ecs().write_resource::<GroupManager>();
|
||||||
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
|
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
|
||||||
// Make sure kicker is the group leader
|
// Make sure kicker is the group leader
|
||||||
@ -267,7 +267,7 @@ pub fn handle_group(server: &mut Server, entity: specs::Entity, manip: GroupMani
|
|||||||
return;
|
return;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let groups = state.ecs().read_storage::<group::Group>();
|
let groups = state.ecs().read_storage::<Group>();
|
||||||
let mut group_manager = state.ecs().write_resource::<GroupManager>();
|
let mut group_manager = state.ecs().write_resource::<GroupManager>();
|
||||||
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
|
let map_markers = state.ecs().read_storage::<comp::MapMarker>();
|
||||||
// Make sure assigner is the group leader
|
// Make sure assigner is the group leader
|
||||||
|
@ -100,7 +100,7 @@ pub fn handle_mount(server: &mut Server, rider: EcsEntity, mount: EcsEntity) {
|
|||||||
let not_mounting_yet = state.ecs().read_storage::<Is<Mount>>().get(mount).is_none();
|
let not_mounting_yet = state.ecs().read_storage::<Is<Mount>>().get(mount).is_none();
|
||||||
|
|
||||||
let within_range = || {
|
let within_range = || {
|
||||||
let positions = state.ecs().read_storage::<comp::Pos>();
|
let positions = state.ecs().read_storage::<Pos>();
|
||||||
within_mounting_range(positions.get(rider), positions.get(mount))
|
within_mounting_range(positions.get(rider), positions.get(mount))
|
||||||
};
|
};
|
||||||
let healths = state.ecs().read_storage::<comp::Health>();
|
let healths = state.ecs().read_storage::<comp::Health>();
|
||||||
@ -234,7 +234,7 @@ pub fn handle_mine_block(
|
|||||||
}
|
}
|
||||||
let item_drop = state
|
let item_drop = state
|
||||||
.create_item_drop(Default::default(), item)
|
.create_item_drop(Default::default(), item)
|
||||||
.with(comp::Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)));
|
.with(Pos(pos.map(|e| e as f32) + Vec3::new(0.5, 0.5, 0.0)));
|
||||||
if let Some(uid) = maybe_uid {
|
if let Some(uid) = maybe_uid {
|
||||||
item_drop.with(LootOwner::new(LootOwnerKind::Player(uid)))
|
item_drop.with(LootOwner::new(LootOwnerKind::Player(uid)))
|
||||||
} else {
|
} else {
|
||||||
@ -257,7 +257,7 @@ pub fn handle_mine_block(
|
|||||||
|
|
||||||
pub fn handle_sound(server: &mut Server, sound: &Sound) {
|
pub fn handle_sound(server: &mut Server, sound: &Sound) {
|
||||||
let ecs = &server.state.ecs();
|
let ecs = &server.state.ecs();
|
||||||
let positions = &ecs.read_storage::<comp::Pos>();
|
let positions = &ecs.read_storage::<Pos>();
|
||||||
let agents = &mut ecs.write_storage::<comp::Agent>();
|
let agents = &mut ecs.write_storage::<comp::Agent>();
|
||||||
|
|
||||||
// TODO: Reduce the complexity of this problem by using spatial partitioning
|
// TODO: Reduce the complexity of this problem by using spatial partitioning
|
||||||
|
@ -33,7 +33,7 @@ use common::{
|
|||||||
use common_net::msg::ServerGeneral;
|
use common_net::msg::ServerGeneral;
|
||||||
|
|
||||||
pub fn swap_lantern(
|
pub fn swap_lantern(
|
||||||
storage: &mut WriteStorage<comp::LightEmitter>,
|
storage: &mut WriteStorage<LightEmitter>,
|
||||||
entity: EcsEntity,
|
entity: EcsEntity,
|
||||||
(lantern_color, lantern_strength): (Rgb<f32>, f32),
|
(lantern_color, lantern_strength): (Rgb<f32>, f32),
|
||||||
) {
|
) {
|
||||||
@ -43,7 +43,7 @@ pub fn swap_lantern(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn snuff_lantern(storage: &mut WriteStorage<comp::LightEmitter>, entity: EcsEntity) {
|
pub fn snuff_lantern(storage: &mut WriteStorage<LightEmitter>, entity: EcsEntity) {
|
||||||
storage.remove(entity);
|
storage.remove(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -212,9 +212,9 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
);
|
);
|
||||||
drop(item_storage);
|
drop(item_storage);
|
||||||
drop(inventories);
|
drop(inventories);
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::EntityCollectFailed {
|
comp::InventoryUpdate::new(InventoryUpdateEvent::EntityCollectFailed {
|
||||||
entity: pickup_uid,
|
entity: pickup_uid,
|
||||||
reason: comp::CollectFailedReason::InventoryFull,
|
reason: CollectFailedReason::InventoryFull,
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
@ -227,10 +227,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
component.",
|
component.",
|
||||||
);
|
);
|
||||||
let ecs = state.ecs();
|
let ecs = state.ecs();
|
||||||
if let Some(group_id) = ecs.read_storage::<comp::Group>().get(entity) {
|
if let Some(group_id) = ecs.read_storage::<Group>().get(entity) {
|
||||||
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
|
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
|
||||||
}
|
}
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Collected(item_msg))
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Collected(item_msg))
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -255,12 +255,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
let event = match inventory.push(item) {
|
let event = match inventory.push(item) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let ecs = state.ecs();
|
let ecs = state.ecs();
|
||||||
if let Some(group_id) =
|
if let Some(group_id) = ecs.read_storage::<Group>().get(entity) {
|
||||||
ecs.read_storage::<comp::Group>().get(entity)
|
|
||||||
{
|
|
||||||
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
|
announce_loot_to_group(group_id, ecs, entity, &item_msg.name());
|
||||||
}
|
}
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Collected(
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Collected(
|
||||||
item_msg,
|
item_msg,
|
||||||
))
|
))
|
||||||
},
|
},
|
||||||
@ -269,9 +267,9 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
Err(_) => {
|
Err(_) => {
|
||||||
drop_item = Some(item_msg);
|
drop_item = Some(item_msg);
|
||||||
comp::InventoryUpdate::new(
|
comp::InventoryUpdate::new(
|
||||||
comp::InventoryUpdateEvent::BlockCollectFailed {
|
InventoryUpdateEvent::BlockCollectFailed {
|
||||||
pos,
|
pos,
|
||||||
reason: comp::CollectFailedReason::InventoryFull,
|
reason: CollectFailedReason::InventoryFull,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@ -343,18 +341,16 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
)
|
)
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
Some(comp::InventoryUpdateEvent::Used)
|
Some(InventoryUpdateEvent::Used)
|
||||||
} else if let Some(item) = inventory.take(
|
} else if let Some(item) = inventory.take(
|
||||||
slot,
|
slot,
|
||||||
&state.ecs().read_resource::<AbilityMap>(),
|
&state.ecs().read_resource::<AbilityMap>(),
|
||||||
&state.ecs().read_resource::<item::MaterialStatManifest>(),
|
&state.ecs().read_resource::<MaterialStatManifest>(),
|
||||||
) {
|
) {
|
||||||
match &*item.kind() {
|
match &*item.kind() {
|
||||||
ItemKind::Consumable { effects, .. } => {
|
ItemKind::Consumable { effects, .. } => {
|
||||||
maybe_effect = Some(effects.clone());
|
maybe_effect = Some(effects.clone());
|
||||||
Some(comp::InventoryUpdateEvent::Consumed(
|
Some(InventoryUpdateEvent::Consumed(item.name().into_owned()))
|
||||||
item.name().into_owned(),
|
|
||||||
))
|
|
||||||
},
|
},
|
||||||
ItemKind::Throwable { kind, .. } => {
|
ItemKind::Throwable { kind, .. } => {
|
||||||
if let Some(pos) =
|
if let Some(pos) =
|
||||||
@ -374,10 +370,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
*kind,
|
*kind,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Some(comp::InventoryUpdateEvent::Used)
|
Some(InventoryUpdateEvent::Used)
|
||||||
},
|
},
|
||||||
ItemKind::Utility {
|
ItemKind::Utility {
|
||||||
kind: comp::item::Utility::Collar,
|
kind: item::Utility::Collar,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
const MAX_PETS: usize = 3;
|
const MAX_PETS: usize = 3;
|
||||||
@ -385,7 +381,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
state.read_storage::<comp::Pos>().get(entity)
|
state.read_storage::<comp::Pos>().get(entity)
|
||||||
{
|
{
|
||||||
if (
|
if (
|
||||||
&state.read_storage::<comp::Alignment>(),
|
&state.read_storage::<Alignment>(),
|
||||||
&state.read_storage::<comp::Agent>(),
|
&state.read_storage::<comp::Agent>(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
@ -399,17 +395,16 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
} else if let Some(tameable_entity) = {
|
} else if let Some(tameable_entity) = {
|
||||||
let nearest_tameable = (
|
let nearest_tameable = (
|
||||||
&state.ecs().entities(),
|
&state.ecs().entities(),
|
||||||
&state.ecs().read_storage::<comp::Body>(),
|
&state.ecs().read_storage::<Body>(),
|
||||||
&state.ecs().read_storage::<comp::Pos>(),
|
&state.ecs().read_storage::<comp::Pos>(),
|
||||||
&state.ecs().read_storage::<comp::Alignment>(),
|
&state.ecs().read_storage::<Alignment>(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
.filter(|(_, _, wild_pos, _)| {
|
.filter(|(_, _, wild_pos, _)| {
|
||||||
wild_pos.0.distance_squared(pos.0) < 5.0f32.powi(2)
|
wild_pos.0.distance_squared(pos.0) < 5.0f32.powi(2)
|
||||||
})
|
})
|
||||||
.filter(|(_, body, _, alignment)| {
|
.filter(|(_, body, _, alignment)| {
|
||||||
alignment == &&comp::Alignment::Wild
|
alignment == &&Alignment::Wild && is_tameable(body)
|
||||||
&& is_tameable(body)
|
|
||||||
})
|
})
|
||||||
.min_by_key(|(_, _, wild_pos, _)| {
|
.min_by_key(|(_, _, wild_pos, _)| {
|
||||||
(wild_pos.0.distance_squared(pos.0) * 100.0) as i32
|
(wild_pos.0.distance_squared(pos.0) * 100.0) as i32
|
||||||
@ -435,7 +430,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
let _ = inventory.insert_or_stack_at(slot, item);
|
let _ = inventory.insert_or_stack_at(slot, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(comp::InventoryUpdateEvent::Used)
|
Some(InventoryUpdateEvent::Used)
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
inventory.insert_or_stack_at(slot, item).expect(
|
inventory.insert_or_stack_at(slot, item).expect(
|
||||||
@ -468,7 +463,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(comp::InventoryUpdateEvent::Used)
|
Some(InventoryUpdateEvent::Used)
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -535,7 +530,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
.write_storage()
|
.write_storage()
|
||||||
.insert(
|
.insert(
|
||||||
entity,
|
entity,
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Swapped),
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Swapped),
|
||||||
)
|
)
|
||||||
.expect("We know entity exists since we got its inventory.");
|
.expect("We know entity exists since we got its inventory.");
|
||||||
},
|
},
|
||||||
@ -576,7 +571,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
.write_storage()
|
.write_storage()
|
||||||
.insert(
|
.insert(
|
||||||
entity,
|
entity,
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Swapped),
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Swapped),
|
||||||
)
|
)
|
||||||
.expect("We know entity exists since we got its inventory.");
|
.expect("We know entity exists since we got its inventory.");
|
||||||
drop(inventories);
|
drop(inventories);
|
||||||
@ -605,7 +600,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
.write_storage()
|
.write_storage()
|
||||||
.insert(
|
.insert(
|
||||||
entity,
|
entity,
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Dropped),
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Dropped),
|
||||||
)
|
)
|
||||||
.expect("We know entity exists since we got its inventory.");
|
.expect("We know entity exists since we got its inventory.");
|
||||||
drop(inventories);
|
drop(inventories);
|
||||||
@ -637,7 +632,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
.write_storage()
|
.write_storage()
|
||||||
.insert(
|
.insert(
|
||||||
entity,
|
entity,
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Dropped),
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Dropped),
|
||||||
)
|
)
|
||||||
.expect("We know entity exists since we got its inventory.");
|
.expect("We know entity exists since we got its inventory.");
|
||||||
drop(inventories);
|
drop(inventories);
|
||||||
@ -692,7 +687,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
&mut inventory,
|
&mut inventory,
|
||||||
slots,
|
slots,
|
||||||
&state.ecs().read_resource::<AbilityMap>(),
|
&state.ecs().read_resource::<AbilityMap>(),
|
||||||
&state.ecs().read_resource::<item::MaterialStatManifest>(),
|
&state.ecs().read_resource::<MaterialStatManifest>(),
|
||||||
)
|
)
|
||||||
.ok()
|
.ok()
|
||||||
}),
|
}),
|
||||||
@ -757,7 +752,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
modifier,
|
modifier,
|
||||||
slots,
|
slots,
|
||||||
&state.ecs().read_resource::<AbilityMap>(),
|
&state.ecs().read_resource::<AbilityMap>(),
|
||||||
&state.ecs().read_resource::<item::MaterialStatManifest>(),
|
&state.ecs().read_resource::<MaterialStatManifest>(),
|
||||||
)
|
)
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
@ -794,7 +789,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv
|
|||||||
if items_were_crafted {
|
if items_were_crafted {
|
||||||
let _ = state.ecs().write_storage().insert(
|
let _ = state.ecs().write_storage().insert(
|
||||||
entity,
|
entity,
|
||||||
comp::InventoryUpdate::new(comp::InventoryUpdateEvent::Craft),
|
comp::InventoryUpdate::new(InventoryUpdateEvent::Craft),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -934,7 +929,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
// Helper function
|
// Helper function
|
||||||
fn test_cylinder(pos: comp::Pos) -> Option<Cylinder> {
|
fn test_cylinder(pos: Pos) -> Option<Cylinder> {
|
||||||
Some(Cylinder::from_components(pos.0, None, None, None))
|
Some(Cylinder::from_components(pos.0, None, None, None))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -26,12 +26,7 @@ const INVITE_TIMEOUT_DUR: Duration = Duration::from_secs(31);
|
|||||||
/// Reduced duration shown to the client to help alleviate latency issues
|
/// Reduced duration shown to the client to help alleviate latency issues
|
||||||
const PRESENTED_INVITE_TIMEOUT_DUR: Duration = Duration::from_secs(30);
|
const PRESENTED_INVITE_TIMEOUT_DUR: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
pub fn handle_invite(
|
pub fn handle_invite(server: &mut Server, inviter: Entity, invitee_uid: Uid, kind: InviteKind) {
|
||||||
server: &mut Server,
|
|
||||||
inviter: specs::Entity,
|
|
||||||
invitee_uid: Uid,
|
|
||||||
kind: InviteKind,
|
|
||||||
) {
|
|
||||||
let max_group_size = server.settings().max_player_group_size;
|
let max_group_size = server.settings().max_player_group_size;
|
||||||
let state = server.state_mut();
|
let state = server.state_mut();
|
||||||
let clients = state.ecs().read_storage::<Client>();
|
let clients = state.ecs().read_storage::<Client>();
|
||||||
@ -61,12 +56,12 @@ pub fn handle_invite(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut pending_invites = state.ecs().write_storage::<PendingInvites>();
|
let mut pending_invites = state.ecs().write_storage::<PendingInvites>();
|
||||||
let mut agents = state.ecs().write_storage::<comp::Agent>();
|
let mut agents = state.ecs().write_storage::<Agent>();
|
||||||
let mut invites = state.ecs().write_storage::<Invite>();
|
let mut invites = state.ecs().write_storage::<Invite>();
|
||||||
|
|
||||||
if let InviteKind::Trade = kind {
|
if let InviteKind::Trade = kind {
|
||||||
// Check whether the inviter is in range of the invitee
|
// Check whether the inviter is in range of the invitee
|
||||||
let positions = state.ecs().read_storage::<comp::Pos>();
|
let positions = state.ecs().read_storage::<Pos>();
|
||||||
if !within_trading_range(positions.get(inviter), positions.get(invitee)) {
|
if !within_trading_range(positions.get(inviter), positions.get(invitee)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -180,18 +175,14 @@ pub fn handle_invite(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn handle_invite_response(
|
pub fn handle_invite_response(server: &mut Server, entity: Entity, response: InviteResponse) {
|
||||||
server: &mut Server,
|
|
||||||
entity: specs::Entity,
|
|
||||||
response: InviteResponse,
|
|
||||||
) {
|
|
||||||
match response {
|
match response {
|
||||||
InviteResponse::Accept => handle_invite_accept(server, entity),
|
InviteResponse::Accept => handle_invite_accept(server, entity),
|
||||||
InviteResponse::Decline => handle_invite_decline(server, entity),
|
InviteResponse::Decline => handle_invite_decline(server, entity),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_invite_accept(server: &mut Server, entity: specs::Entity) {
|
pub fn handle_invite_accept(server: &mut Server, entity: Entity) {
|
||||||
let index = server.index.clone();
|
let index = server.index.clone();
|
||||||
let state = server.state_mut();
|
let state = server.state_mut();
|
||||||
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
|
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
|
||||||
@ -324,7 +315,7 @@ fn handle_invite_answer(
|
|||||||
client
|
client
|
||||||
.send_fallible(ServerGeneral::FinishedTrade(TradeResult::Declined));
|
.send_fallible(ServerGeneral::FinishedTrade(TradeResult::Declined));
|
||||||
}
|
}
|
||||||
if let Some(agent) = state.ecs().write_storage::<comp::Agent>().get_mut(e) {
|
if let Some(agent) = state.ecs().write_storage::<Agent>().get_mut(e) {
|
||||||
agent
|
agent
|
||||||
.inbox
|
.inbox
|
||||||
.push_back(AgentEvent::FinishedTrade(TradeResult::Declined));
|
.push_back(AgentEvent::FinishedTrade(TradeResult::Declined));
|
||||||
@ -342,7 +333,7 @@ fn handle_invite_answer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_invite_decline(server: &mut Server, entity: specs::Entity) {
|
pub fn handle_invite_decline(server: &mut Server, entity: Entity) {
|
||||||
let state = server.state_mut();
|
let state = server.state_mut();
|
||||||
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
|
if let Some((inviter, kind)) = get_inviter_and_kind(entity, state) {
|
||||||
// Inform inviter of rejection
|
// Inform inviter of rejection
|
||||||
|
@ -223,12 +223,12 @@ fn persist_entity(state: &mut State, entity: EcsEntity) -> EcsEntity {
|
|||||||
PresenceKind::Character(char_id) => {
|
PresenceKind::Character(char_id) => {
|
||||||
let waypoint = state
|
let waypoint = state
|
||||||
.ecs()
|
.ecs()
|
||||||
.read_storage::<common::comp::Waypoint>()
|
.read_storage::<comp::Waypoint>()
|
||||||
.get(entity)
|
.get(entity)
|
||||||
.cloned();
|
.cloned();
|
||||||
let map_marker = state
|
let map_marker = state
|
||||||
.ecs()
|
.ecs()
|
||||||
.read_storage::<common::comp::MapMarker>()
|
.read_storage::<comp::MapMarker>()
|
||||||
.get(entity)
|
.get(entity)
|
||||||
.cloned();
|
.cloned();
|
||||||
// Store last battle mode change
|
// Store last battle mode change
|
||||||
@ -421,8 +421,9 @@ pub fn handle_possess(server: &mut Server, possessor_uid: Uid, possessee_uid: Ui
|
|||||||
if let Some(player) = players.get(possessee) {
|
if let Some(player) = players.get(possessee) {
|
||||||
use common_net::msg;
|
use common_net::msg;
|
||||||
|
|
||||||
let add_player_msg = ServerGeneral::PlayerListUpdate(
|
let add_player_msg = ServerGeneral::PlayerListUpdate(PlayerListUpdate::Add(
|
||||||
msg::server::PlayerListUpdate::Add(possessee_uid, msg::server::PlayerInfo {
|
possessee_uid,
|
||||||
|
msg::server::PlayerInfo {
|
||||||
player_alias: player.alias.clone(),
|
player_alias: player.alias.clone(),
|
||||||
is_online: true,
|
is_online: true,
|
||||||
is_moderator: admins.contains(possessee),
|
is_moderator: admins.contains(possessee),
|
||||||
@ -432,11 +433,10 @@ pub fn handle_possess(server: &mut Server, possessor_uid: Uid, possessee_uid: Ui
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
uuid: player.uuid(),
|
uuid: player.uuid(),
|
||||||
}),
|
},
|
||||||
);
|
));
|
||||||
let remove_player_msg = ServerGeneral::PlayerListUpdate(
|
let remove_player_msg =
|
||||||
msg::server::PlayerListUpdate::Remove(possessor_uid),
|
ServerGeneral::PlayerListUpdate(PlayerListUpdate::Remove(possessor_uid));
|
||||||
);
|
|
||||||
|
|
||||||
drop((clients, players)); // need to drop so we can use `notify_players` below
|
drop((clients, players)); // need to drop so we can use `notify_players` below
|
||||||
state.notify_players(remove_player_msg);
|
state.notify_players(remove_player_msg);
|
||||||
|
@ -333,7 +333,7 @@ impl Server {
|
|||||||
state.ecs_mut().register::<Presence>();
|
state.ecs_mut().register::<Presence>();
|
||||||
state.ecs_mut().register::<wiring::WiringElement>();
|
state.ecs_mut().register::<wiring::WiringElement>();
|
||||||
state.ecs_mut().register::<wiring::Circuit>();
|
state.ecs_mut().register::<wiring::Circuit>();
|
||||||
state.ecs_mut().register::<comp::Anchor>();
|
state.ecs_mut().register::<Anchor>();
|
||||||
state.ecs_mut().register::<comp::Pet>();
|
state.ecs_mut().register::<comp::Pet>();
|
||||||
state.ecs_mut().register::<login_provider::PendingLogin>();
|
state.ecs_mut().register::<login_provider::PendingLogin>();
|
||||||
state.ecs_mut().register::<RepositionOnChunkLoad>();
|
state.ecs_mut().register::<RepositionOnChunkLoad>();
|
||||||
@ -346,7 +346,7 @@ impl Server {
|
|||||||
Ok(file) => match ron::de::from_reader(&file) {
|
Ok(file) => match ron::de::from_reader(&file) {
|
||||||
Ok(vec) => vec,
|
Ok(vec) => vec,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
tracing::warn!(?error, ?file, "Couldn't deserialize banned words file");
|
warn!(?error, ?file, "Couldn't deserialize banned words file");
|
||||||
return Err(Error::Other(format!(
|
return Err(Error::Other(format!(
|
||||||
"Couldn't read banned words file \"{}\"",
|
"Couldn't read banned words file \"{}\"",
|
||||||
path.to_string_lossy()
|
path.to_string_lossy()
|
||||||
@ -354,7 +354,7 @@ impl Server {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
tracing::warn!(?error, ?path, "Couldn't open banned words file");
|
warn!(?error, ?path, "Couldn't open banned words file");
|
||||||
return Err(Error::Other(format!(
|
return Err(Error::Other(format!(
|
||||||
"Couldn't open banned words file \"{}\". Error: {}",
|
"Couldn't open banned words file \"{}\". Error: {}",
|
||||||
path.to_string_lossy(),
|
path.to_string_lossy(),
|
||||||
@ -365,8 +365,8 @@ impl Server {
|
|||||||
banned_words.append(&mut list);
|
banned_words.append(&mut list);
|
||||||
}
|
}
|
||||||
let banned_words_count = banned_words.len();
|
let banned_words_count = banned_words.len();
|
||||||
tracing::debug!(?banned_words_count);
|
debug!(?banned_words_count);
|
||||||
tracing::trace!(?banned_words);
|
trace!(?banned_words);
|
||||||
state.ecs_mut().insert(AliasValidator::new(banned_words));
|
state.ecs_mut().insert(AliasValidator::new(banned_words));
|
||||||
|
|
||||||
#[cfg(feature = "worldgen")]
|
#[cfg(feature = "worldgen")]
|
||||||
@ -759,10 +759,10 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Prevent anchor entity chains which are not currently supported
|
// Prevent anchor entity chains which are not currently supported
|
||||||
let anchors = self.state.ecs().read_storage::<comp::Anchor>();
|
let anchors = self.state.ecs().read_storage::<Anchor>();
|
||||||
let anchored_anchor_entities: Vec<Entity> = (
|
let anchored_anchor_entities: Vec<Entity> = (
|
||||||
&self.state.ecs().entities(),
|
&self.state.ecs().entities(),
|
||||||
&self.state.ecs().read_storage::<comp::Anchor>(),
|
&self.state.ecs().read_storage::<Anchor>(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
.filter_map(|(_, anchor)| match anchor {
|
.filter_map(|(_, anchor)| match anchor {
|
||||||
@ -792,7 +792,7 @@ impl Server {
|
|||||||
&self.state.ecs().entities(),
|
&self.state.ecs().entities(),
|
||||||
&self.state.ecs().read_storage::<comp::Pos>(),
|
&self.state.ecs().read_storage::<comp::Pos>(),
|
||||||
!&self.state.ecs().read_storage::<Presence>(),
|
!&self.state.ecs().read_storage::<Presence>(),
|
||||||
self.state.ecs().read_storage::<comp::Anchor>().maybe(),
|
self.state.ecs().read_storage::<Anchor>().maybe(),
|
||||||
)
|
)
|
||||||
.join()
|
.join()
|
||||||
.filter(|(_, pos, _, anchor)| {
|
.filter(|(_, pos, _, anchor)| {
|
||||||
@ -847,15 +847,9 @@ impl Server {
|
|||||||
// 7 Persistence updates
|
// 7 Persistence updates
|
||||||
let before_persistence_updates = Instant::now();
|
let before_persistence_updates = Instant::now();
|
||||||
|
|
||||||
let character_loader = self
|
let character_loader = self.state.ecs().read_resource::<CharacterLoader>();
|
||||||
.state
|
|
||||||
.ecs()
|
|
||||||
.read_resource::<persistence::character_loader::CharacterLoader>();
|
|
||||||
|
|
||||||
let character_updater = self
|
let character_updater = self.state.ecs().read_resource::<CharacterUpdater>();
|
||||||
.state
|
|
||||||
.ecs()
|
|
||||||
.read_resource::<persistence::character_updater::CharacterUpdater>();
|
|
||||||
|
|
||||||
// Get character-related database responses and notify the requesting client
|
// Get character-related database responses and notify the requesting client
|
||||||
character_loader
|
character_loader
|
||||||
@ -1005,7 +999,7 @@ impl Server {
|
|||||||
|
|
||||||
{
|
{
|
||||||
// Report timing info
|
// Report timing info
|
||||||
let tick_metrics = self.state.ecs().read_resource::<metrics::TickMetrics>();
|
let tick_metrics = self.state.ecs().read_resource::<TickMetrics>();
|
||||||
|
|
||||||
let tt = &tick_metrics.tick_time;
|
let tt = &tick_metrics.tick_time;
|
||||||
tt.with_label_values(&["new connections"])
|
tt.with_label_values(&["new connections"])
|
||||||
@ -1049,8 +1043,8 @@ impl Server {
|
|||||||
|
|
||||||
fn initialize_client(
|
fn initialize_client(
|
||||||
&mut self,
|
&mut self,
|
||||||
client: crate::connection_handler::IncomingClient,
|
client: connection_handler::IncomingClient,
|
||||||
) -> Result<Option<specs::Entity>, Error> {
|
) -> Result<Option<Entity>, Error> {
|
||||||
if self.settings().max_players <= self.state.ecs().read_storage::<Client>().join().count() {
|
if self.settings().max_players <= self.state.ecs().read_storage::<Client>().join().count() {
|
||||||
trace!(
|
trace!(
|
||||||
?client.participant,
|
?client.participant,
|
||||||
@ -1166,7 +1160,7 @@ impl Server {
|
|||||||
while let Ok(sender) = self.connection_handler.info_requester_receiver.try_recv() {
|
while let Ok(sender) = self.connection_handler.info_requester_receiver.try_recv() {
|
||||||
// can fail, e.g. due to timeout or network prob.
|
// can fail, e.g. due to timeout or network prob.
|
||||||
trace!("sending info to connection_handler");
|
trace!("sending info to connection_handler");
|
||||||
let _ = sender.send(crate::connection_handler::ServerInfoPacket {
|
let _ = sender.send(connection_handler::ServerInfoPacket {
|
||||||
info: self.get_server_info(),
|
info: self.get_server_info(),
|
||||||
time: self.state.get_time(),
|
time: self.state.get_time(),
|
||||||
});
|
});
|
||||||
|
@ -164,13 +164,13 @@ impl LoginProvider {
|
|||||||
info!(?username, "New User");
|
info!(?username, "New User");
|
||||||
Some(Ok((username, uuid)))
|
Some(Ok((username, uuid)))
|
||||||
},
|
},
|
||||||
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
|
Err(oneshot::error::TryRecvError::Closed) => {
|
||||||
error!("channel got closed to early, this shouldn't happen");
|
error!("channel got closed to early, this shouldn't happen");
|
||||||
Some(Err(RegisterError::AuthError(
|
Some(Err(RegisterError::AuthError(
|
||||||
"Internal Error verifying".to_string(),
|
"Internal Error verifying".to_string(),
|
||||||
)))
|
)))
|
||||||
},
|
},
|
||||||
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None,
|
Err(oneshot::error::TryRecvError::Empty) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -186,7 +186,7 @@ impl LoginProvider {
|
|||||||
match async {
|
match async {
|
||||||
let uuid = srv.validate(token).await?;
|
let uuid = srv.validate(token).await?;
|
||||||
let username = srv.uuid_to_username(uuid).await?;
|
let username = srv.uuid_to_username(uuid).await?;
|
||||||
let r: Result<_, authc::AuthClientError> = Ok((username, uuid));
|
let r: Result<_, AuthClientError> = Ok((username, uuid));
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
|
@ -543,9 +543,7 @@ pub fn edit_character(
|
|||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|c| c.character.id == Some(character_id))
|
.find(|c| c.character.id == Some(character_id))
|
||||||
{
|
{
|
||||||
if let (crate::comp::Body::Humanoid(new), crate::comp::Body::Humanoid(old)) =
|
if let (comp::Body::Humanoid(new), comp::Body::Humanoid(old)) = (body, char.body) {
|
||||||
(body, char.body)
|
|
||||||
{
|
|
||||||
if new.species != old.species || new.body_type != old.body_type {
|
if new.species != old.species || new.body_type != old.body_type {
|
||||||
warn!(
|
warn!(
|
||||||
"Character edit rejected due to failed validation - Character ID: {} \
|
"Character edit rejected due to failed validation - Character ID: {} \
|
||||||
@ -948,7 +946,7 @@ fn delete_pets(
|
|||||||
pub fn update(
|
pub fn update(
|
||||||
char_id: CharacterId,
|
char_id: CharacterId,
|
||||||
char_skill_set: comp::SkillSet,
|
char_skill_set: comp::SkillSet,
|
||||||
inventory: comp::Inventory,
|
inventory: Inventory,
|
||||||
pets: Vec<PetPersistenceData>,
|
pets: Vec<PetPersistenceData>,
|
||||||
char_waypoint: Option<comp::Waypoint>,
|
char_waypoint: Option<comp::Waypoint>,
|
||||||
active_abilities: comp::ability::ActiveAbilities,
|
active_abilities: comp::ability::ActiveAbilities,
|
||||||
|
@ -28,7 +28,7 @@ use tracing::{trace, warn};
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ItemModelPair {
|
pub struct ItemModelPair {
|
||||||
pub comp: Arc<common::comp::item::ItemId>,
|
pub comp: Arc<item::ItemId>,
|
||||||
pub model: Item,
|
pub model: Item,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -193,23 +193,23 @@ pub fn convert_body_to_database_json(
|
|||||||
comp_body: &CompBody,
|
comp_body: &CompBody,
|
||||||
) -> Result<(&str, String), PersistenceError> {
|
) -> Result<(&str, String), PersistenceError> {
|
||||||
Ok(match comp_body {
|
Ok(match comp_body {
|
||||||
common::comp::Body::Humanoid(body) => (
|
Body::Humanoid(body) => (
|
||||||
"humanoid",
|
"humanoid",
|
||||||
serde_json::to_string(&HumanoidBody::from(body))?,
|
serde_json::to_string(&HumanoidBody::from(body))?,
|
||||||
),
|
),
|
||||||
common::comp::Body::QuadrupedLow(body) => (
|
Body::QuadrupedLow(body) => (
|
||||||
"quadruped_low",
|
"quadruped_low",
|
||||||
serde_json::to_string(&GenericBody::from(body))?,
|
serde_json::to_string(&GenericBody::from(body))?,
|
||||||
),
|
),
|
||||||
common::comp::Body::QuadrupedMedium(body) => (
|
Body::QuadrupedMedium(body) => (
|
||||||
"quadruped_medium",
|
"quadruped_medium",
|
||||||
serde_json::to_string(&GenericBody::from(body))?,
|
serde_json::to_string(&GenericBody::from(body))?,
|
||||||
),
|
),
|
||||||
common::comp::Body::QuadrupedSmall(body) => (
|
Body::QuadrupedSmall(body) => (
|
||||||
"quadruped_small",
|
"quadruped_small",
|
||||||
serde_json::to_string(&GenericBody::from(body))?,
|
serde_json::to_string(&GenericBody::from(body))?,
|
||||||
),
|
),
|
||||||
common::comp::Body::BirdMedium(body) => (
|
Body::BirdMedium(body) => (
|
||||||
"bird_medium",
|
"bird_medium",
|
||||||
serde_json::to_string(&GenericBody::from(body))?,
|
serde_json::to_string(&GenericBody::from(body))?,
|
||||||
),
|
),
|
||||||
@ -544,8 +544,8 @@ pub fn convert_body_from_database(
|
|||||||
// extra fields on its body struct
|
// extra fields on its body struct
|
||||||
"humanoid" => {
|
"humanoid" => {
|
||||||
let json_model = serde_json::de::from_str::<HumanoidBody>(body_data)?;
|
let json_model = serde_json::de::from_str::<HumanoidBody>(body_data)?;
|
||||||
CompBody::Humanoid(common::comp::humanoid::Body {
|
CompBody::Humanoid(humanoid::Body {
|
||||||
species: common::comp::humanoid::ALL_SPECIES
|
species: humanoid::ALL_SPECIES
|
||||||
.get(json_model.species as usize)
|
.get(json_model.species as usize)
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
PersistenceError::ConversionError(format!(
|
PersistenceError::ConversionError(format!(
|
||||||
@ -554,7 +554,7 @@ pub fn convert_body_from_database(
|
|||||||
))
|
))
|
||||||
})?
|
})?
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
body_type: common::comp::humanoid::ALL_BODY_TYPES
|
body_type: humanoid::ALL_BODY_TYPES
|
||||||
.get(json_model.body_type as usize)
|
.get(json_model.body_type as usize)
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
PersistenceError::ConversionError(format!(
|
PersistenceError::ConversionError(format!(
|
||||||
@ -600,16 +600,16 @@ pub fn convert_character_from_database(character: &Character) -> common::charact
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn convert_stats_from_database(alias: String) -> common::comp::Stats {
|
pub fn convert_stats_from_database(alias: String) -> Stats {
|
||||||
let mut new_stats = common::comp::Stats::empty();
|
let mut new_stats = Stats::empty();
|
||||||
new_stats.name = alias;
|
new_stats.name = alias;
|
||||||
new_stats
|
new_stats
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn convert_skill_set_from_database(skill_groups: &[SkillGroup]) -> common::comp::SkillSet {
|
pub fn convert_skill_set_from_database(skill_groups: &[SkillGroup]) -> SkillSet {
|
||||||
let (skillless_skill_groups, deserialized_skills) =
|
let (skillless_skill_groups, deserialized_skills) =
|
||||||
convert_skill_groups_from_database(skill_groups);
|
convert_skill_groups_from_database(skill_groups);
|
||||||
common::comp::SkillSet::load_from_database(skillless_skill_groups, deserialized_skills)
|
SkillSet::load_from_database(skillless_skill_groups, deserialized_skills)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
@ -618,9 +618,9 @@ fn convert_skill_groups_from_database(
|
|||||||
) -> (
|
) -> (
|
||||||
// Skill groups in the vec do not contain skills, those are added later. The skill group only
|
// Skill groups in the vec do not contain skills, those are added later. The skill group only
|
||||||
// contains fields related to experience and skill points
|
// contains fields related to experience and skill points
|
||||||
HashMap<skillset::SkillGroupKind, skillset::SkillGroup>,
|
HashMap<SkillGroupKind, skillset::SkillGroup>,
|
||||||
//
|
//
|
||||||
HashMap<skillset::SkillGroupKind, Result<Vec<skills::Skill>, skillset::SkillsPersistenceError>>,
|
HashMap<SkillGroupKind, Result<Vec<Skill>, skillset::SkillsPersistenceError>>,
|
||||||
) {
|
) {
|
||||||
let mut new_skill_groups = HashMap::new();
|
let mut new_skill_groups = HashMap::new();
|
||||||
let mut deserialized_skills = HashMap::new();
|
let mut deserialized_skills = HashMap::new();
|
||||||
@ -657,7 +657,7 @@ fn convert_skill_groups_from_database(
|
|||||||
Err(SkillsPersistenceError::HashMismatch)
|
Err(SkillsPersistenceError::HashMismatch)
|
||||||
} else {
|
} else {
|
||||||
// Else attempt to deserialize skills from a json string
|
// Else attempt to deserialize skills from a json string
|
||||||
match serde_json::from_str::<Vec<skills::Skill>>(&skill_group.skills) {
|
match serde_json::from_str::<Vec<Skill>>(&skill_group.skills) {
|
||||||
// If it correctly deserializes, return the persisted skills
|
// If it correctly deserializes, return the persisted skills
|
||||||
Ok(skills) => Ok(skills),
|
Ok(skills) => Ok(skills),
|
||||||
// Else if doesn't deserialize correctly, force a respec
|
// Else if doesn't deserialize correctly, force a respec
|
||||||
@ -702,7 +702,7 @@ pub fn convert_skill_groups_to_database<'a, I: Iterator<Item = &'a skillset::Ski
|
|||||||
|
|
||||||
pub fn convert_active_abilities_to_database(
|
pub fn convert_active_abilities_to_database(
|
||||||
entity_id: CharacterId,
|
entity_id: CharacterId,
|
||||||
active_abilities: &ability::ActiveAbilities,
|
active_abilities: &ActiveAbilities,
|
||||||
) -> AbilitySets {
|
) -> AbilitySets {
|
||||||
let ability_sets = json_models::active_abilities_to_db_model(active_abilities);
|
let ability_sets = json_models::active_abilities_to_db_model(active_abilities);
|
||||||
AbilitySets {
|
AbilitySets {
|
||||||
@ -711,9 +711,7 @@ pub fn convert_active_abilities_to_database(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn convert_active_abilities_from_database(
|
pub fn convert_active_abilities_from_database(ability_sets: &AbilitySets) -> ActiveAbilities {
|
||||||
ability_sets: &AbilitySets,
|
|
||||||
) -> ability::ActiveAbilities {
|
|
||||||
let ability_sets = serde_json::from_str::<Vec<DatabaseAbilitySet>>(&ability_sets.ability_sets)
|
let ability_sets = serde_json::from_str::<Vec<DatabaseAbilitySet>>(&ability_sets.ability_sets)
|
||||||
.unwrap_or_else(|err| {
|
.unwrap_or_else(|err| {
|
||||||
common_base::dev_panic!(format!(
|
common_base::dev_panic!(format!(
|
||||||
|
@ -118,7 +118,7 @@ pub struct DatabaseAbilitySet {
|
|||||||
abilities: Vec<String>,
|
abilities: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn aux_ability_to_string(ability: common::comp::ability::AuxiliaryAbility) -> String {
|
fn aux_ability_to_string(ability: comp::ability::AuxiliaryAbility) -> String {
|
||||||
use common::comp::ability::AuxiliaryAbility;
|
use common::comp::ability::AuxiliaryAbility;
|
||||||
match ability {
|
match ability {
|
||||||
AuxiliaryAbility::MainWeapon(index) => format!("Main Weapon:index:{}", index),
|
AuxiliaryAbility::MainWeapon(index) => format!("Main Weapon:index:{}", index),
|
||||||
@ -127,7 +127,7 @@ fn aux_ability_to_string(ability: common::comp::ability::AuxiliaryAbility) -> St
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn aux_ability_from_string(ability: &str) -> common::comp::ability::AuxiliaryAbility {
|
fn aux_ability_from_string(ability: &str) -> comp::ability::AuxiliaryAbility {
|
||||||
use common::comp::ability::AuxiliaryAbility;
|
use common::comp::ability::AuxiliaryAbility;
|
||||||
let mut parts = ability.split(":index:");
|
let mut parts = ability.split(":index:");
|
||||||
match parts.next() {
|
match parts.next() {
|
||||||
@ -184,7 +184,7 @@ fn aux_ability_from_string(ability: &str) -> common::comp::ability::AuxiliaryAbi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn tool_kind_to_string(tool: Option<common::comp::item::tool::ToolKind>) -> String {
|
fn tool_kind_to_string(tool: Option<comp::item::tool::ToolKind>) -> String {
|
||||||
use common::comp::item::tool::ToolKind::*;
|
use common::comp::item::tool::ToolKind::*;
|
||||||
String::from(match tool {
|
String::from(match tool {
|
||||||
Some(Sword) => "Sword",
|
Some(Sword) => "Sword",
|
||||||
@ -208,7 +208,7 @@ fn tool_kind_to_string(tool: Option<common::comp::item::tool::ToolKind>) -> Stri
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn tool_kind_from_string(tool: String) -> Option<common::comp::item::tool::ToolKind> {
|
fn tool_kind_from_string(tool: String) -> Option<comp::item::tool::ToolKind> {
|
||||||
use common::comp::item::tool::ToolKind::*;
|
use common::comp::item::tool::ToolKind::*;
|
||||||
match tool.as_str() {
|
match tool.as_str() {
|
||||||
"Sword" => Some(Sword),
|
"Sword" => Some(Sword),
|
||||||
|
@ -1022,7 +1022,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_entity_configs() {
|
fn test_entity_configs() {
|
||||||
let dummy_pos = Vec3::new(0.0, 0.0, 0.0);
|
let dummy_pos = Vec3::new(0.0, 0.0, 0.0);
|
||||||
let mut dummy_rng = rand::thread_rng();
|
let mut dummy_rng = thread_rng();
|
||||||
// Bird Large test
|
// Bird Large test
|
||||||
for bird_large_species in BIRD_LARGE_ROSTER {
|
for bird_large_species in BIRD_LARGE_ROSTER {
|
||||||
let female_body = comp::bird_large::Body {
|
let female_body = comp::bird_large::Body {
|
||||||
@ -1035,13 +1035,9 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let female_config = bird_large_config(female_body);
|
let female_config = bird_large_config(female_body);
|
||||||
std::mem::drop(
|
drop(EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng));
|
||||||
EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng),
|
|
||||||
);
|
|
||||||
let male_config = bird_large_config(male_body);
|
let male_config = bird_large_config(male_body);
|
||||||
std::mem::drop(
|
drop(EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng));
|
||||||
EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
// Bird Medium test
|
// Bird Medium test
|
||||||
for bird_med_species in BIRD_MEDIUM_ROSTER {
|
for bird_med_species in BIRD_MEDIUM_ROSTER {
|
||||||
@ -1055,19 +1051,15 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let female_config = bird_medium_config(female_body);
|
let female_config = bird_medium_config(female_body);
|
||||||
std::mem::drop(
|
drop(EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng));
|
||||||
EntityInfo::at(dummy_pos).with_asset_expect(female_config, &mut dummy_rng),
|
|
||||||
);
|
|
||||||
let male_config = bird_medium_config(male_body);
|
let male_config = bird_medium_config(male_body);
|
||||||
std::mem::drop(
|
drop(EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng));
|
||||||
EntityInfo::at(dummy_pos).with_asset_expect(male_config, &mut dummy_rng),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
// Humanoid test
|
// Humanoid test
|
||||||
for kind in RtSimEntityKind::iter() {
|
for kind in RtSimEntityKind::iter() {
|
||||||
for rank in TravelerRank::iter() {
|
for rank in TravelerRank::iter() {
|
||||||
let config = humanoid_config(kind, rank);
|
let config = humanoid_config(kind, rank);
|
||||||
std::mem::drop(EntityInfo::at(dummy_pos).with_asset_expect(config, &mut dummy_rng));
|
drop(EntityInfo::at(dummy_pos).with_asset_expect(config, &mut dummy_rng));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@ pub use self::v1::*;
|
|||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub enum AdminsRaw {
|
pub enum AdminsRaw {
|
||||||
V0(v0::Admins),
|
V0(v0::Admins),
|
||||||
V1(v1::Admins),
|
V1(Admins),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Admins> for AdminsRaw {
|
impl From<Admins> for AdminsRaw {
|
||||||
|
@ -19,7 +19,7 @@ pub use self::v1::*;
|
|||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub enum BanlistRaw {
|
pub enum BanlistRaw {
|
||||||
V0(v0::Banlist),
|
V0(v0::Banlist),
|
||||||
V1(v1::Banlist),
|
V1(Banlist),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Banlist> for BanlistRaw {
|
impl From<Banlist> for BanlistRaw {
|
||||||
|
@ -19,7 +19,7 @@ pub use self::v1::*;
|
|||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub enum ServerDescriptionRaw {
|
pub enum ServerDescriptionRaw {
|
||||||
V0(v0::ServerDescription),
|
V0(v0::ServerDescription),
|
||||||
V1(v1::ServerDescription),
|
V1(ServerDescription),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ServerDescription> for ServerDescriptionRaw {
|
impl From<ServerDescription> for ServerDescriptionRaw {
|
||||||
|
@ -18,7 +18,7 @@ pub use self::v1::*;
|
|||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
pub enum WhitelistRaw {
|
pub enum WhitelistRaw {
|
||||||
V0(v0::Whitelist),
|
V0(v0::Whitelist),
|
||||||
V1(v1::Whitelist),
|
V1(Whitelist),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Whitelist> for WhitelistRaw {
|
impl From<Whitelist> for WhitelistRaw {
|
||||||
|
@ -50,8 +50,8 @@ pub trait StateExt {
|
|||||||
stats: comp::Stats,
|
stats: comp::Stats,
|
||||||
skill_set: comp::SkillSet,
|
skill_set: comp::SkillSet,
|
||||||
health: Option<comp::Health>,
|
health: Option<comp::Health>,
|
||||||
poise: comp::Poise,
|
poise: Poise,
|
||||||
inventory: comp::Inventory,
|
inventory: Inventory,
|
||||||
body: comp::Body,
|
body: comp::Body,
|
||||||
) -> EcsEntityBuilder;
|
) -> EcsEntityBuilder;
|
||||||
/// Build a static object entity
|
/// Build a static object entity
|
||||||
@ -139,7 +139,7 @@ impl StateExt for State {
|
|||||||
Effect::Damage(damage) => {
|
Effect::Damage(damage) => {
|
||||||
let inventories = self.ecs().read_storage::<Inventory>();
|
let inventories = self.ecs().read_storage::<Inventory>();
|
||||||
let stats = self.ecs().read_storage::<comp::Stats>();
|
let stats = self.ecs().read_storage::<comp::Stats>();
|
||||||
let groups = self.ecs().read_storage::<comp::Group>();
|
let groups = self.ecs().read_storage::<Group>();
|
||||||
|
|
||||||
let damage_contributor = source.and_then(|uid| {
|
let damage_contributor = source.and_then(|uid| {
|
||||||
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
|
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
|
||||||
@ -159,7 +159,7 @@ impl StateExt for State {
|
|||||||
0.0,
|
0.0,
|
||||||
1.0,
|
1.0,
|
||||||
*time,
|
*time,
|
||||||
rand::random(),
|
random(),
|
||||||
);
|
);
|
||||||
self.ecs()
|
self.ecs()
|
||||||
.write_storage::<comp::Health>()
|
.write_storage::<comp::Health>()
|
||||||
@ -176,7 +176,7 @@ impl StateExt for State {
|
|||||||
.get(entity)
|
.get(entity)
|
||||||
{
|
{
|
||||||
if !character_state.is_stunned() {
|
if !character_state.is_stunned() {
|
||||||
let groups = self.ecs().read_storage::<comp::Group>();
|
let groups = self.ecs().read_storage::<Group>();
|
||||||
let damage_contributor = source.and_then(|uid| {
|
let damage_contributor = source.and_then(|uid| {
|
||||||
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
|
self.ecs().entity_from_uid(uid.0).map(|attacker_entity| {
|
||||||
DamageContributor::new(uid, groups.get(attacker_entity).cloned())
|
DamageContributor::new(uid, groups.get(attacker_entity).cloned())
|
||||||
@ -191,7 +191,7 @@ impl StateExt for State {
|
|||||||
time: *time,
|
time: *time,
|
||||||
};
|
};
|
||||||
self.ecs()
|
self.ecs()
|
||||||
.write_storage::<comp::Poise>()
|
.write_storage::<Poise>()
|
||||||
.get_mut(entity)
|
.get_mut(entity)
|
||||||
.map(|mut poise| poise.change(poise_change));
|
.map(|mut poise| poise.change(poise_change));
|
||||||
}
|
}
|
||||||
@ -219,8 +219,8 @@ impl StateExt for State {
|
|||||||
stats: comp::Stats,
|
stats: comp::Stats,
|
||||||
skill_set: comp::SkillSet,
|
skill_set: comp::SkillSet,
|
||||||
health: Option<comp::Health>,
|
health: Option<comp::Health>,
|
||||||
poise: comp::Poise,
|
poise: Poise,
|
||||||
inventory: comp::Inventory,
|
inventory: Inventory,
|
||||||
body: comp::Body,
|
body: comp::Body,
|
||||||
) -> EcsEntityBuilder {
|
) -> EcsEntityBuilder {
|
||||||
self.ecs_mut()
|
self.ecs_mut()
|
||||||
@ -310,7 +310,7 @@ impl StateExt for State {
|
|||||||
.with(body)
|
.with(body)
|
||||||
.with(comp::Scale(comp::ship::AIRSHIP_SCALE))
|
.with(comp::Scale(comp::ship::AIRSHIP_SCALE))
|
||||||
.with(comp::Controller::default())
|
.with(comp::Controller::default())
|
||||||
.with(comp::inventory::Inventory::with_empty())
|
.with(Inventory::with_empty())
|
||||||
.with(comp::CharacterState::default())
|
.with(comp::CharacterState::default())
|
||||||
// TODO: some of these are required in order for the character_behavior system to
|
// TODO: some of these are required in order for the character_behavior system to
|
||||||
// recognize a possesed airship; that system should be refactored to use `.maybe()`
|
// recognize a possesed airship; that system should be refactored to use `.maybe()`
|
||||||
@ -561,7 +561,7 @@ impl StateExt for State {
|
|||||||
);
|
);
|
||||||
self.write_component_ignore_entity_dead(entity, comp::Health::new(body, health_level));
|
self.write_component_ignore_entity_dead(entity, comp::Health::new(body, health_level));
|
||||||
self.write_component_ignore_entity_dead(entity, comp::Energy::new(body, energy_level));
|
self.write_component_ignore_entity_dead(entity, comp::Energy::new(body, energy_level));
|
||||||
self.write_component_ignore_entity_dead(entity, comp::Poise::new(body));
|
self.write_component_ignore_entity_dead(entity, Poise::new(body));
|
||||||
self.write_component_ignore_entity_dead(entity, stats);
|
self.write_component_ignore_entity_dead(entity, stats);
|
||||||
self.write_component_ignore_entity_dead(entity, active_abilities);
|
self.write_component_ignore_entity_dead(entity, active_abilities);
|
||||||
self.write_component_ignore_entity_dead(entity, skill_set);
|
self.write_component_ignore_entity_dead(entity, skill_set);
|
||||||
@ -952,13 +952,8 @@ impl StateExt for State {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_to_group(g: &comp::Group, ecs: &specs::World, msg: &comp::ChatMsg) {
|
fn send_to_group(g: &Group, ecs: &specs::World, msg: &comp::ChatMsg) {
|
||||||
for (client, group) in (
|
for (client, group) in (&ecs.read_storage::<Client>(), &ecs.read_storage::<Group>()).join() {
|
||||||
&ecs.read_storage::<Client>(),
|
|
||||||
&ecs.read_storage::<comp::Group>(),
|
|
||||||
)
|
|
||||||
.join()
|
|
||||||
{
|
|
||||||
if g == group {
|
if g == group {
|
||||||
client.send_fallible(ServerGeneral::ChatMsg(msg.clone()));
|
client.send_fallible(ServerGeneral::ChatMsg(msg.clone()));
|
||||||
}
|
}
|
||||||
|
@ -1104,7 +1104,7 @@ impl<'a> AgentData<'a> {
|
|||||||
self.chat_npc(msg, event_emitter);
|
self.chat_npc(msg, event_emitter);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = thread_rng();
|
||||||
if let Some(extreme_trait) =
|
if let Some(extreme_trait) =
|
||||||
self.rtsim_entity.and_then(|e| {
|
self.rtsim_entity.and_then(|e| {
|
||||||
e.brain.personality.random_chat_trait(&mut rng)
|
e.brain.personality.random_chat_trait(&mut rng)
|
||||||
|
@ -924,7 +924,7 @@ impl<'a> AgentData<'a> {
|
|||||||
_ =>
|
_ =>
|
||||||
// if some illegal value slipped in, get zero vector
|
// if some illegal value slipped in, get zero vector
|
||||||
{
|
{
|
||||||
vek::Vec2::zero()
|
Vec2::zero()
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let obstacle = read_data
|
let obstacle = read_data
|
||||||
|
@ -30,7 +30,7 @@ pub fn add_server_systems(dispatch_builder: &mut DispatcherBuilder) {
|
|||||||
dispatch::<melee::Sys>(dispatch_builder, &[&projectile::Sys::sys_name()]);
|
dispatch::<melee::Sys>(dispatch_builder, &[&projectile::Sys::sys_name()]);
|
||||||
//Note: server should not depend on interpolation system
|
//Note: server should not depend on interpolation system
|
||||||
dispatch::<agent::Sys>(dispatch_builder, &[]);
|
dispatch::<agent::Sys>(dispatch_builder, &[]);
|
||||||
dispatch::<terrain::Sys>(dispatch_builder, &[&msg::terrain::Sys::sys_name()]);
|
dispatch::<terrain::Sys>(dispatch_builder, &[&terrain::Sys::sys_name()]);
|
||||||
dispatch::<waypoint::Sys>(dispatch_builder, &[]);
|
dispatch::<waypoint::Sys>(dispatch_builder, &[]);
|
||||||
dispatch::<invite_timeout::Sys>(dispatch_builder, &[]);
|
dispatch::<invite_timeout::Sys>(dispatch_builder, &[]);
|
||||||
dispatch::<persistence::Sys>(dispatch_builder, &[]);
|
dispatch::<persistence::Sys>(dispatch_builder, &[]);
|
||||||
|
@ -110,7 +110,7 @@ impl<'a> System<'a> for Sys {
|
|||||||
for (entity, client, pending) in
|
for (entity, client, pending) in
|
||||||
(&read_data.entities, &read_data.clients, &mut pending_logins).join()
|
(&read_data.entities, &read_data.clients, &mut pending_logins).join()
|
||||||
{
|
{
|
||||||
if let Err(e) = || -> std::result::Result<(), crate::error::Error> {
|
if let Err(e) = || -> Result<(), crate::error::Error> {
|
||||||
#[cfg(feature = "plugins")]
|
#[cfg(feature = "plugins")]
|
||||||
let ecs_world = EcsWorld {
|
let ecs_world = EcsWorld {
|
||||||
entities: &read_data.entities,
|
entities: &read_data.entities,
|
||||||
@ -140,7 +140,7 @@ impl<'a> System<'a> for Sys {
|
|||||||
entity,
|
entity,
|
||||||
common::comp::DisconnectReason::Kicked,
|
common::comp::DisconnectReason::Kicked,
|
||||||
));
|
));
|
||||||
client.send(ServerRegisterAnswer::Err(e))?;
|
client.send(Err(e))?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
},
|
},
|
||||||
Ok((username, uuid)) => (username, uuid),
|
Ok((username, uuid)) => (username, uuid),
|
||||||
@ -183,7 +183,7 @@ impl<'a> System<'a> for Sys {
|
|||||||
|
|
||||||
if !player.is_valid() {
|
if !player.is_valid() {
|
||||||
// Invalid player
|
// Invalid player
|
||||||
client.send(ServerRegisterAnswer::Err(RegisterError::InvalidCharacter))?;
|
client.send(Err(RegisterError::InvalidCharacter))?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -201,7 +201,7 @@ impl<'a> System<'a> for Sys {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tell the client its request was successful.
|
// Tell the client its request was successful.
|
||||||
client.send(ServerRegisterAnswer::Ok(()))?;
|
client.send(Ok(()))?;
|
||||||
|
|
||||||
// Send initial player list
|
// Send initial player list
|
||||||
client.send(ServerGeneral::PlayerListUpdate(PlayerListUpdate::Init(
|
client.send(ServerGeneral::PlayerListUpdate(PlayerListUpdate::Init(
|
||||||
@ -213,7 +213,7 @@ impl<'a> System<'a> for Sys {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}() {
|
}() {
|
||||||
tracing::trace!(?e, "failed to process register")
|
trace!(?e, "failed to process register")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
for e in finished_pending {
|
for e in finished_pending {
|
||||||
|
@ -214,7 +214,7 @@ pub fn initialize_region_subscription(world: &World, entity: specs::Entity) {
|
|||||||
let fuzzy_chunk = (Vec2::<f32>::from(client_pos.0))
|
let fuzzy_chunk = (Vec2::<f32>::from(client_pos.0))
|
||||||
.map2(TerrainChunkSize::RECT_SIZE, |e, sz| e as i32 / sz as i32);
|
.map2(TerrainChunkSize::RECT_SIZE, |e, sz| e as i32 / sz as i32);
|
||||||
let chunk_size = TerrainChunkSize::RECT_SIZE.reduce_max() as f32;
|
let chunk_size = TerrainChunkSize::RECT_SIZE.reduce_max() as f32;
|
||||||
let regions = common::region::regions_in_vd(
|
let regions = regions_in_vd(
|
||||||
client_pos.0,
|
client_pos.0,
|
||||||
(presence.view_distance as f32 * chunk_size) as f32
|
(presence.view_distance as f32 * chunk_size) as f32
|
||||||
+ (presence::CHUNK_FUZZ as f32 + chunk_size) * 2.0f32.sqrt(),
|
+ (presence::CHUNK_FUZZ as f32 + chunk_size) * 2.0f32.sqrt(),
|
||||||
|
@ -88,10 +88,7 @@ impl TerrainPersistence {
|
|||||||
File::open(&path)
|
File::open(&path)
|
||||||
.ok()
|
.ok()
|
||||||
.map(|f| {
|
.map(|f| {
|
||||||
let bytes = match std::io::BufReader::new(f)
|
let bytes = match io::BufReader::new(f).bytes().collect::<Result<Vec<_>, _>>() {
|
||||||
.bytes()
|
|
||||||
.collect::<Result<Vec<_>, _>>()
|
|
||||||
{
|
|
||||||
Ok(bytes) => bytes,
|
Ok(bytes) => bytes,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!(
|
error!(
|
||||||
@ -101,7 +98,7 @@ impl TerrainPersistence {
|
|||||||
return Chunk::default();
|
return Chunk::default();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
match Chunk::deserialize_from(std::io::Cursor::new(bytes)) {
|
match Chunk::deserialize_from(io::Cursor::new(bytes)) {
|
||||||
Some(chunk) => chunk,
|
Some(chunk) => chunk,
|
||||||
None => {
|
None => {
|
||||||
// Find an untaken name for a backup
|
// Find an untaken name for a backup
|
||||||
|
@ -134,7 +134,7 @@ pub struct SkeletonAttr {
|
|||||||
snapper: bool,
|
snapper: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -47,7 +47,7 @@ impl Animation for ChargeAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -131,7 +131,7 @@ impl Skeleton for BipedLargeSkeleton {
|
|||||||
lantern: None,
|
lantern: None,
|
||||||
// TODO: see quadruped_medium for how to animate this
|
// TODO: see quadruped_medium for how to animate this
|
||||||
mount_bone: Transform {
|
mount_bone: Transform {
|
||||||
position: common::comp::Body::BipedLarge(body)
|
position: comp::Body::BipedLarge(body)
|
||||||
.mount_offset()
|
.mount_offset()
|
||||||
.into_tuple()
|
.into_tuple()
|
||||||
.into(),
|
.into(),
|
||||||
@ -173,7 +173,7 @@ pub struct SkeletonAttr {
|
|||||||
height: f32,
|
height: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -105,7 +105,7 @@ impl Animation for RunAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -77,7 +77,7 @@ impl Skeleton for BipedSmallSkeleton {
|
|||||||
lantern: None,
|
lantern: None,
|
||||||
// TODO: see quadruped_medium for how to animate this
|
// TODO: see quadruped_medium for how to animate this
|
||||||
mount_bone: Transform {
|
mount_bone: Transform {
|
||||||
position: common::comp::Body::BipedSmall(body)
|
position: comp::Body::BipedSmall(body)
|
||||||
.mount_offset()
|
.mount_offset()
|
||||||
.into_tuple()
|
.into_tuple()
|
||||||
.into(),
|
.into(),
|
||||||
@ -100,7 +100,7 @@ pub struct SkeletonAttr {
|
|||||||
scaler: f32,
|
scaler: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -62,7 +62,7 @@ impl Animation for RunAnimation {
|
|||||||
let sideabs = side.abs();
|
let sideabs = side.abs();
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -43,7 +43,7 @@ impl Animation for AlphaAnimation {
|
|||||||
let move1mirror = move1base * pullback * mirror;
|
let move1mirror = move1base * pullback * mirror;
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -75,7 +75,7 @@ impl Animation for DashAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -46,7 +46,7 @@ impl Animation for FlyAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -100,7 +100,7 @@ impl Skeleton for BirdLargeSkeleton {
|
|||||||
lantern: None,
|
lantern: None,
|
||||||
// TODO: see quadruped_medium for how to animate this
|
// TODO: see quadruped_medium for how to animate this
|
||||||
mount_bone: Transform {
|
mount_bone: Transform {
|
||||||
position: common::comp::Body::BirdLarge(body)
|
position: comp::Body::BirdLarge(body)
|
||||||
.mount_offset()
|
.mount_offset()
|
||||||
.into_tuple()
|
.into_tuple()
|
||||||
.into(),
|
.into(),
|
||||||
@ -129,7 +129,7 @@ pub struct SkeletonAttr {
|
|||||||
wyvern: bool,
|
wyvern: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -53,7 +53,7 @@ impl Animation for RunAnimation {
|
|||||||
let foot2b = (mixed_vel * 1.0 * lab * speedmult + PI / 2.0).sin() * speednorm; //1.6
|
let foot2b = (mixed_vel * 1.0 * lab * speedmult + PI / 2.0).sin() * speednorm; //1.6
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -54,7 +54,7 @@ impl Skeleton for BirdMediumSkeleton {
|
|||||||
lantern: None,
|
lantern: None,
|
||||||
// TODO: see quadruped_medium for how to animate this
|
// TODO: see quadruped_medium for how to animate this
|
||||||
mount_bone: Transform {
|
mount_bone: Transform {
|
||||||
position: common::comp::Body::BirdMedium(body)
|
position: comp::Body::BirdMedium(body)
|
||||||
.mount_offset()
|
.mount_offset()
|
||||||
.into_tuple()
|
.into_tuple()
|
||||||
.into(),
|
.into(),
|
||||||
@ -75,7 +75,7 @@ pub struct SkeletonAttr {
|
|||||||
feed: f32,
|
feed: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -42,7 +42,7 @@ impl Animation for JumpAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -157,7 +157,7 @@ impl Skeleton for CharacterSkeleton {
|
|||||||
lantern: Some((lantern_mat * Vec4::new(0.0, 0.5, -6.0, 1.0)).xyz()),
|
lantern: Some((lantern_mat * Vec4::new(0.0, 0.5, -6.0, 1.0)).xyz()),
|
||||||
// TODO: see quadruped_medium for how to animate this
|
// TODO: see quadruped_medium for how to animate this
|
||||||
mount_bone: Transform {
|
mount_bone: Transform {
|
||||||
position: common::comp::Body::Humanoid(body)
|
position: comp::Body::Humanoid(body)
|
||||||
.mount_offset()
|
.mount_offset()
|
||||||
.into_tuple()
|
.into_tuple()
|
||||||
.into(),
|
.into(),
|
||||||
@ -243,7 +243,7 @@ impl Default for SkeletonAttr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::convert::TryFrom<&'a comp::Body> for SkeletonAttr {
|
impl<'a> TryFrom<&'a comp::Body> for SkeletonAttr {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
fn try_from(body: &'a comp::Body) -> Result<Self, Self::Error> {
|
||||||
|
@ -60,7 +60,7 @@ impl Animation for MountAnimation {
|
|||||||
let speed = (Vec2::<f32>::from(velocity).magnitude()).min(24.0);
|
let speed = (Vec2::<f32>::from(velocity).magnitude()).min(24.0);
|
||||||
let canceler = (speed / 24.0).powf(0.6);
|
let canceler = (speed / 24.0).powf(0.6);
|
||||||
let _x_tilt = avg_vel.z.atan2(avg_vel.xy().magnitude()) * canceler;
|
let _x_tilt = avg_vel.z.atan2(avg_vel.xy().magnitude()) * canceler;
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -51,7 +51,7 @@ impl Animation for RollAnimation {
|
|||||||
|
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.0001 && m.is_finite())
|
.map(|m| m > 0.0001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -92,7 +92,7 @@ impl Animation for RunAnimation {
|
|||||||
let sideabs = side.abs();
|
let sideabs = side.abs();
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -53,7 +53,7 @@ impl Animation for ShootAnimation {
|
|||||||
let lab: f32 = 1.0;
|
let lab: f32 = 1.0;
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -62,7 +62,7 @@ impl Animation for SneakAnimation {
|
|||||||
|
|
||||||
let orientation: Vec2<f32> = Vec2::from(orientation);
|
let orientation: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(orientation, last_ori)
|
let tilt = if vek::Vec2::new(orientation, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -61,7 +61,7 @@ impl Animation for SneakEquipAnimation {
|
|||||||
|
|
||||||
let orientation: Vec2<f32> = Vec2::from(orientation);
|
let orientation: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(orientation, last_ori)
|
let tilt = if vek::Vec2::new(orientation, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -72,7 +72,7 @@ impl Animation for SneakWieldAnimation {
|
|||||||
|
|
||||||
let orientation: Vec2<f32> = Vec2::from(orientation);
|
let orientation: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(orientation, last_ori)
|
let tilt = if vek::Vec2::new(orientation, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
@ -37,7 +37,7 @@ impl Animation for StandAnimation {
|
|||||||
let impact = (avg_vel.z).max(-15.0);
|
let impact = (avg_vel.z).max(-15.0);
|
||||||
let ori: Vec2<f32> = Vec2::from(orientation);
|
let ori: Vec2<f32> = Vec2::from(orientation);
|
||||||
let last_ori = Vec2::from(last_ori);
|
let last_ori = Vec2::from(last_ori);
|
||||||
let tilt = if ::vek::Vec2::new(ori, last_ori)
|
let tilt = if vek::Vec2::new(ori, last_ori)
|
||||||
.map(|o| o.magnitude_squared())
|
.map(|o| o.magnitude_squared())
|
||||||
.map(|m| m > 0.001 && m.is_finite())
|
.map(|m| m > 0.001 && m.is_finite())
|
||||||
.reduce_and()
|
.reduce_and()
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user