tx2_core/
serialization.rs

1use serde::{Deserialize, Serialize};
2use crate::entity::EntityId;
3use crate::component::ComponentId;
4use crate::world::World;
5use tx2_link::{
6    SerializedComponent, SerializedEntity, WorldSnapshot, Delta, DeltaChange,
7    protocol::ComponentData,
8};
9
10pub struct Serializer;
11
12impl Serializer {
13    pub fn create_snapshot(world: &World) -> WorldSnapshot {
14        let mut entities = Vec::new();
15        
16        for entity in world.get_all_entities() {
17            let mut serialized_components = Vec::new();
18            for component in world.get_all_components(entity.id) {
19                serialized_components.push(SerializedComponent {
20                    id: component.component_id(),
21                    data: ComponentData::from_json_value(component.to_json()),
22                });
23            }
24            
25            entities.push(SerializedEntity {
26                id: entity.id,
27                components: serialized_components,
28            });
29        }
30
31        WorldSnapshot {
32            entities,
33            timestamp: 0.0,
34            version: "1.0.0".to_string(),
35        }
36    }
37}
38
39pub struct DeltaCompressor {
40    inner: tx2_link::DeltaCompressor,
41}
42
43impl DeltaCompressor {
44    pub fn new() -> Self {
45        Self {
46            inner: tx2_link::DeltaCompressor::new(),
47        }
48    }
49
50    pub fn create_delta(&mut self, world: &World) -> Delta {
51        let snapshot = Serializer::create_snapshot(world);
52        self.inner.create_delta(snapshot)
53    }
54
55    pub fn reset(&mut self) {
56        self.inner.reset();
57    }
58}