Fix warnings and clippy recommendations in common

This commit is contained in:
timokoesters
2019-07-01 22:42:43 +02:00
parent c7c4295a93
commit f5da167ce5
26 changed files with 84 additions and 118 deletions

View File

@ -25,7 +25,7 @@ fn main() {
info!("Starting chat-cli..."); info!("Starting chat-cli...");
// Set up an fps clock. // Set up an fps clock.
let mut clock = Clock::new(); let mut clock = Clock::start();
println!("Enter your username"); println!("Enter your username");
let username = read_input(); let username = read_input();

View File

@ -51,13 +51,16 @@ pub fn load_map<A: Asset + 'static, F: FnOnce(A) -> A>(
specifier: &str, specifier: &str,
f: F, f: F,
) -> Result<Arc<A>, Error> { ) -> Result<Arc<A>, Error> {
Ok(ASSETS let mut assets_write = ASSETS.write().unwrap();
.write() match assets_write.get(specifier) {
.unwrap() Some(asset) => Ok(Arc::clone(asset).downcast()?),
.entry(specifier.to_string()) None => {
.or_insert(Arc::new(f(A::load(specifier)?))) let asset = Arc::new(f(A::load(specifier)?));
.clone() let clone = Arc::clone(&asset);
.downcast()?) assets_write.insert(specifier.to_owned(), clone);
Ok(asset)
}
}
} }
/// Function used to load assets. /// Function used to load assets.
@ -84,7 +87,7 @@ pub fn load<A: Asset + 'static>(specifier: &str) -> Result<Arc<A>, Error> {
/// let my_image = assets::load_expect::<DynamicImage>("core.ui.backgrounds.city"); /// let my_image = assets::load_expect::<DynamicImage>("core.ui.backgrounds.city");
/// ``` /// ```
pub fn load_expect<A: Asset + 'static>(specifier: &str) -> Arc<A> { pub fn load_expect<A: Asset + 'static>(specifier: &str) -> Arc<A> {
load(specifier).expect(&format!("Failed loading essential asset: {}", specifier)) load(specifier).unwrap_or_else(|_| panic!("Failed loading essential asset: {}", specifier))
} }
/// Asset Trait /// Asset Trait

View File

@ -13,8 +13,7 @@ pub struct Clock {
} }
impl Clock { impl Clock {
#[allow(dead_code)] pub fn start() -> Self {
pub fn new() -> Self {
Self { Self {
last_sys_time: Instant::now(), last_sys_time: Instant::now(),
last_delta: None, last_delta: None,
@ -23,22 +22,18 @@ impl Clock {
} }
} }
#[allow(dead_code)]
pub fn get_tps(&self) -> f64 { pub fn get_tps(&self) -> f64 {
1.0 / self.running_tps_average 1.0 / self.running_tps_average
} }
#[allow(dead_code)]
pub fn get_last_delta(&self) -> Duration { pub fn get_last_delta(&self) -> Duration {
self.last_delta.unwrap_or(Duration::new(0, 0)) self.last_delta.unwrap_or_else(|| Duration::new(0, 0))
} }
#[allow(dead_code)]
pub fn get_avg_delta(&self) -> Duration { pub fn get_avg_delta(&self) -> Duration {
Duration::from_secs_f64(self.running_tps_average) Duration::from_secs_f64(self.running_tps_average)
} }
#[allow(dead_code)]
pub fn tick(&mut self, tgt: Duration) { pub fn tick(&mut self, tgt: Duration) {
let delta = Instant::now().duration_since(self.last_sys_time); let delta = Instant::now().duration_since(self.last_sys_time);

View File

@ -1,4 +1,4 @@
use specs::{Component, FlaggedStorage, NullStorage, VecStorage}; use specs::{Component, FlaggedStorage, VecStorage};
#[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ActionState { pub struct ActionState {

View File

@ -32,7 +32,7 @@ impl From<&DotVoxData> for Segment {
if let Some(&color) = palette.get(voxel.i as usize) { if let Some(&color) = palette.get(voxel.i as usize) {
// TODO: Maybe don't ignore this error? // TODO: Maybe don't ignore this error?
let _ = segment.set( let _ = segment.set(
Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| e as i32), Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| i32::from(e)),
Cell::new(color), Cell::new(color),
); );
} }

View File

@ -13,8 +13,8 @@ pub enum NpcKind {
} }
impl NpcKind { impl NpcKind {
fn as_str(&self) -> &'static str { fn as_str(self) -> &'static str {
match *self { match self {
NpcKind::Humanoid => "humanoid", NpcKind::Humanoid => "humanoid",
NpcKind::Wolf => "wolf", NpcKind::Wolf => "wolf",
NpcKind::Pig => "pig", NpcKind::Pig => "pig",

View File

@ -82,7 +82,6 @@ impl Default for ChunkChanges {
} }
} }
} }
impl ChunkChanges { impl ChunkChanges {
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.new_chunks.clear(); self.new_chunks.clear();
@ -99,15 +98,17 @@ pub struct State {
thread_pool: Arc<ThreadPool>, thread_pool: Arc<ThreadPool>,
} }
impl State { impl Default for State {
/// Create a new `State`. /// Create a new `State`.
pub fn new() -> Self { fn default() -> Self {
Self { Self {
ecs: sphynx::World::new(specs::World::new(), Self::setup_sphynx_world), ecs: sphynx::World::new(specs::World::new(), Self::setup_sphynx_world),
thread_pool: Arc::new(ThreadPoolBuilder::new().build().unwrap()), thread_pool: Arc::new(ThreadPoolBuilder::new().build().unwrap()),
} }
} }
}
impl State {
/// Create a new `State` from an ECS state package. /// Create a new `State` from an ECS state package.
pub fn from_state_package( pub fn from_state_package(
state_package: sphynx::StatePackage<EcsCompPacket, EcsResPacket>, state_package: sphynx::StatePackage<EcsCompPacket, EcsResPacket>,

View File

@ -1,23 +1,17 @@
use crate::{ use crate::{
comp::{ comp::{ActionState, Attacking, Controller, Gliding, OnGround, Rolling, Vel, Wielding},
ActionState, Animation, AnimationInfo, Attacking, Controller, ForceUpdate, Gliding,
Jumping, OnGround, Ori, Pos, Rolling, Vel, Wielding,
},
state::DeltaTime,
sys::phys::MOVEMENT_THRESHOLD_VEL, sys::phys::MOVEMENT_THRESHOLD_VEL,
}; };
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use specs::{Entities, Join, ReadStorage, System, WriteStorage};
/// This system will set the ActionState component as specified by other components /// This system will set the ActionState component as specified by other components
pub struct Sys; pub struct Sys;
impl<'a> System<'a> for Sys { impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Entities<'a>, Entities<'a>,
Read<'a, DeltaTime>,
ReadStorage<'a, Controller>, ReadStorage<'a, Controller>,
ReadStorage<'a, Vel>, ReadStorage<'a, Vel>,
ReadStorage<'a, OnGround>, ReadStorage<'a, OnGround>,
ReadStorage<'a, Jumping>,
ReadStorage<'a, Gliding>, ReadStorage<'a, Gliding>,
ReadStorage<'a, Attacking>, ReadStorage<'a, Attacking>,
ReadStorage<'a, Wielding>, ReadStorage<'a, Wielding>,
@ -29,11 +23,9 @@ impl<'a> System<'a> for Sys {
&mut self, &mut self,
( (
entities, entities,
dt,
controllers, // To make sure it only runs on the single client and the server controllers, // To make sure it only runs on the single client and the server
velocities, velocities,
on_grounds, on_grounds,
jumpings,
glidings, glidings,
attackings, attackings,
wieldings, wieldings,
@ -42,22 +34,20 @@ impl<'a> System<'a> for Sys {
): Self::SystemData, ): Self::SystemData,
) { ) {
for ( for (
entity, _entity,
vel, vel,
_controller, _controller,
on_ground, on_ground,
jumping,
gliding, gliding,
attacking, attacking,
wielding, wielding,
rolling, rolling,
mut action_state, action_state,
) in ( ) in (
&entities, &entities,
&velocities, &velocities,
&controllers, &controllers,
on_grounds.maybe(), on_grounds.maybe(),
jumpings.maybe(),
glidings.maybe(), glidings.maybe(),
attackings.maybe(), attackings.maybe(),
wieldings.maybe(), wieldings.maybe(),

View File

@ -1,5 +1,4 @@
use crate::comp::{Agent, Attacking, Controller, Jumping, Pos}; use crate::comp::{Agent, Controller, Pos};
use log::warn;
use rand::{seq::SliceRandom, thread_rng}; use rand::{seq::SliceRandom, thread_rng};
use specs::{Entities, Join, ReadStorage, System, WriteStorage}; use specs::{Entities, Join, ReadStorage, System, WriteStorage};
use vek::*; use vek::*;
@ -12,15 +11,10 @@ impl<'a> System<'a> for Sys {
WriteStorage<'a, Agent>, WriteStorage<'a, Agent>,
ReadStorage<'a, Pos>, ReadStorage<'a, Pos>,
WriteStorage<'a, Controller>, WriteStorage<'a, Controller>,
WriteStorage<'a, Jumping>,
WriteStorage<'a, Attacking>,
); );
fn run( fn run(&mut self, (entities, mut agents, positions, mut controllers): Self::SystemData) {
&mut self, for (_entity, agent, pos, controller) in
(entities, mut agents, positions, mut controllers, mut jumps, mut attacks): Self::SystemData,
) {
for (entity, agent, pos, controller) in
(&entities, &mut agents, &positions, &mut controllers).join() (&entities, &mut agents, &positions, &mut controllers).join()
{ {
match agent { match agent {

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
comp::{ActionState, Animation, AnimationInfo, ForceUpdate}, comp::{ActionState, Animation, AnimationInfo},
state::DeltaTime, state::DeltaTime,
}; };
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage};
@ -46,9 +46,9 @@ impl<'a> System<'a> for Sys {
let new_time = animation_infos let new_time = animation_infos
.get(entity) .get(entity)
.filter(|i| i.animation == animation) .filter(|i| i.animation == animation)
.map(|i| i.time + dt.0 as f64); .map(|i| i.time + f64::from(dt.0));
animation_infos.insert( let _ = animation_infos.insert(
entity, entity,
AnimationInfo { AnimationInfo {
animation, animation,

View File

@ -1,10 +1,7 @@
use crate::{ use crate::{
comp::{ comp::{Attacking, ForceUpdate, HealthSource, Ori, Pos, Stats, Vel},
Attacking, HealthSource, Stats, Wielding, {ForceUpdate, Ori, Pos, Vel},
},
state::{DeltaTime, Uid}, state::{DeltaTime, Uid},
}; };
use log::warn;
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage};
/// This system is responsible for handling accepted inputs like moving or attacking /// This system is responsible for handling accepted inputs like moving or attacking
@ -18,7 +15,6 @@ impl<'a> System<'a> for Sys {
ReadStorage<'a, Ori>, ReadStorage<'a, Ori>,
WriteStorage<'a, Vel>, WriteStorage<'a, Vel>,
WriteStorage<'a, Attacking>, WriteStorage<'a, Attacking>,
WriteStorage<'a, Wielding>,
WriteStorage<'a, Stats>, WriteStorage<'a, Stats>,
WriteStorage<'a, ForceUpdate>, WriteStorage<'a, ForceUpdate>,
); );
@ -33,7 +29,6 @@ impl<'a> System<'a> for Sys {
orientations, orientations,
mut velocities, mut velocities,
mut attackings, mut attackings,
mut wieldings,
mut stats, mut stats,
mut force_updates, mut force_updates,
): Self::SystemData, ): Self::SystemData,
@ -44,7 +39,7 @@ impl<'a> System<'a> for Sys {
.filter_map(|(entity, uid, pos, ori, mut attacking)| { .filter_map(|(entity, uid, pos, ori, mut attacking)| {
if !attacking.applied { if !attacking.applied {
// Go through all other entities // Go through all other entities
for (b, pos_b, mut vel_b, mut stat_b) in for (b, pos_b, mut vel_b, stat_b) in
(&entities, &positions, &mut velocities, &mut stats).join() (&entities, &positions, &mut velocities, &mut stats).join()
{ {
// Check if it is a hit // Check if it is a hit

View File

@ -1,23 +1,16 @@
use crate::{ use crate::comp::{
comp::{ ActionState, Attacking, Controller, Gliding, Jumping, MoveDir, Respawning, Rolling, Stats, Vel,
ActionState, Animation, AnimationInfo, Attacking, Controller, Gliding, HealthSource,
Jumping, MoveDir, OnGround, Respawning, Rolling, Stats, {ForceUpdate, Ori, Pos, Vel},
},
state::DeltaTime,
}; };
use specs::{Entities, Join, Read, ReadStorage, System, WriteStorage}; use specs::{Entities, Join, ReadStorage, System, WriteStorage};
/// This system is responsible for validating controller inputs /// This system is responsible for validating controller inputs
pub struct Sys; pub struct Sys;
impl<'a> System<'a> for Sys { impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Entities<'a>, Entities<'a>,
Read<'a, DeltaTime>,
ReadStorage<'a, Controller>, ReadStorage<'a, Controller>,
ReadStorage<'a, Stats>, ReadStorage<'a, Stats>,
ReadStorage<'a, Pos>,
ReadStorage<'a, Vel>, ReadStorage<'a, Vel>,
ReadStorage<'a, Ori>,
WriteStorage<'a, ActionState>, WriteStorage<'a, ActionState>,
WriteStorage<'a, MoveDir>, WriteStorage<'a, MoveDir>,
WriteStorage<'a, Jumping>, WriteStorage<'a, Jumping>,
@ -31,12 +24,9 @@ impl<'a> System<'a> for Sys {
&mut self, &mut self,
( (
entities, entities,
dt,
controllers, controllers,
stats, stats,
positions,
velocities, velocities,
orientations,
mut action_states, mut action_states,
mut move_dirs, mut move_dirs,
mut jumpings, mut jumpings,
@ -46,13 +36,11 @@ impl<'a> System<'a> for Sys {
mut glidings, mut glidings,
): Self::SystemData, ): Self::SystemData,
) { ) {
for (entity, controller, stats, pos, vel, ori, mut a) in ( for (entity, controller, stats, vel, mut a) in (
&entities, &entities,
&controllers, &controllers,
&stats, &stats,
&positions,
&velocities, &velocities,
&orientations,
// Although this is changed, it is only kept for this system // Although this is changed, it is only kept for this system
// as it will be replaced in the action state system // as it will be replaced in the action state system
&mut action_states, &mut action_states,
@ -62,14 +50,14 @@ impl<'a> System<'a> for Sys {
if stats.is_dead { if stats.is_dead {
// Respawn // Respawn
if controller.respawn { if controller.respawn {
respawns.insert(entity, Respawning); let _ = respawns.insert(entity, Respawning);
} }
continue; continue;
} }
// Move dir // Move dir
if !a.rolling { if !a.rolling {
move_dirs.insert( let _ = move_dirs.insert(
entity, entity,
MoveDir(if controller.move_dir.magnitude_squared() > 1.0 { MoveDir(if controller.move_dir.magnitude_squared() > 1.0 {
controller.move_dir.normalized() controller.move_dir.normalized()
@ -81,16 +69,16 @@ impl<'a> System<'a> for Sys {
// Glide // Glide
if controller.glide && !a.on_ground && !a.attacking && !a.rolling { if controller.glide && !a.on_ground && !a.attacking && !a.rolling {
glidings.insert(entity, Gliding); let _ = glidings.insert(entity, Gliding);
a.gliding = true; a.gliding = true;
} else { } else {
glidings.remove(entity); let _ = glidings.remove(entity);
a.gliding = false; a.gliding = false;
} }
// Attack // Attack
if controller.attack && !a.attacking && !a.gliding && !a.rolling { if controller.attack && !a.attacking && !a.gliding && !a.rolling {
attackings.insert(entity, Attacking::start()); let _ = attackings.insert(entity, Attacking::start());
a.attacking = true; a.attacking = true;
} }
@ -102,13 +90,13 @@ impl<'a> System<'a> for Sys {
&& !a.attacking && !a.attacking
&& !a.gliding && !a.gliding
{ {
rollings.insert(entity, Rolling::start()); let _ = rollings.insert(entity, Rolling::start());
a.rolling = true; a.rolling = true;
} }
// Jump // Jump
if controller.jump && a.on_ground && vel.0.z <= 0.0 { if controller.jump && a.on_ground && vel.0.z <= 0.0 {
jumpings.insert(entity, Jumping); let _ = jumpings.insert(entity, Jumping);
a.on_ground = false; a.on_ground = false;
} }
} }

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
comp::{ActionState, Gliding, Jumping, MoveDir, OnGround, Ori, Pos, Rolling, Stats, Vel}, comp::{ActionState, Jumping, MoveDir, OnGround, Ori, Pos, Rolling, Stats, Vel},
state::DeltaTime, state::DeltaTime,
terrain::TerrainMap, terrain::TerrainMap,
vol::{ReadVol, Vox}, vol::{ReadVol, Vox},
@ -45,7 +45,6 @@ impl<'a> System<'a> for Sys {
ReadExpect<'a, TerrainMap>, ReadExpect<'a, TerrainMap>,
Read<'a, DeltaTime>, Read<'a, DeltaTime>,
ReadStorage<'a, MoveDir>, ReadStorage<'a, MoveDir>,
ReadStorage<'a, Gliding>,
ReadStorage<'a, Stats>, ReadStorage<'a, Stats>,
ReadStorage<'a, ActionState>, ReadStorage<'a, ActionState>,
WriteStorage<'a, Jumping>, WriteStorage<'a, Jumping>,
@ -63,7 +62,6 @@ impl<'a> System<'a> for Sys {
terrain, terrain,
dt, dt,
move_dirs, move_dirs,
glidings,
stats, stats,
action_states, action_states,
mut jumpings, mut jumpings,
@ -225,7 +223,7 @@ impl<'a> System<'a> for Sys {
}; };
// Determine the block that we are colliding with most (based on minimum collision axis) // Determine the block that we are colliding with most (based on minimum collision axis)
let (block_pos, block_aabb) = near_iter let (_block_pos, block_aabb) = near_iter
.clone() .clone()
// Calculate the block's position in world space // Calculate the block's position in world space
.map(|(i, j, k)| pos.0.map(|e| e.floor() as i32) + Vec3::new(i, j, k)) .map(|(i, j, k)| pos.0.map(|e| e.floor() as i32) + Vec3::new(i, j, k))
@ -262,7 +260,13 @@ impl<'a> System<'a> for Sys {
// Determine an appropriate resolution vector (i.e: the minimum distance needed to push out of the block) // Determine an appropriate resolution vector (i.e: the minimum distance needed to push out of the block)
let max_axis = dir.map(|e| e.abs()).reduce_partial_min(); let max_axis = dir.map(|e| e.abs()).reduce_partial_min();
let resolve_dir = -dir.map(|e| if e.abs() == max_axis { e } else { 0.0 }); let resolve_dir = -dir.map(|e| {
if e.abs().to_bits() == max_axis.to_bits() {
e
} else {
0.0
}
});
// When the resolution direction is pointing upwards, we must be on the ground // When the resolution direction is pointing upwards, we must be on the ground
if resolve_dir.z > 0.0 && vel.0.z <= 0.0 { if resolve_dir.z > 0.0 && vel.0.z <= 0.0 {
@ -302,7 +306,7 @@ impl<'a> System<'a> for Sys {
} }
if on_ground { if on_ground {
on_grounds.insert(entity, OnGround); let _ = on_grounds.insert(entity, OnGround);
// If we're not on the ground but the space below us is free, then "snap" to the ground // If we're not on the ground but the space below us is free, then "snap" to the ground
} else if collision_with(pos.0 - Vec3::unit_z() * 1.05, near_iter.clone()) } else if collision_with(pos.0 - Vec3::unit_z() * 1.05, near_iter.clone())
&& vel.0.z < 0.0 && vel.0.z < 0.0
@ -310,7 +314,7 @@ impl<'a> System<'a> for Sys {
&& was_on_ground && was_on_ground
{ {
pos.0.z = (pos.0.z - 0.05).floor(); pos.0.z = (pos.0.z - 0.05).floor();
on_grounds.insert(entity, OnGround); let _ = on_grounds.insert(entity, OnGround);
} }
} }
} }

View File

@ -33,7 +33,7 @@ impl<'a> System<'a> for Sys {
stat.is_dead = true; stat.is_dead = true;
} }
if let Some(change) = &mut stat.health.last_change { if let Some(change) = &mut stat.health.last_change {
change.1 += dt.0 as f64; change.1 += f64::from(dt.0);
} }
} }
} }

View File

@ -16,7 +16,7 @@ impl Block {
} }
} }
pub fn get_color(&self) -> Option<Rgb<u8>> { pub fn get_color(self) -> Option<Rgb<u8>> {
if self.is_empty() { if self.is_empty() {
None None
} else { } else {
@ -24,7 +24,7 @@ impl Block {
} }
} }
pub fn get_opacity(&self) -> Option<f32> { pub fn get_opacity(self) -> Option<f32> {
match self.kind { match self.kind {
0 => None, 0 => None,
1 => Some(0.85), 1 => Some(0.85),

View File

@ -117,7 +117,7 @@ impl ReadVol for Chonk {
- Vec3::unit_z() - Vec3::unit_z()
* (self.z_offset + sub_chunk_idx as i32 * SUB_CHUNK_HEIGHT as i32); * (self.z_offset + sub_chunk_idx as i32 * SUB_CHUNK_HEIGHT as i32);
chunk.get(rpos).map_err(|err| ChonkError::ChunkError(err)) chunk.get(rpos).map_err(ChonkError::ChunkError)
} }
} }
} }
@ -197,7 +197,7 @@ impl WriteVol for Chonk {
let mut new_chunk = Chunk::filled(*cblock, ()); let mut new_chunk = Chunk::filled(*cblock, ());
for (map_pos, map_block) in map { for (map_pos, map_block) in map {
new_chunk new_chunk
.set(map_pos.map(|e| e as i32), *map_block) .set(map_pos.map(|e| i32::from(e)), *map_block)
.unwrap(); // Can't fail (I hope!) .unwrap(); // Can't fail (I hope!)
} }
@ -217,9 +217,9 @@ impl WriteVol for Chonk {
Ok(()) Ok(())
} }
*/ */
SubChunk::Heterogeneous(chunk) => chunk SubChunk::Heterogeneous(chunk) => {
.set(rpos, block) chunk.set(rpos, block).map_err(ChonkError::ChunkError)
.map_err(|err| ChonkError::ChunkError(err)), }
//_ => unimplemented!(), //_ => unimplemented!(),
} }
} }

View File

@ -86,13 +86,13 @@ impl Asset for Structure {
let color = palette let color = palette
.get(index as usize) .get(index as usize)
.copied() .copied()
.unwrap_or(Rgb::broadcast(0)); .unwrap_or_else(|| Rgb::broadcast(0));
StructureBlock::Block(Block::new(1, color)) StructureBlock::Block(Block::new(1, color))
} }
}; };
let _ = vol.set( let _ = vol.set(
Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| e as i32), Vec3::new(voxel.x, voxel.y, voxel.z).map(|e| i32::from(e)),
block, block,
); );
} }

View File

@ -56,7 +56,6 @@ impl Iterator for VoxPosIter {
/// A volume that has a finite size. /// A volume that has a finite size.
pub trait SizedVol: BaseVol { pub trait SizedVol: BaseVol {
/// Get the size of the volume. /// Get the size of the volume.
#[inline(always)]
fn get_size(&self) -> Vec3<u32>; fn get_size(&self) -> Vec3<u32>;
/// Iterate through all potential voxel positions in this volume. /// Iterate through all potential voxel positions in this volume.
@ -71,10 +70,8 @@ pub trait SizedVol: BaseVol {
/// A volume that provides read access to its voxel data. /// A volume that provides read access to its voxel data.
pub trait ReadVol: BaseVol { pub trait ReadVol: BaseVol {
/// Get a reference to the voxel at the provided position in the volume. /// Get a reference to the voxel at the provided position in the volume.
#[inline(always)]
fn get(&self, pos: Vec3<i32>) -> Result<&Self::Vox, Self::Err>; fn get(&self, pos: Vec3<i32>) -> Result<&Self::Vox, Self::Err>;
#[inline(always)]
unsafe fn get_unchecked(&self, pos: Vec3<i32>) -> &Self::Vox { unsafe fn get_unchecked(&self, pos: Vec3<i32>) -> &Self::Vox {
self.get(pos).unwrap() self.get(pos).unwrap()
} }
@ -103,7 +100,6 @@ pub trait SampleVol<I>: BaseVol {
/// A volume that provides write access to its voxel data. /// A volume that provides write access to its voxel data.
pub trait WriteVol: BaseVol { pub trait WriteVol: BaseVol {
/// Set the voxel at the provided position in the volume to the provided value. /// Set the voxel at the provided position in the volume to the provided value.
#[inline(always)]
fn set(&mut self, pos: Vec3<i32>, vox: Self::Vox) -> Result<(), Self::Err>; fn set(&mut self, pos: Vec3<i32>, vox: Self::Vox) -> Result<(), Self::Err>;
} }

View File

@ -29,7 +29,7 @@ impl<V: BaseVol, S: VolSize> VolMap2d<V, S> {
pos.into().map2(S::SIZE.into(), |e, sz: u32| { pos.into().map2(S::SIZE.into(), |e, sz: u32| {
// Horrid, but it's faster than a cheetah with a red bull blood transfusion // Horrid, but it's faster than a cheetah with a red bull blood transfusion
let log2 = (sz - 1).count_ones(); let log2 = (sz - 1).count_ones();
((((e as i64 + (1 << 32)) as u64) >> log2) - (1 << (32 - log2))) as i32 ((((i64::from(e) + (1 << 32)) as u64) >> log2) - (1 << (32 - log2))) as i32
}) })
} }
@ -37,7 +37,7 @@ impl<V: BaseVol, S: VolSize> VolMap2d<V, S> {
pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> { pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> {
let offs = pos.map2(S::SIZE, |e, sz| { let offs = pos.map2(S::SIZE, |e, sz| {
// Horrid, but it's even faster than the aforementioned cheetah // Horrid, but it's even faster than the aforementioned cheetah
(((e as i64 + (1 << 32)) as u64) & (sz - 1) as u64) as i32 (((i64::from(e) + (1 << 32)) as u64) & u64::from(sz - 1)) as i32
}); });
Vec3::new(offs.x, offs.y, pos.z) Vec3::new(offs.x, offs.y, pos.z)
} }
@ -57,7 +57,7 @@ impl<V: BaseVol + ReadVol + Debug, S: VolSize> ReadVol for VolMap2d<V, S> {
.ok_or(VolMap2dErr::NoSuchChunk) .ok_or(VolMap2dErr::NoSuchChunk)
.and_then(|chunk| { .and_then(|chunk| {
let co = Self::chunk_offs(pos); let co = Self::chunk_offs(pos);
chunk.get(co).map_err(|err| VolMap2dErr::ChunkErr(err)) chunk.get(co).map_err(VolMap2dErr::ChunkErr)
}) })
} }
@ -87,7 +87,7 @@ impl<I: Into<Aabr<i32>>, V: BaseVol + ReadVol + Debug, S: VolSize> SampleVol<I>
for y in chunk_min.y..=chunk_max.y { for y in chunk_min.y..=chunk_max.y {
let chunk_key = Vec2::new(x, y); let chunk_key = Vec2::new(x, y);
let chunk = self.get_key_arc(chunk_key).map(|v| v.clone()); let chunk = self.get_key_arc(chunk_key).cloned();
if let Some(chunk) = chunk { if let Some(chunk) = chunk {
sample.insert(chunk_key, chunk); sample.insert(chunk_key, chunk);
@ -110,7 +110,7 @@ impl<V: BaseVol + WriteVol + Clone + Debug, S: VolSize + Clone> WriteVol for Vol
let co = Self::chunk_offs(pos); let co = Self::chunk_offs(pos);
Arc::make_mut(chunk) Arc::make_mut(chunk)
.set(co, vox) .set(co, vox)
.map_err(|err| VolMap2dErr::ChunkErr(err)) .map_err(VolMap2dErr::ChunkErr)
}) })
} }
} }
@ -169,7 +169,7 @@ impl<V: BaseVol, S: VolSize> VolMap2d<V, S> {
Self::chunk_key(pos) Self::chunk_key(pos)
} }
pub fn iter<'a>(&'a self) -> ChunkIter<'a, V> { pub fn iter(&self) -> ChunkIter<V> {
ChunkIter { ChunkIter {
iter: self.chunks.iter(), iter: self.chunks.iter(),
} }

View File

@ -28,7 +28,7 @@ impl<V: BaseVol, S: VolSize> VolMap3d<V, S> {
pos.map2(S::SIZE, |e, sz| { pos.map2(S::SIZE, |e, sz| {
// Horrid, but it's faster than a cheetah with a red bull blood transfusion // Horrid, but it's faster than a cheetah with a red bull blood transfusion
let log2 = (sz - 1).count_ones(); let log2 = (sz - 1).count_ones();
((((e as i64 + (1 << 32)) as u64) >> log2) - (1 << (32 - log2))) as i32 ((((i64::from(e) + (1 << 32)) as u64) >> log2) - (1 << (32 - log2))) as i32
}) })
} }
@ -36,7 +36,7 @@ impl<V: BaseVol, S: VolSize> VolMap3d<V, S> {
pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> { pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> {
pos.map2(S::SIZE, |e, sz| { pos.map2(S::SIZE, |e, sz| {
// Horrid, but it's even faster than the aforementioned cheetah // Horrid, but it's even faster than the aforementioned cheetah
(((e as i64 + (1 << 32)) as u64) & (sz - 1) as u64) as i32 (((i64::from(e) + (1 << 32)) as u64) & u64::from(sz - 1)) as i32
}) })
} }
} }
@ -55,7 +55,7 @@ impl<V: BaseVol + ReadVol + Debug, S: VolSize> ReadVol for VolMap3d<V, S> {
.ok_or(VolMap3dErr::NoSuchChunk) .ok_or(VolMap3dErr::NoSuchChunk)
.and_then(|chunk| { .and_then(|chunk| {
let co = Self::chunk_offs(pos); let co = Self::chunk_offs(pos);
chunk.get(co).map_err(|err| VolMap3dErr::ChunkErr(err)) chunk.get(co).map_err(VolMap3dErr::ChunkErr)
}) })
} }
} }
@ -78,7 +78,7 @@ impl<I: Into<Aabb<i32>>, V: BaseVol + ReadVol + Debug, S: VolSize> SampleVol<I>
for z in chunk_min.z..=chunk_max.z { for z in chunk_min.z..=chunk_max.z {
let chunk_key = Vec3::new(x, y, z); let chunk_key = Vec3::new(x, y, z);
let chunk = self.get_key_arc(chunk_key).map(|v| v.clone()); let chunk = self.get_key_arc(chunk_key).cloned();
if let Some(chunk) = chunk { if let Some(chunk) = chunk {
sample.insert(chunk_key, chunk); sample.insert(chunk_key, chunk);
@ -102,7 +102,7 @@ impl<V: BaseVol + WriteVol + Clone + Debug, S: VolSize + Clone> WriteVol for Vol
let co = Self::chunk_offs(pos); let co = Self::chunk_offs(pos);
Arc::make_mut(chunk) Arc::make_mut(chunk)
.set(co, vox) .set(co, vox)
.map_err(|err| VolMap3dErr::ChunkErr(err)) .map_err(VolMap3dErr::ChunkErr)
}) })
} }
} }
@ -153,7 +153,7 @@ impl<V: BaseVol, S: VolSize> VolMap3d<V, S> {
Self::chunk_key(pos) Self::chunk_key(pos)
} }
pub fn iter<'a>(&'a self) -> ChunkIter<'a, V> { pub fn iter(&self) -> ChunkIter<V> {
ChunkIter { ChunkIter {
iter: self.chunks.iter(), iter: self.chunks.iter(),
} }

View File

@ -12,7 +12,7 @@ fn main() {
info!("Starting server-cli..."); info!("Starting server-cli...");
// Set up an fps clock // Set up an fps clock
let mut clock = Clock::new(); let mut clock = Clock::start();
// Create server // Create server
let mut server = Server::new().expect("Failed to create server instance!"); let mut server = Server::new().expect("Failed to create server instance!");

View File

@ -80,7 +80,7 @@ impl Server {
pub fn bind<A: Into<SocketAddr>>(addrs: A) -> Result<Self, Error> { pub fn bind<A: Into<SocketAddr>>(addrs: A) -> Result<Self, Error> {
let (chunk_tx, chunk_rx) = mpsc::channel(); let (chunk_tx, chunk_rx) = mpsc::channel();
let mut state = State::new(); let mut state = State::default();
state state
.ecs_mut() .ecs_mut()
.add_resource(SpawnPoint(Vec3::new(16_384.0, 16_384.0, 305.0))); .add_resource(SpawnPoint(Vec3::new(16_384.0, 16_384.0, 305.0)));

View File

@ -42,7 +42,7 @@ const BG_COLOR: Rgba<f32> = Rgba {
impl PlayState for CharSelectionState { impl PlayState for CharSelectionState {
fn play(&mut self, _: Direction, global_state: &mut GlobalState) -> PlayStateResult { fn play(&mut self, _: Direction, global_state: &mut GlobalState) -> PlayStateResult {
// Set up an fps clock. // Set up an fps clock.
let mut clock = Clock::new(); let mut clock = Clock::start();
let mut current_client_state = self.client.borrow().get_client_state(); let mut current_client_state = self.client.borrow().get_client_state();
while let ClientState::Pending | ClientState::Registered = current_client_state { while let ClientState::Pending | ClientState::Registered = current_client_state {

View File

@ -38,7 +38,7 @@ const BG_COLOR: Rgba<f32> = Rgba {
impl PlayState for MainMenuState { impl PlayState for MainMenuState {
fn play(&mut self, _: Direction, global_state: &mut GlobalState) -> PlayStateResult { fn play(&mut self, _: Direction, global_state: &mut GlobalState) -> PlayStateResult {
// Set up an fps clock. // Set up an fps clock.
let mut clock = Clock::new(); let mut clock = Clock::start();
// Used for client creation. // Used for client creation.
let mut client_init: Option<ClientInit> = None; let mut client_init: Option<ClientInit> = None;

View File

@ -88,7 +88,7 @@ impl PlayState for SessionState {
global_state.window.grab_cursor(true); global_state.window.grab_cursor(true);
// Set up an fps clock. // Set up an fps clock.
let mut clock = Clock::new(); let mut clock = Clock::start();
self.client.borrow_mut().clear_terrain(); self.client.borrow_mut().clear_terrain();
// Game loop // Game loop

View File

@ -65,7 +65,7 @@ fn run_server(mut server: Server, rec: Receiver<Msg>) {
info!("Starting server-cli..."); info!("Starting server-cli...");
// Set up an fps clock // Set up an fps clock
let mut clock = Clock::new(); let mut clock = Clock::start();
loop { loop {
let events = server let events = server