bevy_replicon/core/replicated_clients/
client_visibility.rs

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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use bevy::{
    ecs::entity::{EntityHashMap, EntityHashSet},
    prelude::*,
    utils::hashbrown::hash_map::Entry,
};

use super::VisibilityPolicy;

/// Entity visibility settings for a client.
pub struct ClientVisibility {
    filter: VisibilityFilter,

    /// Visibility for a specific entity that has been cached for re-referencing.
    ///
    /// Used as an optimization by server replication.
    cached_visibility: Visibility,
}

impl ClientVisibility {
    /// Creates a new instance based on the preconfigured policy.
    pub(super) fn new(policy: VisibilityPolicy) -> Self {
        match policy {
            VisibilityPolicy::All => Self::with_filter(VisibilityFilter::All),
            VisibilityPolicy::Blacklist => Self::with_filter(VisibilityFilter::Blacklist {
                list: Default::default(),
                added: Default::default(),
                removed: Default::default(),
            }),
            VisibilityPolicy::Whitelist => Self::with_filter(VisibilityFilter::Whitelist {
                list: Default::default(),
                added: Default::default(),
                removed: Default::default(),
            }),
        }
    }

    /// Creates a new instance with a specific filter.
    fn with_filter(filter: VisibilityFilter) -> Self {
        Self {
            filter,
            cached_visibility: Default::default(),
        }
    }

    /// Resets the filter state to as it was after [`Self::new`].
    ///
    /// `cached_visibility` remains untouched.
    pub(super) fn clear(&mut self) {
        match &mut self.filter {
            VisibilityFilter::All => (),
            VisibilityFilter::Blacklist {
                list,
                added,
                removed,
            } => {
                list.clear();
                added.clear();
                removed.clear();
            }
            VisibilityFilter::Whitelist {
                list,
                added,
                removed,
            } => {
                list.clear();
                added.clear();
                removed.clear();
            }
        }
    }

    /// Updates list information and its sets based on the filter.
    ///
    /// Should be called after each tick.
    pub(crate) fn update(&mut self) {
        match &mut self.filter {
            VisibilityFilter::All => (),
            VisibilityFilter::Blacklist {
                list,
                added,
                removed,
            } => {
                // Remove all entities queued for removal.
                for entity in removed.drain() {
                    list.remove(&entity);
                }
                added.clear();
            }
            VisibilityFilter::Whitelist {
                list,
                added,
                removed,
            } => {
                // Change all recently added entities to `WhitelistInfo::Visible`
                // from `WhitelistInfo::JustVisible`.
                for entity in added.drain() {
                    list.insert(entity, WhitelistInfo::Visible);
                }
                removed.clear();
            }
        }
    }

    /// Removes a despawned entity tracked by this client.
    pub(super) fn remove_despawned(&mut self, entity: Entity) {
        match &mut self.filter {
            VisibilityFilter::All { .. } => (),
            VisibilityFilter::Blacklist {
                list,
                added,
                removed,
            } => {
                if list.remove(&entity).is_some() {
                    added.remove(&entity);
                    removed.remove(&entity);
                }
            }
            VisibilityFilter::Whitelist {
                list,
                added,
                removed,
            } => {
                if list.remove(&entity).is_some() {
                    added.remove(&entity);
                    removed.remove(&entity);
                }
            }
        }
    }

    /// Drains all entities for which visibility was lost during this tick.
    pub(super) fn drain_lost_visibility(&mut self) -> impl Iterator<Item = Entity> + '_ {
        match &mut self.filter {
            VisibilityFilter::All { .. } => VisibilityLostIter::AllVisible,
            VisibilityFilter::Blacklist { added, .. } => VisibilityLostIter::Lost(added.drain()),
            VisibilityFilter::Whitelist { removed, .. } => {
                VisibilityLostIter::Lost(removed.drain())
            }
        }
    }

    /// Sets visibility for a specific entity.
    ///
    /// Does nothing if the visibility policy for the server plugin is set to [`VisibilityPolicy::All`].
    pub fn set_visibility(&mut self, entity: Entity, visibile: bool) {
        match &mut self.filter {
            VisibilityFilter::All { .. } => {
                if visibile {
                    debug!(
                        "ignoring visibility enable due to {:?}",
                        VisibilityPolicy::All
                    );
                } else {
                    warn!(
                        "ignoring visibility disable due to {:?}",
                        VisibilityPolicy::All
                    );
                }
            }
            VisibilityFilter::Blacklist {
                list,
                added,
                removed,
            } => {
                if visibile {
                    // If the entity is already visibile, do nothing.
                    let Entry::Occupied(mut entry) = list.entry(entity) else {
                        return;
                    };

                    // If the entity was previously added in this tick, then undo it.
                    if added.remove(&entity) {
                        entry.remove();
                        return;
                    }

                    // For blacklisting an entity we don't remove the entity right away.
                    // Instead we mark it as queued for removal and remove it
                    // later in `Self::update`. This allows us to avoid accessing
                    // the blacklist's `removed` field in `Self::get_visibility_state`.
                    entry.insert(BlacklistInfo::QueuedForRemoval);
                    removed.insert(entity);
                } else {
                    // If the entity is already registered, reset its removal status.
                    if list.insert(entity, BlacklistInfo::Hidden).is_some() {
                        removed.remove(&entity);
                        return;
                    };

                    added.insert(entity);
                }
            }
            VisibilityFilter::Whitelist {
                list,
                added,
                removed,
            } => {
                if visibile {
                    // Similar to blacklist removal, we don't just add the entity to the list.
                    // Instead we mark it as `WhitelistInfo::JustAdded` and then set it to
                    // 'WhitelistInfo::Visible' in `Self::update`.
                    // This allows us to avoid accessing the whitelist's `added` field in
                    // `Self::get_visibility_state`.
                    if *list.entry(entity).or_insert(WhitelistInfo::JustAdded)
                        == WhitelistInfo::JustAdded
                    {
                        // Do not mark an entry as newly added if the entry was already in the list.
                        added.insert(entity);
                    }
                    removed.remove(&entity);
                } else {
                    // If the entity is not in the whitelist, do nothing.
                    if list.remove(&entity).is_none() {
                        return;
                    }

                    // If the entity was added in this tick, then undo it.
                    if added.remove(&entity) {
                        return;
                    }

                    removed.insert(entity);
                }
            }
        }
    }

    /// Checks if a specific entity is visible.
    pub fn is_visible(&self, entity: Entity) -> bool {
        match self.get_visibility_state(entity) {
            Visibility::Hidden => false,
            Visibility::Gained | Visibility::Visible => true,
        }
    }

    /// Caches visibility for a specific entity.
    ///
    /// Can be obtained later from [`Self::cached_visibility`].
    pub(crate) fn cache_visibility(&mut self, entity: Entity) {
        self.cached_visibility = self.get_visibility_state(entity);
    }

    /// Returns visibility cached by the last call of [`Self::cache_visibility`].
    pub(crate) fn cached_visibility(&self) -> Visibility {
        self.cached_visibility
    }

    /// Returns visibility of a specific entity.
    fn get_visibility_state(&self, entity: Entity) -> Visibility {
        match &self.filter {
            VisibilityFilter::All => Visibility::Visible,
            VisibilityFilter::Blacklist { list, .. } => match list.get(&entity) {
                Some(BlacklistInfo::QueuedForRemoval) => Visibility::Gained,
                Some(BlacklistInfo::Hidden) => Visibility::Hidden,
                None => Visibility::Visible,
            },
            VisibilityFilter::Whitelist { list, .. } => match list.get(&entity) {
                Some(WhitelistInfo::JustAdded) => Visibility::Gained,
                Some(WhitelistInfo::Visible) => Visibility::Visible,
                None => Visibility::Hidden,
            },
        }
    }
}

/// Filter for [`ClientVisibility`] based on [`VisibilityPolicy`].
enum VisibilityFilter {
    All,
    Blacklist {
        /// All blacklisted entities and an indicator of whether they are in the queue for deletion
        /// at the end of this tick.
        list: EntityHashMap<BlacklistInfo>,

        /// All entities that were removed from the list in this tick.
        ///
        /// Visibility of these entities has been lost.
        added: EntityHashSet,

        /// All entities that were added to the list in this tick.
        ///
        /// Visibility of these entities has been gained.
        removed: EntityHashSet,
    },
    Whitelist {
        /// All whitelisted entities and an indicator of whether they were added to the list in
        /// this tick.
        list: EntityHashMap<WhitelistInfo>,

        /// All entities that were added to the list in this tick.
        ///
        /// Visibility of these entities has been gained.
        added: EntityHashSet,

        /// All entities that were removed from the list in this tick.
        ///
        /// Visibility of these entities has been lost.
        removed: EntityHashSet,
    },
}

#[derive(PartialEq, Clone, Copy)]
enum WhitelistInfo {
    Visible,
    JustAdded,
}

#[derive(PartialEq, Clone, Copy)]
enum BlacklistInfo {
    Hidden,
    QueuedForRemoval,
}

/// Visibility state for an entity in the current tick, from the perspective of one client.
///
/// Note that the distinction between 'lost visibility' and 'don't have visibility' is not exposed here.
/// There is only [`Visibility::Hidden`] to encompass both variants.
///
/// Lost visibility is handled separately with [`ClientVisibility::drain_lost_visibility`].
#[derive(PartialEq, Default, Clone, Copy)]
pub(crate) enum Visibility {
    /// The client does not have visibility of the entity in this tick.
    #[default]
    Hidden,
    /// The client gained visibility of the entity in this tick (it was not visible in the previous tick).
    Gained,
    /// The entity is visible to the client (and was visible in the previous tick).
    Visible,
}

enum VisibilityLostIter<T> {
    AllVisible,
    Lost(T),
}

impl<T: Iterator> Iterator for VisibilityLostIter<T> {
    type Item = T::Item;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            VisibilityLostIter::AllVisible => None,
            VisibilityLostIter::Lost(entities) => entities.next(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::All);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(
            visibility.is_visible(Entity::PLACEHOLDER),
            "shouldn't have any effect for this policy"
        );
    }

    #[test]
    fn blacklist_insertion() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Blacklist);
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));

        visibility.update();

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn blacklist_empty_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Blacklist);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn blacklist_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Blacklist);
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        visibility.update();
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(removed.contains(&Entity::PLACEHOLDER));

        visibility.update();

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn blacklist_insertion_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Blacklist);

        // Insert and remove from the list.
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn blacklist_duplicate_insertion() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Blacklist);
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        visibility.update();

        // Duplicate insertion.
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Blacklist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn whitelist_insertion() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Whitelist);
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a whitelist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));

        visibility.update();

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn whitelist_empty_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Whitelist);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a whitelist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn whitelist_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Whitelist);
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        visibility.update();
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a whitelist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(removed.contains(&Entity::PLACEHOLDER));

        visibility.update();

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = &visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn whitelist_insertion_removal() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Whitelist);

        // Insert and remove from the list.
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        visibility.set_visibility(Entity::PLACEHOLDER, false);
        assert!(!visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(!list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }

    #[test]
    fn whitelist_duplicate_insertion() {
        let mut visibility = ClientVisibility::new(VisibilityPolicy::Whitelist);
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        visibility.update();

        // Duplicate insertion.
        visibility.set_visibility(Entity::PLACEHOLDER, true);
        assert!(visibility.is_visible(Entity::PLACEHOLDER));

        let VisibilityFilter::Whitelist {
            list,
            added,
            removed,
        } = visibility.filter
        else {
            panic!("filter should be a blacklist");
        };

        assert!(list.contains_key(&Entity::PLACEHOLDER));
        assert!(!added.contains(&Entity::PLACEHOLDER));
        assert!(!removed.contains(&Entity::PLACEHOLDER));
    }
}