bevy_replicon 0.42.0

A server-authoritative replication crate for Bevy
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
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
use core::marker::PhantomData;

use bevy::{ecs::component::Immutable, prelude::*};

use crate::shared::replication::registry::{
    ReplicationRegistry, component_mask::ComponentMask, receive_fns::MutWrite,
};

/// Component that controls remote entity visibility.
///
/// Should be registered via [`crate::server::visibility::AppVisibilityExt`].
pub trait VisibilityFilter: Component<Mutability = Immutable> {
    /**
    Component on the client entity that will be passed to [`Self::is_visible`].

    # Examples

    Different component for the client and replicated entities:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component)]
    #[component(immutable)]
    struct Moderator;

    #[derive(Component)]
    #[component(immutable)]
    struct SensitiveInfo;

    impl VisibilityFilter for SensitiveInfo {
        type ClientComponent = Moderator;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            // Only moderators can see entities with sensitive information.
            component.is_some()
        }
    }
    ```

    You can use `Self` to check for same component on both the client and replicated entities:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct SpectatorOnly;

    impl VisibilityFilter for SpectatorOnly {
        type ClientComponent = Self;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            // Visible only if the client also has `SpectatorOnly`.
            component.is_some()
        }
    }
    ```
     */
    type ClientComponent: Component<Mutability = Immutable>;

    /**
    Defines what data is affected when the filter denies visibility.

    - To hide the entire entity, this type must be [`Entity`].
    - To hide a single component on the entity, this type must be [`SingleComponent`].
    - To hide more than one component on the entity, this type must be a tuple of those [`Component`]s.

    # Examples

    Hide the entire entity:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct Team(u8);

    impl VisibilityFilter for Team {
        type ClientComponent = Self;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            component.is_some_and(|c| self == c)
        }
    }
    ```

    Hide only a single component:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct Team(u8);

    impl VisibilityFilter for Team {
        type ClientComponent = Self;
        type Scope = SingleComponent<Health>;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            component.is_some_and(|c| self == c)
        }
    }

    #[derive(Component)]
    struct Health(u8);
    ```

    Hide multiple components:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct Team(u8);

    impl VisibilityFilter for Team {
        type ClientComponent = Self;
        type Scope = (Health, Stats);

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            component.is_some_and(|c| self == c)
        }
    }

    #[derive(Component)]
    struct Health(u8);

    #[derive(Component)]
    struct Stats {
    // ...
    }
    ```
    */
    type Scope: FilterScope;

    /**
    Controls when a [`Self::Scope`] is present on a client.

    - For an entity scope, this describes when the entity is spawned or despawned.
    - For a component scope, it describes when the components are inserted or removed.

    Changes are replicated only while the scope is visible.

    # Examples

    Keep a previously discovered entity on the client when it leaves
    the client's field of view.

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component)]
    #[component(immutable)]
    struct VisibilityPosition(Vec2);

    impl VisibilityFilter for VisibilityPosition {
        type ClientComponent = ClientView;
        type Scope = Entity;
        const LIFETIME: ScopeLifetime = ScopeLifetime::AfterFirstVisibility;

        fn is_visible(
            &self,
            _client: Entity,
            component: Option<&Self::ClientComponent>,
        ) -> bool {
            component.is_some_and(|view| {
                self.0.distance_squared(view.position) <= view.radius.powi(2)
            })
        }
    }

    #[derive(Component)]
    #[component(immutable)]
    struct ClientView {
        position: Vec2,
        radius: f32,
    }
    ```

    Replicate an entity to all clients except its owner.
    The owner receives only the initial state, but simulates on its own.

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component)]
    #[component(immutable)]
    struct OwnedBy(Entity);

    impl VisibilityFilter for OwnedBy {
        type ClientComponent = AuthorizedClient;
        type Scope = Entity;
        const LIFETIME: ScopeLifetime = ScopeLifetime::AlwaysPresent;

        fn is_visible(&self, client: Entity, _: Option<&Self::ClientComponent>) -> bool {
            self.0 != client
        }
    }
    ```
     */
    const LIFETIME: ScopeLifetime = ScopeLifetime::WhileVisible;

    /**
    Returns `true` if a client should see [`Self::Scope`] for an entity with this component
    based on [`Self::ClientComponent`] .

    # Examples

    Visible if the component is present on both the entity and the client:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    /// Only astral players can see other astral entities.
    #[derive(Component)]
    #[component(immutable)] // Component should be immutable.
    struct Astral;

    impl VisibilityFilter for Astral {
        type ClientComponent = Self;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            component.is_some()
        }
    }
    ```

    Visible if the component is present on the entity, but missing on the client:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component)]
    #[component(immutable)]
    struct Unit;

    #[derive(Component)]
    #[component(immutable)]
    struct Blind;

    impl VisibilityFilter for Blind {
        type ClientComponent = Unit;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            // Blind clients cannot see units.
            component.is_none()
        }
    }
    ```

    Visible if the entity and the client have equal component values:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct Team(u8);

    impl VisibilityFilter for Team {
        type ClientComponent = Self;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            // Visible if the client belongs to the same team.
            component.is_some_and(|c| self == c)
        }
    }
    ```

    Visible if client has all bits the entity has:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    use bitflags::bitflags;

    bitflags! {
        #[derive(Component, Clone, Copy)]
        #[component(immutable)]
        pub(crate) struct RemoteVisibility: u8 {
            const SPIRIT = 0b0001;
            const STEALTH = 0b0010;
            const SHADOW = 0b0100;
            const QUEST_ONLY = 0b1000;
        }
    }

    impl VisibilityFilter for RemoteVisibility {
        type ClientComponent = Self;
        type Scope = Entity;

        fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
            component.is_some_and(|&c| self.contains(c))
        }
    }
    ```

    Visible if the component references the client entity:

    ```
    # use bevy::prelude::*;
    # use bevy_replicon::prelude::*;
    #[derive(Component, PartialEq)]
    #[component(immutable)]
    struct Owner(Entity);

    impl VisibilityFilter for Owner {
        type ClientComponent = AuthorizedClient; // All clients authorized for replication have this component.
        type Scope = Entity;

        fn is_visible(&self, client: Entity, _component: Option<&Self::ClientComponent>) -> bool {
            self.0 == client
        }
    }
    ```
    */
    fn is_visible(&self, client: Entity, component: Option<&Self::ClientComponent>) -> bool;
}

/// Data affected by [`VisibilityFilter`].
#[derive(Clone)]
pub enum VisibilityScope {
    /// Whole entity.
    Entity,
    /// Specific components on the entity.
    Components(ComponentMask),
    /// All components on the entity, except these.
    AllExcept(ComponentMask),
}

/// Controls when a [`VisibilityScope`] is present on a client.
///
/// See also [`VisibilityFilter::Scope`] and
/// [`FilterRegistry::register_scope`](crate::server::visibility::registry::FilterRegistry::register_scope).
#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Copy)]
pub enum ScopeLifetime {
    /// Inserted/spawned when it becomes visible and despawns when loses
    /// visibility.
    ///
    /// The scope is present only while it is visible.
    ///
    /// It's spawned/inserted when it becomes visible, and despawned/removed
    /// when it becomes hidden.
    WhileVisible,

    /// The scope remains present after becoming visible for the first time.
    ///
    /// It's not spawned/inserted until it first becomes visible. After
    /// that, it remains present when hidden, but receives changes only while
    /// visible.
    ///
    /// When visibility is regained, existing components receive their latest
    /// state. However, component removals and entity despawns that happen while
    /// hidden won't be reapplied, so the client may retain stale components
    /// or entities.
    AfterFirstVisibility,

    /// The scope is always present, regardless of visibility.
    ///
    /// It's spawned/inserted regardless of the visibility, but receives changes
    /// only while visible.
    ///
    /// As with [`Self::AfterFirstVisibility`], removals and despawns that happen
    /// while hidden are not reapplied.
    AlwaysPresent,
}

/// Associates the type with a visibility scope.
pub trait FilterScope {
    /// Returns data that should be hidden when [`VisibilityFilter::is_visible`] returns `false`.
    fn visibility_scope(world: &mut World, registry: &mut ReplicationRegistry) -> VisibilityScope;
}

/// A [`FilterScope`] with components.
///
/// Implemented for [`SingleComponent`] and tuples of [`Component`]s.
///
/// Used for [`AllExcept`] in order to limit it to components.
pub trait ComponentsScope: FilterScope {}

#[deprecated(since = "0.39.0", note = "Renamed into `SingleComponent`")]
pub type ComponentScope<A> = SingleComponent<A>;

/// A scope for a single component `A`.
///
/// We can't implement [`FilterScope`] for both tuples and all types that implement [`Component`].
/// This is why this wrapper is needed to set the scope for only a single component.
///
/// If you need a [`FilterScope`] for multiple components, use a tuple directly, e.g. `(C1, C2)`.
pub struct SingleComponent<A: Component>(PhantomData<A>);

impl<C: Component<Mutability: MutWrite<C>>> FilterScope for SingleComponent<C> {
    fn visibility_scope(world: &mut World, registry: &mut ReplicationRegistry) -> VisibilityScope {
        let mut mask = ComponentMask::default();
        let (index, _) = registry.init_component_fns::<C>(world);
        mask.insert(index);
        VisibilityScope::Components(mask)
    }
}

impl<C: Component<Mutability: MutWrite<C>>> ComponentsScope for SingleComponent<C> {}

impl FilterScope for Entity {
    fn visibility_scope(
        _world: &mut World,
        _registry: &mut ReplicationRegistry,
    ) -> VisibilityScope {
        VisibilityScope::Entity
    }
}

/// Hides every component on the entity except those in `S` when the filter denies visibility.
///
/// `S` must be a [`ComponentsScope`]: [`SingleComponent`] or a tuple of [`Component`]s.
/// Useful for keeping a stripped-down view of an entity replicated past its full
/// visibility range, e.g. only its transform and light.
///
/// # Examples
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_replicon::prelude::*;
/// #[derive(Component, PartialEq)]
/// #[component(immutable)]
/// struct InRange(bool);
///
/// impl VisibilityFilter for InRange {
///     type ClientComponent = Self;
///     // Out-of-range clients keep only `Transform` and `PointLight`.
///     type Scope = AllExcept<(Transform, PointLight)>;
///
///     fn is_visible(&self, _client: Entity, component: Option<&Self::ClientComponent>) -> bool {
///         component.is_some_and(|c| c.0)
///     }
/// }
/// # #[derive(Component)] struct PointLight;
/// ```
pub struct AllExcept<S>(PhantomData<S>);

impl<S: ComponentsScope> FilterScope for AllExcept<S> {
    fn visibility_scope(world: &mut World, registry: &mut ReplicationRegistry) -> VisibilityScope {
        let VisibilityScope::Components(mask) = S::visibility_scope(world, registry) else {
            unreachable!("`ComponentsScope` always yields `VisibilityScope::Components`");
        };
        VisibilityScope::AllExcept(mask)
    }
}

macro_rules! impl_filter_scope {
    ($($C:ident),*) => {
        impl<$($C: Component<Mutability: MutWrite<$C>>),*> FilterScope for ($($C,)*) {
            fn visibility_scope(world: &mut World, registry: &mut ReplicationRegistry) -> VisibilityScope {
                let mut mask = ComponentMask::default();
                $(
                    let (index, _) = registry.init_component_fns::<$C>(world);
                    mask.insert(index);
                )*
                VisibilityScope::Components(mask)
            }
        }

        impl<$($C: Component<Mutability: MutWrite<$C>>),*> ComponentsScope for ($($C,)*) {}
    };
}

variadics_please::all_tuples!(impl_filter_scope, 2, 10, C);