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" version = "0.2.0"
dependencies = [ dependencies = [
"lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "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)", "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)", "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)", "threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)",

View File

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

View File

@ -8,7 +8,6 @@ use std::{
fs::File, fs::File,
io::BufReader, io::BufReader,
io::Read, io::Read,
path::PathBuf,
sync::{Arc, RwLock}, 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> { pub fn load_from_path(name: &str) -> Result<BufReader<File>, Error> {
match try_open_with_path(name) { 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())), None => Err(Error::NotFound(name.to_owned())),
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,17 +1,12 @@
pub mod cell; pub mod cell;
// Library use self::cell::Cell;
use dot_vox::DotVoxData;
use vek::*;
// Crate
use crate::{ use crate::{
vol::{Vox, WriteVol}, vol::{Vox, WriteVol},
volumes::dyna::Dyna, volumes::dyna::Dyna,
}; };
use dot_vox::DotVoxData;
// Local use vek::*;
use self::cell::Cell;
/// A type representing a volume that may be part of an animated figure. /// 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)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Armor { 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), Helmet(actor::Head),
Shoulders(actor::Shoulder), Shoulders(actor::Shoulder),
Chestplate(actor::Chest), Chestplate(actor::Chest),

View File

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

View File

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

View File

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

View File

@ -2,8 +2,6 @@ use crate::assets;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use serde_json; use serde_json;
use std::fs::File;
use std::io::Error;
use std::sync::Arc; use std::sync::Arc;
pub enum NpcKind { 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 dir = (self.to - self.from).normalized();
let max = (self.to - self.from).magnitude(); 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 { for _ in 0..self.max_iter {
pos = self.from + dir * dist; let pos = self.from + dir * dist;
ipos = pos.map(|e| e.floor() as i32); let ipos = pos.map(|e| e.floor() as i32);
// Allow one iteration above max. // Allow one iteration above max.
if dist > max { if dist > max {

View File

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

View File

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

View File

@ -1,20 +1,14 @@
// Library use crate::comp::{phys::Pos, Agent, Attacking, Control, Jumping};
use rand::Rng; use log::warn;
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use rand::{seq::SliceRandom, thread_rng};
use specs::{Entities, Join, ReadStorage, System, WriteStorage};
use vek::*; use vek::*;
// Crate
use crate::{
comp::{phys::Pos, Agent, Attacking, Control, Jumping},
state::Time,
};
// Basic ECS AI agent system // Basic ECS AI agent system
pub struct Sys; pub struct Sys;
impl<'a> System<'a> for Sys { impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Read<'a, Time>,
Entities<'a>, Entities<'a>,
WriteStorage<'a, Agent>, WriteStorage<'a, Agent>,
ReadStorage<'a, Pos>, ReadStorage<'a, Pos>,
@ -25,7 +19,7 @@ impl<'a> System<'a> for Sys {
fn run( fn run(
&mut self, &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 for (entity, agent, pos, control) in
(&entities, &mut agents, &positions, &mut controls).join() (&entities, &mut agents, &positions, &mut controls).join()
@ -48,7 +42,9 @@ impl<'a> System<'a> for Sys {
let tgt_pos = tgt_pos.0 + *offset; let tgt_pos = tgt_pos.0 + *offset;
if tgt_pos.z > pos.0.z + 1.0 { 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. // Move towards the target.
@ -79,7 +75,9 @@ impl<'a> System<'a> for Sys {
control.move_dir = Vec2::zero(); control.move_dir = Vec2::zero();
if rand::random::<f32>() < 0.2 { if rand::random::<f32>() < 0.2 {
attacks.insert(entity, Attacking::start()); attacks
.insert(entity, Attacking::start())
.expect("Inserting attacking for an entity failed!");
} }
false false
@ -107,7 +105,8 @@ impl<'a> System<'a> for Sys {
.map(|(e, _)| e) .map(|(e, _)| e)
.collect::<Vec<_>>(); .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 crate::{comp::AnimationInfo, state::DeltaTime};
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use specs::{Join, Read, System, WriteStorage};
use vek::*;
// Crate
use crate::{
comp::{phys::Pos, Animation, AnimationInfo, Stats},
state::DeltaTime,
};
// Basic ECS AI agent system // Basic ECS AI agent system
pub struct Sys; pub struct Sys;
@ -15,7 +8,7 @@ impl<'a> System<'a> for Sys {
type SystemData = (Read<'a, DeltaTime>, WriteStorage<'a, AnimationInfo>); type SystemData = (Read<'a, DeltaTime>, WriteStorage<'a, AnimationInfo>);
fn run(&mut self, (dt, mut animation_infos): Self::SystemData) { 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; 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::{ use crate::{
comp::{ comp::{
phys::{ForceUpdate, Ori, Pos, Vel}, phys::{ForceUpdate, Ori, Pos, Vel},
Animation, AnimationInfo, Attacking, Control, Gliding, HealthSource, Jumping, Respawning, Animation, AnimationInfo, Attacking, Control, Gliding, HealthSource, Jumping, Stats,
Stats,
}, },
state::{DeltaTime, Time, Uid}, state::{DeltaTime, Uid},
terrain::TerrainMap, terrain::TerrainMap,
vol::{ReadVol, Vox}, vol::{ReadVol, Vox},
}; };
use log::warn;
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, System, WriteStorage};
use vek::*;
// Basic ECS AI agent system // Basic ECS AI agent system
pub struct Sys; pub struct Sys;
@ -31,7 +28,6 @@ impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Entities<'a>, Entities<'a>,
ReadStorage<'a, Uid>, ReadStorage<'a, Uid>,
Read<'a, Time>,
Read<'a, DeltaTime>, Read<'a, DeltaTime>,
ReadExpect<'a, TerrainMap>, ReadExpect<'a, TerrainMap>,
ReadStorage<'a, Pos>, ReadStorage<'a, Pos>,
@ -41,7 +37,6 @@ impl<'a> System<'a> for Sys {
WriteStorage<'a, Stats>, WriteStorage<'a, Stats>,
ReadStorage<'a, Control>, ReadStorage<'a, Control>,
WriteStorage<'a, Jumping>, WriteStorage<'a, Jumping>,
WriteStorage<'a, Respawning>,
WriteStorage<'a, Gliding>, WriteStorage<'a, Gliding>,
WriteStorage<'a, Attacking>, WriteStorage<'a, Attacking>,
WriteStorage<'a, ForceUpdate>, WriteStorage<'a, ForceUpdate>,
@ -52,7 +47,6 @@ impl<'a> System<'a> for Sys {
( (
entities, entities,
uids, uids,
time,
dt, dt,
terrain, terrain,
positions, positions,
@ -60,10 +54,9 @@ impl<'a> System<'a> for Sys {
mut orientations, mut orientations,
mut animation_infos, mut animation_infos,
mut stats, mut stats,
mut controls, controls,
mut jumps, mut jumps,
mut respawns, glides,
mut glides,
mut attacks, mut attacks,
mut force_updates, mut force_updates,
): Self::SystemData, ): Self::SystemData,
@ -140,21 +133,23 @@ impl<'a> System<'a> for Sys {
.unwrap_or(AnimationInfo::default()); .unwrap_or(AnimationInfo::default());
let changed = last.animation != animation; let changed = last.animation != animation;
animation_infos.insert( if let Err(err) = animation_infos.insert(
entity, entity,
AnimationInfo { AnimationInfo {
animation, animation,
time: if changed { 0.0 } else { last.time }, time: if changed { 0.0 } else { last.time },
changed, changed,
}, },
); ) {
warn!("Inserting AnimationInfo for an entity failed: {:?}", err);
}
} }
for (entity, &uid, pos, ori, attacking) in for (entity, &uid, pos, ori, attacking) in
(&entities, &uids, &positions, &orientations, &mut attacks).join() (&entities, &uids, &positions, &orientations, &mut attacks).join()
{ {
if !attacking.applied { 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() (&entities, &positions, &mut stats, &mut velocities).join()
{ {
// Check if it is a hit // 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 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 += (pos_b.0 - pos.0).normalized() * 10.0;
vel_b.0.z = 15.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; attacking.applied = true;

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
use crate::ray::{Ray, RayUntil}; use crate::ray::Ray;
use std::fmt::Debug; use std::fmt::Debug;
use vek::*; 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 crate::vol::{BaseVol, ReadVol, SizedVol, VolSize, Vox, WriteVol};
use serde_derive::{Deserialize, Serialize};
use std::marker::PhantomData;
use vek::*;
#[derive(Debug)] #[derive(Debug)]
pub enum ChunkErr { pub enum ChunkErr {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,4 @@
use crate::Error;
use common::{ use common::{
comp,
msg::{ClientMsg, ClientState, RequestStateError, ServerMsg}, msg::{ClientMsg, ClientState, RequestStateError, ServerMsg},
net::PostBox, net::PostBox,
}; };
@ -84,7 +82,7 @@ impl Clients {
} }
pub fn notify_ingame_if<F: FnMut(EcsEntity) -> bool>(&mut self, msg: ServerMsg, mut f: F) { 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 if client.client_state == ClientState::Spectator
|| client.client_state == ClientState::Character || 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 server
.state .state
.ecs_mut() .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 match server
.state .state
.read_component_cloned::<comp::phys::Pos>(entity) .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 match server
.state .state
.read_component_cloned::<comp::phys::Pos>(entity) .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 match server
.state .state
.read_component_cloned::<comp::phys::Pos>(entity) .read_component_cloned::<comp::phys::Pos>(entity)

View File

@ -20,10 +20,8 @@ use common::{
terrain::{TerrainChunk, TerrainChunkSize}, terrain::{TerrainChunk, TerrainChunkSize},
vol::VolSize, vol::VolSize,
}; };
use specs::{ use log::warn;
join::Join, saveload::MarkedBuilder, world::EntityBuilder as EcsEntityBuilder, Builder, use specs::{join::Join, world::EntityBuilder as EcsEntityBuilder, Builder, Entity as EcsEntity};
Entity as EcsEntity,
};
use std::{ use std::{
collections::HashSet, collections::HashSet,
i32, i32,
@ -87,7 +85,7 @@ impl Server {
.ecs_mut() .ecs_mut()
.add_resource(SpawnPoint(Vec3::new(16_384.0, 16_384.0, 280.0))); .add_resource(SpawnPoint(Vec3::new(16_384.0, 16_384.0, 280.0)));
let mut this = Self { let this = Self {
state, state,
world: Arc::new(World::generate(DEFAULT_WORLD_SEED)), 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) Ok(this)
} }
@ -264,7 +250,9 @@ impl Server {
self.state.write_component(entity, comp::phys::ForceUpdate); self.state.write_component(entity, comp::phys::ForceUpdate);
client.force_state(ClientState::Dead); client.force_state(ClientState::Dead);
} else { } 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; continue;
} }
} }
@ -388,7 +376,7 @@ impl Server {
fn handle_new_connections(&mut self) -> Result<Vec<Event>, Error> { fn handle_new_connections(&mut self) -> Result<Vec<Event>, Error> {
let mut frontend_events = Vec::new(); 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 entity = self.state.ecs_mut().create_entity_synced().build();
let mut client = Client { let mut client = Client {
client_state: ClientState::Connected, client_state: ClientState::Connected,
@ -623,7 +611,9 @@ impl Server {
// Handle client disconnects. // Handle client disconnects.
for entity in disconnected_clients { 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 }); frontend_events.push(Event::ClientDisconnected { entity });
} }
@ -647,8 +637,7 @@ impl Server {
state.write_component(entity, player); state.write_component(entity, player);
// Sync physics // Sync physics
for (entity, &uid, &pos, &vel, &ori) in ( for (&uid, &pos, &vel, &ori) in (
&state.ecs().entities(),
&state.ecs().read_storage::<Uid>(), &state.ecs().read_storage::<Uid>(),
&state.ecs().read_storage::<comp::phys::Pos>(), &state.ecs().read_storage::<comp::phys::Pos>(),
&state.ecs().read_storage::<comp::phys::Vel>(), &state.ecs().read_storage::<comp::phys::Vel>(),
@ -665,8 +654,7 @@ impl Server {
} }
// Sync animations // Sync animations
for (entity, &uid, &animation_info) in ( for (&uid, &animation_info) in (
&state.ecs().entities(),
&state.ecs().read_storage::<Uid>(), &state.ecs().read_storage::<Uid>(),
&state.ecs().read_storage::<comp::AnimationInfo>(), &state.ecs().read_storage::<comp::AnimationInfo>(),
) )
@ -710,7 +698,7 @@ impl Server {
}; };
let state = &self.state; let state = &self.state;
let mut clients = &mut self.clients; let clients = &mut self.clients;
let in_vd = |entity| { let in_vd = |entity| {
// Get client position. // Get client position.

View File

@ -1,12 +1,7 @@
// Standard use super::{super::Animation, CharacterSkeleton};
use std::{f32::consts::PI, ops::Mul}; use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct Input { pub struct Input {
pub attack: bool, pub attack: bool,
} }
@ -24,9 +19,9 @@ impl Animation for AttackAnimation {
let mut next = (*skeleton).clone(); let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 4.0).sin(); let wave = (anim_time as f32 * 4.0).sin();
let wave_quicken = (1.0 - (anim_time as f32 * 16.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_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_double = 1.0 - (anim_time as f32 * 24.0).cos();
let wave_quick = (anim_time as f32 * 0.5).sin(); let wave_quick = (anim_time as f32 * 0.5).sin();
let wave_cos = (anim_time as f32 * 12.0).cos(); let wave_cos = (anim_time as f32 * 12.0).cos();
let wave_slow = (anim_time as f32 * 10.0 + PI).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}; use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct GlidingAnimation; pub struct GlidingAnimation;
impl Animation for 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 = (anim_time as f32 * 7.0).sin();
let wave_slow_cos = (anim_time as f32 * 7.0).cos(); let wave_slow_cos = (anim_time as f32 * 7.0).cos();
let arc_wave = (1.0f32.ln_1p() - 1.5).abs(); 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 fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos(); let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_stop = (anim_time as f32 * 1.5).min(PI / 2.0).sin(); 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}; use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, CharacterSkeleton, SCALE};
pub struct Input { pub struct Input {
pub attack: bool, pub attack: bool,
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,12 +1,7 @@
// Standard use super::{super::Animation, QuadrupedSkeleton};
use std::{f32::consts::PI, ops::Mul}; use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct IdleAnimation; pub struct IdleAnimation;
impl Animation for IdleAnimation { impl Animation for IdleAnimation {
@ -21,7 +16,7 @@ impl Animation for IdleAnimation {
let mut next = (*skeleton).clone(); let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 14.0).sin(); 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 = (anim_time as f32 * 1.0 + PI).sin();
let wave_ultra_slow_cos = (anim_time as f32 * 1.0 + PI).cos(); let wave_ultra_slow_cos = (anim_time as f32 * 1.0 + PI).cos();
let fuzz_wave = (anim_time as f32 * 12.0).sin(); 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; use std::f32::consts::PI;
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct JumpAnimation; pub struct JumpAnimation;
impl Animation for JumpAnimation { impl Animation for JumpAnimation {
@ -21,7 +16,7 @@ impl Animation for JumpAnimation {
let mut next = (*skeleton).clone(); let mut next = (*skeleton).clone();
let wave = (anim_time as f32 * 14.0).sin(); 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 fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos(); let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_slow = (anim_time as f32 * 7.0 + PI).sin(); 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::jump::JumpAnimation;
pub use self::run::RunAnimation; pub use self::run::RunAnimation;
// Crate
use crate::render::FigureBoneData;
// Local
use super::{Bone, Skeleton}; use super::{Bone, Skeleton};
use crate::render::FigureBoneData;
const SCALE: f32 = 11.0; const SCALE: f32 = 11.0;

View File

@ -1,12 +1,7 @@
// Standard use super::{super::Animation, QuadrupedSkeleton};
use std::f32::consts::PI; use std::f32::consts::PI;
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, QuadrupedSkeleton, SCALE};
pub struct RunAnimation; pub struct RunAnimation;
impl Animation for RunAnimation { impl Animation for RunAnimation {
@ -23,7 +18,7 @@ impl Animation for RunAnimation {
let wave = (anim_time as f32 * 14.0).sin(); let wave = (anim_time as f32 * 14.0).sin();
let wave_quick = (anim_time as f32 * 20.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_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 fuzz_wave = (anim_time as f32 * 12.0).sin();
let wave_cos = (anim_time as f32 * 14.0).cos(); let wave_cos = (anim_time as f32 * 14.0).cos();
let wave_slow = (anim_time as f32 * 7.0 + PI).sin(); 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}; use std::{f32::consts::PI, ops::Mul};
// Library
use vek::*; use vek::*;
// Local
use super::{super::Animation, QuadrupedMediumSkeleton, SCALE};
pub struct IdleAnimation; pub struct IdleAnimation;
impl Animation for IdleAnimation { impl Animation for IdleAnimation {

View File

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

View File

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

View File

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

View File

@ -1,19 +1,7 @@
use crate::settings::AudioSettings; use crate::settings::AudioSettings;
use common::assets; use common::assets;
use rand::prelude::*; use rodio::{Decoder, Device, SpatialSink};
use rodio::{Decoder, Device, Source, SpatialSink}; use std::iter::Iterator;
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::*;
pub struct AudioFrontend { pub struct AudioFrontend {
device: Device, device: Device,
@ -25,7 +13,7 @@ pub struct AudioFrontend {
impl AudioFrontend { impl AudioFrontend {
pub fn new(settings: &AudioSettings) -> Self { pub fn new(settings: &AudioSettings) -> Self {
let mut device = match &settings.audio_device { let device = match &settings.audio_device {
Some(dev) => rodio::output_devices() Some(dev) => rodio::output_devices()
.find(|x| &x.name() == dev) .find(|x| &x.name() == dev)
.or_else(rodio::default_output_device) .or_else(rodio::default_output_device)
@ -33,7 +21,7 @@ impl AudioFrontend {
None => rodio::default_output_device().expect("No audio devices found"), 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]); 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); 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 crate::render::RenderError;
use client;
use std::any;
/// Represents any error that may be triggered by Voxygen. /// Represents any error that may be triggered by Voxygen.
#[derive(Debug)] #[derive(Debug)]

View File

@ -2,7 +2,7 @@ use super::{img_ids::Imgs, Fonts, TEXT_COLOR, XP_COLOR};
use conrod_core::{ use conrod_core::{
color, color,
widget::{self, Button, Image, Rectangle, Text}, 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! { widget_ids! {

View File

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

View File

@ -1,17 +1,11 @@
use super::{img_ids::Imgs, Fonts, Show, TEXT_COLOR}; use super::{img_ids::Imgs, Fonts, Show, TEXT_COLOR};
use crate::{ use crate::{
render::Renderer, ui::{ImageSlider, ToggleButton},
ui::{ GlobalState,
self,
img_ids::{ImageGraphic, VoxelGraphic},
ImageSlider, ScaleMode, ToggleButton, Ui,
},
window::Window,
AudioFrontend, GlobalState,
}; };
use conrod_core::{ use conrod_core::{
color, 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, Colorable, Labelable, Positionable, Sizeable, Widget, WidgetCommon,
}; };
widget_ids! { widget_ids! {

View File

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

View File

@ -2,13 +2,13 @@ mod scene;
mod ui; mod ui;
use crate::{ use crate::{
render::Renderer,
session::SessionState, session::SessionState,
window::{Event, Window}, window::{Event, Window},
Direction, GlobalState, PlayState, PlayStateResult, Direction, GlobalState, PlayState, PlayStateResult,
}; };
use client::{self, Client}; 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 scene::Scene;
use std::{cell::RefCell, rc::Rc, time::Duration}; use std::{cell::RefCell, rc::Rc, time::Duration};
use ui::CharSelectionUi; use ui::CharSelectionUi;
@ -112,7 +112,7 @@ impl PlayState for CharSelectionState {
.borrow_mut() .borrow_mut()
.tick(comp::Control::default(), clock.get_last_delta()) .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; return PlayStateResult::Pop;
} }
self.client.borrow_mut().cleanup(); self.client.borrow_mut().cleanup();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,5 @@
// Library
use gfx::{self, traits::FactoryExt};
// Local
use super::{gfx_backend, RenderError}; 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 /// 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. /// the rendering process that does not change throughout a single render pass.

View File

@ -1,4 +1,3 @@
// Local
use super::Pipeline; use super::Pipeline;
/// A `Vec`-based mesh structure used to store mesh data on the CPU. /// 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")] #[cfg(feature = "gl")]
use gfx_device_gl as gfx_backend; use gfx_device_gl as gfx_backend;
// Library
use gfx; use gfx;
/// Used to represent one of many possible errors that may be omitted by the rendering subsystem. /// 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::{ use gfx::{
self, self,
gfx_constant_struct_meta, gfx_constant_struct_meta,
@ -11,12 +14,6 @@ use gfx::{
}; };
use vek::*; use vek::*;
// Local
use super::{
super::{util::arr_to_mat, Pipeline, TgtColorFmt, TgtDepthFmt},
Globals,
};
gfx_defines! { gfx_defines! {
vertex Vertex { vertex Vertex {
pos: [f32; 3] = "v_pos", pos: [f32; 3] = "v_pos",

View File

@ -4,7 +4,7 @@ pub mod skybox;
pub mod terrain; pub mod terrain;
pub mod ui; pub mod ui;
// Library use super::util::arr_to_mat;
use gfx::{ use gfx::{
self, self,
gfx_constant_struct_meta, gfx_constant_struct_meta,
@ -14,9 +14,6 @@ use gfx::{
}; };
use vek::*; use vek::*;
// Local
use super::util::arr_to_mat;
gfx_defines! { gfx_defines! {
constant Globals { constant Globals {
view_mat: [[f32; 4]; 4] = "view_mat", 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::{ use gfx::{
self, self,
gfx_constant_struct_meta, gfx_constant_struct_meta,
@ -10,12 +13,6 @@ use gfx::{
gfx_vertex_struct_meta, gfx_vertex_struct_meta,
}; };
// Local
use super::{
super::{Mesh, Pipeline, Tri, WinColorFmt, WinDepthFmt},
Globals,
};
gfx_defines! { gfx_defines! {
vertex Vertex { vertex Vertex {
pos: [f32; 2] = "v_pos", pos: [f32; 2] = "v_pos",

View File

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

View File

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

View File

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

View File

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

View File

@ -9,7 +9,6 @@ use crate::{
render::{ render::{
Consts, FigureBoneData, FigureLocals, FigurePipeline, Globals, Mesh, Model, Renderer, Consts, FigureBoneData, FigureLocals, FigurePipeline, Globals, Mesh, Model, Renderer,
}, },
Error,
}; };
use client::Client; use client::Client;
use common::{ use common::{
@ -21,16 +20,15 @@ use common::{
Shoulder, Weapon, WolfEars, WolfFootLB, WolfFootLF, WolfFootRB, WolfFootRF, Shoulder, Weapon, WolfEars, WolfFootLB, WolfFootLF, WolfFootRB, WolfFootRF,
WolfHeadLower, WolfHeadUpper, WolfJaw, WolfTail, WolfTorsoBack, WolfTorsoMid, WolfHeadLower, WolfHeadUpper, WolfJaw, WolfTail, WolfTorsoBack, WolfTorsoMid,
}, },
Body, HumanoidBody, QuadrupedBody, QuadrupedMediumBody, Body,
}, },
figure::Segment, figure::Segment,
msg,
msg::ClientState,
terrain::TerrainChunkSize, terrain::TerrainChunkSize,
vol::VolSize, vol::VolSize,
}; };
use dot_vox::DotVoxData; 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 std::{collections::HashMap, f32};
use vek::*; use vek::*;
@ -54,7 +52,7 @@ impl FigureModelCache {
tick: u64, tick: u64,
) -> &Model<FigurePipeline> { ) -> &Model<FigurePipeline> {
match self.models.get_mut(&body) { match self.models.get_mut(&body) {
Some((model, last_used)) => { Some((_model, last_used)) => {
*last_used = tick; *last_used = tick;
} }
None => { None => {
@ -523,7 +521,7 @@ impl FigureMgr {
// Change in health as color! // Change in health as color!
let col = stats let col = stats
.and_then(|stats| stats.hp.last_change) .and_then(|stats| stats.hp.last_change)
.map(|(change_by, time, _)| { .map(|(_, time, _)| {
Rgba::broadcast(1.0) Rgba::broadcast(1.0)
+ Rgba::new(0.0, -1.0, -1.0, 0.0) + Rgba::new(0.0, -1.0, -1.0, 0.0)
.map(|c| (c / (1.0 + DAMAGE_FADE_COEFFICIENT * time)) as f32) .map(|c| (c / (1.0 + DAMAGE_FADE_COEFFICIENT * time)) as f32)
@ -532,7 +530,7 @@ impl FigureMgr {
match actor { match actor {
comp::Actor::Character { body, .. } => match body { comp::Actor::Character { body, .. } => match body {
Body::Humanoid(body) => { Body::Humanoid(_) => {
let state = self.character_states.entry(entity).or_insert_with(|| { let state = self.character_states.entry(entity).or_insert_with(|| {
FigureState::new(renderer, CharacterSkeleton::new()) FigureState::new(renderer, CharacterSkeleton::new())
}); });
@ -570,7 +568,7 @@ impl FigureMgr {
state.skeleton.interpolate(&target_skeleton); state.skeleton.interpolate(&target_skeleton);
state.update(renderer, pos.0, ori.0, col); state.update(renderer, pos.0, ori.0, col);
} }
Body::Quadruped(body) => { Body::Quadruped(_) => {
let state = self.quadruped_states.entry(entity).or_insert_with(|| { let state = self.quadruped_states.entry(entity).or_insert_with(|| {
FigureState::new(renderer, QuadrupedSkeleton::new()) FigureState::new(renderer, QuadrupedSkeleton::new())
}); });
@ -599,7 +597,7 @@ impl FigureMgr {
state.skeleton.interpolate(&target_skeleton); state.skeleton.interpolate(&target_skeleton);
state.update(renderer, pos.0, ori.0, col); state.update(renderer, pos.0, ori.0, col);
} }
Body::QuadrupedMedium(body) => { Body::QuadrupedMedium(_) => {
let state = let state =
self.quadruped_medium_states self.quadruped_medium_states
.entry(entity) .entry(entity)
@ -686,7 +684,7 @@ impl FigureMgr {
.reduce_and() .reduce_and()
}) })
// Don't render dead entities // 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 { match actor {
comp::Actor::Character { body, .. } => { comp::Actor::Character { body, .. } => {
@ -708,7 +706,7 @@ impl FigureMgr {
renderer.render_figure(model, globals, locals, bone_consts); renderer.render_figure(model, globals, locals, bone_consts);
} else { } 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 self::{camera::Camera, figure::FigureMgr, terrain::Terrain};
use crate::{ use crate::{
anim::{
character::{CharacterSkeleton, RunAnimation},
Animation,
},
mesh::Meshable,
render::{ render::{
create_pp_mesh, create_skybox_mesh, Consts, FigureLocals, Globals, Model, create_pp_mesh, create_skybox_mesh, Consts, Globals, Model, PostProcessLocals,
PostProcessLocals, PostProcessPipeline, Renderer, SkyboxLocals, SkyboxPipeline, PostProcessPipeline, Renderer, SkyboxLocals, SkyboxPipeline,
}, },
window::Event, window::Event,
}; };
use client::Client; use client::Client;
use common::{comp, figure::Segment}; use common::comp;
use dot_vox;
use vek::*; use vek::*;
// TODO: Don't hard-code this. // TODO: Don't hard-code this.

View File

@ -264,7 +264,7 @@ impl Terrain {
} }
pub fn render(&self, renderer: &mut Renderer, globals: &Consts<Globals>) { 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 { if chunk.visible {
renderer.render_terrain_chunk(&chunk.model, globals, &chunk.locals); renderer.render_terrain_chunk(&chunk.model, globals, &chunk.locals);
} }

View File

@ -9,8 +9,8 @@ use crate::{
}; };
use client::{self, Client}; use client::{self, Client};
use common::{clock::Clock, comp, comp::phys::Pos, msg::ClientState}; use common::{clock::Clock, comp, comp::phys::Pos, msg::ClientState};
use glutin::MouseButton; use log::{error, warn};
use std::{cell::RefCell, mem, rc::Rc, time::Duration}; use std::{cell::RefCell, rc::Rc, time::Duration};
use vek::*; use vek::*;
const FPS: u64 = 60; const FPS: u64 = 60;
@ -110,8 +110,6 @@ impl PlayState for SessionState {
while let ClientState::Pending | ClientState::Character | ClientState::Dead = while let ClientState::Pending | ClientState::Character | ClientState::Dead =
current_client_state current_client_state
{ {
let alive = self.client.borrow().get_client_state() == ClientState::Character;
// Handle window events. // Handle window events.
for event in global_state.window.fetch_events() { for event in global_state.window.fetch_events() {
// Pass all events to the ui first. // Pass all events to the ui first.
@ -147,7 +145,7 @@ impl PlayState for SessionState {
// Perform an in-game tick. // Perform an in-game tick.
if let Err(err) = self.tick(clock.get_last_delta()) { 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; return PlayStateResult::Pop;
} }
@ -190,19 +188,25 @@ impl PlayState for SessionState {
self.client.borrow_mut().set_view_distance(view_distance); self.client.borrow_mut().set_view_distance(view_distance);
global_state.settings.graphics.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) => { HudEvent::AdjustVolume(volume) => {
global_state.audio.set_volume(volume); global_state.audio.set_volume(volume);
global_state.settings.audio.music_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) => { HudEvent::ChangeAudioDevice(name) => {
global_state.audio.set_device(name.clone()); global_state.audio.set_device(name.clone());
global_state.settings.audio.audio_device = Some(name); 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 { impl Settings {
pub fn load() -> Self { pub fn load() -> Self {
let default_settings = Settings::default();
let path = Settings::get_settings_path(); let path = Settings::get_settings_path();
// If file doesn't exist, use the default settings. // 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(); server.cleanup();
match rec.try_recv() { match rec.try_recv() {
Ok(msg) => break, Ok(_msg) => break,
Err(err) => match err { Err(err) => match err {
TryRecvError::Empty => (), TryRecvError::Empty => (),
TryRecvError::Disconnected => break, TryRecvError::Disconnected => break,

View File

@ -69,7 +69,7 @@ impl GraphicCache {
.atlas .atlas
.allocate(size2(i32::from(dims.x), i32::from(dims.y))) .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); let (min, max) = (rectangle.min, rectangle.max);
Aabr { Aabr {
min: Vec2::new(min.x as u16, min.y as u16), min: Vec2::new(min.x as u16, min.y as u16),

View File

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

View File

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

View File

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

View File

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

View File

@ -5,15 +5,11 @@ mod structure;
use common::{ use common::{
terrain::{Block, TerrainChunk, TerrainChunkMeta, TerrainChunkSize}, terrain::{Block, TerrainChunk, TerrainChunkMeta, TerrainChunkSize},
vol::{SizedVol, VolSize, Vox, WriteVol}, vol::{VolSize, Vox, WriteVol},
}; };
use fxhash::FxHashMap; use fxhash::FxHashMap;
use noise::{BasicMulti, MultiFractal, NoiseFn, Perlin, Seedable}; use noise::{BasicMulti, MultiFractal, Seedable};
use std::{ use std::{hash::Hash, time::Duration};
hash::Hash,
ops::{Add, Div, Mul, Neg, Sub},
time::Duration,
};
use vek::*; use vek::*;
#[derive(Debug)] #[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 { 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 &self
.map .map
.entry(k) .entry(k)

View File

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