Removes most unused imports; changes some unused variables to underscores or provides a leading underscore; removes some unnecessary variables and mutable declarations; and performs other miscellaneous warning fixes.

This commit is contained in:
Cody 2019-06-06 14:48:41 +00:00 committed by Joshua Barretto
parent 5c812a73bc
commit 14ac5babd4
91 changed files with 307 additions and 526 deletions

1
Cargo.lock generated
View File

@ -2610,6 +2610,7 @@ name = "veloren-server"
version = "0.2.0"
dependencies = [
"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"scan_fmt 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"specs 0.14.3 (registry+https://github.com/rust-lang/crates.io-index)",
"threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@ -14,7 +14,7 @@ use common::{
state::State,
terrain::chonk::ChonkMetrics,
};
use log::{info, log_enabled};
use log::{debug, info, log_enabled};
use std::{
collections::HashMap,
net::SocketAddr,
@ -53,17 +53,17 @@ impl Client {
/// Create a new `Client`.
#[allow(dead_code)]
pub fn new<A: Into<SocketAddr>>(addr: A, view_distance: Option<u32>) -> Result<Self, Error> {
let mut client_state = ClientState::Connected;
let client_state = ClientState::Connected;
let mut postbox = PostBox::to(addr)?;
// Wait for initial sync
let (mut state, entity, server_info) = match postbox.next_message() {
let (state, entity, server_info) = match postbox.next_message() {
Some(ServerMsg::InitialSync {
ecs_state,
entity_uid,
server_info,
}) => {
let mut state = State::from_state_package(ecs_state);
let state = State::from_state_package(ecs_state);
let entity = state
.ecs()
.entity_from_uid(entity_uid)
@ -320,7 +320,7 @@ impl Client {
}
// Update the server about the player's current animation.
if let Some(mut animation_info) = self
if let Some(animation_info) = self
.state
.ecs_mut()
.write_storage::<comp::AnimationInfo>()
@ -409,6 +409,7 @@ impl Client {
self.client_state = state;
}
ServerMsg::StateAnswer(Err((error, state))) => {
debug!("{:?}", error);
self.client_state = state;
}
ServerMsg::ForceState(state) => {

View File

@ -8,7 +8,6 @@ use std::{
fs::File,
io::BufReader,
io::Read,
path::PathBuf,
sync::{Arc, RwLock},
};
@ -141,7 +140,7 @@ fn try_open_with_path(name: &str) -> Option<File> {
pub fn load_from_path(name: &str) -> Result<BufReader<File>, Error> {
match try_open_with_path(name) {
Some(mut f) => Ok(BufReader::new(f)),
Some(f) => Ok(BufReader::new(f)),
None => Err(Error::NotFound(name.to_owned())),
}
}

View File

@ -1,4 +1,3 @@
// Standard
use std::{
thread,
time::{Duration, SystemTime},

View File

@ -1,7 +1,5 @@
use crate::inventory::Inventory;
use rand::prelude::*;
use rand::{seq::SliceRandom, thread_rng};
use specs::{Component, FlaggedStorage, VecStorage};
use vek::*;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Race {
@ -219,18 +217,19 @@ pub struct HumanoidBody {
impl HumanoidBody {
pub fn random() -> Self {
let mut rng = thread_rng();
Self {
race: *thread_rng().choose(&ALL_RACES).unwrap(),
body_type: *thread_rng().choose(&ALL_BODY_TYPES).unwrap(),
head: *thread_rng().choose(&ALL_HEADS).unwrap(),
chest: *thread_rng().choose(&ALL_CHESTS).unwrap(),
belt: *thread_rng().choose(&ALL_BELTS).unwrap(),
pants: *thread_rng().choose(&ALL_PANTS).unwrap(),
hand: *thread_rng().choose(&ALL_HANDS).unwrap(),
foot: *thread_rng().choose(&ALL_FEET).unwrap(),
weapon: *thread_rng().choose(&ALL_WEAPONS).unwrap(),
shoulder: *thread_rng().choose(&ALL_SHOULDERS).unwrap(),
draw: *thread_rng().choose(&ALL_DRAW).unwrap(),
race: *(&ALL_RACES).choose(&mut rng).unwrap(),
body_type: *(&ALL_BODY_TYPES).choose(&mut rng).unwrap(),
head: *(&ALL_HEADS).choose(&mut rng).unwrap(),
chest: *(&ALL_CHESTS).choose(&mut rng).unwrap(),
belt: *(&ALL_BELTS).choose(&mut rng).unwrap(),
pants: *(&ALL_PANTS).choose(&mut rng).unwrap(),
hand: *(&ALL_HANDS).choose(&mut rng).unwrap(),
foot: *(&ALL_FEET).choose(&mut rng).unwrap(),
weapon: *(&ALL_WEAPONS).choose(&mut rng).unwrap(),
shoulder: *(&ALL_SHOULDERS).choose(&mut rng).unwrap(),
draw: *(&ALL_DRAW).choose(&mut rng).unwrap(),
}
}
}
@ -261,13 +260,14 @@ pub struct QuadrupedBody {
impl QuadrupedBody {
pub fn random() -> Self {
let mut rng = thread_rng();
Self {
race: *thread_rng().choose(&ALL_QRACES).unwrap(),
body_type: *thread_rng().choose(&ALL_QBODY_TYPES).unwrap(),
pig_head: *thread_rng().choose(&ALL_QPIG_HEADS).unwrap(),
pig_chest: *thread_rng().choose(&ALL_QPIG_CHESTS).unwrap(),
pig_leg_l: *thread_rng().choose(&ALL_QPIG_LEG_LS).unwrap(),
pig_leg_r: *thread_rng().choose(&ALL_QPIG_LEG_RS).unwrap(),
race: *(&ALL_QRACES).choose(&mut rng).unwrap(),
body_type: *(&ALL_QBODY_TYPES).choose(&mut rng).unwrap(),
pig_head: *(&ALL_QPIG_HEADS).choose(&mut rng).unwrap(),
pig_chest: *(&ALL_QPIG_CHESTS).choose(&mut rng).unwrap(),
pig_leg_l: *(&ALL_QPIG_LEG_LS).choose(&mut rng).unwrap(),
pig_leg_r: *(&ALL_QPIG_LEG_RS).choose(&mut rng).unwrap(),
}
}
}
@ -312,20 +312,21 @@ pub struct QuadrupedMediumBody {
impl QuadrupedMediumBody {
pub fn random() -> Self {
let mut rng = thread_rng();
Self {
race: *thread_rng().choose(&ALL_QMRACES).unwrap(),
body_type: *thread_rng().choose(&ALL_QMBODY_TYPES).unwrap(),
wolf_head_upper: *thread_rng().choose(&ALL_QMWOLF_HEADS_UPPER).unwrap(),
wolf_jaw: *thread_rng().choose(&ALL_QMWOLF_JAWS).unwrap(),
wolf_head_lower: *thread_rng().choose(&ALL_QMWOLF_HEADS_LOWER).unwrap(),
wolf_tail: *thread_rng().choose(&ALL_QMWOLF_TAILS).unwrap(),
wolf_torso_back: *thread_rng().choose(&ALL_QMWOLF_TORSOS_BACK).unwrap(),
wolf_torso_mid: *thread_rng().choose(&ALL_QMWOLF_TORSOS_MID).unwrap(),
wolf_ears: *thread_rng().choose(&ALL_QMWOLF_EARS).unwrap(),
wolf_foot_lf: *thread_rng().choose(&ALL_QMWOLF_FEET_LF).unwrap(),
wolf_foot_rf: *thread_rng().choose(&ALL_QMWOLF_FEET_RF).unwrap(),
wolf_foot_lb: *thread_rng().choose(&ALL_QMWOLF_FEET_LB).unwrap(),
wolf_foot_rb: *thread_rng().choose(&ALL_QMWOLF_FEET_RB).unwrap(),
race: *(&ALL_QMRACES).choose(&mut rng).unwrap(),
body_type: *(&ALL_QMBODY_TYPES).choose(&mut rng).unwrap(),
wolf_head_upper: *(&ALL_QMWOLF_HEADS_UPPER).choose(&mut rng).unwrap(),
wolf_jaw: *(&ALL_QMWOLF_JAWS).choose(&mut rng).unwrap(),
wolf_head_lower: *(&ALL_QMWOLF_HEADS_LOWER).choose(&mut rng).unwrap(),
wolf_tail: *(&ALL_QMWOLF_TAILS).choose(&mut rng).unwrap(),
wolf_torso_back: *(&ALL_QMWOLF_TORSOS_BACK).choose(&mut rng).unwrap(),
wolf_torso_mid: *(&ALL_QMWOLF_TORSOS_MID).choose(&mut rng).unwrap(),
wolf_ears: *(&ALL_QMWOLF_EARS).choose(&mut rng).unwrap(),
wolf_foot_lf: *(&ALL_QMWOLF_FEET_LF).choose(&mut rng).unwrap(),
wolf_foot_rf: *(&ALL_QMWOLF_FEET_RF).choose(&mut rng).unwrap(),
wolf_foot_lb: *(&ALL_QMWOLF_FEET_LB).choose(&mut rng).unwrap(),
wolf_foot_rb: *(&ALL_QMWOLF_FEET_RB).choose(&mut rng).unwrap(),
}
}
}

View File

@ -1,5 +1,4 @@
use specs::{Component, FlaggedStorage, VecStorage};
use vek::*;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Animation {

View File

@ -1,4 +1,4 @@
use specs::{Component, FlaggedStorage, NullStorage, VecStorage};
use specs::{Component, NullStorage, VecStorage};
use vek::*;
// Position

View File

@ -1,10 +1,11 @@
use crate::state::{Time, Uid};
use specs::{Component, FlaggedStorage, NullStorage, VecStorage};
use crate::state::Uid;
use specs::{Component, FlaggedStorage, VecStorage};
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum HealthSource {
Attack { by: Uid }, // TODO: Implement weapon
Suicide,
Unknown,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]

View File

@ -1,8 +1,5 @@
// Library
use vek::*;
// Crate
use crate::vol::Vox;
use vek::*;
/// A type representing a single voxel in a figure.
#[derive(Copy, Clone, Debug)]

View File

@ -1,17 +1,12 @@
pub mod cell;
// Library
use dot_vox::DotVoxData;
use vek::*;
// Crate
use self::cell::Cell;
use crate::{
vol::{Vox, WriteVol},
volumes::dyna::Dyna,
};
// Local
use self::cell::Cell;
use dot_vox::DotVoxData;
use vek::*;
/// A type representing a volume that may be part of an animated figure.
///

View File

@ -3,7 +3,7 @@ use specs::{Component, VecStorage};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Armor {
//TODO: Don't make armor be a body part. Wearing enemy's head is funny but also creepy thing to do.
// TODO: Don't make armor be a body part. Wearing enemy's head is funny but also creepy thing to do.
Helmet(actor::Head),
Shoulders(actor::Shoulder),
Chestplate(actor::Chest),

View File

@ -1,4 +1,3 @@
//Library
use specs::{Component, VecStorage};
//Re-Exports

View File

@ -4,7 +4,6 @@
trait_alias,
bind_by_move_pattern_guards,
option_flattening, // Converts Option<Option<Item>> into Option<Item> TODO: Remove this once this feature becomes stable
copysign,
)]
#[macro_use]

View File

@ -1,3 +1,4 @@
use log::warn;
use serde::{de::DeserializeOwned, Serialize};
use std::{
collections::VecDeque,
@ -10,7 +11,7 @@ use std::{
mpsc, Arc,
},
thread,
time::{Duration, Instant},
time::Duration,
};
#[derive(Clone, Debug)]
@ -34,7 +35,7 @@ impl From<bincode::Error> for Error {
}
impl From<mpsc::TryRecvError> for Error {
fn from(error: mpsc::TryRecvError) -> Self {
fn from(_error: mpsc::TryRecvError) -> Self {
Error::ChannelFailure
}
}
@ -51,7 +52,7 @@ pub struct PostOffice<S: PostMsg, R: PostMsg> {
impl<S: PostMsg, R: PostMsg> PostOffice<S, R> {
pub fn bind<A: Into<SocketAddr>>(addr: A) -> Result<Self, Error> {
let mut listener = TcpListener::bind(addr.into())?;
let listener = TcpListener::bind(addr.into())?;
listener.set_nonblocking(true)?;
Ok(Self {
@ -74,7 +75,7 @@ impl<S: PostMsg, R: PostMsg> PostOffice<S, R> {
loop {
match self.listener.accept() {
Ok((stream, sock)) => new.push(PostBox::from_stream(stream).unwrap()),
Ok((stream, _sock)) => new.push(PostBox::from_stream(stream).unwrap()),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => {
@ -179,7 +180,7 @@ impl<S: PostMsg, R: PostMsg> PostBox<S, R> {
'work: while running.load(Ordering::Relaxed) {
for _ in 0..30 {
// Get stream errors
// Get stream errors.
match stream.take_error() {
Ok(Some(e)) | Err(e) => {
recv_tx.send(Err(e.into())).unwrap();
@ -307,7 +308,9 @@ impl<S: PostMsg, R: PostMsg> PostBox<S, R> {
thread::sleep(Duration::from_millis(10));
}
stream.shutdown(Shutdown::Both);
if let Err(err) = stream.shutdown(Shutdown::Both) {
warn!("TCP worker stream shutdown failed: {:?}", err);
}
}
}
@ -321,6 +324,7 @@ impl<S: PostMsg, R: PostMsg> Drop for PostBox<S, R> {
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
fn create_postoffice<S: PostMsg, R: PostMsg>(
id: u16,
@ -416,8 +420,6 @@ mod tests {
#[test]
fn send_recv_both() {
let (mut postoffice, sock) = create_postoffice::<u32, u32>(4).unwrap();
let test_msgs = vec![1, 1337, 42, -48];
let mut client = PostBox::<u32, u32>::to(sock).unwrap();
loop_for(Duration::from_millis(250), || ());
let mut server = postoffice.new_postboxes().next().unwrap();

View File

@ -2,8 +2,6 @@ use crate::assets;
use lazy_static::lazy_static;
use rand::seq::SliceRandom;
use serde_json;
use std::fs::File;
use std::io::Error;
use std::sync::Arc;
pub enum NpcKind {

View File

@ -47,12 +47,9 @@ impl<'a, V: ReadVol, F: RayUntil<V::Vox>> Ray<'a, V, F> {
let dir = (self.to - self.from).normalized();
let max = (self.to - self.from).magnitude();
let mut pos = self.from;
let mut ipos = pos.map(|e| e.floor() as i32);
for _ in 0..self.max_iter {
pos = self.from + dir * dist;
ipos = pos.map(|e| e.floor() as i32);
let pos = self.from + dir * dist;
let ipos = pos.map(|e| e.floor() as i32);
// Allow one iteration above max.
if dist > max {

View File

@ -10,10 +10,9 @@ use crate::{
use rayon::{ThreadPool, ThreadPoolBuilder};
use serde_derive::{Deserialize, Serialize};
use specs::{
saveload::{MarkedBuilder, MarkerAllocator},
shred::{Fetch, FetchMut},
storage::{MaskedStorage as EcsMaskedStorage, Storage as EcsStorage},
Builder, Component, DispatcherBuilder, Entity as EcsEntity, EntityBuilder as EcsEntityBuilder,
Component, DispatcherBuilder, Entity as EcsEntity,
};
use sphynx;
use std::{collections::HashSet, sync::Arc, time::Duration};

View File

@ -1,17 +1,5 @@
// Library
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{
phys::{Ori, Pos, Vel},
Animation, AnimationInfo, Attacking,
},
state::DeltaTime,
terrain::TerrainMap,
vol::{ReadVol, Vox},
};
use crate::{comp::Attacking, state::DeltaTime};
use specs::{Entities, Join, Read, System, WriteStorage};
// Basic ECS AI agent system
pub struct Sys;
@ -24,16 +12,14 @@ impl<'a> System<'a> for Sys {
);
fn run(&mut self, (entities, dt, mut attacks): Self::SystemData) {
for (entity, attack) in (&entities, &mut attacks).join() {
for attack in (&mut attacks).join() {
attack.time += dt.0;
}
let finished_attacks = (&entities, &mut attacks)
.join()
.filter(|(e, a)| {
a.time > 0.25 // TODO: constant
})
.map(|(e, a)| e)
.filter(|(_, a)| a.time > 0.25) // TODO: constant
.map(|(e, _)| e)
.collect::<Vec<_>>();
for entity in finished_attacks {

View File

@ -1,20 +1,14 @@
// Library
use rand::Rng;
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage};
use crate::comp::{phys::Pos, Agent, Attacking, Control, Jumping};
use log::warn;
use rand::{seq::SliceRandom, thread_rng};
use specs::{Entities, Join, ReadStorage, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{phys::Pos, Agent, Attacking, Control, Jumping},
state::Time,
};
// Basic ECS AI agent system
pub struct Sys;
impl<'a> System<'a> for Sys {
type SystemData = (
Read<'a, Time>,
Entities<'a>,
WriteStorage<'a, Agent>,
ReadStorage<'a, Pos>,
@ -25,7 +19,7 @@ impl<'a> System<'a> for Sys {
fn run(
&mut self,
(time, entities, mut agents, positions, mut controls, mut jumps, mut attacks): Self::SystemData,
(entities, mut agents, positions, mut controls, mut jumps, mut attacks): Self::SystemData,
) {
for (entity, agent, pos, control) in
(&entities, &mut agents, &positions, &mut controls).join()
@ -48,7 +42,9 @@ impl<'a> System<'a> for Sys {
let tgt_pos = tgt_pos.0 + *offset;
if tgt_pos.z > pos.0.z + 1.0 {
jumps.insert(entity, Jumping);
if let Err(err) = jumps.insert(entity, Jumping) {
warn!("Inserting Jumping for an entity failed: {:?}", err,);
}
}
// Move towards the target.
@ -79,7 +75,9 @@ impl<'a> System<'a> for Sys {
control.move_dir = Vec2::zero();
if rand::random::<f32>() < 0.2 {
attacks.insert(entity, Attacking::start());
attacks
.insert(entity, Attacking::start())
.expect("Inserting attacking for an entity failed!");
}
false
@ -107,7 +105,8 @@ impl<'a> System<'a> for Sys {
.map(|(e, _)| e)
.collect::<Vec<_>>();
*target = rand::thread_rng().choose(&entities).cloned();
let mut rng = thread_rng();
*target = (&entities).choose(&mut rng).cloned();
}
}
}

View File

@ -1,12 +1,5 @@
// Library
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{phys::Pos, Animation, AnimationInfo, Stats},
state::DeltaTime,
};
use crate::{comp::AnimationInfo, state::DeltaTime};
use specs::{Join, Read, System, WriteStorage};
// Basic ECS AI agent system
pub struct Sys;
@ -15,7 +8,7 @@ impl<'a> System<'a> for Sys {
type SystemData = (Read<'a, DeltaTime>, WriteStorage<'a, AnimationInfo>);
fn run(&mut self, (dt, mut animation_infos): Self::SystemData) {
for (mut animation_info) in (&mut animation_infos).join() {
for mut animation_info in (&mut animation_infos).join() {
animation_info.time += dt.0 as f64;
}
}

View File

@ -1,18 +1,15 @@
// Library
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{
phys::{ForceUpdate, Ori, Pos, Vel},
Animation, AnimationInfo, Attacking, Control, Gliding, HealthSource, Jumping, Respawning,
Stats,
Animation, AnimationInfo, Attacking, Control, Gliding, HealthSource, Jumping, Stats,
},
state::{DeltaTime, Time, Uid},
state::{DeltaTime, Uid},
terrain::TerrainMap,
vol::{ReadVol, Vox},
};
use log::warn;
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, System, WriteStorage};
use vek::*;
// Basic ECS AI agent system
pub struct Sys;
@ -31,7 +28,6 @@ impl<'a> System<'a> for Sys {
type SystemData = (
Entities<'a>,
ReadStorage<'a, Uid>,
Read<'a, Time>,
Read<'a, DeltaTime>,
ReadExpect<'a, TerrainMap>,
ReadStorage<'a, Pos>,
@ -41,7 +37,6 @@ impl<'a> System<'a> for Sys {
WriteStorage<'a, Stats>,
ReadStorage<'a, Control>,
WriteStorage<'a, Jumping>,
WriteStorage<'a, Respawning>,
WriteStorage<'a, Gliding>,
WriteStorage<'a, Attacking>,
WriteStorage<'a, ForceUpdate>,
@ -52,7 +47,6 @@ impl<'a> System<'a> for Sys {
(
entities,
uids,
time,
dt,
terrain,
positions,
@ -60,10 +54,9 @@ impl<'a> System<'a> for Sys {
mut orientations,
mut animation_infos,
mut stats,
mut controls,
controls,
mut jumps,
mut respawns,
mut glides,
glides,
mut attacks,
mut force_updates,
): Self::SystemData,
@ -140,21 +133,23 @@ impl<'a> System<'a> for Sys {
.unwrap_or(AnimationInfo::default());
let changed = last.animation != animation;
animation_infos.insert(
if let Err(err) = animation_infos.insert(
entity,
AnimationInfo {
animation,
time: if changed { 0.0 } else { last.time },
changed,
},
);
) {
warn!("Inserting AnimationInfo for an entity failed: {:?}", err);
}
}
for (entity, &uid, pos, ori, attacking) in
(&entities, &uids, &positions, &orientations, &mut attacks).join()
{
if !attacking.applied {
for (b, pos_b, mut stat_b, mut vel_b) in
for (b, pos_b, stat_b, mut vel_b) in
(&entities, &positions, &mut stats, &mut velocities).join()
{
// Check if it is a hit
@ -167,7 +162,9 @@ impl<'a> System<'a> for Sys {
stat_b.hp.change_by(-10, HealthSource::Attack { by: uid }); // TODO: variable damage and weapon
vel_b.0 += (pos_b.0 - pos.0).normalized() * 10.0;
vel_b.0.z = 15.0;
force_updates.insert(b, ForceUpdate);
if let Err(err) = force_updates.insert(b, ForceUpdate) {
warn!("Inserting ForceUpdate for an entity failed: {:?}", err);
}
}
}
attacking.applied = true;

View File

@ -1,12 +1,9 @@
// Library
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{Dying, Stats},
comp::{Dying, HealthSource, Stats},
state::DeltaTime,
};
use log::warn;
use specs::{Entities, Join, Read, System, WriteStorage};
// Basic ECS AI agent system
pub struct Sys;
@ -23,16 +20,20 @@ impl<'a> System<'a> for Sys {
for (entity, mut stat) in (&entities, &mut stats).join() {
if stat.should_die() && !stat.is_dead {
// TODO: Replace is_dead with client states
dyings.insert(
if let Err(err) = dyings.insert(
entity,
Dying {
cause: stat
.hp
.last_change
.expect("Nothing caused the entity to die")
.2, // Safe because damage is necessary for death
cause: match stat.hp.last_change {
Some(change) => change.2,
None => {
warn!("Nothing caused an entity to die!");
HealthSource::Unknown
}
},
},
);
) {
warn!("Inserting Dying for an entity failed: {:?}", err);
}
stat.is_dead = true;
}
if let Some(change) = &mut stat.hp.last_change {

View File

@ -1,9 +1,7 @@
use crate::vol::Vox;
use serde_derive::{Deserialize, Serialize};
use vek::*;
// Crate
use crate::vol::Vox;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Block {
kind: u8,

View File

@ -1,11 +1,11 @@
use super::{block::Block, TerrainChunkMeta, TerrainChunkSize};
use crate::{
vol::{BaseVol, ReadVol, VolSize, WriteVol},
vol::{BaseVol, ReadVol, WriteVol},
volumes::chunk::{Chunk, ChunkErr},
};
use fxhash::FxHashMap;
use serde_derive::{Deserialize, Serialize};
use std::{collections::HashMap, ops::Add};
use std::ops::Add;
use vek::*;
#[derive(Debug)]
@ -181,8 +181,8 @@ impl WriteVol for Chonk {
self.sub_chunks[sub_chunk_idx] = SubChunk::Hash(*cblock, map);
Ok(())
}
SubChunk::Hash(cblock, map) if block == *cblock => Ok(()),
SubChunk::Hash(cblock, map) if map.len() < 4096 => {
SubChunk::Hash(cblock, _map) if block == *cblock => Ok(()),
SubChunk::Hash(_cblock, map) if map.len() < 4096 => {
map.insert(rpos.map(|e| e as u8), block);
Ok(())
}

View File

@ -6,10 +6,7 @@ pub mod structure;
// Reexports
pub use self::{biome::BiomeKind, block::Block, structure::Structure};
use crate::{
vol::VolSize,
volumes::{chunk::Chunk, vol_map_2d::VolMap2d},
};
use crate::{vol::VolSize, volumes::vol_map_2d::VolMap2d};
use serde_derive::{Deserialize, Serialize};
use vek::*;

View File

@ -1,6 +1,6 @@
use super::Block;
use crate::{
assets::{self, load_from_path, Asset},
assets::{self, Asset},
vol::{BaseVol, ReadVol, Vox, WriteVol},
volumes::dyna::{Dyna, DynaErr},
};

View File

@ -1,4 +1,4 @@
use crate::ray::{Ray, RayUntil};
use crate::ray::Ray;
use std::fmt::Debug;
use vek::*;

View File

@ -1,12 +1,7 @@
// Standard
use std::marker::PhantomData;
// Library
use serde_derive::{Deserialize, Serialize};
use vek::*;
// Local
use crate::vol::{BaseVol, ReadVol, SizedVol, VolSize, Vox, WriteVol};
use serde_derive::{Deserialize, Serialize};
use std::marker::PhantomData;
use vek::*;
#[derive(Debug)]
pub enum ChunkErr {

View File

@ -1,10 +1,7 @@
// Library
use crate::vol::{BaseVol, ReadVol, SizedVol, Vox, WriteVol};
use serde_derive::{Deserialize, Serialize};
use vek::*;
// Local
use crate::vol::{BaseVol, ReadVol, SizedVol, Vox, WriteVol};
#[derive(Debug)]
pub enum DynaErr {
OutOfBounds,

View File

@ -1,18 +1,9 @@
use crate::{
terrain::TerrainChunkMeta,
vol::{BaseVol, ReadVol, SampleVol, SizedVol, VolSize, Vox, WriteVol},
volumes::{
chunk::{Chunk, ChunkErr},
dyna::{Dyna, DynaErr},
},
vol::{BaseVol, ReadVol, SampleVol, VolSize, WriteVol},
volumes::dyna::DynaErr,
};
use fxhash::FxHashMap;
use std::{
collections::{hash_map, HashMap},
fmt::Debug,
marker::PhantomData,
sync::Arc,
};
use std::{collections::hash_map, fmt::Debug, marker::PhantomData, sync::Arc};
use vek::*;
#[derive(Debug)]

View File

@ -1,10 +1,6 @@
use crate::{
terrain::TerrainChunkMeta,
vol::{BaseVol, ReadVol, SampleVol, SizedVol, VolSize, Vox, WriteVol},
volumes::{
chunk::{Chunk, ChunkErr},
dyna::{Dyna, DynaErr},
},
vol::{BaseVol, ReadVol, SampleVol, VolSize, WriteVol},
volumes::dyna::DynaErr,
};
use std::{collections::HashMap, fmt::Debug, marker::PhantomData, sync::Arc};
use vek::*;

View File

@ -24,9 +24,9 @@ fn main() {
for event in events {
match event {
Event::ClientConnected { entity } => info!("Client connected!"),
Event::ClientDisconnected { entity } => info!("Client disconnected!"),
Event::Chat { entity, msg } => info!("[Client] {}", msg),
Event::ClientConnected { entity: _ } => info!("Client connected!"),
Event::ClientDisconnected { entity: _ } => info!("Client disconnected!"),
Event::Chat { entity: _, msg } => info!("[Client] {}", msg),
}
}

View File

@ -8,6 +8,7 @@ edition = "2018"
common = { package = "veloren-common", path = "../common" }
world = { package = "veloren-world", path = "../world" }
log = "0.4"
specs = "0.14"
vek = "0.9"
threadpool = "1.7"

View File

@ -1,6 +1,4 @@
use crate::Error;
use common::{
comp,
msg::{ClientMsg, ClientState, RequestStateError, ServerMsg},
net::PostBox,
};
@ -84,7 +82,7 @@ impl Clients {
}
pub fn notify_ingame_if<F: FnMut(EcsEntity) -> bool>(&mut self, msg: ServerMsg, mut f: F) {
for (entity, client) in self.clients.iter_mut().filter(|(e, _)| f(**e)) {
for (_entity, client) in self.clients.iter_mut().filter(|(e, _)| f(**e)) {
if client.client_state == ClientState::Spectator
|| client.client_state == ClientState::Character
{

View File

@ -154,7 +154,7 @@ fn handle_goto(server: &mut Server, entity: EcsEntity, args: String, action: &Ch
}
}
fn handle_kill(server: &mut Server, entity: EcsEntity, args: String, action: &ChatCommand) {
fn handle_kill(server: &mut Server, entity: EcsEntity, _args: String, _action: &ChatCommand) {
server
.state
.ecs_mut()
@ -222,7 +222,7 @@ fn handle_tp(server: &mut Server, entity: EcsEntity, args: String, action: &Chat
}
}
fn handle_pet_pig(server: &mut Server, entity: EcsEntity, args: String, action: &ChatCommand) {
fn handle_pet_pig(server: &mut Server, entity: EcsEntity, _args: String, _action: &ChatCommand) {
match server
.state
.read_component_cloned::<comp::phys::Pos>(entity)
@ -250,7 +250,7 @@ fn handle_pet_pig(server: &mut Server, entity: EcsEntity, args: String, action:
}
}
fn handle_pet_wolf(server: &mut Server, entity: EcsEntity, args: String, action: &ChatCommand) {
fn handle_pet_wolf(server: &mut Server, entity: EcsEntity, _args: String, _action: &ChatCommand) {
match server
.state
.read_component_cloned::<comp::phys::Pos>(entity)
@ -278,7 +278,7 @@ fn handle_pet_wolf(server: &mut Server, entity: EcsEntity, args: String, action:
}
}
fn handle_enemy(server: &mut Server, entity: EcsEntity, args: String, action: &ChatCommand) {
fn handle_enemy(server: &mut Server, entity: EcsEntity, _args: String, _action: &ChatCommand) {
match server
.state
.read_component_cloned::<comp::phys::Pos>(entity)

View File

@ -20,10 +20,8 @@ use common::{
terrain::{TerrainChunk, TerrainChunkSize},
vol::VolSize,
};
use specs::{
join::Join, saveload::MarkedBuilder, world::EntityBuilder as EcsEntityBuilder, Builder,
Entity as EcsEntity,
};
use log::warn;
use specs::{join::Join, world::EntityBuilder as EcsEntityBuilder, Builder, Entity as EcsEntity};
use std::{
collections::HashSet,
i32,
@ -87,7 +85,7 @@ impl Server {
.ecs_mut()
.add_resource(SpawnPoint(Vec3::new(16_384.0, 16_384.0, 280.0)));
let mut this = Self {
let this = Self {
state,
world: Arc::new(World::generate(DEFAULT_WORLD_SEED)),
@ -107,18 +105,6 @@ impl Server {
},
};
/*
for i in 0..4 {
this.create_npc(
"Tobermory".to_owned(),
comp::Body::Humanoid(comp::HumanoidBody::random()),
)
.with(comp::Actions::default())
.with(comp::Agent::Wanderer(Vec2::zero()))
.build();
}
*/
Ok(this)
}
@ -264,7 +250,9 @@ impl Server {
self.state.write_component(entity, comp::phys::ForceUpdate);
client.force_state(ClientState::Dead);
} else {
self.state.ecs_mut().delete_entity_synced(entity);
if let Err(err) = self.state.ecs_mut().delete_entity_synced(entity) {
warn!("Failed to delete client not found in kill list: {:?}", err);
}
continue;
}
}
@ -388,7 +376,7 @@ impl Server {
fn handle_new_connections(&mut self) -> Result<Vec<Event>, Error> {
let mut frontend_events = Vec::new();
for mut postbox in self.postoffice.new_postboxes() {
for postbox in self.postoffice.new_postboxes() {
let entity = self.state.ecs_mut().create_entity_synced().build();
let mut client = Client {
client_state: ClientState::Connected,
@ -623,7 +611,9 @@ impl Server {
// Handle client disconnects.
for entity in disconnected_clients {
self.state.ecs_mut().delete_entity_synced(entity);
if let Err(err) = self.state.ecs_mut().delete_entity_synced(entity) {
warn!("Failed to delete disconnected client: {:?}", err);
}
frontend_events.push(Event::ClientDisconnected { entity });
}
@ -647,8 +637,7 @@ impl Server {
state.write_component(entity, player);
// Sync physics
for (entity, &uid, &pos, &vel, &ori) in (
&state.ecs().entities(),
for (&uid, &pos, &vel, &ori) in (
&state.ecs().read_storage::<Uid>(),
&state.ecs().read_storage::<comp::phys::Pos>(),
&state.ecs().read_storage::<comp::phys::Vel>(),
@ -665,8 +654,7 @@ impl Server {
}
// Sync animations
for (entity, &uid, &animation_info) in (
&state.ecs().entities(),
for (&uid, &animation_info) in (
&state.ecs().read_storage::<Uid>(),
&state.ecs().read_storage::<comp::AnimationInfo>(),
)
@ -710,7 +698,7 @@ impl Server {
};
let state = &self.state;
let mut clients = &mut self.clients;
let clients = &mut self.clients;
let in_vd = |entity| {
// Get client position.

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, CharacterSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct Input {
pub attack: bool,
}
@ -24,9 +19,9 @@ impl Animation for AttackAnimation {
let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 4.0).sin();
let wave_quicken = (1.0 - (anim_time as f32 * 16.0).cos());
let wave_quicken_slow = (1.0 - (anim_time as f32 * 12.0).cos());
let wave_quicken_double = (1.0 - (anim_time as f32 * 24.0).cos());
let wave_quicken = 1.0 - (anim_time as f32 * 16.0).cos();
let wave_quicken_slow = 1.0 - (anim_time as f32 * 12.0).cos();
let wave_quicken_double = 1.0 - (anim_time as f32 * 24.0).cos();
let wave_quick = (anim_time as f32 * 0.5).sin();
let wave_cos = (anim_time as f32 * 12.0).cos();
let wave_slow = (anim_time as f32 * 10.0 + PI).cos();

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, CharacterSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct GlidingAnimation;
impl Animation for GlidingAnimation {
@ -23,7 +18,7 @@ impl Animation for GlidingAnimation {
let wave_slow = (anim_time as f32 * 7.0).sin();
let wave_slow_cos = (anim_time as f32 * 7.0).cos();
let arc_wave = (1.0f32.ln_1p() - 1.5).abs();
let wave_test = (wave.cbrt());
let wave_test = wave.cbrt();
let fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_stop = (anim_time as f32 * 1.5).min(PI / 2.0).sin();

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, CharacterSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct Input {
pub attack: bool,
}

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, CharacterSkeleton};
use std::f32::consts::PI;
// Library
use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct JumpAnimation;
impl Animation for JumpAnimation {

View File

@ -11,11 +11,8 @@ pub use self::idle::IdleAnimation;
pub use self::jump::JumpAnimation;
pub use self::run::RunAnimation;
// Crate
use crate::render::FigureBoneData;
// Local
use super::{Bone, Skeleton};
use crate::render::FigureBoneData;
const SCALE: f32 = 11.0;

View File

@ -1,12 +1,7 @@
// Standard
use std::{f32::consts::PI, ops::Mul};
// Library
use super::{super::Animation, CharacterSkeleton};
use std::ops::Mul;
use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct RunAnimation;
impl Animation for RunAnimation {

View File

@ -1,9 +1,6 @@
// Crate
use super::Skeleton;
use crate::render::FigureBoneData;
// Local
use super::{Bone, Skeleton};
const SCALE: f32 = 44.0;
pub struct FixtureSkeleton;

View File

@ -3,11 +3,8 @@ pub mod fixture;
pub mod quadruped;
pub mod quadrupedmedium;
// Library
use vek::*;
// Crate
use crate::render::FigureBoneData;
use vek::*;
#[derive(Copy, Clone)]
pub struct Bone {

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct IdleAnimation;
impl Animation for IdleAnimation {
@ -21,7 +16,7 @@ impl Animation for IdleAnimation {
let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 14.0).sin();
let wave_test = (wave.cbrt());
let wave_test = wave.cbrt();
let wave_ultra_slow = (anim_time as f32 * 1.0 + PI).sin();
let wave_ultra_slow_cos = (anim_time as f32 * 1.0 + PI).cos();
let fuzz_wave = (anim_time as f32 * 12.0).sin();

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedSkeleton};
use std::f32::consts::PI;
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct JumpAnimation;
impl Animation for JumpAnimation {
@ -21,7 +16,7 @@ impl Animation for JumpAnimation {
let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 14.0).sin();
let wave_test = (wave.cbrt());
let wave_test = wave.cbrt();
let fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_slow = (anim_time as f32 * 7.0 + PI).sin();

View File

@ -7,11 +7,8 @@ pub use self::idle::IdleAnimation;
pub use self::jump::JumpAnimation;
pub use self::run::RunAnimation;
// Crate
use crate::render::FigureBoneData;
// Local
use super::{Bone, Skeleton};
use crate::render::FigureBoneData;
const SCALE: f32 = 11.0;

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedSkeleton};
use std::f32::consts::PI;
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct RunAnimation;
impl Animation for RunAnimation {
@ -23,7 +18,7 @@ impl Animation for RunAnimation {
let wave = (anim_time as f32 * 14.0).sin();
let wave_quick = (anim_time as f32 * 20.0).sin();
let wave_quick_cos = (anim_time as f32 * 20.0).cos();
let wave_test = (wave.cbrt());
let wave_test = wave.cbrt();
let fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_slow = (anim_time as f32 * 7.0 + PI).sin();

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedMediumSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedMediumSkeleton, SCALE};
pub struct IdleAnimation;
impl Animation for IdleAnimation {

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedMediumSkeleton};
use std::f32::consts::PI;
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedMediumSkeleton, SCALE};
pub struct JumpAnimation;
impl Animation for JumpAnimation {

View File

@ -7,11 +7,8 @@ pub use self::idle::IdleAnimation;
pub use self::jump::JumpAnimation;
pub use self::run::RunAnimation;
// Crate
use crate::render::FigureBoneData;
// Local
use super::{Bone, Skeleton};
use crate::render::FigureBoneData;
const SCALE: f32 = 11.0;

View File

@ -1,12 +1,7 @@
// Standard
use super::{super::Animation, QuadrupedMediumSkeleton};
use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*;
// Local
use super::{super::Animation, QuadrupedMediumSkeleton, SCALE};
pub struct RunAnimation;
impl Animation for RunAnimation {

View File

@ -1,19 +1,7 @@
use crate::settings::AudioSettings;
use common::assets;
use rand::prelude::*;
use rodio::{Decoder, Device, Source, SpatialSink};
use std::{
collections::HashMap,
fs::File,
io::BufReader,
iter::{Filter, Iterator},
path::PathBuf,
sync::mpsc::{channel, Receiver, Sender, TryRecvError},
thread,
thread::{sleep, JoinHandle},
time::Duration,
};
use vek::*;
use rodio::{Decoder, Device, SpatialSink};
use std::iter::Iterator;
pub struct AudioFrontend {
device: Device,
@ -25,7 +13,7 @@ pub struct AudioFrontend {
impl AudioFrontend {
pub fn new(settings: &AudioSettings) -> Self {
let mut device = match &settings.audio_device {
let device = match &settings.audio_device {
Some(dev) => rodio::output_devices()
.find(|x| &x.name() == dev)
.or_else(rodio::default_output_device)
@ -33,7 +21,7 @@ impl AudioFrontend {
None => rodio::default_output_device().expect("No audio devices found"),
};
let mut sink =
let sink =
rodio::SpatialSink::new(&device, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]);
sink.set_volume(settings.music_volume);

View File

@ -1,11 +1,6 @@
// Standard
use std::any;
// Project
use client;
// Crate
use crate::render::RenderError;
use client;
use std::any;
/// Represents any error that may be triggered by Voxygen.
#[derive(Debug)]

View File

@ -2,7 +2,7 @@ use super::{img_ids::Imgs, Fonts, TEXT_COLOR, XP_COLOR};
use conrod_core::{
color,
widget::{self, Button, Image, Rectangle, Text},
widget_ids, Color, Colorable, Labelable, Positionable, Sizeable, Widget, WidgetCommon,
widget_ids, Color, Colorable, Positionable, Sizeable, Widget, WidgetCommon,
};
widget_ids! {

View File

@ -25,15 +25,14 @@ use small_window::{SmallWindow, SmallWindowType};
use crate::{
render::{Consts, Globals, Renderer},
scene::camera::Camera,
settings::{ControlSettings, Settings},
ui::{Ingame, Ingameable, ScaleMode, Ui},
settings::ControlSettings,
ui::{Ingameable, ScaleMode, Ui},
window::{Event as WinEvent, GameInput, Window},
GlobalState,
};
use client::Client;
use common::{comp, terrain::TerrainChunkSize, vol::VolSize};
use conrod_core::{
color, graph,
widget::{self, Button, Image, Rectangle, Text},
widget_ids, Color, Colorable, Labelable, Positionable, Sizeable, Widget,
};
@ -339,7 +338,7 @@ impl Hud {
})
.reduce_and()
})
.map(|(entity, pos, actor, _, player)| match actor {
.map(|(_, pos, actor, _, player)| match actor {
comp::Actor::Character {
name: char_name, ..
} => {
@ -751,7 +750,7 @@ impl Hud {
_ => false,
},
// Else the player is typing in chat
WinEvent::InputUpdate(key, _) => self.typing(),
WinEvent::InputUpdate(_key, _) => self.typing(),
WinEvent::Char(_) => self.typing(),
_ => false,

View File

@ -1,17 +1,11 @@
use super::{img_ids::Imgs, Fonts, Show, TEXT_COLOR};
use crate::{
render::Renderer,
ui::{
self,
img_ids::{ImageGraphic, VoxelGraphic},
ImageSlider, ScaleMode, ToggleButton, Ui,
},
window::Window,
AudioFrontend, GlobalState,
ui::{ImageSlider, ToggleButton},
GlobalState,
};
use conrod_core::{
color,
widget::{self, Button, DropDownList, Image, List, Rectangle, Scrollbar, Text},
widget::{self, Button, DropDownList, Image, Rectangle, Scrollbar, Text},
widget_ids, Colorable, Labelable, Positionable, Sizeable, Widget, WidgetCommon,
};
widget_ids! {

View File

@ -22,12 +22,9 @@ pub mod window;
pub use crate::error::Error;
use crate::{audio::AudioFrontend, menu::main::MainMenuState, settings::Settings, window::Window};
use log;
use log::{debug, error, info, warn};
use simplelog::{CombinedLogger, Config, TermLogger, WriteLogger};
use std::{fs::File, mem, panic, str::FromStr, thread};
/// The URL of the default public server that Voxygen will connect to.
const DEFAULT_PUBLIC_SERVER: &'static str = "server.veloren.net";
use std::{fs::File, mem, panic, str::FromStr};
/// A type used to store state that is shared between all play states.
pub struct GlobalState {
@ -80,12 +77,10 @@ pub trait PlayState {
fn main() {
// Set up the global state.
let mut settings = Settings::load();
let window = Window::new(&settings).expect("Failed to create window!");
let settings = Settings::load();
let mut global_state = GlobalState {
audio: AudioFrontend::new(&settings.audio),
window,
window: Window::new(&settings).expect("Failed to create window!"),
settings,
};
@ -155,7 +150,7 @@ fn main() {
settings_clone.log.file, reason, panic_info,
);
log::error!(
error!(
"VOXYGEN HAS PANICKED\n\n{}\n\nBacktrace:\n{:?}",
msg,
backtrace::Backtrace::new(),
@ -174,7 +169,7 @@ fn main() {
let mut states: Vec<Box<dyn PlayState>> = vec![Box::new(MainMenuState::new(&mut global_state))];
states
.last()
.map(|current_state| log::info!("Started game with state '{}'", current_state.name()));
.map(|current_state| info!("Started game with state '{}'", current_state.name()));
// What's going on here?
// ---------------------
@ -192,10 +187,10 @@ fn main() {
match state_result {
PlayStateResult::Shutdown => {
direction = Direction::Backwards;
log::info!("Shutting down all states...");
info!("Shutting down all states...");
while states.last().is_some() {
states.pop().map(|old_state| {
log::info!("Popped state '{}'.", old_state.name());
debug!("Popped state '{}'.", old_state.name());
global_state.on_play_state_changed();
});
}
@ -203,20 +198,20 @@ fn main() {
PlayStateResult::Pop => {
direction = Direction::Backwards;
states.pop().map(|old_state| {
log::info!("Popped state '{}'.", old_state.name());
debug!("Popped state '{}'.", old_state.name());
global_state.on_play_state_changed();
});
}
PlayStateResult::Push(new_state) => {
direction = Direction::Forwards;
log::info!("Pushed state '{}'.", new_state.name());
debug!("Pushed state '{}'.", new_state.name());
states.push(new_state);
global_state.on_play_state_changed();
}
PlayStateResult::Switch(mut new_state) => {
direction = Direction::Forwards;
states.last_mut().map(|old_state| {
log::info!(
debug!(
"Switching to state '{}' from state '{}'.",
new_state.name(),
old_state.name()
@ -228,6 +223,7 @@ fn main() {
}
}
// Save settings to add new fields or create the file if it is not already there
// TODO: Handle this result.
global_state.settings.save_to_file();
if let Err(err) = global_state.settings.save_to_file() {
warn!("Failed to save settings: {:?}", err);
}
}

View File

@ -2,13 +2,13 @@ mod scene;
mod ui;
use crate::{
render::Renderer,
session::SessionState,
window::{Event, Window},
Direction, GlobalState, PlayState, PlayStateResult,
};
use client::{self, Client};
use common::{clock::Clock, comp, msg::ClientMsg, msg::ClientState};
use common::{clock::Clock, comp, msg::ClientState};
use log::error;
use scene::Scene;
use std::{cell::RefCell, rc::Rc, time::Duration};
use ui::CharSelectionUi;
@ -112,7 +112,7 @@ impl PlayState for CharSelectionState {
.borrow_mut()
.tick(comp::Control::default(), clock.get_last_delta())
{
log::error!("Failed to tick the scene: {:?}", err);
error!("Failed to tick the scene: {:?}", err);
return PlayStateResult::Pop;
}
self.client.borrow_mut().cleanup();

View File

@ -14,8 +14,8 @@ use crate::{
},
};
use client::Client;
use common::comp::HumanoidBody;
use common::{comp, figure::Segment};
use common::comp::{self, HumanoidBody};
use log::error;
use vek::*;
struct Skybox {
@ -85,7 +85,7 @@ impl Scene {
let (view_mat, proj_mat, cam_pos) = self.camera.compute_dependents(client);
renderer.update_consts(
if let Err(err) = renderer.update_consts(
&mut self.globals,
&[Globals::new(
view_mat,
@ -97,7 +97,9 @@ impl Scene {
client.state().get_time(),
renderer.get_resolution(),
)],
);
) {
error!("Renderer failed to update: {:?}", err);
}
self.figure_model_cache.clean(client.get_tick());

View File

@ -8,18 +8,15 @@ use crate::{
window::Window,
};
use common::comp::{
actor::{Belt, BodyType, Chest, Foot, Hand, Head, Pants, Race, Weapon, ALL_CHESTS},
actor::{BodyType, Race, Weapon, ALL_CHESTS},
HumanoidBody,
};
use conrod_core::{
color,
color::TRANSPARENT,
graph,
widget::{text_box::Event as TextBoxEvent, Button, Image, Rectangle, Scrollbar, Text, TextBox},
widget_ids, Borderable, Color, Colorable, Labelable, Positionable, Sizeable, Widget,
WidgetCommon,
};
use std::sync::Arc;
widget_ids! {
struct Ids {

View File

@ -4,7 +4,7 @@ use log::info;
use std::{
net::ToSocketAddrs,
sync::mpsc::{channel, Receiver, TryRecvError},
thread::{self, JoinHandle},
thread,
time::Duration,
};

View File

@ -3,12 +3,10 @@ mod start_singleplayer;
mod ui;
use super::char_selection::CharSelectionState;
use crate::{
window::{Event, Window},
Direction, GlobalState, PlayState, PlayStateResult,
};
use crate::{window::Event, Direction, GlobalState, PlayState, PlayStateResult};
use client_init::{ClientInit, Error as InitError};
use common::{clock::Clock, comp};
use log::warn;
use start_singleplayer::StartSingleplayerState;
use std::time::Duration;
use ui::{Event as MainMenuEvent, MainMenuUi};
@ -101,8 +99,9 @@ impl PlayState for MainMenuState {
if !net_settings.servers.contains(&server_address) {
net_settings.servers.push(server_address.clone());
}
// TODO: Handle this result.
global_state.settings.save_to_file();
if let Err(err) = global_state.settings.save_to_file() {
warn!("Failed to save settings: {:?}", err);
}
// Don't try to connect if there is already a connection in progress.
client_init = client_init.or(Some(ClientInit::new(
(server_address, DEFAULT_PORT, false),

View File

@ -1,9 +1,8 @@
use super::{client_init::ClientInit, DEFAULT_PORT};
use super::client_init::ClientInit;
use crate::{
menu::char_selection::CharSelectionState, singleplayer::Singleplayer, Direction, GlobalState,
PlayState, PlayStateResult,
};
use client::Client;
use common::comp;
use log::warn;
use std::net::SocketAddr;

View File

@ -5,18 +5,15 @@ use crate::{
img_ids::{ImageGraphic, VoxelGraphic},
ScaleMode, Ui,
},
GlobalState, DEFAULT_PUBLIC_SERVER,
GlobalState,
};
use conrod_core::{
color,
color::TRANSPARENT,
position::Relative,
widget::{
text_box::Event as TextBoxEvent, Button, Image, List, Rectangle, Scrollbar, Text, TextBox,
},
widget::{text_box::Event as TextBoxEvent, Button, Image, List, Rectangle, Text, TextBox},
widget_ids, Borderable, Color, Colorable, Labelable, Positionable, Sizeable, Widget,
};
use std::sync::Arc;
widget_ids! {
struct Ids {
@ -311,7 +308,7 @@ impl MainMenuUi {
let net_settings = &global_state.settings.networking;
// TODO: Draw scroll bar or remove it.
let (mut items, scrollbar) = List::flow_down(net_settings.servers.len())
let (mut items, _scrollbar) = List::flow_down(net_settings.servers.len())
.top_left_with_margins_on(self.ids.servers_frame, 0.0, 5.0)
.w_h(400.0, 300.0)
.scrollbar_next_to()

View File

@ -2,7 +2,6 @@ pub mod segment;
pub mod terrain;
mod vol;
// Crate
use crate::render::{self, Mesh};
pub trait Meshable {

View File

@ -1,17 +1,12 @@
// Library
use vek::*;
// Project
use common::{
figure::Segment,
vol::{ReadVol, SizedVol, Vox},
};
// Crate
use crate::{
mesh::{vol, Meshable},
render::{self, FigurePipeline, Mesh, Quad},
render::{self, FigurePipeline, Mesh},
};
use common::{
figure::Segment,
vol::{ReadVol, SizedVol},
};
use vek::*;
type FigureVertex = <FigurePipeline as render::Pipeline>::Vertex;

View File

@ -1,11 +1,11 @@
use crate::{
mesh::{vol, Meshable},
render::{self, Mesh, Quad, TerrainPipeline},
render::{self, Mesh, TerrainPipeline},
};
use common::{
terrain::Block,
vol::{BaseVol, ReadVol, SizedVol, VolSize, Vox},
volumes::{dyna::Dyna, vol_map_2d::VolMap2d, vol_map_3d::VolMap3d},
vol::{BaseVol, ReadVol, VolSize},
volumes::vol_map_2d::VolMap2d,
};
use std::fmt::Debug;
use vek::*;

View File

@ -1,8 +1,5 @@
// Library
use gfx::{self, traits::FactoryExt};
// Local
use super::{gfx_backend, RenderError};
use gfx::{self, traits::FactoryExt};
/// A handle to a series of constants sitting on the GPU. This is used to hold information used in
/// the rendering process that does not change throughout a single render pass.

View File

@ -1,4 +1,3 @@
// Local
use super::Pipeline;
/// A `Vec`-based mesh structure used to store mesh data on the CPU.

View File

@ -31,7 +31,6 @@ pub use self::{
#[cfg(feature = "gl")]
use gfx_device_gl as gfx_backend;
// Library
use gfx;
/// Used to represent one of many possible errors that may be omitted by the rendering subsystem.

View File

@ -1,4 +1,7 @@
// Library
use super::{
super::{util::arr_to_mat, Pipeline, TgtColorFmt, TgtDepthFmt},
Globals,
};
use gfx::{
self,
gfx_constant_struct_meta,
@ -11,12 +14,6 @@ use gfx::{
};
use vek::*;
// Local
use super::{
super::{util::arr_to_mat, Pipeline, TgtColorFmt, TgtDepthFmt},
Globals,
};
gfx_defines! {
vertex Vertex {
pos: [f32; 3] = "v_pos",

View File

@ -4,7 +4,7 @@ pub mod skybox;
pub mod terrain;
pub mod ui;
// Library
use super::util::arr_to_mat;
use gfx::{
self,
gfx_constant_struct_meta,
@ -14,9 +14,6 @@ use gfx::{
};
use vek::*;
// Local
use super::util::arr_to_mat;
gfx_defines! {
constant Globals {
view_mat: [[f32; 4]; 4] = "view_mat",

View File

@ -1,4 +1,7 @@
// Library
use super::{
super::{Mesh, Pipeline, Tri, WinColorFmt, WinDepthFmt},
Globals,
};
use gfx::{
self,
gfx_constant_struct_meta,
@ -10,12 +13,6 @@ use gfx::{
gfx_vertex_struct_meta,
};
// Local
use super::{
super::{Mesh, Pipeline, Tri, WinColorFmt, WinDepthFmt},
Globals,
};
gfx_defines! {
vertex Vertex {
pos: [f32; 2] = "v_pos",

View File

@ -1,4 +1,7 @@
// Library
use super::{
super::{Mesh, Pipeline, Quad, TgtColorFmt, TgtDepthFmt},
Globals,
};
use gfx::{
self,
gfx_constant_struct_meta,
@ -10,12 +13,6 @@ use gfx::{
gfx_vertex_struct_meta,
};
// Local
use super::{
super::{Mesh, Pipeline, Quad, TgtColorFmt, TgtDepthFmt},
Globals,
};
gfx_defines! {
vertex Vertex {
pos: [f32; 3] = "v_pos",

View File

@ -12,7 +12,7 @@ use gfx::{
gfx_pipeline_inner,
gfx_vertex_struct_meta,
};
use std::ops::{Add, Div, Mul};
use std::ops::Mul;
use vek::*;
gfx_defines! {
@ -42,7 +42,7 @@ impl Vertex {
.as_slice()
.into_iter()
.enumerate()
.find(|(i, e)| **e != 0.0)
.find(|(_i, e)| **e != 0.0)
.unwrap_or((0, &1.0));
let norm_bits = (norm_axis << 1) | if *norm_dir > 0.0 { 1 } else { 0 };

View File

@ -1,14 +1,9 @@
// Standard
use std::marker::PhantomData;
// Library
use super::{gfx_backend, Pipeline, RenderError};
use gfx::{self, traits::Factory};
use image::{DynamicImage, GenericImageView};
use std::marker::PhantomData;
use vek::Vec2;
// Local
use super::{gfx_backend, Pipeline, RenderError};
type ShaderFormat = (gfx::format::R8_G8_B8_A8, gfx::format::Srgb);
/// Represents an image that has been uploaded to the GPU.

View File

@ -1,11 +1,6 @@
use client::Client;
use common::vol::{ReadVol, SampleVol};
// Standard
use common::vol::ReadVol;
use std::f32::consts::PI;
// Library
use vek::*;
const NEAR_PLANE: f32 = 0.1;

View File

@ -9,7 +9,6 @@ use crate::{
render::{
Consts, FigureBoneData, FigureLocals, FigurePipeline, Globals, Mesh, Model, Renderer,
},
Error,
};
use client::Client;
use common::{
@ -21,16 +20,15 @@ use common::{
Shoulder, Weapon, WolfEars, WolfFootLB, WolfFootLF, WolfFootRB, WolfFootRF,
WolfHeadLower, WolfHeadUpper, WolfJaw, WolfTail, WolfTorsoBack, WolfTorsoMid,
},
Body, HumanoidBody, QuadrupedBody, QuadrupedMediumBody,
Body,
},
figure::Segment,
msg,
msg::ClientState,
terrain::TerrainChunkSize,
vol::VolSize,
};
use dot_vox::DotVoxData;
use specs::{Component, Entity as EcsEntity, Join, VecStorage};
use log::warn;
use specs::{Entity as EcsEntity, Join};
use std::{collections::HashMap, f32};
use vek::*;
@ -54,7 +52,7 @@ impl FigureModelCache {
tick: u64,
) -> &Model<FigurePipeline> {
match self.models.get_mut(&body) {
Some((model, last_used)) => {
Some((_model, last_used)) => {
*last_used = tick;
}
None => {
@ -523,7 +521,7 @@ impl FigureMgr {
// Change in health as color!
let col = stats
.and_then(|stats| stats.hp.last_change)
.map(|(change_by, time, _)| {
.map(|(_, time, _)| {
Rgba::broadcast(1.0)
+ Rgba::new(0.0, -1.0, -1.0, 0.0)
.map(|c| (c / (1.0 + DAMAGE_FADE_COEFFICIENT * time)) as f32)
@ -532,7 +530,7 @@ impl FigureMgr {
match actor {
comp::Actor::Character { body, .. } => match body {
Body::Humanoid(body) => {
Body::Humanoid(_) => {
let state = self.character_states.entry(entity).or_insert_with(|| {
FigureState::new(renderer, CharacterSkeleton::new())
});
@ -570,7 +568,7 @@ impl FigureMgr {
state.skeleton.interpolate(&target_skeleton);
state.update(renderer, pos.0, ori.0, col);
}
Body::Quadruped(body) => {
Body::Quadruped(_) => {
let state = self.quadruped_states.entry(entity).or_insert_with(|| {
FigureState::new(renderer, QuadrupedSkeleton::new())
});
@ -599,7 +597,7 @@ impl FigureMgr {
state.skeleton.interpolate(&target_skeleton);
state.update(renderer, pos.0, ori.0, col);
}
Body::QuadrupedMedium(body) => {
Body::QuadrupedMedium(_) => {
let state =
self.quadruped_medium_states
.entry(entity)
@ -686,7 +684,7 @@ impl FigureMgr {
.reduce_and()
})
// Don't render dead entities
.filter(|(e, _, _, _, a, _, stats)| stats.map_or(true, |s| !s.is_dead))
.filter(|(_, _, _, _, _, _, stats)| stats.map_or(true, |s| !s.is_dead))
{
match actor {
comp::Actor::Character { body, .. } => {
@ -708,7 +706,7 @@ impl FigureMgr {
renderer.render_figure(model, globals, locals, bone_consts);
} else {
log::error!("Body has no saved figure");
warn!("Body has no saved figure");
}
}
}

View File

@ -4,20 +4,14 @@ pub mod terrain;
use self::{camera::Camera, figure::FigureMgr, terrain::Terrain};
use crate::{
anim::{
character::{CharacterSkeleton, RunAnimation},
Animation,
},
mesh::Meshable,
render::{
create_pp_mesh, create_skybox_mesh, Consts, FigureLocals, Globals, Model,
PostProcessLocals, PostProcessPipeline, Renderer, SkyboxLocals, SkyboxPipeline,
create_pp_mesh, create_skybox_mesh, Consts, Globals, Model, PostProcessLocals,
PostProcessPipeline, Renderer, SkyboxLocals, SkyboxPipeline,
},
window::Event,
};
use client::Client;
use common::{comp, figure::Segment};
use dot_vox;
use common::comp;
use vek::*;
// TODO: Don't hard-code this.

View File

@ -264,7 +264,7 @@ impl Terrain {
}
pub fn render(&self, renderer: &mut Renderer, globals: &Consts<Globals>) {
for (pos, chunk) in &self.chunks {
for (_pos, chunk) in &self.chunks {
if chunk.visible {
renderer.render_terrain_chunk(&chunk.model, globals, &chunk.locals);
}

View File

@ -9,8 +9,8 @@ use crate::{
};
use client::{self, Client};
use common::{clock::Clock, comp, comp::phys::Pos, msg::ClientState};
use glutin::MouseButton;
use std::{cell::RefCell, mem, rc::Rc, time::Duration};
use log::{error, warn};
use std::{cell::RefCell, rc::Rc, time::Duration};
use vek::*;
const FPS: u64 = 60;
@ -110,8 +110,6 @@ impl PlayState for SessionState {
while let ClientState::Pending | ClientState::Character | ClientState::Dead =
current_client_state
{
let alive = self.client.borrow().get_client_state() == ClientState::Character;
// Handle window events.
for event in global_state.window.fetch_events() {
// Pass all events to the ui first.
@ -147,7 +145,7 @@ impl PlayState for SessionState {
// Perform an in-game tick.
if let Err(err) = self.tick(clock.get_last_delta()) {
log::error!("Failed to tick the scene: {:?}", err);
error!("Failed to tick the scene: {:?}", err);
return PlayStateResult::Pop;
}
@ -190,19 +188,25 @@ impl PlayState for SessionState {
self.client.borrow_mut().set_view_distance(view_distance);
global_state.settings.graphics.view_distance = view_distance;
global_state.settings.save_to_file();
if let Err(err) = global_state.settings.save_to_file() {
warn!("Failed to save settings: {:?}", err);
}
}
HudEvent::AdjustVolume(volume) => {
global_state.audio.set_volume(volume);
global_state.settings.audio.music_volume = volume;
global_state.settings.save_to_file();
if let Err(err) = global_state.settings.save_to_file() {
warn!("Failed to save settings: {:?}", err);
}
}
HudEvent::ChangeAudioDevice(name) => {
global_state.audio.set_device(name.clone());
global_state.settings.audio.audio_device = Some(name);
global_state.settings.save_to_file();
if let Err(err) = global_state.settings.save_to_file() {
warn!("Failed to save settings!\n{:?}", err);
}
}
}
}

View File

@ -125,8 +125,6 @@ impl Default for Settings {
impl Settings {
pub fn load() -> Self {
let default_settings = Settings::default();
let path = Settings::get_settings_path();
// If file doesn't exist, use the default settings.

View File

@ -84,7 +84,7 @@ fn run_server(mut server: Server, rec: Receiver<Msg>) {
server.cleanup();
match rec.try_recv() {
Ok(msg) => break,
Ok(_msg) => break,
Err(err) => match err {
TryRecvError::Empty => (),
TryRecvError::Disconnected => break,

View File

@ -69,7 +69,7 @@ impl GraphicCache {
.atlas
.allocate(size2(i32::from(dims.x), i32::from(dims.y)))
{
Some(Allocation { id, rectangle }) => {
Some(Allocation { id: _, rectangle }) => {
let (min, max) = (rectangle.min, rectangle.max);
Aabr {
min: Vec2::new(min.x as u16, min.y as u16),

View File

@ -40,7 +40,7 @@ impl<'a> Pipeline for Voxel {
Vert {
pos,
col,
norm,
norm: _,
ao_level,
}: &Self::Vertex,
) -> ([f32; 3], Self::VsOut) {

View File

@ -23,7 +23,6 @@ use crate::{
create_ui_quad, create_ui_tri, Consts, DynamicModel, Globals, Mesh, RenderError, Renderer,
UiLocals, UiMode, UiPipeline,
},
scene::camera::Camera,
window::Window,
Error,
};
@ -40,6 +39,7 @@ use conrod_core::{
Rect, UiBuilder, UiCell,
};
use graphic::Id as GraphicId;
use log::warn;
use scale::Scale;
use std::io::Read;
use std::ops::Range;
@ -110,7 +110,7 @@ impl Ui {
let scale = Scale::new(window, ScaleMode::Absolute(1.0));
let win_dims = scale.scaled_window_size().into_array();
let mut renderer = window.renderer_mut();
let renderer = window.renderer_mut();
Ok(Self {
ui: UiBuilder::new(win_dims).build(),
@ -402,7 +402,10 @@ impl Ui {
|aabr, data| {
let offset = aabr.min.into_array();
let size = aabr.size().into_array();
renderer.update_texture(cache_tex, offset, size, data);
if let Err(err) = renderer.update_texture(cache_tex, offset, size, data)
{
warn!("Failed to update texture: {:?}", err);
}
},
) {
Some(aabr) => Aabr {
@ -444,7 +447,11 @@ impl Ui {
.map(|x| [255, 255, 255, *x])
.collect::<Vec<[u8; 4]>>();
renderer.update_texture(cache_tex, offset, size, &new_data);
if let Err(err) =
renderer.update_texture(cache_tex, offset, size, &new_data)
{
warn!("Failed to update texture: {:?}", err);
}
})
.unwrap();

View File

@ -1,10 +1,9 @@
use conrod_core::{
builder_methods, image,
builder_methods,
position::Dimension,
widget::{self, button, Id},
widget_ids, Color, Position, Positionable, Rect, Sizeable, Ui, UiCell, Widget, WidgetCommon,
widget::{self, Id},
Position, Ui, UiCell, Widget, WidgetCommon,
};
use std::slice;
use vek::*;
#[derive(Clone, WidgetCommon)]
@ -24,7 +23,7 @@ pub trait Ingameable: Widget + Sized {
// should pass focus to the window if these are clicked
// (they are not displayed where conrod thinks they are)
.graphics_for(ui.window)
//.parent(parent_id) // is this needed
//.parent(parent_id) // TODO: Is this needed?
.set(id, ui)
}
fn position_ingame(self, pos: Vec3<f32>) -> Ingame<Self> {
@ -186,7 +185,7 @@ impl Widget for IngameAnchor {
}
fn update(self, args: widget::UpdateArgs<Self>) -> Self::Event {
let widget::UpdateArgs { id, state, ui, .. } = args;
let widget::UpdateArgs { id: _, state, .. } = args;
let IngameAnchor { parameters, .. } = self;
// Update pos if it has changed

View File

@ -3,6 +3,7 @@ use crate::{
settings::Settings,
ui, Error,
};
use log::{error, warn};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use vek::*;
@ -311,7 +312,7 @@ impl Window {
let mut path = PathBuf::from("./screenshots");
if !path.exists() {
if let Err(err) = std::fs::create_dir(&path) {
log::error!("Couldn't create folder for screenshot: {:?}", err);
warn!("Couldn't create folder for screenshot: {:?}", err);
}
}
path.push(format!(
@ -322,11 +323,11 @@ impl Window {
.unwrap_or(0)
));
if let Err(err) = img.save(&path) {
log::error!("Couldn't save screenshot: {:?}", err);
warn!("Couldn't save screenshot: {:?}", err);
}
});
}
Err(err) => log::error!(
Err(err) => error!(
"Couldn't create screenshot due to renderer error: {:?}",
err
),

View File

@ -5,15 +5,11 @@ mod structure;
use common::{
terrain::{Block, TerrainChunk, TerrainChunkMeta, TerrainChunkSize},
vol::{SizedVol, VolSize, Vox, WriteVol},
vol::{VolSize, Vox, WriteVol},
};
use fxhash::FxHashMap;
use noise::{BasicMulti, MultiFractal, NoiseFn, Perlin, Seedable};
use std::{
hash::Hash,
ops::{Add, Div, Mul, Neg, Sub},
time::Duration,
};
use noise::{BasicMulti, MultiFractal, Seedable};
use std::{hash::Hash, time::Duration};
use vek::*;
#[derive(Debug)]
@ -120,7 +116,7 @@ impl<K: Hash + Eq + Copy, V> Cache<K, V> {
}
pub fn get<F: FnOnce(K) -> V>(&mut self, k: K, f: F) -> &V {
let mut counter = &mut self.counter;
let counter = &mut self.counter;
&self
.map
.entry(k)

View File

@ -5,10 +5,7 @@ use common::{
vol::{ReadVol, VolSize, Vox},
};
use lazy_static::lazy_static;
use noise::{
BasicMulti, HybridMulti, MultiFractal, NoiseFn, OpenSimplex, RidgedMulti, Seedable,
SuperSimplex,
};
use noise::{BasicMulti, HybridMulti, MultiFractal, NoiseFn, RidgedMulti, Seedable, SuperSimplex};
use std::{
f32,
ops::{Add, Div, Mul, Neg, Sub},