naia_hecs_shared/
world_wrapper.rs

1use std::{
2    default::Default,
3    ops::{Deref, DerefMut},
4};
5
6use hecs::{Entity, World};
7
8use naia_shared::{
9    ComponentFieldUpdate, ComponentKind, ComponentUpdate, LocalEntityAndGlobalEntityConverter,
10    ReplicaDynMutWrapper, ReplicaDynRefWrapper, ReplicaMutWrapper, ReplicaRefWrapper, Replicate,
11    SerdeErr, WorldMutType, WorldRefType,
12};
13
14use crate::{
15    component_ref::{ComponentMut, ComponentRef},
16    Protocol, WorldData,
17};
18
19#[derive(Default)]
20pub struct WorldWrapper {
21    pub inner: World,
22    data: WorldData,
23}
24
25impl WorldWrapper {
26    pub fn wrap(protocol: &mut Protocol, world: World) -> Self {
27        Self {
28            inner: world,
29            data: protocol.world_data(),
30        }
31    }
32
33    pub fn new(protocol: &mut Protocol) -> Self {
34        Self {
35            inner: World::new(),
36            data: protocol.world_data(),
37        }
38    }
39}
40
41impl Deref for WorldWrapper {
42    type Target = World;
43
44    fn deref(&self) -> &Self::Target {
45        &self.inner
46    }
47}
48
49impl DerefMut for WorldWrapper {
50    fn deref_mut(&mut self) -> &mut Self::Target {
51        &mut self.inner
52    }
53}
54
55impl WorldRefType<Entity> for &WorldWrapper {
56    fn has_entity(&self, entity: &Entity) -> bool {
57        has_entity(&self.inner, entity)
58    }
59
60    fn entities(&self) -> Vec<Entity> {
61        entities(&self.inner)
62    }
63
64    fn has_component<R: Replicate>(&self, entity: &Entity) -> bool {
65        has_component::<R>(&self.inner, entity)
66    }
67
68    fn has_component_of_kind(&self, entity: &Entity, component_kind: &ComponentKind) -> bool {
69        has_component_of_kind(&self.inner, &self.data, entity, component_kind)
70    }
71
72    fn component<R: Replicate>(&self, entity: &Entity) -> Option<ReplicaRefWrapper<R>> {
73        component::<R>(&self.inner, entity)
74    }
75
76    fn component_of_kind<'a>(
77        &'a self,
78        entity: &Entity,
79        component_kind: &ComponentKind,
80    ) -> Option<ReplicaDynRefWrapper<'a>> {
81        component_of_kind(&self.inner, &self.data, entity, component_kind)
82    }
83}
84
85impl WorldRefType<Entity> for &mut WorldWrapper {
86    fn has_entity(&self, entity: &Entity) -> bool {
87        has_entity(&self.inner, entity)
88    }
89
90    fn entities(&self) -> Vec<Entity> {
91        entities(&self.inner)
92    }
93
94    fn has_component<R: Replicate>(&self, entity: &Entity) -> bool {
95        has_component::<R>(&self.inner, entity)
96    }
97
98    fn has_component_of_kind(&self, entity: &Entity, component_kind: &ComponentKind) -> bool {
99        has_component_of_kind(&self.inner, &self.data, entity, component_kind)
100    }
101
102    fn component<R: Replicate>(&self, entity: &Entity) -> Option<ReplicaRefWrapper<R>> {
103        component::<R>(&self.inner, entity)
104    }
105
106    fn component_of_kind<'a>(
107        &'a self,
108        entity: &Entity,
109        component_kind: &ComponentKind,
110    ) -> Option<ReplicaDynRefWrapper<'a>> {
111        component_of_kind(&self.inner, &self.data, entity, component_kind)
112    }
113}
114
115impl WorldMutType<Entity> for &mut WorldWrapper {
116    fn spawn_entity(&mut self) -> Entity {
117        self.inner.spawn(())
118    }
119
120    fn duplicate_entity(&mut self, entity: &Entity) -> Entity {
121        let new_entity = WorldMutType::<Entity>::spawn_entity(self);
122
123        WorldMutType::<Entity>::duplicate_components(self, &new_entity, entity);
124
125        new_entity
126    }
127
128    fn duplicate_components(&mut self, mutable_entity: &Entity, immutable_entity: &Entity) {
129        for component_kind in WorldMutType::<Entity>::component_kinds(self, immutable_entity) {
130            let mut component_copy_opt: Option<Box<dyn Replicate>> = None;
131            if let Some(component) = self.component_of_kind(immutable_entity, &component_kind) {
132                component_copy_opt = Some(component.copy_to_box());
133            }
134            if let Some(component_copy) = component_copy_opt {
135                self.insert_boxed_component(mutable_entity, component_copy);
136            }
137        }
138    }
139
140    fn despawn_entity(&mut self, entity: &Entity) {
141        self.inner
142            .despawn(*entity)
143            .expect("error despawning Entity");
144    }
145
146    fn component_kinds(&mut self, entity: &Entity) -> Vec<ComponentKind> {
147        let mut kinds = Vec::new();
148
149        if let Ok(entity_ref) = self.inner.entity(*entity) {
150            for component_type in entity_ref.component_types() {
151                kinds.push(ComponentKind::from(component_type));
152            }
153        }
154
155        kinds
156    }
157
158    fn component_mut<R: Replicate>(&mut self, entity: &Entity) -> Option<ReplicaMutWrapper<R>> {
159        if let Ok(hecs_mut) = self.inner.get::<&mut R>(*entity) {
160            let wrapper = ComponentMut(hecs_mut);
161            let component_mut = ReplicaMutWrapper::new(wrapper);
162            return Some(component_mut);
163        }
164        None
165    }
166
167    fn component_mut_of_kind<'a>(
168        &'a mut self,
169        entity: &Entity,
170        component_kind: &ComponentKind,
171    ) -> Option<ReplicaDynMutWrapper<'a>> {
172        if let Some(access) = self.data.component_access(component_kind) {
173            if let Some(component) = access.component_mut(&mut self.inner, entity) {
174                return Some(component);
175            }
176        }
177        return None;
178    }
179
180    fn component_apply_update(
181        &mut self,
182        converter: &dyn LocalEntityAndGlobalEntityConverter,
183        entity: &Entity,
184        component_kind: &ComponentKind,
185        update: ComponentUpdate,
186    ) -> Result<(), SerdeErr> {
187        if let Some(access) = self.data.component_access(component_kind) {
188            if let Some(mut component) = access.component_mut(&mut self.inner, entity) {
189                component.read_apply_update(converter, update)?;
190            }
191        }
192        Ok(())
193    }
194
195    fn component_apply_field_update(
196        &mut self,
197        converter: &dyn LocalEntityAndGlobalEntityConverter,
198        entity: &Entity,
199        component_kind: &ComponentKind,
200        update: ComponentFieldUpdate,
201    ) -> Result<(), SerdeErr> {
202        if let Some(access) = self.data.component_access(component_kind) {
203            if let Some(mut component) = access.component_mut(&mut self.inner, entity) {
204                let _update_result = component.read_apply_field_update(converter, update);
205            }
206        }
207        Ok(())
208    }
209
210    fn mirror_entities(&mut self, new_entity: &Entity, old_entity: &Entity) {
211        for component_kind in WorldMutType::<Entity>::component_kinds(self, old_entity) {
212            WorldMutType::<Entity>::mirror_components(
213                self,
214                new_entity,
215                old_entity,
216                &component_kind,
217            );
218        }
219    }
220
221    fn mirror_components(
222        &mut self,
223        mutable_entity: &Entity,
224        immutable_entity: &Entity,
225        component_kind: &ComponentKind,
226    ) {
227        if let Some(accessor) = self.data.component_access(component_kind) {
228            accessor.mirror_components(&mut self.inner, mutable_entity, immutable_entity);
229        }
230    }
231
232    fn insert_component<R: Replicate>(&mut self, entity: &Entity, component: R) {
233        self.inner
234            .insert_one(*entity, component)
235            .expect("error inserting Component");
236    }
237
238    fn insert_boxed_component(&mut self, entity: &Entity, boxed_component: Box<dyn Replicate>) {
239        let component_kind = boxed_component.kind();
240        if let Some(accessor) = self.data.component_access(&component_kind) {
241            return accessor.insert_component(&mut self.inner, entity, boxed_component);
242        } else {
243            panic!("shouldn't happen")
244        }
245    }
246
247    fn remove_component<R: Replicate>(&mut self, entity: &Entity) -> Option<R> {
248        self.inner.remove_one::<R>(*entity).ok()
249    }
250
251    fn remove_component_of_kind(
252        &mut self,
253        entity: &Entity,
254        component_kind: &ComponentKind,
255    ) -> Option<Box<dyn Replicate>> {
256        if let Some(accessor) = self.data.component_access(component_kind) {
257            return accessor.remove_component(&mut self.inner, entity);
258        }
259        None
260    }
261}
262
263// private static methods
264
265fn has_entity(world: &World, entity: &Entity) -> bool {
266    world.contains(*entity)
267}
268
269fn entities(world: &World) -> Vec<Entity> {
270    let mut output = Vec::new();
271
272    for entity in world.iter() {
273        output.push(entity.entity());
274    }
275
276    output
277}
278
279fn has_component<R: Replicate>(world: &World, entity: &Entity) -> bool {
280    let result = world.get::<&R>(*entity);
281    result.is_ok()
282}
283
284fn has_component_of_kind(
285    world: &World,
286    world_data: &WorldData,
287    entity: &Entity,
288    component_kind: &ComponentKind,
289) -> bool {
290    return component_of_kind(world, world_data, entity, component_kind).is_some();
291}
292
293fn component<'a, R: Replicate>(
294    world: &'a World,
295    entity: &Entity,
296) -> Option<ReplicaRefWrapper<'a, R>> {
297    if let Ok(hecs_ref) = world.get::<&R>(*entity) {
298        let wrapper = ComponentRef(hecs_ref);
299        let component_ref = ReplicaRefWrapper::new(wrapper);
300        return Some(component_ref);
301    }
302    None
303}
304
305fn component_of_kind<'a>(
306    world: &'a World,
307    world_data: &'a WorldData,
308    entity: &Entity,
309    component_kind: &ComponentKind,
310) -> Option<ReplicaDynRefWrapper<'a>> {
311    if let Some(access) = world_data.component_access(component_kind) {
312        return access.component(world, entity);
313    }
314    None
315}