naia_shared/world/component/
entity_property.rs

1use std::hash::Hash;
2
3use log::{info, warn};
4use naia_serde::{BitCounter, BitReader, BitWrite, BitWriter, Serde, SerdeErr};
5
6use crate::{
7    world::entity::{
8        entity_converters::{
9            EntityAndGlobalEntityConverter, LocalEntityAndGlobalEntityConverter,
10            LocalEntityAndGlobalEntityConverterMut,
11        },
12        global_entity::GlobalEntity,
13        local_entity::OwnedLocalEntity,
14    },
15    EntityAuthAccessor, PropertyMutator, RemoteEntity,
16};
17
18#[derive(Clone)]
19enum EntityRelation {
20    HostOwned(HostOwnedRelation),
21    RemoteOwned(RemoteOwnedRelation),
22    RemoteWaiting(RemoteWaitingRelation),
23    RemotePublic(RemotePublicRelation),
24    Delegated(DelegatedRelation),
25    Local(LocalRelation),
26    Invalid,
27}
28
29impl EntityRelation {
30    fn clone_delegated(&self) -> Option<DelegatedRelation> {
31        match self {
32            EntityRelation::Delegated(inner) => Some(inner.clone()),
33            _ => None,
34        }
35    }
36    fn clone_public(&self) -> Option<RemotePublicRelation> {
37        match self {
38            EntityRelation::RemotePublic(inner) => Some(inner.clone()),
39            _ => None,
40        }
41    }
42    fn name(&self) -> &str {
43        match self {
44            EntityRelation::HostOwned(_) => "HostOwned",
45            EntityRelation::RemoteOwned(_) => "RemoteOwned",
46            EntityRelation::RemoteWaiting(_) => "RemoteWaiting",
47            EntityRelation::RemotePublic(_) => "RemotePublic",
48            EntityRelation::Delegated(_) => "Delegated",
49            EntityRelation::Local(_) => "Local",
50            EntityRelation::Invalid => "Invalid",
51        }
52    }
53    fn write(
54        &self,
55        writer: &mut dyn BitWrite,
56        converter: &mut dyn LocalEntityAndGlobalEntityConverterMut,
57    ) {
58        match self {
59            EntityRelation::HostOwned(inner) => {
60                inner.write(writer, converter);
61            }
62            EntityRelation::RemotePublic(inner) => {
63                inner.write(writer, converter);
64            }
65            EntityRelation::Delegated(inner) => {
66                inner.write(writer, converter);
67            }
68            EntityRelation::RemoteOwned(_)
69            | EntityRelation::RemoteWaiting(_)
70            | EntityRelation::Local(_)
71            | EntityRelation::Invalid => {
72                panic!(
73                    "EntityProperty of inner type: `{:}` should never be written.",
74                    self.name()
75                );
76            }
77        }
78    }
79    fn set_mutator(&mut self, mutator: &PropertyMutator) {
80        match self {
81            EntityRelation::HostOwned(inner) => {
82                inner.set_mutator(mutator);
83            }
84            EntityRelation::RemoteOwned(_)
85            | EntityRelation::RemoteWaiting(_)
86            | EntityRelation::RemotePublic(_)
87            | EntityRelation::Local(_)
88            | EntityRelation::Delegated(_)
89            | EntityRelation::Invalid => {
90                panic!(
91                    "EntityProperty of inner type: `{:}` cannot call set_mutator()",
92                    self.name()
93                );
94            }
95        }
96    }
97    fn bit_length(&self, converter: &mut dyn LocalEntityAndGlobalEntityConverterMut) -> u32 {
98        match self {
99            EntityRelation::HostOwned(inner) => inner.bit_length(converter),
100            EntityRelation::Delegated(inner) => inner.bit_length(converter),
101            EntityRelation::RemotePublic(inner) => inner.bit_length(converter),
102            EntityRelation::RemoteOwned(_)
103            | EntityRelation::RemoteWaiting(_)
104            | EntityRelation::Local(_)
105            | EntityRelation::Invalid => {
106                panic!(
107                    "EntityProperty of inner type: `{:}` should never be written, so no need for their bit length.", self.name()
108                );
109            }
110        }
111    }
112    fn get<E: Copy + Eq + Hash>(
113        &self,
114        converter: &dyn EntityAndGlobalEntityConverter<E>,
115    ) -> Option<E> {
116        let inner_global_entity = self.get_global_entity();
117
118        if let Some(global_entity) = inner_global_entity {
119            if let Ok(world_entity) = converter.global_entity_to_entity(&global_entity) {
120                return Some(world_entity);
121            } else {
122                warn!("Could not find World Entity from Global Entity `{:?}`, in order to get the EntityRelation value!", global_entity);
123                return None;
124            }
125        }
126        warn!("Could not get EntityRelation value, because EntityRelation has no GlobalEntity!");
127        return None;
128    }
129    fn set<E: Copy + Eq + Hash>(
130        &mut self,
131        converter: &dyn EntityAndGlobalEntityConverter<E>,
132        entity: &E,
133    ) {
134        match self {
135            EntityRelation::HostOwned(inner) => {
136                inner.set(converter, entity);
137            }
138            EntityRelation::Local(inner) => {
139                inner.set(converter, entity);
140            }
141            EntityRelation::Delegated(inner) => {
142                inner.set(converter, entity);
143            }
144            EntityRelation::RemoteOwned(_)
145            | EntityRelation::RemoteWaiting(_)
146            | EntityRelation::RemotePublic(_)
147            | EntityRelation::Invalid => {
148                panic!("Remote EntityProperty should never be set manually.");
149            }
150        }
151    }
152    fn set_to_none(&mut self) {
153        match self {
154            EntityRelation::HostOwned(inner) => {
155                inner.set_to_none();
156            }
157            EntityRelation::Local(inner) => {
158                inner.set_to_none();
159            }
160            EntityRelation::Delegated(inner) => {
161                inner.set_to_none();
162            }
163            EntityRelation::RemoteOwned(_)
164            | EntityRelation::RemoteWaiting(_)
165            | EntityRelation::RemotePublic(_)
166            | EntityRelation::Invalid => {
167                panic!("Remote EntityProperty should never be set manually.");
168            }
169        }
170    }
171    fn mirror(&mut self, other: &EntityProperty) {
172        match self {
173            EntityRelation::HostOwned(inner) => match &other.inner {
174                EntityRelation::HostOwned(other_inner) => {
175                    inner.set_global_entity(&other_inner.global_entity);
176                }
177                EntityRelation::RemoteOwned(other_inner) => {
178                    inner.set_global_entity(&other_inner.global_entity);
179                }
180                EntityRelation::RemotePublic(other_inner) => {
181                    inner.set_global_entity(&other_inner.global_entity);
182                }
183                EntityRelation::Local(other_inner) => {
184                    inner.set_global_entity(&other_inner.global_entity);
185                }
186                EntityRelation::Delegated(other_inner) => {
187                    inner.set_global_entity(&other_inner.global_entity);
188                }
189                EntityRelation::RemoteWaiting(_) => {
190                    inner.mirror_waiting();
191                }
192                EntityRelation::Invalid => {
193                    panic!("Invalid EntityProperty should never be mirrored.");
194                }
195            },
196            EntityRelation::Local(inner) => match &other.inner {
197                EntityRelation::HostOwned(other_inner) => {
198                    inner.set_global_entity(&other_inner.global_entity);
199                }
200                EntityRelation::RemoteOwned(other_inner) => {
201                    inner.set_global_entity(&other_inner.global_entity);
202                }
203                EntityRelation::RemotePublic(other_inner) => {
204                    inner.set_global_entity(&other_inner.global_entity);
205                }
206                EntityRelation::Local(other_inner) => {
207                    inner.set_global_entity(&other_inner.global_entity);
208                }
209                EntityRelation::Delegated(other_inner) => {
210                    inner.set_global_entity(&other_inner.global_entity);
211                }
212                EntityRelation::RemoteWaiting(_) => {
213                    inner.mirror_waiting();
214                }
215                EntityRelation::Invalid => {
216                    panic!("Invalid EntityProperty should never be mirrored.");
217                }
218            },
219            EntityRelation::Delegated(inner) => match &other.inner {
220                EntityRelation::HostOwned(other_inner) => {
221                    inner.set_global_entity(&other_inner.global_entity);
222                }
223                EntityRelation::RemoteOwned(other_inner) => {
224                    inner.set_global_entity(&other_inner.global_entity);
225                }
226                EntityRelation::RemotePublic(other_inner) => {
227                    inner.set_global_entity(&other_inner.global_entity);
228                }
229                EntityRelation::Local(other_inner) => {
230                    inner.set_global_entity(&other_inner.global_entity);
231                }
232                EntityRelation::Delegated(other_inner) => {
233                    inner.set_global_entity(&other_inner.global_entity);
234                }
235                EntityRelation::RemoteWaiting(_) => {
236                    inner.mirror_waiting();
237                }
238                EntityRelation::Invalid => {
239                    panic!("Invalid EntityProperty should never be mirrored.");
240                }
241            },
242            EntityRelation::RemoteOwned(_)
243            | EntityRelation::RemoteWaiting(_)
244            | EntityRelation::RemotePublic(_) => {
245                panic!("Remote EntityProperty should never be set manually.");
246            }
247            EntityRelation::Invalid => {
248                panic!("Invalid EntityProperty should never be set manually.");
249            }
250        }
251    }
252    fn waiting_local_entity(&self) -> Option<RemoteEntity> {
253        match self {
254            EntityRelation::HostOwned(_)
255            | EntityRelation::RemoteOwned(_)
256            | EntityRelation::RemotePublic(_)
257            | EntityRelation::Local(_)
258            | EntityRelation::Delegated(_)
259            | EntityRelation::Invalid => None,
260            EntityRelation::RemoteWaiting(inner) => Some(inner.remote_entity),
261        }
262    }
263    pub fn write_local_entity(
264        &self,
265        converter: &dyn LocalEntityAndGlobalEntityConverter,
266        writer: &mut BitWriter,
267    ) {
268        match self {
269            EntityRelation::RemoteOwned(inner) => {
270                inner.write_local_entity(converter, writer);
271            }
272            EntityRelation::RemotePublic(inner) => {
273                inner.write_local_entity(converter, writer);
274            }
275            EntityRelation::Delegated(inner) => {
276                inner.write_local_entity(converter, writer);
277            }
278            EntityRelation::HostOwned(_)
279            | EntityRelation::RemoteWaiting(_)
280            | EntityRelation::Local(_)
281            | EntityRelation::Invalid => {
282                panic!(
283                    "This type of EntityProperty: `{:?}` can't use this method",
284                    self.name()
285                );
286            }
287        }
288    }
289
290    fn get_global_entity(&self) -> Option<GlobalEntity> {
291        match self {
292            EntityRelation::HostOwned(inner) => inner.global_entity,
293            EntityRelation::RemoteOwned(inner) => inner.global_entity,
294            EntityRelation::RemotePublic(inner) => inner.global_entity,
295            EntityRelation::Local(inner) => inner.global_entity,
296            EntityRelation::Delegated(inner) => inner.global_entity,
297            EntityRelation::RemoteWaiting(_) | EntityRelation::Invalid => None,
298        }
299    }
300}
301
302#[derive(Clone)]
303pub struct EntityProperty {
304    inner: EntityRelation,
305}
306
307impl EntityProperty {
308    // Should only be used by Messages
309    pub fn new() -> Self {
310        Self {
311            inner: EntityRelation::HostOwned(HostOwnedRelation::new()),
312        }
313    }
314
315    // Should only be used by Components
316    pub fn host_owned(mutator_index: u8) -> Self {
317        Self {
318            inner: EntityRelation::HostOwned(HostOwnedRelation::with_mutator(mutator_index)),
319        }
320    }
321
322    // Read and create from Remote host
323    pub fn new_read(
324        reader: &mut BitReader,
325        converter: &dyn LocalEntityAndGlobalEntityConverter,
326    ) -> Result<Self, SerdeErr> {
327        let exists = bool::de(reader)?;
328        if exists {
329            // LocalEntity is reversed on write, don't worry here
330            let local_entity = OwnedLocalEntity::de(reader)?;
331
332            if let Ok(global_entity) = local_entity.convert_to_global(converter) {
333                let mut new_impl = RemoteOwnedRelation::new_empty();
334                new_impl.global_entity = Some(global_entity);
335
336                let new_self = Self {
337                    inner: EntityRelation::RemoteOwned(new_impl),
338                };
339
340                Ok(new_self)
341            } else {
342                if let OwnedLocalEntity::Remote(remote_entity_id) = local_entity {
343                    let new_impl = RemoteWaitingRelation::new(RemoteEntity::new(remote_entity_id));
344
345                    let new_self = Self {
346                        inner: EntityRelation::RemoteWaiting(new_impl),
347                    };
348
349                    Ok(new_self)
350                } else {
351                    Ok(Self {
352                        inner: EntityRelation::Invalid,
353                    })
354                }
355            }
356        } else {
357            let mut new_impl = RemoteOwnedRelation::new_empty();
358            new_impl.global_entity = None;
359
360            let new_self = Self {
361                inner: EntityRelation::RemoteOwned(new_impl),
362            };
363
364            Ok(new_self)
365        }
366    }
367
368    pub fn read_write(reader: &mut BitReader, writer: &mut BitWriter) -> Result<(), SerdeErr> {
369        let exists = bool::de(reader)?;
370        exists.ser(writer);
371        if exists {
372            OwnedLocalEntity::de(reader)?.ser(writer);
373        }
374        Ok(())
375    }
376
377    pub fn read(
378        &mut self,
379        reader: &mut BitReader,
380        converter: &dyn LocalEntityAndGlobalEntityConverter,
381    ) -> Result<(), SerdeErr> {
382        let exists = bool::de(reader)?;
383        let local_entity_opt = if exists {
384            Some(OwnedLocalEntity::de(reader)?)
385        } else {
386            None
387        };
388
389        let eval = (
390            self.inner.clone_public(),
391            self.inner.clone_delegated(),
392            local_entity_opt,
393            local_entity_opt.map(|local_entity| local_entity.convert_to_global(converter)),
394        );
395        self.inner = match eval {
396            (None, None, None, None) => {
397                EntityRelation::RemoteOwned(RemoteOwnedRelation::new_empty())
398            }
399            (None, None, Some(local_entity), Some(Err(_))) => {
400                info!("1 setting inner to RemoteWaiting");
401                EntityRelation::RemoteWaiting(RemoteWaitingRelation::new(
402                    local_entity.take_remote(),
403                ))
404            }
405            (None, None, Some(_), Some(Ok(global_entity))) => EntityRelation::RemoteOwned(
406                RemoteOwnedRelation::new_with_value(Some(global_entity)),
407            ),
408            (Some(public_relation), None, None, None) => EntityRelation::RemotePublic(
409                RemotePublicRelation::new(None, public_relation.index, &public_relation.mutator),
410            ),
411            (Some(public_relation), None, Some(local_entity), Some(Err(_))) => {
412                EntityRelation::RemoteWaiting(RemoteWaitingRelation::new_public(
413                    local_entity.take_remote(),
414                    public_relation.index,
415                    &public_relation.mutator,
416                ))
417            }
418            (Some(public_relation), None, Some(_), Some(Ok(global_entity))) => {
419                EntityRelation::RemotePublic(RemotePublicRelation::new(
420                    Some(global_entity),
421                    public_relation.index,
422                    &public_relation.mutator,
423                ))
424            }
425            (None, Some(delegated_relation), None, None) => {
426                EntityRelation::Delegated(delegated_relation.read_none())
427            }
428            (None, Some(delegated_relation), Some(local_entity), Some(Err(_))) => {
429                info!("3 setting inner to RemoteWaiting");
430                EntityRelation::RemoteWaiting(RemoteWaitingRelation::new_delegated(
431                    local_entity.take_remote(),
432                    &delegated_relation.auth_accessor,
433                    &delegated_relation.mutator,
434                    delegated_relation.index,
435                ))
436            }
437            (None, Some(delegate_relation), Some(_), Some(Ok(global_entity))) => {
438                EntityRelation::Delegated(delegate_relation.read_some(global_entity))
439            }
440            _ => {
441                panic!("This shouldn't be possible. Unknown read case for EntityProperty.")
442            }
443        };
444
445        Ok(())
446    }
447
448    pub fn waiting_complete(&mut self, converter: &dyn LocalEntityAndGlobalEntityConverter) {
449        match &mut self.inner {
450            EntityRelation::RemoteOwned(_)
451            | EntityRelation::RemotePublic(_)
452            | EntityRelation::Delegated(_) => {
453                // already complete! this is intended behavior:
454                // waiting Component/Message only sets EntityProperty to RemoteWaiting if it doesn't have an entity in-scope
455                // but the entire Component/Message is put on the waitlist if even one of it's EntityProperties is RemoteWaiting
456                // and `waiting_complete` is called on all of them, so we skip the already in-scope ones here
457            }
458            EntityRelation::RemoteWaiting(inner) => {
459                let new_global_entity = {
460                    if let Ok(global_entity) =
461                        converter.remote_entity_to_global_entity(&inner.remote_entity)
462                    {
463                        Some(global_entity)
464                    } else {
465                        panic!("Error completing waiting EntityProperty! Could not convert RemoteEntity to GlobalEntity!");
466                        // I hit this 2 times
467                    }
468                };
469
470                if let Some((index, mutator)) = &inner.will_publish {
471                    if let Some(accessor) = &inner.will_delegate {
472                        // will publish and delegate
473                        let mut new_impl =
474                            DelegatedRelation::new(new_global_entity, accessor, mutator, *index);
475                        new_impl.global_entity = new_global_entity;
476                        self.inner = EntityRelation::Delegated(new_impl);
477                    } else {
478                        // will publish but not delegate
479                        let new_impl =
480                            RemotePublicRelation::new(new_global_entity, *index, mutator);
481                        self.inner = EntityRelation::RemotePublic(new_impl);
482                    }
483                } else {
484                    // will not publish or delegate
485                    let mut new_impl = RemoteOwnedRelation::new_empty();
486                    new_impl.global_entity = new_global_entity;
487                    self.inner = EntityRelation::RemoteOwned(new_impl);
488                }
489            }
490            EntityRelation::HostOwned(_) | EntityRelation::Local(_) | EntityRelation::Invalid => {
491                panic!(
492                    "Can't complete EntityProperty of type: `{:?}`!",
493                    self.inner.name()
494                );
495            }
496        }
497    }
498
499    /// Migrate Remote Property to Public version
500    pub fn remote_publish(&mut self, mutator_index: u8, mutator: &PropertyMutator) {
501        match &mut self.inner {
502            EntityRelation::RemoteOwned(inner) => {
503                let inner_value = inner.global_entity.clone();
504                self.inner = EntityRelation::RemotePublic(RemotePublicRelation::new(
505                    inner_value,
506                    mutator_index,
507                    mutator,
508                ));
509            }
510            EntityRelation::RemoteWaiting(inner) => {
511                inner.remote_publish(mutator_index, mutator);
512            }
513            EntityRelation::HostOwned(_)
514            | EntityRelation::RemotePublic(_)
515            | EntityRelation::Local(_)
516            | EntityRelation::Delegated(_)
517            | EntityRelation::Invalid => {
518                panic!(
519                    "EntityProperty of type: `{:?}` should never be made public twice.",
520                    self.inner.name()
521                );
522            }
523        }
524    }
525
526    /// Migrate Remote Property to Public version
527    pub fn remote_unpublish(&mut self) {
528        match &mut self.inner {
529            EntityRelation::RemotePublic(inner) => {
530                let inner_value = inner.global_entity.clone();
531                self.inner = EntityRelation::RemoteOwned(RemoteOwnedRelation {
532                    global_entity: inner_value,
533                });
534            }
535            EntityRelation::RemoteWaiting(inner) => {
536                inner.remote_unpublish();
537            }
538            EntityRelation::HostOwned(_)
539            | EntityRelation::RemoteOwned(_)
540            | EntityRelation::Local(_)
541            | EntityRelation::Delegated(_)
542            | EntityRelation::Invalid => {
543                panic!(
544                    "EntityProperty of type: `{:?}` should never be unpublished.",
545                    self.inner.name()
546                );
547            }
548        }
549    }
550
551    /// Migrate Host/RemotePublic Property to Delegated version
552    pub fn enable_delegation(
553        &mut self,
554        accessor: &EntityAuthAccessor,
555        mutator_opt: Option<(u8, &PropertyMutator)>,
556    ) {
557        let inner_value = self.inner.get_global_entity();
558
559        let (mutator_index, mutator) = {
560            if let Some((mutator_index, mutator)) = mutator_opt {
561                // with mutator
562                match &mut self.inner {
563                    EntityRelation::RemoteOwned(_) => (mutator_index, mutator),
564                    EntityRelation::RemoteWaiting(inner) => {
565                        inner.remote_delegate(accessor);
566                        return;
567                    }
568                    EntityRelation::Local(_)
569                    | EntityRelation::RemotePublic(_)
570                    | EntityRelation::HostOwned(_)
571                    | EntityRelation::Delegated(_)
572                    | EntityRelation::Invalid => {
573                        panic!(
574                            "EntityProperty of type `{:?}` should never enable delegation.",
575                            self.inner.name()
576                        );
577                    }
578                }
579            } else {
580                // without mutator
581                match &mut self.inner {
582                    EntityRelation::HostOwned(inner) => (
583                        inner.index,
584                        inner
585                            .mutator
586                            .as_ref()
587                            .expect("should have a mutator by now"),
588                    ),
589                    EntityRelation::RemotePublic(inner) => (inner.index, &inner.mutator),
590                    EntityRelation::Local(_)
591                    | EntityRelation::RemoteOwned(_)
592                    | EntityRelation::RemoteWaiting(_)
593                    | EntityRelation::Delegated(_)
594                    | EntityRelation::Invalid => {
595                        panic!(
596                            "EntityProperty of type `{:?}` should never enable delegation.",
597                            self.inner.name()
598                        );
599                    }
600                }
601            }
602        };
603
604        self.inner = EntityRelation::Delegated(DelegatedRelation::new(
605            inner_value,
606            accessor,
607            mutator,
608            mutator_index,
609        ));
610    }
611
612    /// Migrate Delegated Property to Host-Owned (Public) version
613    pub fn disable_delegation(&mut self) {
614        match &mut self.inner {
615            EntityRelation::Delegated(inner) => {
616                let inner_value = inner.global_entity.clone();
617                let mut new_inner = HostOwnedRelation::with_mutator(inner.index);
618                new_inner.set_mutator(&inner.mutator);
619                new_inner.global_entity = inner_value;
620                self.inner = EntityRelation::HostOwned(new_inner);
621            }
622            EntityRelation::RemoteWaiting(inner) => {
623                inner.remote_undelegate();
624            }
625            EntityRelation::HostOwned(_)
626            | EntityRelation::RemoteOwned(_)
627            | EntityRelation::RemotePublic(_)
628            | EntityRelation::Local(_)
629            | EntityRelation::Invalid => {
630                panic!(
631                    "EntityProperty of type: `{:?}` should never disable delegation.",
632                    self.inner.name()
633                );
634            }
635        }
636    }
637
638    /// Migrate Host Property to Local version
639    pub fn localize(&mut self) {
640        match &mut self.inner {
641            EntityRelation::HostOwned(inner) => {
642                let inner_value = inner.global_entity.clone();
643                self.inner = EntityRelation::Local(LocalRelation::new(inner_value));
644            }
645            EntityRelation::Delegated(inner) => {
646                let inner_value = inner.global_entity.clone();
647                self.inner = EntityRelation::Local(LocalRelation::new(inner_value));
648            }
649            EntityRelation::RemoteOwned(_)
650            | EntityRelation::RemotePublic(_)
651            | EntityRelation::RemoteWaiting(_)
652            | EntityRelation::Local(_)
653            | EntityRelation::Invalid => {
654                panic!(
655                    "EntityProperty of type: `{:?}` should never be made local.",
656                    self.inner.name()
657                );
658            }
659        }
660    }
661
662    // Pass-through
663
664    pub fn set_mutator(&mut self, mutator: &PropertyMutator) {
665        self.inner.set_mutator(mutator);
666    }
667
668    // Serialization / deserialization
669
670    pub fn bit_length(&self, converter: &mut dyn LocalEntityAndGlobalEntityConverterMut) -> u32 {
671        self.inner.bit_length(converter)
672    }
673
674    pub fn write(
675        &self,
676        writer: &mut dyn BitWrite,
677        converter: &mut dyn LocalEntityAndGlobalEntityConverterMut,
678    ) {
679        self.inner.write(writer, converter);
680    }
681
682    pub fn get<E: Copy + Eq + Hash>(
683        &self,
684        converter: &dyn EntityAndGlobalEntityConverter<E>,
685    ) -> Option<E> {
686        self.inner.get(converter)
687    }
688
689    pub fn set<E: Copy + Eq + Hash>(
690        &mut self,
691        converter: &dyn EntityAndGlobalEntityConverter<E>,
692        entity: &E,
693    ) {
694        self.inner.set(converter, entity);
695    }
696
697    pub fn set_to_none(&mut self) {
698        self.inner.set_to_none();
699    }
700
701    pub fn mirror(&mut self, other: &EntityProperty) {
702        self.inner.mirror(other);
703    }
704
705    pub fn waiting_local_entity(&self) -> Option<RemoteEntity> {
706        self.inner.waiting_local_entity()
707    }
708
709    // used for writing out ready local entity value when splitting updates
710    pub fn write_local_entity(
711        &self,
712        converter: &dyn LocalEntityAndGlobalEntityConverter,
713        writer: &mut BitWriter,
714    ) {
715        self.inner.write_local_entity(converter, writer);
716    }
717}
718
719// HostOwnedRelation
720#[derive(Clone)]
721struct HostOwnedRelation {
722    global_entity: Option<GlobalEntity>,
723    mutator: Option<PropertyMutator>,
724    index: u8,
725}
726
727impl HostOwnedRelation {
728    pub fn new() -> Self {
729        Self {
730            global_entity: None,
731            mutator: None,
732            index: 0,
733        }
734    }
735
736    pub fn with_mutator(mutate_index: u8) -> Self {
737        Self {
738            global_entity: None,
739            mutator: None,
740            index: mutate_index,
741        }
742    }
743
744    pub fn set_mutator(&mut self, mutator: &PropertyMutator) {
745        self.mutator = Some(mutator.clone_new());
746    }
747
748    pub fn write(
749        &self,
750        writer: &mut dyn BitWrite,
751        converter: &mut dyn LocalEntityAndGlobalEntityConverterMut,
752    ) {
753        let Some(global_entity) = &self.global_entity else {
754            false.ser(writer);
755            return;
756        };
757        let Ok(owned_local_entity) = converter.get_or_reserve_entity(global_entity) else {
758            false.ser(writer);
759            return;
760        };
761
762        // Must reverse the LocalEntity because the Host<->Remote
763        // relationship inverts after this data goes over the wire
764        let reversed_local_entity = owned_local_entity.to_reversed();
765
766        true.ser(writer);
767        reversed_local_entity.ser(writer);
768    }
769
770    pub fn bit_length(&self, converter: &mut dyn LocalEntityAndGlobalEntityConverterMut) -> u32 {
771        let mut bit_counter = BitCounter::new(0, 0, u32::MAX);
772        self.write(&mut bit_counter, converter);
773        return bit_counter.bits_needed();
774    }
775
776    pub fn set<E: Copy + Eq + Hash>(
777        &mut self,
778        converter: &dyn EntityAndGlobalEntityConverter<E>,
779        world_entity: &E,
780    ) {
781        if let Ok(new_global_entity) = converter.entity_to_global_entity(world_entity) {
782            self.global_entity = Some(new_global_entity);
783            self.mutate();
784        } else {
785            warn!("Could not find Global Entity from World Entity, in order to set the EntityRelation value!");
786            return;
787        }
788    }
789
790    pub fn set_to_none(&mut self) {
791        self.global_entity = None;
792        self.mutate();
793    }
794
795    pub fn mirror_waiting(&mut self) {
796        self.global_entity = None;
797        self.mutate();
798    }
799
800    pub fn set_global_entity(&mut self, other_global_entity: &Option<GlobalEntity>) {
801        self.global_entity = other_global_entity.clone();
802        self.mutate();
803    }
804
805    fn mutate(&mut self) {
806        let _success = if let Some(mutator) = &mut self.mutator {
807            mutator.mutate(self.index)
808        } else {
809            false
810        };
811    }
812}
813
814// RemoteOwnedRelation
815#[derive(Clone, Debug)]
816struct RemoteOwnedRelation {
817    global_entity: Option<GlobalEntity>,
818}
819
820impl RemoteOwnedRelation {
821    fn new_empty() -> Self {
822        Self {
823            global_entity: None,
824        }
825    }
826
827    fn new_with_value(global_entity: Option<GlobalEntity>) -> Self {
828        Self { global_entity }
829    }
830
831    pub fn write_local_entity(
832        &self,
833        converter: &dyn LocalEntityAndGlobalEntityConverter,
834        writer: &mut BitWriter,
835    ) {
836        let Some(global_entity) = &self.global_entity else {
837            false.ser(writer);
838            return;
839        };
840        let Ok(owned_entity) = converter.global_entity_to_owned_entity(&global_entity) else {
841            warn!("Could not find Local Entity from Global Entity, in order to write the EntityRelation value! This should not happen.");
842            false.ser(writer);
843            return;
844        };
845        true.ser(writer);
846        owned_entity.ser(writer);
847    }
848}
849
850// RemoteWaitingRelation
851#[derive(Clone)]
852struct RemoteWaitingRelation {
853    remote_entity: RemoteEntity,
854    will_publish: Option<(u8, PropertyMutator)>,
855    will_delegate: Option<EntityAuthAccessor>,
856}
857
858impl RemoteWaitingRelation {
859    fn new(remote_entity: RemoteEntity) -> Self {
860        Self {
861            remote_entity,
862            will_publish: None,
863            will_delegate: None,
864        }
865    }
866    fn new_public(remote_entity: RemoteEntity, index: u8, mutator: &PropertyMutator) -> Self {
867        Self {
868            remote_entity,
869            will_publish: Some((index, mutator.clone_new())),
870            will_delegate: None,
871        }
872    }
873    fn new_delegated(
874        local_entity: RemoteEntity,
875        auth_accessor: &EntityAuthAccessor,
876        mutator: &PropertyMutator,
877        index: u8,
878    ) -> Self {
879        Self {
880            remote_entity: local_entity,
881            will_publish: Some((index, mutator.clone_new())),
882            will_delegate: Some(auth_accessor.clone()),
883        }
884    }
885    pub(crate) fn remote_publish(&mut self, index: u8, mutator: &PropertyMutator) {
886        self.will_publish = Some((index, mutator.clone_new()));
887    }
888    pub(crate) fn remote_unpublish(&mut self) {
889        self.will_publish = None;
890    }
891    pub(crate) fn remote_delegate(&mut self, accessor: &EntityAuthAccessor) {
892        self.will_delegate = Some(accessor.clone());
893    }
894    pub(crate) fn remote_undelegate(&mut self) {
895        self.will_delegate = None;
896    }
897}
898
899// RemoteOwnedRelation
900#[derive(Clone)]
901struct RemotePublicRelation {
902    global_entity: Option<GlobalEntity>,
903    mutator: PropertyMutator,
904    index: u8,
905}
906
907impl RemotePublicRelation {
908    pub fn new(global_entity: Option<GlobalEntity>, index: u8, mutator: &PropertyMutator) -> Self {
909        Self {
910            global_entity,
911            mutator: mutator.clone_new(),
912            index,
913        }
914    }
915
916    pub fn bit_length(&self, converter: &mut dyn LocalEntityAndGlobalEntityConverterMut) -> u32 {
917        let mut bit_counter = BitCounter::new(0, 0, u32::MAX);
918        self.write(&mut bit_counter, converter);
919        return bit_counter.bits_needed();
920    }
921
922    pub fn write(
923        &self,
924        writer: &mut dyn BitWrite,
925        converter: &mut dyn LocalEntityAndGlobalEntityConverterMut,
926    ) {
927        let Some(global_entity) = &self.global_entity else {
928            false.ser(writer);
929            return;
930        };
931        let Ok(local_entity) = converter.get_or_reserve_entity(global_entity) else {
932            false.ser(writer);
933            return;
934        };
935
936        // Must reverse the LocalEntity because the Host<->Remote
937        // relationship inverts after this data goes over the wire
938        let reversed_local_entity = local_entity.to_reversed();
939
940        true.ser(writer);
941        reversed_local_entity.ser(writer);
942    }
943
944    pub fn write_local_entity(
945        &self,
946        converter: &dyn LocalEntityAndGlobalEntityConverter,
947        writer: &mut BitWriter,
948    ) {
949        let Some(global_entity) = &self.global_entity else {
950            false.ser(writer);
951            return;
952        };
953        let Ok(owned_entity) = converter.global_entity_to_owned_entity(&global_entity) else {
954            warn!("Could not find Local Entity from Global Entity, in order to write the EntityRelation value! This should not happen.");
955            false.ser(writer);
956            return;
957        };
958        true.ser(writer);
959        owned_entity.ser(writer);
960    }
961}
962
963// DelegatedRelation
964#[derive(Clone)]
965struct DelegatedRelation {
966    global_entity: Option<GlobalEntity>,
967    auth_accessor: EntityAuthAccessor,
968    mutator: PropertyMutator,
969    index: u8,
970}
971
972impl DelegatedRelation {
973    /// Create a new DelegatedRelation
974    pub fn new(
975        global_entity: Option<GlobalEntity>,
976        auth_accessor: &EntityAuthAccessor,
977        mutator: &PropertyMutator,
978        index: u8,
979    ) -> Self {
980        Self {
981            global_entity,
982            auth_accessor: auth_accessor.clone(),
983            mutator: mutator.clone_new(),
984            index,
985        }
986    }
987
988    pub fn set<E: Copy + Eq + Hash>(
989        &mut self,
990        converter: &dyn EntityAndGlobalEntityConverter<E>,
991        world_entity: &E,
992    ) {
993        if let Ok(new_global_entity) = converter.entity_to_global_entity(world_entity) {
994            self.global_entity = Some(new_global_entity);
995            self.mutate();
996        } else {
997            warn!("Could not find Global Entity from World Entity, in order to set the EntityRelation value!");
998            return;
999        }
1000    }
1001
1002    pub fn set_to_none(&mut self) {
1003        self.global_entity = None;
1004        self.mutate();
1005    }
1006
1007    pub fn set_global_entity(&mut self, other_global_entity: &Option<GlobalEntity>) {
1008        self.global_entity = other_global_entity.clone();
1009        self.mutate();
1010    }
1011
1012    pub fn mirror_waiting(&mut self) {
1013        self.global_entity = None;
1014        self.mutate();
1015    }
1016
1017    pub fn read_none(mut self) -> Self {
1018        if self.can_read() {
1019            self.global_entity = None;
1020            self.mutate();
1021        }
1022
1023        self
1024    }
1025
1026    pub fn read_some(mut self, global_entity: GlobalEntity) -> Self {
1027        if self.can_read() {
1028            self.global_entity = Some(global_entity);
1029            self.mutate();
1030        }
1031
1032        self
1033    }
1034
1035    pub fn bit_length(&self, converter: &mut dyn LocalEntityAndGlobalEntityConverterMut) -> u32 {
1036        if !self.can_write() {
1037            panic!("Must have Authority over Entity before performing this operation.");
1038        }
1039        let mut bit_counter = BitCounter::new(0, 0, u32::MAX);
1040        self.write(&mut bit_counter, converter);
1041        return bit_counter.bits_needed();
1042    }
1043
1044    pub fn write(
1045        &self,
1046        writer: &mut dyn BitWrite,
1047        converter: &mut dyn LocalEntityAndGlobalEntityConverterMut,
1048    ) {
1049        if !self.can_write() {
1050            panic!("Must have Authority over Entity before performing this operation.");
1051        }
1052
1053        let Some(global_entity) = &self.global_entity else {
1054            false.ser(writer);
1055            return;
1056        };
1057        let Ok(local_entity) = converter.get_or_reserve_entity(global_entity) else {
1058            false.ser(writer);
1059            return;
1060        };
1061
1062        // Must reverse the LocalEntity because the Host<->Remote
1063        // relationship inverts after this data goes over the wire
1064        let reversed_local_entity = local_entity.to_reversed();
1065
1066        true.ser(writer);
1067        reversed_local_entity.ser(writer);
1068    }
1069
1070    pub fn write_local_entity(
1071        &self,
1072        converter: &dyn LocalEntityAndGlobalEntityConverter,
1073        writer: &mut BitWriter,
1074    ) {
1075        let Some(global_entity) = &self.global_entity else {
1076            false.ser(writer);
1077            return;
1078        };
1079        let Ok(host_entity) = converter.global_entity_to_owned_entity(&global_entity) else {
1080            warn!("Could not find Local Entity from Global Entity, in order to write the EntityRelation value! This should not happen.");
1081            false.ser(writer);
1082            return;
1083        };
1084        true.ser(writer);
1085        host_entity.ser(writer);
1086    }
1087
1088    fn mutate(&mut self) {
1089        if !self.can_mutate() {
1090            panic!("Must request authority to mutate a Delegated EntityProperty.");
1091        }
1092        let _success = self.mutator.mutate(self.index);
1093    }
1094
1095    fn can_mutate(&self) -> bool {
1096        self.auth_accessor.auth_status().can_mutate()
1097    }
1098
1099    fn can_read(&self) -> bool {
1100        self.auth_accessor.auth_status().can_read()
1101    }
1102
1103    fn can_write(&self) -> bool {
1104        self.auth_accessor.auth_status().can_write()
1105    }
1106}
1107
1108// LocalRelation
1109#[derive(Clone, Debug)]
1110struct LocalRelation {
1111    global_entity: Option<GlobalEntity>,
1112}
1113
1114impl LocalRelation {
1115    pub fn new(global_entity: Option<GlobalEntity>) -> Self {
1116        Self { global_entity }
1117    }
1118
1119    pub fn set<E: Copy + Eq + Hash>(
1120        &mut self,
1121        converter: &dyn EntityAndGlobalEntityConverter<E>,
1122        world_entity: &E,
1123    ) {
1124        if let Ok(new_global_entity) = converter.entity_to_global_entity(world_entity) {
1125            self.global_entity = Some(new_global_entity);
1126        } else {
1127            warn!("Could not find Global Entity from World Entity, in order to set the EntityRelation value!");
1128            return;
1129        }
1130    }
1131
1132    pub fn set_to_none(&mut self) {
1133        self.global_entity = None;
1134    }
1135
1136    pub fn mirror_waiting(&mut self) {
1137        self.global_entity = None;
1138    }
1139
1140    pub fn set_global_entity(&mut self, other_global_entity: &Option<GlobalEntity>) {
1141        self.global_entity = other_global_entity.clone();
1142    }
1143}