naia-client 0.25.0

Provides a cross-platform client that can send/receive messages to/from a server, and has a pool of in-scope entities/components that is synced with the server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};

use log::info;

use naia_shared::{
    AuthorityError, ComponentKind, ComponentKinds, EntityAuthAccessor, EntityAuthStatus,
    GlobalDiffHandler, GlobalEntity, GlobalWorldManagerType, HostAuthHandler, HostType,
    InScopeEntities, MutChannelType, PropertyMutator, Replicate,
};

use super::global_entity_record::GlobalEntityRecord;
use crate::{
    world::{entity_owner::EntityOwner, mut_channel::MutChannelData},
    Publicity,
};

pub struct GlobalWorldManager {
    /// Manages authorization to mutate delegated Entities
    auth_handler: HostAuthHandler,
    /// Manages mutation of individual Component properties
    diff_handler: Arc<RwLock<GlobalDiffHandler>>,
    /// Information about entities in the internal ECS World
    entity_records: HashMap<GlobalEntity, GlobalEntityRecord>,
}

impl GlobalWorldManager {
    pub fn new() -> Self {
        Self {
            auth_handler: HostAuthHandler::new(),
            diff_handler: Arc::new(RwLock::new(GlobalDiffHandler::new())),
            entity_records: HashMap::default(),
        }
    }

    // Entities
    pub fn entities(&self) -> Vec<GlobalEntity> {
        let mut output = Vec::new();

        for global_entity in self.entity_records.keys() {
            output.push(*global_entity);
        }

        output
    }

    pub fn has_entity(&self, global_entity: &GlobalEntity) -> bool {
        self.entity_records.contains_key(global_entity)
    }

    pub fn entity_owner(&self, global_entity: &GlobalEntity) -> Option<EntityOwner> {
        if let Some(record) = self.entity_records.get(global_entity) {
            return Some(record.owner());
        }
        None
    }

    // Spawn
    pub fn host_spawn_entity(&mut self, global_entity: &GlobalEntity) {
        if self.entity_records.contains_key(global_entity) {
            panic!("entity already initialized!");
        }
        // info!("Inserting entity record for {:?}", global_entity);
        self.entity_records
            .insert(*global_entity, GlobalEntityRecord::new(EntityOwner::Client));
    }

    // Despawn
    pub fn host_despawn_entity(
        &mut self,
        global_entity: &GlobalEntity,
    ) -> Option<GlobalEntityRecord> {
        // Clean up associated components
        for component_kind in self.component_kinds(global_entity).unwrap() {
            self.host_remove_component(global_entity, &component_kind);
        }

        // Despawn from World Record
        if !self.entity_records.contains_key(global_entity) {
            panic!("entity does not exist!");
        }

        self.entity_records.remove(global_entity)
    }

    // Component Kinds
    pub fn component_kinds(&self, global_entity: &GlobalEntity) -> Option<Vec<ComponentKind>> {
        if !self.entity_records.contains_key(global_entity) {
            return None;
        }

        let component_kind_set = self
            .entity_records
            .get(global_entity)
            .unwrap()
            .component_kinds();
        Some(component_kind_set.iter().copied().collect())
    }

    // Insert Component
    pub fn host_insert_component(
        &mut self,
        component_kinds: &ComponentKinds,
        global_entity: &GlobalEntity,
        component: &mut dyn Replicate,
    ) {
        let component_kind = component.kind();
        let diff_mask_length: u8 = component.diff_mask_size();

        if !self.entity_records.contains_key(global_entity) {
            panic!("entity does not exist!");
        }
        self.entity_records
            .get_mut(global_entity)
            .unwrap()
            .insert_component(component_kind);

        let prop_mutator = self.register_component(
            component_kinds,
            global_entity,
            &component_kind,
            diff_mask_length,
        );

        component.set_mutator(&prop_mutator);
    }

    /// Returns true if this component was already registered for host-side
    /// tracking (i.e. the entity is delegated and the GlobalDiffHandler
    /// already has this entity+component registered).  Used by callers to
    /// skip redundant setup when authority is granted to a client for an
    /// entity whose delegation was already enabled.
    pub fn component_already_host_registered(
        &self,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
    ) -> bool {
        self.entity_is_delegated(global_entity)
            && self
                .diff_handler
                .read()
                .expect("GlobalDiffHandler lock")
                .has_component(global_entity, component_kind)
    }

    // Remove Component
    pub fn host_remove_component(
        &mut self,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
    ) {
        if !self.entity_records.contains_key(global_entity) {
            panic!("entity does not exist!");
        }
        self.entity_records
            .get_mut(global_entity)
            .unwrap()
            .remove_component(component_kind);

        self.diff_handler
            .as_ref()
            .write()
            .expect("Haven't initialized DiffHandler")
            .deregister_component(global_entity, component_kind);
    }

    pub fn remote_spawn_entity(&mut self, global_entity: &GlobalEntity) {
        if self.entity_records.contains_key(global_entity) {
            panic!("entity already initialized!");
        }
        // info!("Remote spawning entity record for {:?}", global_entity);
        self.entity_records
            .insert(*global_entity, GlobalEntityRecord::new(EntityOwner::Server));
    }

    pub fn remove_entity_record(&mut self, global_entity: &GlobalEntity) {
        self.entity_records
            .remove(global_entity)
            .expect("Cannot despawn non-existant entity!");
    }

    pub fn remote_insert_component(
        &mut self,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
    ) {
        // info!("Remote inserting component {:?} for {:?}", component_kind, global_entity);

        if !self.entity_records.contains_key(global_entity) {
            panic!("entity does not exist!");
        }
        self.entity_records
            .get_mut(global_entity)
            .unwrap()
            .insert_component(*component_kind);
    }

    pub fn remove_component_record(
        &mut self,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
    ) {
        if !self.entity_records.contains_key(global_entity) {
            panic!("entity does not exist!");
        }
        self.entity_records
            .get_mut(global_entity)
            .unwrap()
            .remove_component(component_kind);
    }

    pub(crate) fn entity_replication_config(
        &self,
        global_entity: &GlobalEntity,
    ) -> Option<Publicity> {
        if let Some(record) = self.entity_records.get(global_entity) {
            return Some(record.replication_config());
        }
        None
    }

    pub(crate) fn entity_publish(&mut self, global_entity: &GlobalEntity) {
        let Some(record) = self.entity_records.get_mut(global_entity) else {
            panic!("entity record does not exist!");
        };
        record.set_replication_config(Publicity::Public);
    }

    pub(crate) fn entity_unpublish(&mut self, global_entity: &GlobalEntity) {
        let Some(record) = self.entity_records.get_mut(global_entity) else {
            panic!("entity record does not exist!");
        };
        record.set_replication_config(Publicity::Private);
    }

    pub(crate) fn entity_has_component(
        &self,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
    ) -> bool {
        if let Some(record) = self.entity_records.get(global_entity) {
            return record.has_component(component_kind);
        }
        false
    }

    pub(crate) fn entity_is_delegated(&self, global_entity: &GlobalEntity) -> bool {
        if let Some(record) = self.entity_records.get(global_entity) {
            return record.replication_config() == Publicity::Delegated;
        }
        false
    }

    pub(crate) fn entity_register_auth_for_delegation(&mut self, global_entity: &GlobalEntity) {
        let Some(record) = self.entity_records.get_mut(global_entity) else {
            panic!("entity record does not exist!");
        };
        if record.replication_config() != Publicity::Public {
            panic!(
                "Can only enable delegation on an Entity that is Public! Config: {:?}",
                record.replication_config()
            );
        }
        self.auth_handler
            .register_entity(HostType::Client, global_entity);
    }

    pub(crate) fn entity_enable_delegation(&mut self, global_entity: &GlobalEntity) {
        // info!("Enabling delegation for {:?}", global_entity);

        let Some(record) = self.entity_records.get_mut(global_entity) else {
            panic!("entity record does not exist!");
        };
        if record.replication_config() != Publicity::Public {
            panic!("Can only enable delegation on an Entity that is Public!");
        }

        record.set_replication_config(Publicity::Delegated);

        if record.owner().is_client() {
            record.set_owner(EntityOwner::Server);
        }
    }

    pub(crate) fn entity_disable_delegation(&mut self, global_entity: &GlobalEntity) {
        let Some(record) = self.entity_records.get_mut(global_entity) else {
            panic!("entity record does not exist!");
        };
        if record.replication_config() != Publicity::Delegated {
            panic!("Can only disable delegation on an Entity that is Delegated!");
        }

        record.set_replication_config(Publicity::Public);
        self.auth_handler.deregister_entity(global_entity);
    }

    pub(crate) fn entity_authority_status(
        &self,
        global_entity: &GlobalEntity,
    ) -> Option<EntityAuthStatus> {
        self.auth_handler
            .auth_status(global_entity)
            .map(|host_status| host_status.status())
    }

    pub(crate) fn entity_request_authority(
        &mut self,
        global_entity: &GlobalEntity,
    ) -> Result<(), AuthorityError> {
        if !self.has_entity(global_entity) {
            // Entity is not in scope — client has no record of it at all.
            return Err(AuthorityError::NotInScope);
        }
        if !self.entity_is_delegated(global_entity) {
            return Err(AuthorityError::NotDelegated);
        }
        let Some(auth_status) = self.auth_handler.auth_status(global_entity) else {
            // Entity is delegated in our records but auth tracking hasn't been
            // initialised yet — treat as not-in-scope (transitional state).
            return Err(AuthorityError::NotInScope);
        };
        if !auth_status.can_request() {
            // Authority is not Available (e.g. already Requested or Granted).
            return Err(AuthorityError::NotAvailable);
        }
        self.auth_handler
            .set_auth_status(global_entity, EntityAuthStatus::Requested);
        Ok(())
    }

    pub(crate) fn entity_release_authority(
        &mut self,
        global_entity: &GlobalEntity,
    ) -> Result<(), AuthorityError> {
        if !self.has_entity(global_entity) {
            return Err(AuthorityError::NotInScope);
        }
        if !self.entity_is_delegated(global_entity) {
            return Err(AuthorityError::NotDelegated);
        }
        let Some(auth_status) = self.auth_handler.auth_status(global_entity) else {
            return Err(AuthorityError::NotInScope);
        };
        if !auth_status.can_release() {
            return Err(AuthorityError::NotHolder);
        }
        self.auth_handler
            .set_auth_status(global_entity, EntityAuthStatus::Releasing);
        Ok(())
    }

    pub(crate) fn entity_update_authority(
        &self,
        global_entity: &GlobalEntity,
        new_auth_status: EntityAuthStatus,
    ) {
        self.auth_handler
            .set_auth_status(global_entity, new_auth_status);
    }
}

impl GlobalWorldManagerType for GlobalWorldManager {
    fn component_kinds(&self, global_entity: &GlobalEntity) -> Option<Vec<ComponentKind>> {
        self.component_kinds(global_entity)
    }

    fn entity_can_relate_to_user(&self, global_entity: &GlobalEntity, _user_key: &u64) -> bool {
        if let Some(record) = self.entity_records.get(global_entity) {
            return match record.owner() {
                EntityOwner::Server | EntityOwner::Client => true,
                EntityOwner::Local => false,
            };
        }
        false
    }

    fn new_mut_channel(&self, diff_mask_length: u8) -> Arc<RwLock<dyn MutChannelType>> {
        let mut_channel = MutChannelData::new(diff_mask_length);
        Arc::new(RwLock::new(mut_channel))
    }

    fn diff_handler(&self) -> Arc<RwLock<GlobalDiffHandler>> {
        self.diff_handler.clone()
    }

    fn register_component(
        &self,
        component_kinds: &ComponentKinds,
        global_entity: &GlobalEntity,
        component_kind: &ComponentKind,
        diff_mask_length: u8,
    ) -> PropertyMutator {
        let mut_sender = self
            .diff_handler
            .as_ref()
            .write()
            .expect("DiffHandler should be initialized")
            .register_component(
                component_kinds,
                self,
                global_entity,
                component_kind,
                diff_mask_length,
            );

        PropertyMutator::new(mut_sender)
    }

    fn get_entity_auth_accessor(&self, global_entity: &GlobalEntity) -> EntityAuthAccessor {
        self.auth_handler.get_accessor(global_entity)
    }

    fn entity_needs_mutator_for_delegation(&self, global_entity: &GlobalEntity) -> bool {
        if let Some(record) = self.entity_records.get(global_entity) {
            let server_owned = record.owner() == EntityOwner::Server;
            let is_public = record.replication_config() == Publicity::Public;

            return server_owned && is_public;
        }
        info!("entity_needs_mutator_for_delegation: entity does not have record");
        false
    }

    fn entity_is_replicating(&self, global_entity: &GlobalEntity) -> bool {
        let Some(record) = self.entity_records.get(global_entity) else {
            panic!("entity does not have record");
        };
        record.is_replicating()
    }

    fn entity_is_static(&self, _global_entity: &GlobalEntity) -> bool {
        // Client entities are never static in the static-entity sense
        false
    }
}

impl InScopeEntities<GlobalEntity> for GlobalWorldManager {
    fn has_entity(&self, global_entity: &GlobalEntity) -> bool {
        self.entity_records.contains_key(global_entity)
    }
}