Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use default serde impls for Entity (bevyengine#6194)
# Objective Currently for entities we serialize only `id`. But this is not very expected behavior. For example, in networking, when the server sends its state, it contains entities and components. On the client, I create new objects and map them (using `EntityMap`) to those received from the server (to know which one matches which). And if `generation` field is missing, this mapping can be broken. Example: 1. Server sends an entity `Entity{ id: 2, generation: 1}` with components. 2. Client puts the received entity in a map and create a new entity that maps to this received entity. The new entity have different `id` and `generation`. Let's call it `Entity{ id: 12, generation: 4}`. 3. Client sends a command for `Entity{ id: 12, generation: 4}`. To do so, it maps local entity to the one from server. But `generation` field is 0 because it was omitted for serialization on the server. So it maps to `Entity{ id: 2, generation: 0}`. 4. Server receives `Entity{ id: 2, generation: 0}` which is invalid. In my game I worked around it by [writing custom serialization](https://github.com/dollisgame/dollis/blob/master/src/core/network/entity_serde.rs) and using `serde(with = "...")`. But it feels like a bad default to me. Using `Entity` over a custom `NetworkId` also have the following advantages: 1. Re-use `MapEntities` trait to map `Entity`s in replicated components. 2. Instead of server `Entity <-> NetworkId ` and `Entity <-> NetworkId`, we map entities only on client. 3. No need to handling uniqueness. It's a rare case, but makes things simpler. For example, I don't need to query for a resource to create an unique ID. Closes bevyengine#6143. ## Solution Use default serde impls. If anyone want to avoid wasting memory on `generation`, they can create a new type that holds `u32`. This is what Bevy do for [DynamicEntity](https://docs.rs/bevy/latest/bevy/scene/struct.DynamicEntity.html) to serialize scenes. And I don't see any use case to serialize an entity id expect this one. --- ## Changelog ### Changed - Entity now serializes / deserializes `generation` field. ## Migration Guide - Entity now fully serialized. If you want to serialze only `id`, as it was before, you can create a new type that wraps `u32`.
- Loading branch information