lightyear_serde 0.25.4

IO primitives for the lightyear networking library
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
//! Map between local and remote entities

use crate::reader::{ReadInteger, ReadVarInt, Reader};
use crate::varint::varint_len;
use crate::writer::WriteInteger;
use crate::{SerializationError, ToBytes};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::entity::{Entity, EntityGeneration, EntityRow};
use bevy_ecs::entity::{EntityMapper, hash_map::EntityHashMap};
use bevy_ecs::world::{EntityWorldMut, World};
use bevy_reflect::Reflect;
#[allow(unused_imports)]
use tracing::{debug, error, info, trace, warn};

const MARKED: u64 = 1 << 62;

/// EntityMap that maps the entity if a mapping is present, or does nothing if not
///
/// The behaviour is different from the `SendEntityMap` or `RemoteEntityMap`, where
/// we return Entity::PLACEHOLDER if the mapping fails.
/// The reason is that `EntityMap` is used for Prediction/Interpolation mapping,
/// where we might not want to apply the mapping. For example, say we spawn C1 and C2
/// and only C1 is predicted to P1. If we add a component Mapped(C2) to C1, we will
/// try to do a mapping from C2 to P2 which doesn't exist. In that case we just want
/// to keep C2 in the component.
#[derive(Default, Debug, Reflect, Deref, DerefMut)]
pub struct EntityMap(pub(crate) EntityHashMap<Entity>);

impl EntityMapper for EntityMap {
    /// Try to map the entity using the map, or don't do anything if it fails
    fn get_mapped(&mut self, entity: Entity) -> Entity {
        self.0.get(&entity).copied().unwrap_or_else(|| {
            debug!("Failed to map entity {entity:?}. Map: {self:?}");
            entity
        })
    }

    fn set_mapped(&mut self, source: Entity, target: Entity) {
        self.0.set_mapped(source, target);
    }
}

#[derive(Default, Debug, Reflect, Deref, DerefMut)]
pub struct SendEntityMap(pub(crate) EntityHashMap<Entity>);

impl EntityMapper for SendEntityMap {
    /// Try to map the entity using the map, or return the initial entity if it doesn't work
    fn get_mapped(&mut self, entity: Entity) -> Entity {
        // if we have the entity in our mapping, map it and mark it as mapped
        // so that on the receive side we don't map it again
        match self.0.get(&entity) {
            Some(mapped) => {
                trace!("Mapping entity {entity:?} to {mapped:?} in SendEntityMap!");
                RemoteEntityMap::mark_mapped(*mapped)
            }
            _ => {
                // otherwise just send the entity as is, and the receiver will map it
                entity
            }
        }
    }

    fn set_mapped(&mut self, source: Entity, target: Entity) {
        self.0.insert(source, target);
    }
}

#[derive(Default, Debug, Reflect, Deref, DerefMut)]
pub struct ReceiveEntityMap(pub(crate) EntityHashMap<Entity>);

impl EntityMapper for ReceiveEntityMap {
    /// Map an entity from the remote World to the local World
    fn get_mapped(&mut self, entity: Entity) -> Entity {
        // if the entity was already mapped on the send side, we don't need to map it again
        // since it's the local world entity
        if RemoteEntityMap::is_mapped(entity) {
            RemoteEntityMap::mark_unmapped(entity)
        } else {
            // if we don't find the entity, return Entity::PLACEHOLDER as an error
            self.0.get(&entity).copied().unwrap_or_else(|| {
                debug!("Receive: Failed to map entity {entity:?}");
                Entity::PLACEHOLDER
            })
        }
    }

    fn set_mapped(&mut self, source: Entity, target: Entity) {
        self.0.insert(source, target);
    }
}

#[derive(Default, Debug, Reflect)]
/// Map between local and remote entities. (used mostly on client because it's when we receive entity updates)
pub struct RemoteEntityMap {
    pub remote_to_local: ReceiveEntityMap,
    pub local_to_remote: SendEntityMap,
}

impl RemoteEntityMap {
    /// Insert a new mapping between a remote entity and a local entity
    #[inline]
    pub fn insert(&mut self, remote_entity: Entity, local_entity: Entity) {
        self.remote_to_local.insert(remote_entity, local_entity);
        self.local_to_remote.insert(local_entity, remote_entity);
    }

    /// Get the local entity corresponding to the remote entity
    ///
    /// It's possible that the remote_entity was already mapped by the sender,
    /// in which case we don't want to map it again
    #[inline]
    pub fn get_local(&self, remote_entity: Entity) -> Option<Entity> {
        let unmapped = Self::mark_unmapped(remote_entity);
        if Self::is_mapped(remote_entity) {
            trace!("Received entity {unmapped:?} was already mapped, returning it as is");
            // the remote_entity is actually local, because it has already been mapped!
            // just remove the mapping bit
            return Some(unmapped);
        };
        self.remote_to_local.get(&unmapped).copied()
    }

    /// We want to map entities in two situations:
    /// - an entity has been replicated to use so we've added it in our Remote->Local mapping. When we receive an entity
    ///   from the sender, we want to check if the entity has been mapped before.
    /// - but in some situations the sender has already mapped the entity; maybe it's because the authority has changes,
    ///   or because the receiver is sending a message about an entity so it does the mapping locally. In which case we don't want
    ///   both the receiver and the sender to apply a mapping, because it wouldn't work.
    ///
    /// So we use a dead bit on the entity to mark it as mapped. If an entity is already marked as mapped, the receiver won't try
    /// to map it again
    pub(crate) const fn mark_mapped(entity: Entity) -> Entity {
        let mut bits = entity.to_bits();
        bits |= MARKED;
        Entity::from_bits(bits)
    }

    pub(crate) const fn mark_unmapped(entity: Entity) -> Entity {
        let mut bits = entity.to_bits();
        bits &= !MARKED;
        Entity::from_bits(bits)
    }

    /// Returns true if the entity already has been mapped
    pub(crate) const fn is_mapped(entity: Entity) -> bool {
        entity.to_bits() & MARKED != 0
    }

    /// Convert a local entity to a network entity that we can send
    /// We will try to map it to a remote entity if we can
    pub fn to_remote(&self, local_entity: Entity) -> Entity {
        match self.local_to_remote.get(&local_entity) {
            Some(remote_entity) => Self::mark_mapped(*remote_entity),
            _ => local_entity,
        }
    }

    /// Get the remote entity corresponding to the local entity in the entity map
    #[inline]
    pub fn get_remote(&self, local_entity: Entity) -> Option<Entity> {
        self.local_to_remote.get(&local_entity).copied()
    }

    /// Get the corresponding local entity for a given remote entity, or create it if it doesn't exist.
    pub fn get_by_remote<'a>(
        &mut self,
        world: &'a mut World,
        remote_entity: Entity,
    ) -> Option<EntityWorldMut<'a>> {
        self.get_local(remote_entity)
            .and_then(|e| world.get_entity_mut(e).ok())
    }

    /// Remove the entity from our mapping and return the local entity
    pub fn remove_by_remote(&mut self, remote_entity: Entity) -> Option<Entity> {
        // the entity is actually local, because it has already been mapped!
        if Self::is_mapped(remote_entity) {
            let local = Self::mark_unmapped(remote_entity);
            if let Some(remote) = self.local_to_remote.remove(&local) {
                self.remote_to_local.remove(&remote);
            }
            return Some(local);
        } else if let Some(local) = self.remote_to_local.remove(&remote_entity) {
            self.local_to_remote.remove(&local);
            return Some(local);
        }
        None
    }

    #[allow(unused)]
    pub(crate) fn is_empty(&self) -> bool {
        self.remote_to_local.is_empty() && self.local_to_remote.is_empty()
    }

    pub fn clear(&mut self) {
        self.local_to_remote.clear();
        self.remote_to_local.clear();
    }
}

/// Serialize Entity as two varints for the index and generation (because they will probably be low).
/// Revisit this when relations comes out
///
/// TODO: optimize for the case where generation == 1, which should be most cases
impl ToBytes for Entity {
    fn bytes_len(&self) -> usize {
        varint_len(self.index() as u64) + 4
    }

    fn to_bytes(&self, buffer: &mut impl WriteInteger) -> Result<(), SerializationError> {
        buffer.write_varint(self.index() as u64)?;
        // TODO: use varint by using index = u32::MAX (which is not allowed) as niche.
        buffer.write_u32(self.generation().to_bits())?;
        Ok(())
    }

    fn from_bytes(buffer: &mut Reader) -> Result<Self, SerializationError>
    where
        Self: Sized,
    {
        let index = buffer.read_varint()?;

        // TODO: use varint by using index = u32::MAX (which is not allowed) as niche.
        // NOTE: not that useful now that we use a high bit to symbolize 'is_masked'
        // let generation = buffer.read_varint()?;
        let generation = EntityGeneration::from_bits(buffer.read_u32()?);
        Ok(Entity::from_row_and_generation(
            EntityRow::from_raw_u32(index as u32).unwrap(),
            generation,
        ))
    }
}

#[cfg(test)]
mod tests {
    use crate::ToBytes;
    use crate::entity_map::RemoteEntityMap;
    use crate::reader::Reader;
    use crate::writer::Writer;
    use bevy_ecs::entity::{Entity, EntityGeneration, EntityRow};
    use test_log::test;

    #[test]
    fn test_entity_serde() {
        let e = Entity::from_row_and_generation(
            EntityRow::from_raw_u32(1).unwrap(),
            EntityGeneration::from_bits(1),
        );

        let mut writer = Writer::with_capacity(100);
        let ser = e.to_bytes(&mut writer).unwrap();
        let mut reader = Reader::from(writer.split());
        let serde_e = Entity::from_bytes(&mut reader).unwrap();
        assert_eq!(e, serde_e);
    }

    #[test]
    fn test_entity_serde_mapped() {
        let entity = Entity::from_raw_u32(10).unwrap();
        assert!(!RemoteEntityMap::is_mapped(entity));
        let entity_mapped = RemoteEntityMap::mark_mapped(entity);
        assert!(RemoteEntityMap::is_mapped(entity_mapped));

        let mut writer = Writer::with_capacity(100);
        let ser = entity_mapped.to_bytes(&mut writer).unwrap();
        let mut reader = Reader::from(writer.split());
        let serde_e = Entity::from_bytes(&mut reader).unwrap();
        assert_eq!(entity_mapped, serde_e);
    }
}

//
// #[cfg(test)]
// mod tests {
//     use crate::client::components::Confirmed;
//     use crate::entity_map::RemoteEntityMap;
//     use crate::prelude::server::{Replicate, SyncTarget};
//     use crate::tests::protocol::*;
//     use crate::tests::stepper::BevyStepper;
//     use bevy::prelude::{default, Entity};
//
//     /// Test marking entities as mapped or not
//     #[test]
//     fn test_marking_entity() {
//         let entity = Entity::from_raw(1);
//         assert!(!RemoteEntityMap::is_mapped(entity));
//         let entity = RemoteEntityMap::mark_mapped(entity);
//         assert!(RemoteEntityMap::is_mapped(entity));
//     }
//
//     // An entity gets replicated from server to client,
//     // then a component gets removed from that entity on server,
//     // that component should also removed on client as well.
//     #[test]
//     fn test_replicated_entity_mapping() {
//         let mut stepper = BevyStepper::default();
//
//         // Create an entity on server
//         let server_entity = stepper
//             .server_app
//             .world_mut()
//             .spawn((ComponentSyncModeFull(0.0), Replicate::default()))
//             .id();
//         // we need to step twice because we run client before server
//         stepper.frame_step();
//         stepper.frame_step();
//
//         // Check that the entity is replicated to client
//         let client_entity = stepper
//             .client_app
//             .world()
//             .resource::<client::ConnectionManager>()
//             .replication_receiver
//             .remote_entity_map
//             .get_local(server_entity)
//             .unwrap();
//         assert_eq!(
//             stepper
//                 .client_app
//                 .world()
//                 .entity(client_entity)
//                 .get::<ComponentSyncModeFull>()
//                 .unwrap(),
//             &ComponentSyncModeFull(0.0)
//         );
//
//         // Create an entity with a component that needs to be mapped
//         let server_entity_2 = stepper
//             .server_app
//             .world_mut()
//             .spawn((ComponentMapEntities(server_entity), Replicate::default()))
//             .id();
//         stepper.frame_step();
//         stepper.frame_step();
//
//         // Check that this entity was replicated correctly, and that the component got mapped
//         let client_entity_2 = stepper
//             .client_app
//             .world()
//             .resource::<client::ConnectionManager>()
//             .replication_receiver
//             .remote_entity_map
//             .get_local(server_entity_2)
//             .unwrap();
//         // the 'server entity' inside the Component4 component got mapped to the corresponding entity on the client
//         assert_eq!(
//             stepper
//                 .client_app
//                 .world()
//                 .entity(client_entity_2)
//                 .get::<ComponentMapEntities>()
//                 .unwrap(),
//             &ComponentMapEntities(client_entity)
//         );
//     }
//
//     /// Check that the EntityMap (used for PredictionEntityMap and InterpolationEntityMap)
//     /// doesn't map to Entity::PLACEHOLDER if the mapping fails.
//     ///
//     /// See: https://github.com/cBournhonesque/lightyear/issues/859
//     /// The reason is that we might have cases where we don't to map from Confirmed to Predicted,
//     /// for example if we spawn two entities C1 and C2 but only one of them is predicted.
//     #[test]
//     fn test_entity_map_no_mapping_found() {
//         let mut stepper = BevyStepper::default();
//         // s1 is predicted, s2 is not
//         let s1 = stepper
//             .server_app
//             .world_mut()
//             .spawn(Replicate {
//                 sync: SyncTarget {
//                     prediction: NetworkTarget::All,
//                     ..default()
//                 },
//                 ..default()
//             })
//             .id();
//         let s2 = stepper
//             .server_app
//             .world_mut()
//             .spawn(Replicate::default())
//             .id();
//         stepper.frame_step();
//         stepper.frame_step();
//         let c1_confirmed = stepper
//             .client_app
//             .world()
//             .resource::<client::ConnectionManager>()
//             .replication_receiver
//             .remote_entity_map
//             .get_local(s1)
//             .unwrap();
//         let c1_predicted = stepper
//             .client_app
//             .world()
//             .get::<Confirmed>(c1_confirmed)
//             .unwrap()
//             .predicted
//             .unwrap();
//         let c2 = stepper
//             .client_app
//             .world()
//             .resource::<client::ConnectionManager>()
//             .replication_receiver
//             .remote_entity_map
//             .get_local(s2)
//             .unwrap();
//         // add a component on s1 that maps to an entity that doesn't have a predicted entity
//         stepper
//             .server_app
//             .world_mut()
//             .entity_mut(s1)
//             .insert(ComponentMapEntities(s2));
//         stepper.frame_step();
//         stepper.frame_step();
//
//         // check that the component is mapped correctly for the confirmed entities
//         assert_eq!(
//             stepper
//                 .client_app
//                 .world()
//                 .get::<ComponentMapEntities>(c1_confirmed)
//                 .unwrap(),
//             &ComponentMapEntities(c2)
//         );
//
//         // check that the component is unmapped for the predicted entities
//         assert_eq!(
//             stepper
//                 .client_app
//                 .world()
//                 .get::<ComponentMapEntities>(c1_predicted)
//                 .unwrap(),
//             &ComponentMapEntities(c2)
//         );
//     }
// }