tx2-link 0.1.1

Binary protocol for syncing ECS worlds with field-level delta compression
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
use crate::protocol::*;
use crate::serialization::{WorldSnapshot, Delta};
use crate::debug;
use ahash::AHashMap;
use std::time::Instant;

pub struct DeltaCompressor {
    previous_snapshot: Option<WorldSnapshot>,
    field_compressor: FieldCompressor,
}

impl DeltaCompressor {
    pub fn new() -> Self {
        Self {
            previous_snapshot: None,
            field_compressor: FieldCompressor::new(),
        }
    }

    pub fn with_field_compression(enable: bool) -> Self {
        Self {
            previous_snapshot: None,
            field_compressor: FieldCompressor::with_enabled(enable),
        }
    }

    pub fn create_delta(&mut self, current_snapshot: WorldSnapshot) -> Delta {
        let start = Instant::now();

        let timestamp = current_snapshot.timestamp;
        let base_timestamp = self.previous_snapshot.as_ref()
            .map(|s| s.timestamp)
            .unwrap_or(0.0);

        let changes = if let Some(prev) = &self.previous_snapshot {
            self.compute_changes(prev, &current_snapshot)
        } else {
            self.create_initial_delta(&current_snapshot)
        };

        let delta = Delta {
            changes,
            timestamp,
            base_timestamp,
        };

        // Debug logging
        if debug::is_debug_enabled() {
            debug::log_delta("Created", &delta);
        }

        if debug::is_trace_enabled() {
            debug::trace_delta(&delta);
            let duration = start.elapsed().as_micros();

            // Estimate sizes for compression ratio
            let original_size = bincode::serialize(&current_snapshot).unwrap_or_default().len();
            let delta_size = bincode::serialize(&delta).unwrap_or_default().len();
            debug::trace_compression(original_size, delta_size, duration);
        }

        self.previous_snapshot = Some(current_snapshot);

        delta
    }

    fn create_initial_delta(&self, snapshot: &WorldSnapshot) -> Vec<DeltaChange> {
        let mut changes = Vec::new();

        for entity in &snapshot.entities {
            changes.push(DeltaChange::EntityAdded {
                entity_id: entity.id,
            });

            for component in &entity.components {
                changes.push(DeltaChange::ComponentAdded {
                    entity_id: entity.id,
                    component_id: component.id.clone(),
                    data: component.data.clone(),
                });
            }
        }

        changes
    }

    fn compute_changes(&self, prev: &WorldSnapshot, curr: &WorldSnapshot) -> Vec<DeltaChange> {
        let mut changes = Vec::new();

        let prev_entities: AHashMap<EntityId, &SerializedEntity> = prev.entities.iter()
            .map(|e| (e.id, e))
            .collect();
        let curr_entities: AHashMap<EntityId, &SerializedEntity> = curr.entities.iter()
            .map(|e| (e.id, e))
            .collect();

        for (entity_id, curr_entity) in &curr_entities {
            if let Some(prev_entity) = prev_entities.get(entity_id) {
                self.compute_component_changes(*entity_id, prev_entity, curr_entity, &mut changes);
            } else {
                changes.push(DeltaChange::EntityAdded {
                    entity_id: *entity_id,
                });

                for component in &curr_entity.components {
                    changes.push(DeltaChange::ComponentAdded {
                        entity_id: *entity_id,
                        component_id: component.id.clone(),
                        data: component.data.clone(),
                    });
                }
            }
        }

        for entity_id in prev_entities.keys() {
            if !curr_entities.contains_key(entity_id) {
                changes.push(DeltaChange::EntityRemoved {
                    entity_id: *entity_id,
                });
            }
        }

        changes
    }

    fn compute_component_changes(
        &self,
        entity_id: EntityId,
        prev_entity: &SerializedEntity,
        curr_entity: &SerializedEntity,
        changes: &mut Vec<DeltaChange>,
    ) {
        let prev_components: AHashMap<&str, &SerializedComponent> = prev_entity.components.iter()
            .map(|c| (c.id.as_str(), c))
            .collect();
        let curr_components: AHashMap<&str, &SerializedComponent> = curr_entity.components.iter()
            .map(|c| (c.id.as_str(), c))
            .collect();

        for (component_id, curr_component) in &curr_components {
            if let Some(prev_component) = prev_components.get(component_id) {
                if !self.components_equal(prev_component, curr_component) {
                    if self.field_compressor.is_enabled() {
                        if let Some(field_deltas) = self.field_compressor.compute_field_deltas(
                            prev_component,
                            curr_component,
                        ) {
                            if !field_deltas.is_empty() {
                                changes.push(DeltaChange::FieldsUpdated {
                                    entity_id,
                                    component_id: component_id.to_string(),
                                    fields: field_deltas,
                                });
                                continue;
                            }
                        }
                    }

                    changes.push(DeltaChange::ComponentUpdated {
                        entity_id,
                        component_id: component_id.to_string(),
                        data: curr_component.data.clone(),
                    });
                }
            } else {
                changes.push(DeltaChange::ComponentAdded {
                    entity_id,
                    component_id: component_id.to_string(),
                    data: curr_component.data.clone(),
                });
            }
        }

        for component_id in prev_components.keys() {
            if !curr_components.contains_key(component_id) {
                changes.push(DeltaChange::ComponentRemoved {
                    entity_id,
                    component_id: component_id.to_string(),
                });
            }
        }
    }

    fn components_equal(&self, a: &SerializedComponent, b: &SerializedComponent) -> bool {
        if a.id != b.id {
            return false;
        }

        match (&a.data, &b.data) {
            (ComponentData::Binary(a_data), ComponentData::Binary(b_data)) => a_data == b_data,
            (ComponentData::Json(a_json), ComponentData::Json(b_json)) => a_json == b_json,
            (ComponentData::Structured(a_map), ComponentData::Structured(b_map)) => a_map == b_map,
            _ => false,
        }
    }

    pub fn reset(&mut self) {
        self.previous_snapshot = None;
    }

    pub fn get_previous_snapshot(&self) -> Option<&WorldSnapshot> {
        self.previous_snapshot.as_ref()
    }
}

impl Default for DeltaCompressor {
    fn default() -> Self {
        Self::new()
    }
}

pub struct FieldCompressor {
    enabled: bool,
}

impl FieldCompressor {
    pub fn new() -> Self {
        Self { enabled: true }
    }

    pub fn with_enabled(enabled: bool) -> Self {
        Self { enabled }
    }

    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    pub fn compute_field_deltas(
        &self,
        prev: &SerializedComponent,
        curr: &SerializedComponent,
    ) -> Option<Vec<FieldDelta>> {
        if !self.enabled {
            return None;
        }

        match (&prev.data, &curr.data) {
            (ComponentData::Structured(prev_fields), ComponentData::Structured(curr_fields)) => {
                let mut deltas = Vec::new();

                for (field_id, curr_value) in curr_fields {
                    if let Some(prev_value) = prev_fields.get(field_id) {
                        if prev_value != curr_value {
                            deltas.push(FieldDelta {
                                field_id: field_id.clone(),
                                old_value: Some(prev_value.clone()),
                                new_value: curr_value.clone(),
                            });
                        }
                    } else {
                        deltas.push(FieldDelta {
                            field_id: field_id.clone(),
                            old_value: None,
                            new_value: curr_value.clone(),
                        });
                    }
                }

                for field_id in prev_fields.keys() {
                    if !curr_fields.contains_key(field_id) {
                        deltas.push(FieldDelta {
                            field_id: field_id.clone(),
                            old_value: prev_fields.get(field_id).cloned(),
                            new_value: FieldValue::Null,
                        });
                    }
                }

                Some(deltas)
            }
            (ComponentData::Json(prev_json_str), ComponentData::Json(curr_json_str)) => {
                if let (Ok(prev_json), Ok(curr_json)) = (
                    serde_json::from_str::<serde_json::Value>(prev_json_str),
                    serde_json::from_str::<serde_json::Value>(curr_json_str)
                ) {
                    if let (Some(prev_obj), Some(curr_obj)) = (prev_json.as_object(), curr_json.as_object()) {
                        let mut deltas = Vec::new();

                        for (key, curr_value) in curr_obj {
                            if let Some(prev_value) = prev_obj.get(key) {
                                if prev_value != curr_value {
                                    deltas.push(FieldDelta {
                                        field_id: key.clone(),
                                        old_value: Some(json_to_field_value(prev_value)),
                                        new_value: json_to_field_value(curr_value),
                                    });
                                }
                            } else {
                                deltas.push(FieldDelta {
                                    field_id: key.clone(),
                                    old_value: None,
                                    new_value: json_to_field_value(curr_value),
                                });
                            }
                        }

                        for key in prev_obj.keys() {
                            if !curr_obj.contains_key(key) {
                                deltas.push(FieldDelta {
                                    field_id: key.clone(),
                                    old_value: prev_obj.get(key).map(json_to_field_value),
                                    new_value: FieldValue::Null,
                                });
                            }
                        }

                        Some(deltas)
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl Default for FieldCompressor {
    fn default() -> Self {
        Self::new()
    }
}

fn json_to_field_value(value: &serde_json::Value) -> FieldValue {
    match value {
        serde_json::Value::Null => FieldValue::Null,
        serde_json::Value::Bool(b) => FieldValue::Bool(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                FieldValue::I64(i)
            } else if let Some(u) = n.as_u64() {
                FieldValue::U64(u)
            } else if let Some(f) = n.as_f64() {
                FieldValue::F64(f)
            } else {
                FieldValue::Null
            }
        }
        serde_json::Value::String(s) => FieldValue::String(s.clone()),
        serde_json::Value::Array(arr) => {
            FieldValue::Array(arr.iter().map(json_to_field_value).collect())
        }
        serde_json::Value::Object(obj) => {
            let map = obj.iter()
                .map(|(k, v)| (k.clone(), json_to_field_value(v)))
                .collect();
            FieldValue::Map(map)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_delta_compression_initial() {
        let mut compressor = DeltaCompressor::new();

        let snapshot = WorldSnapshot {
            entities: vec![
                SerializedEntity {
                    id: 1,
                    components: vec![
                        SerializedComponent {
                            id: "Position".to_string(),
                            data: ComponentData::from_json_value(serde_json::json!({"x": 10.0, "y": 20.0})),
                        }
                    ],
                }
            ],
            timestamp: 100.0,
            version: "1.0.0".to_string(),
        };

        let delta = compressor.create_delta(snapshot);

        assert_eq!(delta.changes.len(), 2);
        assert!(matches!(delta.changes[0], DeltaChange::EntityAdded { .. }));
        assert!(matches!(delta.changes[1], DeltaChange::ComponentAdded { .. }));
    }

    #[test]
    fn test_delta_compression_update() {
        let mut compressor = DeltaCompressor::new();

        let snapshot1 = WorldSnapshot {
            entities: vec![
                SerializedEntity {
                    id: 1,
                    components: vec![
                        SerializedComponent {
                            id: "Position".to_string(),
                            data: ComponentData::from_json_value(serde_json::json!({"x": 10.0, "y": 20.0})),
                        }
                    ],
                }
            ],
            timestamp: 100.0,
            version: "1.0.0".to_string(),
        };

        compressor.create_delta(snapshot1);

        let snapshot2 = WorldSnapshot {
            entities: vec![
                SerializedEntity {
                    id: 1,
                    components: vec![
                        SerializedComponent {
                            id: "Position".to_string(),
                            data: ComponentData::from_json_value(serde_json::json!({"x": 15.0, "y": 20.0})),
                        }
                    ],
                }
            ],
            timestamp: 200.0,
            version: "1.0.0".to_string(),
        };

        let delta = compressor.create_delta(snapshot2);

        assert!(delta.changes.iter().any(|c| matches!(c, DeltaChange::ComponentUpdated { .. } | DeltaChange::FieldsUpdated { .. })));
    }

    #[test]
    fn test_field_level_delta() {
        let compressor = FieldCompressor::new();

        let mut prev_fields = HashMap::new();
        prev_fields.insert("x".to_string(), FieldValue::F64(10.0));
        prev_fields.insert("y".to_string(), FieldValue::F64(20.0));

        let mut curr_fields = HashMap::new();
        curr_fields.insert("x".to_string(), FieldValue::F64(15.0));
        curr_fields.insert("y".to_string(), FieldValue::F64(20.0));

        let prev_component = SerializedComponent {
            id: "Position".to_string(),
            data: ComponentData::Structured(prev_fields),
        };

        let curr_component = SerializedComponent {
            id: "Position".to_string(),
            data: ComponentData::Structured(curr_fields),
        };

        let deltas = compressor.compute_field_deltas(&prev_component, &curr_component).unwrap();

        assert_eq!(deltas.len(), 1);
        assert_eq!(deltas[0].field_id, "x");
    }
}