Rename UidAllocator to IdMaps everywhere, also rename lookup_entity to

uid_entity.

Also made more progress on changes in common/src/uid.rs

(does not compile so don't know if all rebase quirks resolved)
This commit is contained in:
Imbris
2023-04-26 00:31:14 -04:00
parent 35922866a8
commit 4094887997
37 changed files with 220 additions and 234 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
common/src/uid.rs
# Rust # Rust
target target

View File

@ -47,7 +47,7 @@ use common::{
TerrainGrid, TerrainGrid,
}, },
trade::{PendingTrade, SitePrices, TradeAction, TradeId, TradeResult}, trade::{PendingTrade, SitePrices, TradeAction, TradeId, TradeResult},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
vol::RectVolSize, vol::RectVolSize,
weather::{Weather, WeatherGrid}, weather::{Weather, WeatherGrid},
}; };
@ -2267,7 +2267,7 @@ impl Client {
if self.uid() != Some(entity_uid) { if self.uid() != Some(entity_uid) {
self.state self.state
.ecs_mut() .ecs_mut()
.delete_entity_and_clear_from_uid_allocator(entity_uid); .delete_entity_and_clear_from_id_maps(entity_uid);
} }
}, },
ServerGeneral::Notification(n) => { ServerGeneral::Notification(n) => {
@ -2744,13 +2744,13 @@ impl Client {
// Clear ecs of all entities // Clear ecs of all entities
self.state.ecs_mut().delete_all(); self.state.ecs_mut().delete_all();
self.state.ecs_mut().maintain(); self.state.ecs_mut().maintain();
self.state.ecs_mut().insert(UidAllocator::default()); self.state.ecs_mut().insert(IdMaps::default());
// Recreate client entity with Uid // Recreate client entity with Uid
let entity_builder = self.state.ecs_mut().create_entity(); let entity_builder = self.state.ecs_mut().create_entity();
let uid = entity_builder let uid = entity_builder
.world .world
.write_resource::<UidAllocator>() .write_resource::<IdMaps>()
.allocate(entity_builder.entity, Some(client_uid)); .allocate(entity_builder.entity, Some(client_uid));
let entity = entity_builder.with(uid).build(); let entity = entity_builder.with(uid).build();

View File

@ -7,7 +7,7 @@ mod sync_ext;
mod track; mod track;
// Reexports // Reexports
pub use common::uid::{Uid, UidAllocator}; pub use common::uid::{Uid, IdMaps};
pub use net_sync::{NetSync, SyncFrom}; pub use net_sync::{NetSync, SyncFrom};
pub use packet::{ pub use packet::{
handle_insert, handle_interp_insert, handle_interp_modify, handle_interp_remove, handle_modify, handle_insert, handle_interp_insert, handle_interp_modify, handle_interp_remove, handle_modify,

View File

@ -4,7 +4,7 @@ use super::{
}; };
use common::{ use common::{
resources::PlayerEntity, resources::PlayerEntity,
uid::{Uid, UidAllocator}, uid::{IdMaps, Uid},
}; };
use specs::{world::Builder, WorldExt}; use specs::{world::Builder, WorldExt};
use tracing::error; use tracing::error;
@ -18,7 +18,7 @@ pub trait WorldSyncExt {
where where
C::Storage: Default + specs::storage::Tracked; C::Storage: Default + specs::storage::Tracked;
fn create_entity_synced(&mut self) -> specs::EntityBuilder; fn create_entity_synced(&mut self) -> specs::EntityBuilder;
fn delete_entity_and_clear_from_uid_allocator(&mut self, uid: Uid); fn delete_entity_and_clear_from_id_maps(&mut self, uid: Uid);
fn uid_from_entity(&self, entity: specs::Entity) -> Option<Uid>; fn uid_from_entity(&self, entity: specs::Entity) -> Option<Uid>;
fn entity_from_uid(&self, uid: Uid) -> Option<specs::Entity>; fn entity_from_uid(&self, uid: Uid) -> Option<specs::Entity>;
fn apply_entity_package<P: CompPacket>( fn apply_entity_package<P: CompPacket>(
@ -32,7 +32,7 @@ pub trait WorldSyncExt {
impl WorldSyncExt for specs::World { impl WorldSyncExt for specs::World {
fn register_sync_marker(&mut self) { fn register_sync_marker(&mut self) {
self.register_synced::<Uid>(); self.register_synced::<Uid>();
self.insert(UidAllocator::new()); self.insert(IdMaps::new());
} }
fn register_synced<C: specs::Component + Clone + Send + Sync>(&mut self) fn register_synced<C: specs::Component + Clone + Send + Sync>(&mut self)
@ -52,12 +52,14 @@ impl WorldSyncExt for specs::World {
} }
fn create_entity_synced(&mut self) -> specs::EntityBuilder { fn create_entity_synced(&mut self) -> specs::EntityBuilder {
// TODO: Add metric for number of new entities created in a tick? Most
// convenient would be to store counter in `IdMaps` so that we don't
// have to fetch another resource nor require an additional parameter here
// nor use globals.
let builder = self.create_entity(); let builder = self.create_entity();
// TODO: if we split the UidAllocator and the IdMaps into two things then we
// need to fetch 2 resources when creating entities.
let uid = builder let uid = builder
.world .world
.write_resource::<UidAllocator>() .write_resource::<IdMaps>()
.allocate(builder.entity); .allocate(builder.entity);
builder.with(uid) builder.with(uid)
} }
@ -65,9 +67,9 @@ impl WorldSyncExt for specs::World {
/// This method should be used from the client-side when processing network /// This method should be used from the client-side when processing network
/// messages that delete entities. /// messages that delete entities.
// TODO: rename method // TODO: rename method
fn delete_entity_and_clear_from_uid_allocator(&mut self, uid: Uid) { fn delete_entity_and_clear_from_id_maps(&mut self, uid: Uid) {
// Clear from uid allocator // Clear from uid allocator
let maybe_entity = self.write_resource::<UidAllocator>().remove_entity_(uid); let maybe_entity = self.write_resource::<IdMaps>().remove_entity_(uid);
if let Some(entity) = maybe_entity { if let Some(entity) = maybe_entity {
if let Err(e) = self.delete_entity(entity) { if let Err(e) = self.delete_entity(entity) {
error!(?e, "Failed to delete entity"); error!(?e, "Failed to delete entity");
@ -82,7 +84,7 @@ impl WorldSyncExt for specs::World {
/// Get an entity from a UID /// Get an entity from a UID
fn entity_from_uid(&self, uid: Uid) -> Option<specs::Entity> { fn entity_from_uid(&self, uid: Uid) -> Option<specs::Entity> {
self.read_resource::<UidAllocator>().lookup_entity(uid) self.read_resource::<IdMaps>().uid_entity(uid)
} }
fn apply_entity_package<P: CompPacket>( fn apply_entity_package<P: CompPacket>(
@ -113,7 +115,7 @@ impl WorldSyncExt for specs::World {
// Attempt to delete entities that were marked for deletion // Attempt to delete entities that were marked for deletion
deleted_entities.into_iter().for_each(|uid| { deleted_entities.into_iter().for_each(|uid| {
self.delete_entity_and_clear_from_uid_allocator(uid.into()); self.delete_entity_and_clear_from_id_maps(uid.into());
}); });
} }
@ -121,10 +123,7 @@ impl WorldSyncExt for specs::World {
// Update components // Update components
let player_entity = self.read_resource::<PlayerEntity>().0; let player_entity = self.read_resource::<PlayerEntity>().0;
package.comp_updates.into_iter().for_each(|(uid, update)| { package.comp_updates.into_iter().for_each(|(uid, update)| {
if let Some(entity) = self if let Some(entity) = self.read_resource::<IdMaps>().uid_entity(uid.into()) {
.read_resource::<UidAllocator>()
.lookup_entity(uid.into())
{
let force_update = player_entity == Some(entity); let force_update = player_entity == Some(entity);
match update { match update {
CompUpdateKind::Inserted(packet) => { CompUpdateKind::Inserted(packet) => {
@ -145,9 +144,7 @@ impl WorldSyncExt for specs::World {
// Private utilities // Private utilities
fn create_entity_with_uid(specs_world: &mut specs::World, entity_uid: u64) -> specs::Entity { fn create_entity_with_uid(specs_world: &mut specs::World, entity_uid: u64) -> specs::Entity {
let entity_uid = Uid::from(entity_uid); let entity_uid = Uid::from(entity_uid);
let existing_entity = specs_world let existing_entity = specs_world.read_resource::<IdMaps>().uid_entity(entity_uid);
.read_resource::<UidAllocator>()
.lookup_entity(entity_uid);
match existing_entity { match existing_entity {
Some(entity) => entity, Some(entity) => entity,
@ -155,7 +152,7 @@ fn create_entity_with_uid(specs_world: &mut specs::World, entity_uid: u64) -> sp
let entity_builder = specs_world.create_entity(); let entity_builder = specs_world.create_entity();
let uid = entity_builder let uid = entity_builder
.world .world
.write_resource::<UidAllocator>() .write_resource::<IdMaps>()
.allocate(entity_builder.entity, Some(entity_uid)); .allocate(entity_builder.entity, Some(entity_uid));
entity_builder.with(uid).build() entity_builder.with(uid).build()
}, },

View File

@ -19,7 +19,7 @@ use crate::{
outcome::Outcome, outcome::Outcome,
resources::Secs, resources::Secs,
states::utils::StageSection, states::utils::StageSection,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::Dir, util::Dir,
}; };
@ -714,7 +714,7 @@ impl Attack {
pub fn may_harm( pub fn may_harm(
alignments: &ReadStorage<Alignment>, alignments: &ReadStorage<Alignment>,
players: &ReadStorage<Player>, players: &ReadStorage<Player>,
uid_allocator: &UidAllocator, id_maps: &IdMaps,
attacker: Option<EcsEntity>, attacker: Option<EcsEntity>,
target: EcsEntity, target: EcsEntity,
) -> bool { ) -> bool {
@ -725,7 +725,7 @@ pub fn may_harm(
if let Some(Alignment::Owned(uid)) = alignment { if let Some(Alignment::Owned(uid)) = alignment {
// return original entity // return original entity
// if can't get owner // if can't get owner
uid_allocator.lookup_entity(uid).unwrap_or(entity) id_maps.uid_entity(uid).unwrap_or(entity)
} else { } else {
entity entity
} }

View File

@ -2,7 +2,7 @@ use crate::{
comp::{self, pet::is_mountable, ship::figuredata::VOXEL_COLLIDER_MANIFEST}, comp::{self, pet::is_mountable, ship::figuredata::VOXEL_COLLIDER_MANIFEST},
link::{Is, Link, LinkHandle, Role}, link::{Is, Link, LinkHandle, Role},
terrain::{Block, TerrainGrid}, terrain::{Block, TerrainGrid},
uid::{Uid, UidAllocator}, uid::{IdMaps, Uid},
vol::ReadVol, vol::ReadVol,
}; };
use hashbrown::HashSet; use hashbrown::HashSet;
@ -41,13 +41,13 @@ pub enum MountingError {
impl Link for Mounting { impl Link for Mounting {
type CreateData<'a> = ( type CreateData<'a> = (
Read<'a, UidAllocator>, Read<'a, IdMaps>,
WriteStorage<'a, Is<Mount>>, WriteStorage<'a, Is<Mount>>,
WriteStorage<'a, Is<Rider>>, WriteStorage<'a, Is<Rider>>,
ReadStorage<'a, Is<VolumeRider>>, ReadStorage<'a, Is<VolumeRider>>,
); );
type DeleteData<'a> = ( type DeleteData<'a> = (
Read<'a, UidAllocator>, Read<'a, IdMaps>,
WriteStorage<'a, Is<Mount>>, WriteStorage<'a, Is<Mount>>,
WriteStorage<'a, Is<Rider>>, WriteStorage<'a, Is<Rider>>,
WriteStorage<'a, comp::Pos>, WriteStorage<'a, comp::Pos>,
@ -56,7 +56,7 @@ impl Link for Mounting {
); );
type Error = MountingError; type Error = MountingError;
type PersistData<'a> = ( type PersistData<'a> = (
Read<'a, UidAllocator>, Read<'a, IdMaps>,
Entities<'a>, Entities<'a>,
ReadStorage<'a, comp::Health>, ReadStorage<'a, comp::Health>,
ReadStorage<'a, comp::Body>, ReadStorage<'a, comp::Body>,
@ -67,9 +67,9 @@ impl Link for Mounting {
fn create( fn create(
this: &LinkHandle<Self>, this: &LinkHandle<Self>,
(uid_allocator, is_mounts, is_riders, is_volume_rider): &mut Self::CreateData<'_>, (id_maps, is_mounts, is_riders, is_volume_rider): &mut Self::CreateData<'_>,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
if this.mount == this.rider { if this.mount == this.rider {
// Forbid self-mounting // Forbid self-mounting
@ -97,9 +97,9 @@ impl Link for Mounting {
fn persist( fn persist(
this: &LinkHandle<Self>, this: &LinkHandle<Self>,
(uid_allocator, entities, healths, bodies, is_mounts, is_riders, character_states): &mut Self::PersistData<'_>, (id_maps, entities, healths, bodies, is_mounts, is_riders, character_states): &mut Self::PersistData<'_>,
) -> bool { ) -> bool {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
if let Some((mount, rider)) = entity(this.mount).zip(entity(this.rider)) { if let Some((mount, rider)) = entity(this.mount).zip(entity(this.rider)) {
let is_alive = |entity| { let is_alive = |entity| {
@ -126,9 +126,11 @@ impl Link for Mounting {
fn delete( fn delete(
this: &LinkHandle<Self>, this: &LinkHandle<Self>,
(uid_allocator, is_mounts, is_riders, positions, force_update, terrain): &mut Self::DeleteData<'_>, (id_maps, is_mounts, is_riders, positions, force_update, terrain): &mut Self::DeleteData<
'_,
>,
) { ) {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
let mount = entity(this.mount); let mount = entity(this.mount);
let rider = entity(this.rider); let rider = entity(this.rider);
@ -218,7 +220,7 @@ impl VolumePos {
pub fn get_block_and_transform( pub fn get_block_and_transform(
&self, &self,
terrain: &TerrainGrid, terrain: &TerrainGrid,
uid_allocator: &UidAllocator, id_maps: &IdMaps,
mut read_pos_and_ori: impl FnMut(Entity) -> Option<(comp::Pos, comp::Ori)>, mut read_pos_and_ori: impl FnMut(Entity) -> Option<(comp::Pos, comp::Ori)>,
colliders: &ReadStorage<comp::Collider>, colliders: &ReadStorage<comp::Collider>,
) -> Option<(Mat4<f32>, comp::Ori, Block)> { ) -> Option<(Mat4<f32>, comp::Ori, Block)> {
@ -228,7 +230,7 @@ impl VolumePos {
comp::Ori::default(), comp::Ori::default(),
*terrain.get(self.pos).ok()?, *terrain.get(self.pos).ok()?,
)), )),
Volume::Entity(uid) => uid_allocator.lookup_entity(uid).and_then(|entity| { Volume::Entity(uid) => id_maps.uid_entity(uid).and_then(|entity| {
let collider = colliders.get(entity)?; let collider = colliders.get(entity)?;
let (pos, ori) = read_pos_and_ori(entity)?; let (pos, ori) = read_pos_and_ori(entity)?;
@ -251,12 +253,12 @@ impl VolumePos {
pub fn get_block( pub fn get_block(
&self, &self,
terrain: &TerrainGrid, terrain: &TerrainGrid,
uid_allocator: &UidAllocator, id_maps: &IdMaps,
colliders: &ReadStorage<comp::Collider>, colliders: &ReadStorage<comp::Collider>,
) -> Option<Block> { ) -> Option<Block> {
match self.kind { match self.kind {
Volume::Terrain => Some(*terrain.get(self.pos).ok()?), Volume::Terrain => Some(*terrain.get(self.pos).ok()?),
Volume::Entity(uid) => uid_allocator.lookup_entity(uid).and_then(|entity| { Volume::Entity(uid) => id_maps.uid_entity(uid).and_then(|entity| {
let collider = colliders.get(entity)?; let collider = colliders.get(entity)?;
let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read(); let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
@ -293,14 +295,14 @@ impl Link for VolumeMounting {
WriteStorage<'a, Is<VolumeRider>>, WriteStorage<'a, Is<VolumeRider>>,
ReadStorage<'a, Is<Rider>>, ReadStorage<'a, Is<Rider>>,
ReadExpect<'a, TerrainGrid>, ReadExpect<'a, TerrainGrid>,
Read<'a, UidAllocator>, Read<'a, IdMaps>,
ReadStorage<'a, comp::Collider>, ReadStorage<'a, comp::Collider>,
); );
type DeleteData<'a> = ( type DeleteData<'a> = (
Write<'a, VolumeRiders>, Write<'a, VolumeRiders>,
WriteStorage<'a, VolumeRiders>, WriteStorage<'a, VolumeRiders>,
WriteStorage<'a, Is<VolumeRider>>, WriteStorage<'a, Is<VolumeRider>>,
Read<'a, UidAllocator>, Read<'a, IdMaps>,
); );
type Error = MountingError; type Error = MountingError;
type PersistData<'a> = ( type PersistData<'a> = (
@ -310,7 +312,7 @@ impl Link for VolumeMounting {
ReadStorage<'a, VolumeRiders>, ReadStorage<'a, VolumeRiders>,
ReadStorage<'a, Is<VolumeRider>>, ReadStorage<'a, Is<VolumeRider>>,
ReadExpect<'a, TerrainGrid>, ReadExpect<'a, TerrainGrid>,
Read<'a, UidAllocator>, Read<'a, IdMaps>,
ReadStorage<'a, comp::Collider>, ReadStorage<'a, comp::Collider>,
); );
@ -322,11 +324,11 @@ impl Link for VolumeMounting {
is_volume_riders, is_volume_riders,
is_riders, is_riders,
terrain_grid, terrain_grid,
uid_allocator, id_maps,
colliders, colliders,
): &mut Self::CreateData<'_>, ): &mut Self::CreateData<'_>,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
let riders = match this.pos.kind { let riders = match this.pos.kind {
Volume::Terrain => &mut *terrain_riders, Volume::Terrain => &mut *terrain_riders,
@ -343,7 +345,7 @@ impl Link for VolumeMounting {
{ {
let block = this let block = this
.pos .pos
.get_block(terrain_grid, uid_allocator, colliders) .get_block(terrain_grid, id_maps, colliders)
.ok_or(MountingError::NoSuchEntity)?; .ok_or(MountingError::NoSuchEntity)?;
if block == this.block { if block == this.block {
@ -367,11 +369,11 @@ impl Link for VolumeMounting {
volume_riders, volume_riders,
is_volume_riders, is_volume_riders,
terrain_grid, terrain_grid,
uid_allocator, id_maps,
colliders, colliders,
): &mut Self::PersistData<'_>, ): &mut Self::PersistData<'_>,
) -> bool { ) -> bool {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
let is_alive = let is_alive =
|entity| entities.is_alive(entity) && healths.get(entity).map_or(true, |h| !h.is_dead); |entity| entities.is_alive(entity) && healths.get(entity).map_or(true, |h| !h.is_dead);
let riders = match this.pos.kind { let riders = match this.pos.kind {
@ -393,7 +395,7 @@ impl Link for VolumeMounting {
let block_exists = this let block_exists = this
.pos .pos
.get_block(terrain_grid, uid_allocator, colliders) .get_block(terrain_grid, id_maps, colliders)
.map_or(false, |block| block == this.block); .map_or(false, |block| block == this.block);
rider_exists && mount_spot_exists && block_exists rider_exists && mount_spot_exists && block_exists
@ -401,9 +403,9 @@ impl Link for VolumeMounting {
fn delete( fn delete(
this: &LinkHandle<Self>, this: &LinkHandle<Self>,
(terrain_riders, volume_riders, is_rider, uid_allocator): &mut Self::DeleteData<'_>, (terrain_riders, volume_riders, is_rider, id_maps): &mut Self::DeleteData<'_>,
) { ) {
let entity = |uid: Uid| uid_allocator.lookup_entity(uid); let entity = |uid: Uid| id_maps.uid_entity(uid);
let riders = match this.pos.kind { let riders = match this.pos.kind {
Volume::Terrain => Some(&mut **terrain_riders), Volume::Terrain => Some(&mut **terrain_riders),

View File

@ -6,8 +6,10 @@ use std::{fmt, u64};
use { use {
crate::character::CharacterId, crate::character::CharacterId,
crate::rtsim::RtSimEntity, crate::rtsim::RtSimEntity,
core::hash::Hash,
hashbrown::HashMap, hashbrown::HashMap,
specs::{Component, Entity, FlaggedStorage, VecStorage}, specs::{Component, Entity, FlaggedStorage, VecStorage},
tracing::error,
}; };
// TODO: could we switch this to `NonZeroU64`? // TODO: could we switch this to `NonZeroU64`?
@ -35,25 +37,19 @@ mod not_wasm {
type Storage = FlaggedStorage<Self, VecStorage<Self>>; type Storage = FlaggedStorage<Self, VecStorage<Self>>;
} }
// NOTE: This is technically only needed by the server code server. Keeping here
// for now since this is related to the other code here.
#[derive(Debug)] #[derive(Debug)]
pub struct UidAllocator { struct UidAllocator {
/// Next Uid. /// Next Uid.
next_uid: u64, next_uid: u64,
} }
impl UidAllocator { impl UidAllocator {
pub fn new() -> Self { Self { next_uid: 0 } } fn new() -> Self { Self { next_uid: 0 } }
pub fn allocate(&mut self, entity: Entity, id: Option<Uid>) -> Uid { fn allocate(&mut self) -> Uid {
let id = id.unwrap_or_else(|| {
let id = self.next_uid; let id = self.next_uid;
self.next_uid += 1; self.next_uid += 1;
Uid(id) Uid(id)
});
self.uid_mapping.insert(id, entity);
id
} }
} }
@ -63,6 +59,9 @@ mod not_wasm {
/// network). /// network).
uid_mapping: HashMap<Uid, Entity>, uid_mapping: HashMap<Uid, Entity>,
// -- Fields below only used on the server --
uid_allocator: UidAllocator,
// Maps below are only used on the server. // Maps below are only used on the server.
/// Character IDs. /// Character IDs.
cid_mapping: HashMap<CharacterId, Entity>, cid_mapping: HashMap<CharacterId, Entity>,
@ -70,34 +69,37 @@ mod not_wasm {
rid_mapping: HashMap<RtsimEntity, Entity>, rid_mapping: HashMap<RtsimEntity, Entity>,
} }
impl IdManager { impl IdMaps {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
uid_mapping: HashMap::new(), uid_mapping: HashMap::new(),
uid_allocator: UidAllocator::new(),
cid_mapping: HashMap::new(), cid_mapping: HashMap::new(),
rid_mapping: HashMap::new(), rid_mapping: HashMap::new(),
} }
} }
/// Given a `Uid` retrieve the corresponding `Entity` /// Given a `Uid` retrieve the corresponding `Entity`.
pub fn uid_entity(&self, id: Uid) -> Option<Entity> { self.uid_mapping.get(&id).copied() } pub fn uid_entity(&self, id: Uid) -> Option<Entity> { self.uid_mapping.get(&id).copied() }
/// Given a `CharacterId` retrieve the corresponding `Entity` /// Given a `CharacterId` retrieve the corresponding `Entity`.
pub fn cid_entity(&self, id: CharacterId) -> Option<Entity> { pub fn cid_entity(&self, id: CharacterId) -> Option<Entity> {
self.uid_mapping.get(&id).copied() self.uid_mapping.get(&id).copied()
} }
/// Given a `Uid` retrieve the corresponding `Entity` /// Given a `RtSimEntity` retrieve the corresponding `Entity`.
pub fn rid_entity(&self, id: RtSimEntity) -> Option<Entity> { pub fn rid_entity(&self, id: RtSimEntity) -> Option<Entity> {
self.uid_mapping.get(&id).copied() self.uid_mapping.get(&id).copied()
} }
// TODO: I think this is suitable to use on both the client and the server.
// NOTE: This is only used on the client? Do we not remove on the server? // NOTE: This is only used on the client? Do we not remove on the server?
// NOTE: We need UID mapping also on the client but we don't need the other // NOTE: We need UID mapping also on the client but we don't need the other
// mappings on the client! // mappings on the client!
// //
// Useful for when a single entity is deleted because it doesn't reconstruct the // Useful for when a single entity is deleted because it doesn't reconstruct the
// entire hashmap // entire hashmap
/// Returns the `Entity` that the provided `Uid` was mapped to.
pub fn remove_entity( pub fn remove_entity(
&mut self, &mut self,
expected_entity: Option<Entity>, expected_entity: Option<Entity>,
@ -108,12 +110,12 @@ mod not_wasm {
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn unexpected_entity<ID>() { fn unexpected_entity<ID>() {
error!("{kind} mapped to an unexpected entity!"); error!("Provided was {kind} mapped to an unexpected entity!");
} }
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn not_present<ID>() { fn not_present<ID>() {
error!("{kind} not mapped to any entity!"); error!("Provided was {kind} not mapped to any entity!");
} }
fn remove<ID: Hash + Eq>( fn remove<ID: Hash + Eq>(
@ -143,51 +145,43 @@ mod not_wasm {
maybe_entity maybe_entity
} }
// TODO: we probably need separate methods here /// Only used on the client (server solely uses `Self::allocate` to
// TODO: document what methods are called only on the client or the server /// allocate and add Uid mappings).
pub fn add_entity( pub fn add_entity(&mut self, uid: Uid, entity: Entity) {
&mut self, Self::insert(&mut self.uid_mapping, uid, entity);
entity: Entity, }
uid: Uid,
cid: Option<CharacterId>, /// Only used on the server.
rid: Option<RtSimEntity>, pub fn add_character(&mut self, cid: CharacterId, entity: Entity) {
) { Self::insert(&mut self.cid_mapping, cid, entity);
}
/// Only used on the server.
pub fn add_rtsim(&mut self, rid: RtSimEntity, entity: Entity) {
Self::insert(&mut self.rid_mapping, rid, entity);
}
/// Allocates a new `Uid` and links it to the provided entity.
///
/// Only used on the server.
pub fn allocate(&mut self, entity: Entity) -> Uid {
let uid = self.uid_allocator.allocate();
self.uid_mapping.insert(uid, entity);
uid
}
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn already_present<ID>() { fn already_present<ID>() {
let kind = core::any::type_name::<ID>(); let kind = core::any::type_name::<ID>();
error!("{kind} already mapped to an entity!!!"); error!("Provided {kind} was already mapped to an entity!!!");
} }
fn insert<ID: Hash + Eq>( fn insert<ID: Hash + Eq>(mapping: &mut HashMap<ID, Entity>, new_id: ID, entity: Entity) {
mapping: &mut HashMap<ID, Entity>,
new_id: ID,
entity: Entity,
) {
if let Some(_previous_entity) = mapping.insert(new_id, entity) { if let Some(_previous_entity) = mapping.insert(new_id, entity) {
already_present::<ID>(); Self::already_present::<ID>();
} }
} }
insert(&mut self.uid_mapping, uid, entity);
if let Some(cid) = cid {
insert(&mut self.cid_mapping, cid, entity);
}
if let Some(rid) = rid {
insert(&mut self.rid_mapping, rid, entity);
}
}
pub fn allocate(&mut self, entity: Entity) -> Uid {
let id = id.unwrap_or_else(|| {
let id = self.next_uid;
self.next_uid += 1;
Uid(id)
});
// TODO: not sure we want to insert here?
self.uid_mapping.insert(id, entity);
id
}
} }
impl Default for UidAllocator { impl Default for UidAllocator {

View File

@ -8,7 +8,7 @@ use wasmer::{Function, Memory, Value};
use common::{ use common::{
comp::{Health, Player}, comp::{Health, Player},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use super::errors::{MemoryAllocationError, PluginModuleError}; use super::errors::{MemoryAllocationError, PluginModuleError};
@ -18,7 +18,7 @@ pub struct EcsWorld<'a, 'b> {
pub health: EcsComponentAccess<'a, 'b, Health>, pub health: EcsComponentAccess<'a, 'b, Health>,
pub uid: EcsComponentAccess<'a, 'b, Uid>, pub uid: EcsComponentAccess<'a, 'b, Uid>,
pub player: EcsComponentAccess<'a, 'b, Player>, pub player: EcsComponentAccess<'a, 'b, Player>,
pub uid_allocator: &'b Read<'a, UidAllocator>, pub id_maps: &'b Read<'a, IdMaps>,
} }
pub enum EcsComponentAccess<'a, 'b, T: Component> { pub enum EcsComponentAccess<'a, 'b, T: Component> {

View File

@ -240,8 +240,8 @@ fn retrieve_action(
}; };
let player = let player =
world world
.uid_allocator .id_maps
.lookup_entity(e) .uid_entity(e)
.ok_or(RetrieveError::EcsAccessError( .ok_or(RetrieveError::EcsAccessError(
EcsAccessError::EcsEntityNotFound(e), EcsAccessError::EcsEntityNotFound(e),
))?; ))?;
@ -269,8 +269,8 @@ fn retrieve_action(
}; };
let player = let player =
world world
.uid_allocator .id_maps
.lookup_entity(e) .uid_entity(e)
.ok_or(RetrieveError::EcsAccessError( .ok_or(RetrieveError::EcsAccessError(
EcsAccessError::EcsEntityNotFound(e), EcsAccessError::EcsEntityNotFound(e),
))?; ))?;

View File

@ -4,7 +4,7 @@ use crate::plugin::memory_manager::EcsWorld;
use crate::plugin::PluginMgr; use crate::plugin::PluginMgr;
use crate::{BuildArea, NoDurabilityArea}; use crate::{BuildArea, NoDurabilityArea};
#[cfg(feature = "plugins")] #[cfg(feature = "plugins")]
use common::uid::UidAllocator; use common::uid::IdMaps;
use common::{ use common::{
calendar::Calendar, calendar::Calendar,
comp, comp,
@ -309,7 +309,7 @@ impl State {
entities: &ecs.entities(), entities: &ecs.entities(),
health: ecs.read_component().into(), health: ecs.read_component().into(),
uid: ecs.read_component().into(), uid: ecs.read_component().into(),
uid_allocator: &ecs.read_resource::<UidAllocator>().into(), id_maps: &ecs.read_resource::<IdMaps>().into(),
player: ecs.read_component().into(), player: ecs.read_component().into(),
}; };
if let Err(e) = plugin_mgr if let Err(e) = plugin_mgr

View File

@ -8,7 +8,7 @@ use common::{
}, },
event::{Emitter, EventBus, ServerEvent}, event::{Emitter, EventBus, ServerEvent},
resources::Time, resources::Time,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use specs::{ use specs::{
@ -21,7 +21,7 @@ pub struct ReadData<'a> {
players: ReadStorage<'a, Player>, players: ReadStorage<'a, Player>,
time: Read<'a, Time>, time: Read<'a, Time>,
server_bus: Read<'a, EventBus<ServerEvent>>, server_bus: Read<'a, EventBus<ServerEvent>>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
cached_spatial_grid: Read<'a, common::CachedSpatialGrid>, cached_spatial_grid: Read<'a, common::CachedSpatialGrid>,
positions: ReadStorage<'a, Pos>, positions: ReadStorage<'a, Pos>,
char_states: ReadStorage<'a, CharacterState>, char_states: ReadStorage<'a, CharacterState>,
@ -95,8 +95,8 @@ impl<'a> System<'a> for Sys {
// Ensure the entity is in the group we want to target // Ensure the entity is in the group we want to target
let same_group = |uid: Uid| { let same_group = |uid: Uid| {
read_data read_data
.uid_allocator .id_maps
.lookup_entity(uid) .uid_entity(uid)
.and_then(|e| read_data.groups.get(e)) .and_then(|e| read_data.groups.get(e))
.map_or(false, |owner_group| { .map_or(false, |owner_group| {
Some(owner_group) == read_data.groups.get(target) Some(owner_group) == read_data.groups.get(target)
@ -166,7 +166,7 @@ fn activate_aura(
Alignment::Owned(uid) => Some(uid), Alignment::Owned(uid) => Some(uid),
_ => None, _ => None,
}) })
.and_then(|uid| read_data.uid_allocator.lookup_entity(*uid)) .and_then(|uid| read_data.id_maps.uid_entity(*uid))
.and_then(|owner| read_data.char_states.get(owner)) .and_then(|owner| read_data.char_states.get(owner))
.map_or(false, CharacterState::is_sitting)) .map_or(false, CharacterState::is_sitting))
}, },
@ -183,13 +183,13 @@ fn activate_aura(
// when we will add this. // when we will add this.
let may_harm = || { let may_harm = || {
let owner = match source { let owner = match source {
BuffSource::Character { by } => read_data.uid_allocator.lookup_entity(by), BuffSource::Character { by } => read_data.id_maps.uid_entity(by),
_ => None, _ => None,
}; };
combat::may_harm( combat::may_harm(
&read_data.alignments, &read_data.alignments,
&read_data.players, &read_data.players,
&read_data.uid_allocator, &read_data.id_maps,
owner, owner,
target, target,
) )

View File

@ -9,7 +9,7 @@ use common::{
outcome::Outcome, outcome::Outcome,
resources::{DeltaTime, Time}, resources::{DeltaTime, Time},
terrain::TerrainGrid, terrain::TerrainGrid,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
vol::ReadVol, vol::ReadVol,
GroupTarget, GroupTarget,
}; };
@ -31,7 +31,7 @@ pub struct ReadData<'a> {
time: Read<'a, Time>, time: Read<'a, Time>,
dt: Read<'a, DeltaTime>, dt: Read<'a, DeltaTime>,
terrain: ReadExpect<'a, TerrainGrid>, terrain: ReadExpect<'a, TerrainGrid>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
cached_spatial_grid: Read<'a, common::CachedSpatialGrid>, cached_spatial_grid: Read<'a, common::CachedSpatialGrid>,
uids: ReadStorage<'a, Uid>, uids: ReadStorage<'a, Uid>,
positions: ReadStorage<'a, Pos>, positions: ReadStorage<'a, Pos>,
@ -97,7 +97,7 @@ impl<'a> System<'a> for Sys {
let beam_owner = beam_segment let beam_owner = beam_segment
.owner .owner
.and_then(|uid| read_data.uid_allocator.lookup_entity(uid)); .and_then(|uid| read_data.id_maps.uid_entity(uid));
// Note: rayon makes it difficult to hold onto a thread-local RNG, if grabbing // Note: rayon makes it difficult to hold onto a thread-local RNG, if grabbing
// this becomes a bottleneck we can look into alternatives. // this becomes a bottleneck we can look into alternatives.
@ -243,7 +243,7 @@ impl<'a> System<'a> for Sys {
let may_harm = combat::may_harm( let may_harm = combat::may_harm(
&read_data.alignments, &read_data.alignments,
&read_data.players, &read_data.players,
&read_data.uid_allocator, &read_data.id_maps,
beam_owner, beam_owner,
target, target,
); );

View File

@ -15,7 +15,7 @@ use common::{
event::{Emitter, EventBus, ServerEvent}, event::{Emitter, EventBus, ServerEvent},
resources::{DeltaTime, Secs, Time}, resources::{DeltaTime, Secs, Time},
terrain::SpriteKind, terrain::SpriteKind,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
Damage, DamageSource, Damage, DamageSource,
}; };
use common_base::prof_span; use common_base::prof_span;
@ -36,7 +36,7 @@ pub struct ReadData<'a> {
energies: ReadStorage<'a, Energy>, energies: ReadStorage<'a, Energy>,
physics_states: ReadStorage<'a, PhysicsState>, physics_states: ReadStorage<'a, PhysicsState>,
groups: ReadStorage<'a, Group>, groups: ReadStorage<'a, Group>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
time: Read<'a, Time>, time: Read<'a, Time>,
msm: ReadExpect<'a, MaterialStatManifest>, msm: ReadExpect<'a, MaterialStatManifest>,
buffs: ReadStorage<'a, Buffs>, buffs: ReadStorage<'a, Buffs>,
@ -276,7 +276,7 @@ impl<'a> System<'a> for Sys {
}) })
.for_each(|(buff_id, buff, uid, aura_key)| { .for_each(|(buff_id, buff, uid, aura_key)| {
let replace = let replace =
if let Some(aura_entity) = read_data.uid_allocator.lookup_entity(*uid) { if let Some(aura_entity) = read_data.id_maps.uid_entity(*uid) {
if let Some(aura) = read_data if let Some(aura) = read_data
.auras .auras
.get(aura_entity) .get(aura_entity)
@ -502,7 +502,7 @@ fn execute_effect(
ModifierKind::Fractional => health.maximum() * amount, ModifierKind::Fractional => health.maximum() * amount,
}; };
let damage_contributor = by.and_then(|uid| { let damage_contributor = by.and_then(|uid| {
read_data.uid_allocator.lookup_entity(uid).map(|entity| { read_data.id_maps.uid_entity(uid).map(|entity| {
DamageContributor::new(uid, read_data.groups.get(entity).cloned()) DamageContributor::new(uid, read_data.groups.get(entity).cloned())
}) })
}); });

View File

@ -6,7 +6,7 @@ use common::{
}, },
event::{EventBus, ServerEvent}, event::{EventBus, ServerEvent},
terrain::TerrainGrid, terrain::TerrainGrid,
uid::UidAllocator, uid::IdMaps,
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use specs::{ use specs::{
@ -18,7 +18,7 @@ use vek::*;
#[derive(SystemData)] #[derive(SystemData)]
pub struct ReadData<'a> { pub struct ReadData<'a> {
entities: Entities<'a>, entities: Entities<'a>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
server_bus: Read<'a, EventBus<ServerEvent>>, server_bus: Read<'a, EventBus<ServerEvent>>,
terrain_grid: ReadExpect<'a, TerrainGrid>, terrain_grid: ReadExpect<'a, TerrainGrid>,
positions: ReadStorage<'a, Pos>, positions: ReadStorage<'a, Pos>,
@ -48,16 +48,14 @@ impl<'a> System<'a> for Sys {
for event in controller.events.drain(..) { for event in controller.events.drain(..) {
match event { match event {
ControlEvent::Mount(mountee_uid) => { ControlEvent::Mount(mountee_uid) => {
if let Some(mountee_entity) = if let Some(mountee_entity) = read_data.id_maps.uid_entity(mountee_uid) {
read_data.uid_allocator.lookup_entity(mountee_uid)
{
server_emitter.emit(ServerEvent::Mount(entity, mountee_entity)); server_emitter.emit(ServerEvent::Mount(entity, mountee_entity));
} }
}, },
ControlEvent::MountVolume(volume) => { ControlEvent::MountVolume(volume) => {
if let Some(block) = volume.get_block( if let Some(block) = volume.get_block(
&read_data.terrain_grid, &read_data.terrain_grid,
&read_data.uid_allocator, &read_data.id_maps,
&read_data.colliders, &read_data.colliders,
) { ) {
if block.is_mountable() { if block.is_mountable() {
@ -79,7 +77,7 @@ impl<'a> System<'a> for Sys {
server_emitter.emit(ServerEvent::DisableLantern(entity)) server_emitter.emit(ServerEvent::DisableLantern(entity))
}, },
ControlEvent::Interact(npc_uid, subject) => { ControlEvent::Interact(npc_uid, subject) => {
if let Some(npc_entity) = read_data.uid_allocator.lookup_entity(npc_uid) { if let Some(npc_entity) = read_data.id_maps.uid_entity(npc_uid) {
server_emitter server_emitter
.emit(ServerEvent::NpcInteract(entity, npc_entity, subject)); .emit(ServerEvent::NpcInteract(entity, npc_entity, subject));
} }

View File

@ -10,7 +10,7 @@ use common::{
outcome::Outcome, outcome::Outcome,
resources::Time, resources::Time,
terrain::TerrainGrid, terrain::TerrainGrid,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::{find_dist::Cylinder, Dir}, util::{find_dist::Cylinder, Dir},
vol::ReadVol, vol::ReadVol,
GroupTarget, GroupTarget,
@ -27,7 +27,7 @@ use vek::*;
pub struct ReadData<'a> { pub struct ReadData<'a> {
time: Read<'a, Time>, time: Read<'a, Time>,
terrain: ReadExpect<'a, TerrainGrid>, terrain: ReadExpect<'a, TerrainGrid>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
entities: Entities<'a>, entities: Entities<'a>,
players: ReadStorage<'a, Player>, players: ReadStorage<'a, Player>,
uids: ReadStorage<'a, Uid>, uids: ReadStorage<'a, Uid>,
@ -213,7 +213,7 @@ impl<'a> System<'a> for Sys {
let may_harm = combat::may_harm( let may_harm = combat::may_harm(
&read_data.alignments, &read_data.alignments,
&read_data.players, &read_data.players,
&read_data.uid_allocator, &read_data.id_maps,
Some(attacker), Some(attacker),
target, target,
); );

View File

@ -3,7 +3,7 @@ use common::{
link::Is, link::Is,
mounting::{Mount, VolumeRider}, mounting::{Mount, VolumeRider},
terrain::TerrainGrid, terrain::TerrainGrid,
uid::UidAllocator, uid::IdMaps,
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use specs::{Entities, Join, Read, ReadExpect, ReadStorage, WriteStorage}; use specs::{Entities, Join, Read, ReadExpect, ReadStorage, WriteStorage};
@ -15,7 +15,7 @@ use vek::*;
pub struct Sys; pub struct Sys;
impl<'a> System<'a> for Sys { impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Read<'a, UidAllocator>, Read<'a, IdMaps>,
ReadExpect<'a, TerrainGrid>, ReadExpect<'a, TerrainGrid>,
Entities<'a>, Entities<'a>,
WriteStorage<'a, Controller>, WriteStorage<'a, Controller>,
@ -36,7 +36,7 @@ impl<'a> System<'a> for Sys {
fn run( fn run(
_job: &mut Job<Self>, _job: &mut Job<Self>,
( (
uid_allocator, id_maps,
terrain, terrain,
entities, entities,
mut controllers, mut controllers,
@ -53,8 +53,8 @@ impl<'a> System<'a> for Sys {
// For each mount... // For each mount...
for (entity, is_mount, body) in (&entities, &is_mounts, bodies.maybe()).join() { for (entity, is_mount, body) in (&entities, &is_mounts, bodies.maybe()).join() {
// ...find the rider... // ...find the rider...
let Some((inputs_and_actions, rider)) = uid_allocator let Some((inputs_and_actions, rider)) = id_maps
.lookup_entity(is_mount.rider) .uid_entity(is_mount.rider)
.and_then(|rider| { .and_then(|rider| {
controllers controllers
.get_mut(rider) .get_mut(rider)
@ -102,7 +102,7 @@ impl<'a> System<'a> for Sys {
for (entity, is_volume_rider) in (&entities, &is_volume_riders).join() { for (entity, is_volume_rider) in (&entities, &is_volume_riders).join() {
if let Some((mut mat, volume_ori, _)) = is_volume_rider.pos.get_block_and_transform( if let Some((mut mat, volume_ori, _)) = is_volume_rider.pos.get_block_and_transform(
&terrain, &terrain,
&uid_allocator, &id_maps,
|e| positions.get(e).copied().zip(orientations.get(e).copied()), |e| positions.get(e).copied().zip(orientations.get(e).copied()),
&colliders, &colliders,
) { ) {
@ -137,10 +137,7 @@ impl<'a> System<'a> for Sys {
let v = match is_volume_rider.pos.kind { let v = match is_volume_rider.pos.kind {
common::mounting::Volume::Terrain => Vec3::zero(), common::mounting::Volume::Terrain => Vec3::zero(),
common::mounting::Volume::Entity(uid) => { common::mounting::Volume::Entity(uid) => {
if let Some(v) = uid_allocator if let Some(v) = id_maps.uid_entity(uid).and_then(|e| velocities.get(e)) {
.lookup_entity(uid)
.and_then(|e| velocities.get(e))
{
v.0 v.0
} else { } else {
Vec3::zero() Vec3::zero()
@ -171,9 +168,8 @@ impl<'a> System<'a> for Sys {
if let Some((actions, inputs)) = inputs { if let Some((actions, inputs)) = inputs {
match is_volume_rider.pos.kind { match is_volume_rider.pos.kind {
common::mounting::Volume::Entity(uid) => { common::mounting::Volume::Entity(uid) => {
if let Some(controller) = uid_allocator if let Some(controller) =
.lookup_entity(uid) id_maps.uid_entity(uid).and_then(|e| controllers.get_mut(e))
.and_then(|e| controllers.get_mut(e))
{ {
controller.inputs = inputs; controller.inputs = inputs;
controller.actions = actions; controller.actions = actions;

View File

@ -8,7 +8,7 @@ use common::{
event::{Emitter, EventBus, ServerEvent}, event::{Emitter, EventBus, ServerEvent},
outcome::Outcome, outcome::Outcome,
resources::{DeltaTime, Time}, resources::{DeltaTime, Time},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::Dir, util::Dir,
GroupTarget, GroupTarget,
}; };
@ -31,7 +31,7 @@ pub struct ReadData<'a> {
entities: Entities<'a>, entities: Entities<'a>,
players: ReadStorage<'a, Player>, players: ReadStorage<'a, Player>,
dt: Read<'a, DeltaTime>, dt: Read<'a, DeltaTime>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
server_bus: Read<'a, EventBus<ServerEvent>>, server_bus: Read<'a, EventBus<ServerEvent>>,
uids: ReadStorage<'a, Uid>, uids: ReadStorage<'a, Uid>,
positions: ReadStorage<'a, Pos>, positions: ReadStorage<'a, Pos>,
@ -85,7 +85,7 @@ impl<'a> System<'a> for Sys {
{ {
let projectile_owner = projectile let projectile_owner = projectile
.owner .owner
.and_then(|uid| read_data.uid_allocator.lookup_entity(uid)); .and_then(|uid| read_data.id_maps.uid_entity(uid));
if physics.on_surface().is_none() && rng.gen_bool(0.05) { if physics.on_surface().is_none() && rng.gen_bool(0.05) {
server_emitter.emit(ServerEvent::Sound { server_emitter.emit(ServerEvent::Sound {
@ -103,8 +103,8 @@ impl<'a> System<'a> for Sys {
// if there is at least one touching entity // if there is at least one touching entity
.and_then(|e| read_data.groups.get(e)) .and_then(|e| read_data.groups.get(e))
.map_or(false, |owner_group| .map_or(false, |owner_group|
Some(owner_group) == read_data.uid_allocator Some(owner_group) == read_data.id_maps
.lookup_entity(other) .uid_entity(other)
.and_then(|e| read_data.groups.get(e)) .and_then(|e| read_data.groups.get(e))
); );
@ -125,7 +125,7 @@ impl<'a> System<'a> for Sys {
let projectile = &mut *projectile; let projectile = &mut *projectile;
let entity_of = |uid: Uid| read_data.uid_allocator.lookup_entity(uid); let entity_of = |uid: Uid| read_data.id_maps.uid_entity(uid);
// Don't hit if there is terrain between the projectile and where the entity was // Don't hit if there is terrain between the projectile and where the entity was
// supposed to be hit by it. // supposed to be hit by it.
@ -333,7 +333,7 @@ fn dispatch_hit(
let may_harm = combat::may_harm( let may_harm = combat::may_harm(
&read_data.alignments, &read_data.alignments,
&read_data.players, &read_data.players,
&read_data.uid_allocator, &read_data.id_maps,
owner, owner,
target, target,
); );

View File

@ -8,7 +8,7 @@ use common::{
event::{EventBus, ServerEvent}, event::{EventBus, ServerEvent},
outcome::Outcome, outcome::Outcome,
resources::{DeltaTime, Time}, resources::{DeltaTime, Time},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::Dir, util::Dir,
GroupTarget, GroupTarget,
}; };
@ -26,7 +26,7 @@ pub struct ReadData<'a> {
time: Read<'a, Time>, time: Read<'a, Time>,
players: ReadStorage<'a, Player>, players: ReadStorage<'a, Player>,
dt: Read<'a, DeltaTime>, dt: Read<'a, DeltaTime>,
uid_allocator: Read<'a, UidAllocator>, id_maps: Read<'a, IdMaps>,
uids: ReadStorage<'a, Uid>, uids: ReadStorage<'a, Uid>,
positions: ReadStorage<'a, Pos>, positions: ReadStorage<'a, Pos>,
orientations: ReadStorage<'a, Ori>, orientations: ReadStorage<'a, Ori>,
@ -91,7 +91,7 @@ impl<'a> System<'a> for Sys {
let shockwave_owner = shockwave let shockwave_owner = shockwave
.owner .owner
.and_then(|uid| read_data.uid_allocator.lookup_entity(uid)); .and_then(|uid| read_data.id_maps.uid_entity(uid));
if rng.gen_bool(0.05) { if rng.gen_bool(0.05) {
server_emitter.emit(ServerEvent::Sound { server_emitter.emit(ServerEvent::Sound {
@ -228,7 +228,7 @@ impl<'a> System<'a> for Sys {
let may_harm = combat::may_harm( let may_harm = combat::may_harm(
&read_data.alignments, &read_data.alignments,
&read_data.players, &read_data.players,
&read_data.uid_allocator, &read_data.id_maps,
shockwave_owner, shockwave_owner,
target, target,
); );

View File

@ -21,7 +21,7 @@ use common::{
rtsim::{Actor, RtSimEntity}, rtsim::{Actor, RtSimEntity},
states::utils::{ForcedMovement, StageSection}, states::utils::{ForcedMovement, StageSection},
terrain::TerrainGrid, terrain::TerrainGrid,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use specs::{ use specs::{
shred::ResourceId, Entities, Entity as EcsEntity, Join, Read, ReadExpect, ReadStorage, shred::ResourceId, Entities, Entity as EcsEntity, Join, Read, ReadExpect, ReadStorage,
@ -284,7 +284,7 @@ impl SwordTactics {
#[derive(SystemData)] #[derive(SystemData)]
pub struct ReadData<'a> { pub struct ReadData<'a> {
pub entities: Entities<'a>, pub entities: Entities<'a>,
pub uid_allocator: Read<'a, UidAllocator>, pub id_maps: Read<'a, IdMaps>,
pub dt: Read<'a, DeltaTime>, pub dt: Read<'a, DeltaTime>,
pub time: Read<'a, Time>, pub time: Read<'a, Time>,
pub cached_spatial_grid: Read<'a, common::CachedSpatialGrid>, pub cached_spatial_grid: Read<'a, common::CachedSpatialGrid>,

View File

@ -65,7 +65,7 @@ pub fn aim_projectile(speed: f32, pos: Vec3<f32>, tgt: Vec3<f32>) -> Option<Dir>
} }
pub fn get_entity_by_id(uid: Uid, read_data: &ReadData) -> Option<EcsEntity> { pub fn get_entity_by_id(uid: Uid, read_data: &ReadData) -> Option<EcsEntity> {
read_data.uid_allocator.lookup_entity(uid) read_data.id_maps.uid_entity(uid)
} }
/// Calculates whether the agent should continue chase or let the target escape. /// Calculates whether the agent should continue chase or let the target escape.

View File

@ -47,7 +47,7 @@ use common::{
resources::{BattleMode, PlayerPhysicsSettings, Secs, Time, TimeOfDay, TimeScale}, resources::{BattleMode, PlayerPhysicsSettings, Secs, Time, TimeOfDay, TimeScale},
rtsim::{Actor, Role}, rtsim::{Actor, Role},
terrain::{Block, BlockKind, CoordinateConversions, SpriteKind, TerrainChunkSize}, terrain::{Block, BlockKind, CoordinateConversions, SpriteKind, TerrainChunkSize},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
vol::ReadVol, vol::ReadVol,
weather, Damage, DamageKind, DamageSource, Explosion, LoadoutBuilder, RadiusEffect, weather, Damage, DamageKind, DamageSource, Explosion, LoadoutBuilder, RadiusEffect,
}; };
@ -245,8 +245,8 @@ fn position_mut<T>(
server server
.state .state
.ecs() .ecs()
.read_resource::<UidAllocator>() .read_resource::<IdMaps>()
.lookup_entity(is_rider.mount) .uid_entity(is_rider.mount)
}) })
.map(Ok) .map(Ok)
.or_else(|| { .or_else(|| {
@ -262,8 +262,8 @@ fn position_mut<T>(
common::mounting::Volume::Entity(uid) => Ok(server common::mounting::Volume::Entity(uid) => Ok(server
.state .state
.ecs() .ecs()
.read_resource::<UidAllocator>() .read_resource::<IdMaps>()
.lookup_entity(uid)?), .uid_entity(uid)?),
}) })
}) })
}) })

View File

@ -32,7 +32,7 @@ use common::{
states::utils::StageSection, states::utils::StageSection,
terrain::{Block, BlockKind, TerrainGrid}, terrain::{Block, BlockKind, TerrainGrid},
trade::{TradeResult, Trades}, trade::{TradeResult, Trades},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::Dir, util::Dir,
vol::ReadVol, vol::ReadVol,
Damage, DamageKind, DamageSource, Explosion, GroupTarget, RadiusEffect, Damage, DamageKind, DamageSource, Explosion, GroupTarget, RadiusEffect,
@ -568,8 +568,8 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, last_change: Healt
| DamageContributor::Group { entity_uid, .. })| { | DamageContributor::Group { entity_uid, .. })| {
state state
.ecs() .ecs()
.read_resource::<UidAllocator>() .read_resource::<IdMaps>()
.lookup_entity(*entity_uid) .uid_entity(*entity_uid)
}, },
) )
.and_then(|killer| state.entity_as_actor(killer)), .and_then(|killer| state.entity_as_actor(killer)),
@ -742,7 +742,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
let settings = server.settings(); let settings = server.settings();
let server_eventbus = ecs.read_resource::<EventBus<ServerEvent>>(); let server_eventbus = ecs.read_resource::<EventBus<ServerEvent>>();
let time = ecs.read_resource::<Time>(); let time = ecs.read_resource::<Time>();
let owner_entity = owner.and_then(|uid| ecs.read_resource::<UidAllocator>().lookup_entity(uid)); let owner_entity = owner.and_then(|uid| ecs.read_resource::<IdMaps>().uid_entity(uid));
let explosion_volume = 6.25 * explosion.radius; let explosion_volume = 6.25 * explosion.radius;
let mut emitter = server_eventbus.emitter(); let mut emitter = server_eventbus.emitter();
@ -947,7 +947,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
let combos = &ecs.read_storage::<comp::Combo>(); let combos = &ecs.read_storage::<comp::Combo>();
let inventories = &ecs.read_storage::<Inventory>(); let inventories = &ecs.read_storage::<Inventory>();
let alignments = &ecs.read_storage::<Alignment>(); let alignments = &ecs.read_storage::<Alignment>();
let uid_allocator = &ecs.read_resource::<UidAllocator>(); let id_maps = &ecs.read_resource::<IdMaps>();
let players = &ecs.read_storage::<Player>(); let players = &ecs.read_storage::<Player>();
let buffs = &ecs.read_storage::<comp::Buffs>(); let buffs = &ecs.read_storage::<comp::Buffs>();
let stats = &ecs.read_storage::<comp::Stats>(); let stats = &ecs.read_storage::<comp::Stats>();
@ -1043,7 +1043,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
let may_harm = combat::may_harm( let may_harm = combat::may_harm(
alignments, alignments,
players, players,
uid_allocator, id_maps,
owner_entity, owner_entity,
entity_b, entity_b,
); );
@ -1072,7 +1072,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
}, },
RadiusEffect::Entity(mut effect) => { RadiusEffect::Entity(mut effect) => {
let alignments = &ecs.read_storage::<Alignment>(); let alignments = &ecs.read_storage::<Alignment>();
let uid_allocator = &ecs.read_resource::<UidAllocator>(); let id_maps = &ecs.read_resource::<IdMaps>();
let players = &ecs.read_storage::<Player>(); let players = &ecs.read_storage::<Player>();
for (entity_b, pos_b, body_b_maybe) in ( for (entity_b, pos_b, body_b_maybe) in (
&ecs.entities(), &ecs.entities(),
@ -1104,7 +1104,7 @@ pub fn handle_explosion(server: &Server, pos: Vec3<f32>, explosion: Explosion, o
// //
// This can be changed later. // This can be changed later.
let may_harm = || { let may_harm = || {
combat::may_harm(alignments, players, uid_allocator, owner_entity, entity_b) combat::may_harm(alignments, players, id_maps, owner_entity, entity_b)
|| owner_entity.map_or(true, |entity_a| entity_a == entity_b) || owner_entity.map_or(true, |entity_a| entity_a == entity_b)
}; };
if strength > 0.0 { if strength > 0.0 {

View File

@ -8,7 +8,7 @@ use common::{
comp, comp,
comp::{group, pet::is_tameable, Presence, PresenceKind}, comp::{group, pet::is_tameable, Presence, PresenceKind},
resources::Time, resources::Time,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use common_base::span; use common_base::span;
use common_net::msg::{PlayerListUpdate, ServerGeneral}; use common_net::msg::{PlayerListUpdate, ServerGeneral};
@ -101,10 +101,10 @@ pub fn handle_exit_ingame(server: &mut Server, entity: EcsEntity, skip_persisten
None => entity_builder, None => entity_builder,
}; };
// Ensure UidAllocator maps this uid to the new entity // Ensure IdMaps maps this uid to the new entity
let uid = entity_builder let uid = entity_builder
.world .world
.write_resource::<UidAllocator>() .write_resource::<IdMaps>()
.allocate(entity_builder.entity, Some(uid.into())); .allocate(entity_builder.entity, Some(uid.into()));
let new_entity = entity_builder.with(uid).build(); let new_entity = entity_builder.with(uid).build();
if let Some(group) = maybe_group { if let Some(group) = maybe_group {

View File

@ -410,7 +410,7 @@ mod tests {
use hashbrown::HashMap; use hashbrown::HashMap;
use super::*; use super::*;
use common::{comp::slot::InvSlotId, uid::UidAllocator}; use common::{comp::slot::InvSlotId, uid::IdMaps};
use specs::{Builder, World}; use specs::{Builder, World};
@ -423,7 +423,7 @@ mod tests {
merchant_inv_size: usize, merchant_inv_size: usize,
) -> (World, EcsEntity, EcsEntity) { ) -> (World, EcsEntity, EcsEntity) {
let mut mockworld = World::new(); let mut mockworld = World::new();
mockworld.insert(UidAllocator::new()); mockworld.insert(IdMaps::new());
mockworld.insert(MaterialStatManifest::load().cloned()); mockworld.insert(MaterialStatManifest::load().cloned());
mockworld.insert(AbilityMap::load().cloned()); mockworld.insert(AbilityMap::load().cloned());
mockworld.register::<Inventory>(); mockworld.register::<Inventory>();
@ -442,10 +442,10 @@ mod tests {
{ {
use specs::saveload::MarkerAllocator; use specs::saveload::MarkerAllocator;
let mut uids = mockworld.write_component::<Uid>(); let mut uids = mockworld.write_component::<Uid>();
let mut uid_allocator = mockworld.write_resource::<UidAllocator>(); let mut id_maps = mockworld.write_resource::<IdMaps>();
uids.insert(player, uid_allocator.allocate(player, None)) uids.insert(player, id_maps.allocate(player, None))
.expect("inserting player uid failed"); .expect("inserting player uid failed");
uids.insert(merchant, uid_allocator.allocate(merchant, None)) uids.insert(merchant, id_maps.allocate(merchant, None))
.expect("inserting merchant uid failed"); .expect("inserting merchant uid failed");
} }

View File

@ -123,7 +123,7 @@ use crate::settings::Protocol;
#[cfg(feature = "plugins")] #[cfg(feature = "plugins")]
use { use {
common::uid::UidAllocator, common::uid::IdMaps,
common_state::plugin::{memory_manager::EcsWorld, PluginMgr}, common_state::plugin::{memory_manager::EcsWorld, PluginMgr},
}; };
@ -1219,7 +1219,7 @@ impl Server {
entities: &self.state.ecs().entities(), entities: &self.state.ecs().entities(),
health: self.state.ecs().read_component().into(), health: self.state.ecs().read_component().into(),
uid: self.state.ecs().read_component().into(), uid: self.state.ecs().read_component().into(),
uid_allocator: &self.state.ecs().read_resource::<UidAllocator>().into(), id_maps: &self.state.ecs().read_resource::<IdMaps>().into(),
player: self.state.ecs().read_component().into(), player: self.state.ecs().read_component().into(),
}; };
let uid = if let Some(uid) = ecs_world.uid.get(entity).copied() { let uid = if let Some(uid) = ecs_world.uid.get(entity).copied() {

View File

@ -27,7 +27,7 @@ use common::{
resources::{Secs, Time, TimeOfDay}, resources::{Secs, Time, TimeOfDay},
rtsim::{Actor, RtSimEntity}, rtsim::{Actor, RtSimEntity},
slowjob::SlowJobPool, slowjob::SlowJobPool,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
LoadoutBuilder, ViewDistances, LoadoutBuilder, ViewDistances,
}; };
use common_net::{ use common_net::{
@ -885,8 +885,8 @@ impl StateExt for State {
.clone() .clone()
.map_group(|_| group_info.map_or_else(|| "???".to_string(), |i| i.name.clone())); .map_group(|_| group_info.map_or_else(|| "???".to_string(), |i| i.name.clone()));
let uid_allocator = ecs.read_resource::<UidAllocator>(); let id_maps = ecs.read_resource::<IdMaps>();
let entity_from_uid = |uid| uid_allocator.lookup_entity(uid); let entity_from_uid = |uid| id_maps.uid_entity(uid);
if msg.chat_type.uid().map_or(true, |sender| { if msg.chat_type.uid().map_or(true, |sender| {
entity_from_uid(sender).map_or(false, |e| { entity_from_uid(sender).map_or(false, |e| {

View File

@ -102,14 +102,12 @@ impl<'a> System<'a> for Sys {
// The entity that is moving, if riding it's the mount, otherwise it's itself // The entity that is moving, if riding it's the mount, otherwise it's itself
let moving_entity = is_rider let moving_entity = is_rider
.and_then(|is_rider| read_data.uid_allocator.lookup_entity(is_rider.mount)) .and_then(|is_rider| read_data.id_maps.uid_entity(is_rider.mount))
.or_else(|| { .or_else(|| {
is_volume_rider.and_then(|is_volume_rider| { is_volume_rider.and_then(|is_volume_rider| {
match is_volume_rider.pos.kind { match is_volume_rider.pos.kind {
Volume::Terrain => None, Volume::Terrain => None,
Volume::Entity(uid) => { Volume::Entity(uid) => read_data.id_maps.uid_entity(uid),
read_data.uid_allocator.lookup_entity(uid)
},
} }
}) })
}) })

View File

@ -244,7 +244,7 @@ fn target_if_attacked(bdata: &mut BehaviorData) -> bool {
&& health.last_change.amount < 0.0 => && health.last_change.amount < 0.0 =>
{ {
if let Some(by) = health.last_change.damage_by() { if let Some(by) = health.last_change.damage_by() {
if let Some(attacker) = bdata.read_data.uid_allocator.lookup_entity(by.uid()) { if let Some(attacker) = bdata.read_data.id_maps.uid_entity(by.uid()) {
// If target is dead or invulnerable (for now, this only // If target is dead or invulnerable (for now, this only
// means safezone), untarget them and idle. // means safezone), untarget them and idle.
if is_dead_or_invulnerable(attacker, bdata.read_data) { if is_dead_or_invulnerable(attacker, bdata.read_data) {

View File

@ -1,6 +1,6 @@
use common::{ use common::{
comp::{group::GroupManager, loot_owner::LootOwnerKind, LootOwner}, comp::{group::GroupManager, loot_owner::LootOwnerKind, LootOwner},
uid::UidAllocator, uid::IdMaps,
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use specs::{Entities, Entity, Join, Read, WriteStorage}; use specs::{Entities, Entity, Join, Read, WriteStorage};
@ -13,7 +13,7 @@ impl<'a> System<'a> for Sys {
type SystemData = ( type SystemData = (
Entities<'a>, Entities<'a>,
WriteStorage<'a, LootOwner>, WriteStorage<'a, LootOwner>,
Read<'a, UidAllocator>, Read<'a, IdMaps>,
Read<'a, GroupManager>, Read<'a, GroupManager>,
); );
@ -23,7 +23,7 @@ impl<'a> System<'a> for Sys {
fn run( fn run(
_job: &mut Job<Self>, _job: &mut Job<Self>,
(entities, mut loot_owners, uid_allocator, group_manager): Self::SystemData, (entities, mut loot_owners, id_maps, group_manager): Self::SystemData,
) { ) {
// Find and remove expired loot ownership. Loot ownership is expired when either // Find and remove expired loot ownership. Loot ownership is expired when either
// the expiry time has passed, or the owner no longer exists // the expiry time has passed, or the owner no longer exists
@ -32,8 +32,8 @@ impl<'a> System<'a> for Sys {
.filter(|(_, loot_owner)| { .filter(|(_, loot_owner)| {
loot_owner.expired() loot_owner.expired()
|| match loot_owner.owner() { || match loot_owner.owner() {
LootOwnerKind::Player(uid) => uid_allocator LootOwnerKind::Player(uid) => id_maps
.lookup_entity(uid) .uid_entity(uid)
.map_or(true, |entity| !entities.is_alive(entity)), .map_or(true, |entity| !entities.is_alive(entity)),
LootOwnerKind::Group(group) => group_manager.group_info(group).is_none(), LootOwnerKind::Group(group) => group_manager.group_info(group).is_none(),
} }

View File

@ -11,7 +11,7 @@ use common::{
recipe::{default_component_recipe_book, default_recipe_book, default_repair_recipe_book}, recipe::{default_component_recipe_book, default_recipe_book, default_repair_recipe_book},
resources::TimeOfDay, resources::TimeOfDay,
shared_server_config::ServerConstants, shared_server_config::ServerConstants,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use common_base::prof_span; use common_base::prof_span;
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
@ -54,7 +54,7 @@ pub struct ReadData<'a> {
trackers: TrackedStorages<'a>, trackers: TrackedStorages<'a>,
_healths: ReadStorage<'a, Health>, // used by plugin feature _healths: ReadStorage<'a, Health>, // used by plugin feature
_plugin_mgr: ReadPlugin<'a>, // used by plugin feature _plugin_mgr: ReadPlugin<'a>, // used by plugin feature
_uid_allocator: Read<'a, UidAllocator>, // used by plugin feature _id_maps: Read<'a, IdMaps>, // used by plugin feature
} }
/// This system will handle new messages from clients /// This system will handle new messages from clients
@ -146,7 +146,7 @@ impl<'a> System<'a> for Sys {
// NOTE: Only the old player list is provided, to avoid scalability // NOTE: Only the old player list is provided, to avoid scalability
// bottlenecks. // bottlenecks.
player: (&players).into(), player: (&players).into(),
uid_allocator: &read_data._uid_allocator, id_maps: &read_data._id_maps,
}; };
// NOTE: this is just default value. // NOTE: this is just default value.

View File

@ -1,7 +1,7 @@
use common::{ use common::{
comp::{Alignment, Pet, PhysicsState, Pos}, comp::{Alignment, Pet, PhysicsState, Pos},
terrain::TerrainGrid, terrain::TerrainGrid,
uid::UidAllocator, uid::IdMaps,
}; };
use common_ecs::{Job, Origin, Phase, System}; use common_ecs::{Job, Origin, Phase, System};
use specs::{Entities, Entity, Join, Read, ReadExpect, ReadStorage, WriteStorage}; use specs::{Entities, Entity, Join, Read, ReadExpect, ReadStorage, WriteStorage};
@ -17,7 +17,7 @@ impl<'a> System<'a> for Sys {
ReadStorage<'a, Alignment>, ReadStorage<'a, Alignment>,
ReadStorage<'a, Pet>, ReadStorage<'a, Pet>,
ReadStorage<'a, PhysicsState>, ReadStorage<'a, PhysicsState>,
Read<'a, UidAllocator>, Read<'a, IdMaps>,
); );
const NAME: &'static str = "pets"; const NAME: &'static str = "pets";
@ -26,7 +26,7 @@ impl<'a> System<'a> for Sys {
fn run( fn run(
_job: &mut Job<Self>, _job: &mut Job<Self>,
(entities, terrain, mut positions, alignments, pets, physics, uid_allocator): Self::SystemData, (entities, terrain, mut positions, alignments, pets, physics, id_maps): Self::SystemData,
) { ) {
const LOST_PET_DISTANCE_THRESHOLD: f32 = 200.0; const LOST_PET_DISTANCE_THRESHOLD: f32 = 200.0;
@ -38,8 +38,8 @@ impl<'a> System<'a> for Sys {
_ => None, _ => None,
}) })
.filter_map(|(pet_entity, pet_pos, owner_uid)| { .filter_map(|(pet_entity, pet_pos, owner_uid)| {
uid_allocator id_maps
.lookup_entity(owner_uid) .uid_entity(owner_uid)
.and_then(|owner_entity| { .and_then(|owner_entity| {
match (positions.get(owner_entity), physics.get(owner_entity)) { match (positions.get(owner_entity), physics.get(owner_entity)) {
(Some(position), Some(physics)) => { (Some(position), Some(physics)) => {

View File

@ -18,7 +18,7 @@ use common::{
combat, combat,
comp::{group::Role, inventory::item::MaterialStatManifest, invite::InviteKind, Stats}, comp::{group::Role, inventory::item::MaterialStatManifest, invite::InviteKind, Stats},
resources::Time, resources::Time,
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
}; };
use common_net::sync::WorldSyncExt; use common_net::sync::WorldSyncExt;
use conrod_core::{ use conrod_core::{
@ -373,7 +373,7 @@ impl<'a> Widget for Group<'a> {
let energy = client_state.ecs().read_storage::<common::comp::Energy>(); let energy = client_state.ecs().read_storage::<common::comp::Energy>();
let buffs = client_state.ecs().read_storage::<common::comp::Buffs>(); let buffs = client_state.ecs().read_storage::<common::comp::Buffs>();
let inventory = client_state.ecs().read_storage::<common::comp::Inventory>(); let inventory = client_state.ecs().read_storage::<common::comp::Inventory>();
let uid_allocator = client_state.ecs().read_resource::<UidAllocator>(); let id_maps = client_state.ecs().read_resource::<IdMaps>();
let bodies = client_state.ecs().read_storage::<common::comp::Body>(); let bodies = client_state.ecs().read_storage::<common::comp::Body>();
let poises = client_state.ecs().read_storage::<common::comp::Poise>(); let poises = client_state.ecs().read_storage::<common::comp::Poise>();
let stances = client_state.ecs().read_storage::<common::comp::Stance>(); let stances = client_state.ecs().read_storage::<common::comp::Stance>();
@ -382,7 +382,7 @@ impl<'a> Widget for Group<'a> {
let mut total_buff_count = 0; let mut total_buff_count = 0;
for (i, &uid) in group_members.iter().copied().enumerate() { for (i, &uid) in group_members.iter().copied().enumerate() {
self.show.group = true; self.show.group = true;
let entity = uid_allocator.lookup_entity(uid); let entity = id_maps.uid_entity(uid);
let stats = entity.and_then(|entity| stats.get(entity)); let stats = entity.and_then(|entity| stats.get(entity));
let skill_set = entity.and_then(|entity| skill_sets.get(entity)); let skill_set = entity.and_then(|entity| skill_sets.get(entity));
let health = entity.and_then(|entity| healths.get(entity)); let health = entity.and_then(|entity| healths.get(entity));

View File

@ -1240,9 +1240,9 @@ impl<'a> Widget for Map<'a> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let group_size = group_members.len(); let group_size = group_members.len();
//let in_group = !group_members.is_empty(); //let in_group = !group_members.is_empty();
let uid_allocator = client_state let id_maps = client_state
.ecs() .ecs()
.read_resource::<common_net::sync::UidAllocator>(); .read_resource::<common_net::sync::IdMaps>();
if state.ids.member_indicators.len() < group_size { if state.ids.member_indicators.len() < group_size {
state.update(|s| { state.update(|s| {
s.ids s.ids
@ -1251,7 +1251,7 @@ impl<'a> Widget for Map<'a> {
}) })
}; };
for (i, &uid) in group_members.iter().copied().enumerate() { for (i, &uid) in group_members.iter().copied().enumerate() {
let entity = uid_allocator.lookup_entity(uid); let entity = id_maps.uid_entity(uid);
let member_pos = entity.and_then(|entity| member_pos.get(entity)); let member_pos = entity.and_then(|entity| member_pos.get(entity));
let stats = entity.and_then(|entity| stats.get(entity)); let stats = entity.and_then(|entity| stats.get(entity));
let name = if let Some(stats) = stats { let name = if let Some(stats) = stats {
@ -1323,8 +1323,8 @@ impl<'a> Widget for Map<'a> {
.get(&uid) .get(&uid)
.map(|info| info.player_alias.as_str()) .map(|info| info.player_alias.as_str())
.or_else(|| { .or_else(|| {
uid_allocator id_maps
.lookup_entity(uid) .uid_entity(uid)
.and_then(|entity| stats.get(entity)) .and_then(|entity| stats.get(entity))
.map(|stats| stats.name.as_str()) .map(|stats| stats.name.as_str())
}) })

View File

@ -762,9 +762,9 @@ impl<'a> Widget for MiniMap<'a> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let group_size = group_members.len(); let group_size = group_members.len();
//let in_group = !group_members.is_empty(); //let in_group = !group_members.is_empty();
let uid_allocator = client_state let id_maps = client_state
.ecs() .ecs()
.read_resource::<common_net::sync::UidAllocator>(); .read_resource::<common_net::sync::IdMaps>();
if state.ids.member_indicators.len() < group_size { if state.ids.member_indicators.len() < group_size {
state.update(|s| { state.update(|s| {
s.ids s.ids
@ -773,7 +773,7 @@ impl<'a> Widget for MiniMap<'a> {
}) })
}; };
for (i, &uid) in group_members.iter().copied().enumerate() { for (i, &uid) in group_members.iter().copied().enumerate() {
let entity = uid_allocator.lookup_entity(uid); let entity = id_maps.uid_entity(uid);
let member_pos = entity.and_then(|entity| member_pos.get(entity)); let member_pos = entity.and_then(|entity| member_pos.get(entity));
if let Some(member_pos) = member_pos { if let Some(member_pos) = member_pos {

View File

@ -48,7 +48,7 @@ use common::{
resources::{DeltaTime, Time}, resources::{DeltaTime, Time},
states::{equipping, idle, utils::StageSection, wielding}, states::{equipping, idle, utils::StageSection, wielding},
terrain::{Block, SpriteKind, TerrainChunk, TerrainGrid}, terrain::{Block, SpriteKind, TerrainChunk, TerrainGrid},
uid::UidAllocator, uid::IdMaps,
util::Dir, util::Dir,
vol::{ReadVol, RectRasterableVol}, vol::{ReadVol, RectRasterableVol},
}; };
@ -829,7 +829,7 @@ impl FigureMgr {
let mut update_buf = [Default::default(); anim::MAX_BONE_COUNT]; let mut update_buf = [Default::default(); anim::MAX_BONE_COUNT];
let uid_allocator = ecs.read_resource::<UidAllocator>(); let id_maps = ecs.read_resource::<IdMaps>();
let bodies = ecs.read_storage::<Body>(); let bodies = ecs.read_storage::<Body>();
@ -1055,7 +1055,7 @@ impl FigureMgr {
let mount_transform_pos = (|| -> Option<_> { let mount_transform_pos = (|| -> Option<_> {
if let Some(is_rider) = is_rider { if let Some(is_rider) = is_rider {
let mount = is_rider.mount; let mount = is_rider.mount;
let mount = uid_allocator.lookup_entity(mount)?; let mount = id_maps.uid_entity(mount)?;
let body = *bodies.get(mount)?; let body = *bodies.get(mount)?;
let meta = self.states.get_mut(&body, &mount)?; let meta = self.states.get_mut(&body, &mount)?;
Some((meta.mount_transform, meta.mount_world_pos)) Some((meta.mount_transform, meta.mount_world_pos))

View File

@ -20,7 +20,7 @@ use common::{
spiral::Spiral2d, spiral::Spiral2d,
states::{self, utils::StageSection}, states::{self, utils::StageSection},
terrain::{Block, SpriteKind, TerrainChunk, TerrainGrid}, terrain::{Block, SpriteKind, TerrainChunk, TerrainGrid},
uid::UidAllocator, uid::IdMaps,
vol::{ReadVol, RectRasterableVol, SizedVol}, vol::{ReadVol, RectRasterableVol, SizedVol},
}; };
use common_base::span; use common_base::span;
@ -288,7 +288,7 @@ impl ParticleMgr {
let ecs = scene_data.state.ecs(); let ecs = scene_data.state.ecs();
if target if target
.and_then(|target| { .and_then(|target| {
ecs.read_resource::<UidAllocator>().lookup_entity(target) ecs.read_resource::<IdMaps>().uid_entity(target)
}) })
.and_then(|entity| { .and_then(|entity| {
ecs.read_storage::<Body>() ecs.read_storage::<Body>()

View File

@ -14,7 +14,7 @@ use common::{
link::Is, link::Is,
mounting::{Mount, Rider, VolumePos, VolumeRider}, mounting::{Mount, Rider, VolumePos, VolumeRider},
terrain::{Block, TerrainGrid, UnlockKind}, terrain::{Block, TerrainGrid, UnlockKind},
uid::{Uid, UidAllocator}, uid::{Uid, IdMaps},
util::find_dist::{Cube, Cylinder, FindDist}, util::find_dist::{Cube, Cylinder, FindDist},
vol::ReadVol, vol::ReadVol,
CachedSpatialGrid, CachedSpatialGrid,
@ -53,12 +53,12 @@ impl Interactable {
fn from_block_pos( fn from_block_pos(
terrain: &TerrainGrid, terrain: &TerrainGrid,
uid_allocator: &UidAllocator, id_maps: &IdMaps,
colliders: &ReadStorage<Collider>, colliders: &ReadStorage<Collider>,
volume_pos: VolumePos, volume_pos: VolumePos,
interaction: Interaction, interaction: Interaction,
) -> Option<Self> { ) -> Option<Self> {
let Some(block) = volume_pos.get_block(terrain, uid_allocator, colliders) else { return None }; let Some(block) = volume_pos.get_block(terrain, id_maps, colliders) else { return None };
let block_interaction = match interaction { let block_interaction = match interaction {
Interaction::Collect => { Interaction::Collect => {
// Check if this is an unlockable sprite // Check if this is an unlockable sprite
@ -346,7 +346,7 @@ pub(super) fn select_interactable(
.and_then(|(_, block_pos, interaction)| { .and_then(|(_, block_pos, interaction)| {
Interactable::from_block_pos( Interactable::from_block_pos(
&terrain, &terrain,
&ecs.read_resource::<UidAllocator>(), &ecs.read_resource::<IdMaps>(),
&ecs.read_storage(), &ecs.read_storage(),
block_pos, block_pos,
*interaction, *interaction,