bevy_replicon 0.39.2

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
use core::cmp::Reverse;

use bevy::{ecs::component::ComponentId, prelude::*};
use log::debug;

use super::registry::{
    ReplicationRegistry,
    receive_fns::{MutWrite, RemoveFn, WriteFn},
};

/// Marker-based replication receive functions for [`App`].
///
/// Allows customizing behavior on clients when receiving updates from the server.
///
/// We check markers on receive instead of archetypes because on client we don't
/// know an incoming entity's archetype in advance.
pub trait AppMarkerExt {
    /// Registers a component as a marker.
    ///
    /// Can be used to override how this component or other components will be written or removed
    /// based on marker-component presence.
    /// For details see [`Self::set_marker_fns`].
    ///
    /// This function registers markers with default [`MarkerConfig`].
    /// See also [`Self::register_marker_with`].
    fn register_marker<M: Component>(&mut self) -> &mut Self;

    /// Same as [`Self::register_marker`], but also accepts marker configuration.
    fn register_marker_with<M: Component>(&mut self, config: MarkerConfig) -> &mut Self;

    /**
    Associates receive functions with a marker for a component.

    If this marker is present on an entity and its priority is the highest,
    then these functions will be called for this component during replication
    instead of [`default_write`](super::registry::receive_fns::default_write) /
    [`default_insert_write`](super::registry::receive_fns::default_insert_write) and
    [`default_remove`](super::registry::receive_fns::default_remove).
    See also [`Self::set_receive_fns`].

    # Examples

    In this example we write all received updates for `Health` component into user's
    `History<Health>` if `Predicted` marker is present on the client entity. In this
    scenario, you'd insert `Predicted` the first time the entity is replicated.
    Then `Health` updates after that will be inserted to the history.

    ```
    # use bevy::state::app::StatesPlugin;
    use bevy::{ecs::component::Mutable, platform::collections::HashMap, prelude::*};
    use bevy_replicon::{
        bytes::Bytes,
        prelude::*,
        shared::{
            replication::{
                receive_markers::MarkerConfig,
                deferred_entity::DeferredEntity,
                registry::{
                    ctx::{RemoveCtx, WriteCtx},
                    rule_fns::RuleFns,
                },
            },
            replicon_tick::RepliconTick,
        },
    };
    use serde::{Deserialize, Serialize};

    # let mut app = App::new();
    # app.add_plugins((StatesPlugin, RepliconPlugins));
    app.replicate::<Health>()
        .register_marker_with::<Predicted>(MarkerConfig {
            need_history: true, // Enable writing for values that are older than the last received value.
            ..Default::default()
        })
        .set_marker_fns::<Predicted, Health>(write_history, remove_history::<Health>);

    /// Instead of writing into a component directly, it writes data into [`History<C>`].
    fn write_history<C: Component<Mutability = Mutable>>(
        ctx: &mut WriteCtx,
        rule_fns: &RuleFns<C>,
        entity: &mut DeferredEntity,
        message: &mut Bytes,
    ) -> Result<()> {
        let component: C = rule_fns.deserialize(ctx, message)?;
        if let Some(mut history) = entity.get_mut::<History<C>>() {
            history.insert(ctx.message_tick, component);
        } else {
            entity.insert(History([(ctx.message_tick, component)].into()));
        }

        Ok(())
    }

    /// Removes component `C` and its history.
    fn remove_history<C: Component>(_ctx: &mut RemoveCtx, entity: &mut DeferredEntity) {
        entity.remove::<History<C>>().remove::<C>();
    }

    /// If this marker is present on an entity, registered components will be stored in [`History<T>`].
    ///
    /// Present only on clients.
    #[derive(Component)]
    struct Predicted;

    /// Stores history of values of `C` received from server.
    ///
    /// Present only on clients.
    #[derive(Component, Deref, DerefMut)]
    struct History<C>(HashMap<RepliconTick, C>);

    #[derive(Component, Deref, DerefMut, Serialize, Deserialize)]
    struct Health(u32);
    ```
    **/
    fn set_marker_fns<M: Component, C: Component<Mutability: MutWrite<C>>>(
        &mut self,
        write: WriteFn<C>,
        remove: RemoveFn,
    ) -> &mut Self;

    /**
    Sets default functions for a component when there are no markers.

    If there are no markers present on an entity, then these functions will
    be called for this component during replication instead of
    [`default_write`](super::registry::receive_fns::default_write) /
    [`default_insert_write`](super::registry::receive_fns::default_insert_write) and
    [`default_remove`](super::registry::receive_fns::default_remove).
    See also [`Self::set_marker_fns`].

    # Examples

    Don't update the component if the client receives the same value:

    ```
    # use bevy::state::app::StatesPlugin;
    use bevy::prelude::*;
    use bevy_replicon::{prelude::*, shared::replication::registry::receive_fns};
    use serde::{Deserialize, Serialize};

    # let mut app = App::new();
    # app.add_plugins((StatesPlugin, RepliconPlugins));
    app.replicate::<Health>().set_receive_fns::<Health>(
        receive_fns::write_if_neq, // We provide a built-in function for it, but you can write your own functions.
        receive_fns::default_remove::<Health>,
    );

    #[derive(Component, Serialize, Deserialize, PartialEq)]
    struct Health(u32);
    ```
    */
    fn set_receive_fns<C: Component<Mutability: MutWrite<C>>>(
        &mut self,
        write: WriteFn<C>,
        remove: RemoveFn,
    ) -> &mut Self;
}

impl AppMarkerExt for App {
    fn register_marker<M: Component>(&mut self) -> &mut Self {
        self.register_marker_with::<M>(MarkerConfig::default())
    }

    fn register_marker_with<M: Component>(&mut self, config: MarkerConfig) -> &mut Self {
        debug!("registering marker `{}`", ShortName::of::<M>());
        let component_id = self.world_mut().register_component::<M>();
        let mut receive_markers = self.world_mut().resource_mut::<ReceiveMarkers>();
        let marker_id = receive_markers.insert(ReceiveMarker {
            component_id,
            config,
        });

        let mut replicaton_fns = self.world_mut().resource_mut::<ReplicationRegistry>();
        replicaton_fns.register_marker(marker_id);

        self
    }

    fn set_marker_fns<M: Component, C: Component<Mutability: MutWrite<C>>>(
        &mut self,
        write: WriteFn<C>,
        remove: RemoveFn,
    ) -> &mut Self {
        debug!(
            "adding fns for marker `{}` for component `{}`",
            ShortName::of::<M>(),
            ShortName::of::<C>()
        );
        let component_id = self.world_mut().register_component::<M>();
        let receive_markers = self.world().resource::<ReceiveMarkers>();
        let marker_id = receive_markers.marker_id(component_id);
        self.world_mut()
            .resource_scope(|world, mut registry: Mut<ReplicationRegistry>| {
                registry.set_marker_fns::<C>(world, marker_id, write, remove);
            });

        self
    }

    fn set_receive_fns<C: Component<Mutability: MutWrite<C>>>(
        &mut self,
        write: WriteFn<C>,
        remove: RemoveFn,
    ) -> &mut Self {
        debug!(
            "setting receive fns for component `{}`",
            ShortName::of::<C>()
        );
        self.world_mut()
            .resource_scope(|world, mut registry: Mut<ReplicationRegistry>| {
                registry.set_receive_fns::<C>(world, write, remove);
            });

        self
    }
}

/// Registered markers that override receive functions if present.
#[derive(Resource, Default)]
pub(crate) struct ReceiveMarkers(Vec<ReceiveMarker>);

impl ReceiveMarkers {
    /// Inserts a new marker, maintaining sorting by their priority in descending order.
    ///
    /// May invalidate previously returned [`ReceiveMarkerIndex`] due to sorting.
    ///
    /// Use [`ReplicationRegistry::register_marker`] to register a slot for receive functions for this marker.
    fn insert(&mut self, marker: ReceiveMarker) -> ReceiveMarkerIndex {
        let key = Reverse(marker.config.priority);
        let index = self
            .0
            .binary_search_by_key(&key, |marker| Reverse(marker.config.priority))
            .unwrap_or_else(|index| index);

        self.0.insert(index, marker);

        ReceiveMarkerIndex(index)
    }

    /// Returns marker ID from its component ID.
    fn marker_id(&self, component_id: ComponentId) -> ReceiveMarkerIndex {
        let index = self
            .0
            .iter()
            .position(|marker| marker.component_id == component_id)
            .unwrap_or_else(|| panic!("marker {component_id:?} wasn't registered"));

        ReceiveMarkerIndex(index)
    }

    pub(super) fn iter_require_history(&self) -> impl Iterator<Item = bool> + '_ {
        self.0.iter().map(|marker| marker.config.need_history)
    }
}

/// Component marker information.
///
/// See also [`ReceiveMarkers`].
struct ReceiveMarker {
    /// Marker ID.
    component_id: ComponentId,

    /// User-registered configuration.
    config: MarkerConfig,
}

/// Parameters for a marker.
#[derive(Default)]
pub struct MarkerConfig {
    /// Priority of this marker.
    ///
    /// All tokens are sorted by priority, and if there are multiple matching
    /// markers, the marker with the highest priority will be used.
    ///
    /// By default set to `0`.
    pub priority: usize,

    /// Represents whether a marker needs to process old mutations.
    ///
    /// Since mutations use [`Channel::Unreliable`](crate::shared::backend::channels::Channel),
    /// a client may receive an older mutation for an entity component. By default these mutations are discarded,
    /// but some markers may need them. If this field is set to `true`, old component mutations will
    /// be passed to the writing function for this marker.
    ///
    /// By default set to `false`.
    pub need_history: bool,
}

/// Stores which markers are present on an entity.
pub(crate) struct EntityMarkers {
    markers: Vec<bool>,
    need_history: bool,
}

impl EntityMarkers {
    pub(crate) fn read<'a>(
        &'a mut self,
        markers: &ReceiveMarkers,
        entity: impl Into<EntityRef<'a>>,
    ) {
        self.markers.clear();
        self.need_history = false;

        let entity = entity.into();
        for marker in &markers.0 {
            let contains = entity.contains_id(marker.component_id);
            self.markers.push(contains);
            if contains && marker.config.need_history {
                self.need_history = true;
            }
        }
    }

    /// Returns a slice of which markers are present on an entity.
    ///
    /// Indices corresponds markers in to [`ReceiveMarkers`].
    pub(super) fn markers(&self) -> &[bool] {
        &self.markers
    }

    /// Returns `true` if an entity has at least one marker that needs history.
    pub(crate) fn need_history(&self) -> bool {
        self.need_history
    }
}

impl FromWorld for EntityMarkers {
    fn from_world(world: &mut World) -> Self {
        let markers = world.resource::<ReceiveMarkers>();
        Self {
            markers: Vec::with_capacity(markers.0.len()),
            need_history: false,
        }
    }
}

/// Can be obtained from [`ReceiveMarkers::insert`].
///
/// Shouldn't be stored anywhere since insertion may invalidate old indices.
#[derive(Clone, Copy, Deref, Debug)]
pub(super) struct ReceiveMarkerIndex(usize);

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::shared::replication::registry::receive_fns;

    #[test]
    #[should_panic]
    fn non_registered_marker() {
        let mut app = App::new();
        app.init_resource::<ReceiveMarkers>()
            .init_resource::<ReplicationRegistry>()
            .set_marker_fns::<Marker, TestComponent>(
                receive_fns::default_write,
                receive_fns::default_remove::<TestComponent>,
            );
    }

    #[test]
    fn sorting() {
        let mut app = App::new();
        app.init_resource::<ReceiveMarkers>()
            .init_resource::<ReplicationRegistry>()
            .register_marker::<MarkerA>()
            .register_marker_with::<MarkerB>(MarkerConfig {
                priority: 2,
                ..Default::default()
            })
            .register_marker_with::<MarkerC>(MarkerConfig {
                priority: 1,
                ..Default::default()
            })
            .register_marker::<MarkerD>();

        let markers = app.world().resource::<ReceiveMarkers>();
        let priorities: Vec<_> = markers
            .0
            .iter()
            .map(|marker| marker.config.priority)
            .collect();
        assert_eq!(priorities, [2, 1, 0, 0]);
    }

    #[derive(Component)]
    struct Marker;

    #[derive(Component)]
    struct MarkerA;

    #[derive(Component)]
    struct MarkerB;

    #[derive(Component)]
    struct MarkerC;

    #[derive(Component)]
    struct MarkerD;

    #[derive(Component, Serialize, Deserialize)]
    struct TestComponent;
}