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
use std::{any::TypeId, collections::VecDeque};

use bevy::{
    ecs::component::ComponentId,
    pbr::OpaqueRendererMethod,
    prelude::*,
    reflect::{DynamicTypePath, FromReflect, GetTypeRegistration, Reflect, ReflectFromReflect},
    utils::{HashMap, HashSet},
};
use bevy_renet::renet::ClientId;

use crate::{
    binreflect::bin_to_reflect, bundle_fix::BundleFixPlugin, client::ClientSyncPlugin,
    proto::AssId, server::ServerSyncPlugin, ClientPlugin, ServerPlugin, SyncComponent, SyncDown,
    SyncExclude, SyncMark, SyncPlugin, SyncUp,
};

#[derive(PartialEq, Eq, Hash)]
pub(crate) struct ComponentChangeId {
    pub(crate) id: Entity,
    pub(crate) name: String,
}

pub(crate) struct ComponentChange {
    pub(crate) change_id: ComponentChangeId,
    pub(crate) data: Box<dyn Reflect>,
}

#[derive(Resource, Default)]
pub(crate) struct SyncTrackerRes {
    /// Mapping of entity ids between server and clients. key: server, value: client
    pub(crate) server_to_client_entities: HashMap<Entity, Entity>,

    pub(crate) registered_componets_for_sync: HashSet<ComponentId>,
    /// Tracks SyncExcludes for component T. key: component id of T, value: component id of SyncExcdlude<T>
    pub(crate) sync_exclude_cid_of_component_cid: HashMap<ComponentId, ComponentId>,
    /// Queue of component changes to be sent over network
    pub(crate) changed_components_to_send: VecDeque<ComponentChange>,
    /// Pushed references (component and handle) that came from network and were applied in world,
    /// so that in the next detect step they will be skipped and avoid ensless loop.
    pub(crate) pushed_component_from_network: HashSet<ComponentChangeId>,
    pub(crate) pushed_handles_from_network: HashSet<AssId>,

    pub(crate) sync_materials: bool,
    pub(crate) sync_meshes: bool,
}

pub(crate) fn sync_material_enabled(tracker: Res<SyncTrackerRes>) -> bool {
    tracker.sync_materials
}

pub(crate) fn sync_mesh_enabled(tracker: Res<SyncTrackerRes>) -> bool {
    tracker.sync_meshes
}

impl SyncTrackerRes {
    pub(crate) fn signal_component_changed(&mut self, id: Entity, data: Box<dyn Reflect>) {
        let name = data.get_represented_type_info().unwrap().type_path().into();
        let change_id = ComponentChangeId { id, name };
        if self.pushed_component_from_network.contains(&change_id) {
            self.pushed_component_from_network.remove(&change_id);
            return;
        }
        self.changed_components_to_send
            .push_back(ComponentChange { change_id, data });
    }

    pub(crate) fn skip_network_handle_change(&mut self, id: AssId) -> bool {
        if self.pushed_handles_from_network.contains(&id) {
            self.pushed_handles_from_network.remove(&id);
            return true;
        }
        false
    }

    pub(crate) fn apply_component_change_from_network(
        e_id: Entity,
        name: String,
        data: &[u8],
        world: &mut World,
    ) -> bool {
        let registry = world.resource::<AppTypeRegistry>().clone();
        let registry = registry.read();
        let component_data = bin_to_reflect(data, &registry);
        let registration = registry.get_with_type_path(name.as_str()).unwrap();
        let reflect_component = registration.data::<ReflectComponent>().unwrap();
        let previous_value = reflect_component.reflect(world.entity(e_id));
        if equals(previous_value, &*component_data) {
            world
                .resource_mut::<SyncTrackerRes>()
                .pushed_component_from_network
                .insert(ComponentChangeId { id: e_id, name });
            let entity = &mut world.entity_mut(e_id);
            reflect_component.apply_or_insert(entity, component_data.as_reflect());
            true
        } else {
            debug!(
                "Skipped component from network: {}v{} - {}",
                e_id.index(),
                e_id.generation(),
                name
            );
            false
        }
    }

    pub(crate) fn apply_material_change_from_network(
        id: AssId,
        material: &[u8],
        world: &mut World,
    ) {
        world
            .resource_mut::<SyncTrackerRes>()
            .pushed_handles_from_network
            .insert(id);
        let registry = world.resource::<AppTypeRegistry>().clone();
        let registry = registry.read();
        let component_data = bin_to_reflect(material, &registry);
        let mut materials = world.resource_mut::<Assets<StandardMaterial>>();
        let mat = *component_data.downcast::<StandardMaterial>().unwrap();
        materials.insert(id, mat);
    }
}

fn equals(previous_value: Option<&dyn Reflect>, component_data: &dyn Reflect) -> bool {
    if previous_value.is_none() {
        return true;
    }
    !previous_value
        .unwrap()
        .reflect_partial_eq(component_data)
        .unwrap_or(true)
}

#[allow(clippy::type_complexity)]
fn sync_detect_server<T: Component + Reflect>(
    mut push: ResMut<SyncTrackerRes>,
    q: Query<(Entity, &T), (With<SyncDown>, Without<SyncExclude<T>>, Changed<T>)>,
) {
    for (e_id, component) in q.iter() {
        push.signal_component_changed(e_id, component.clone_value());
    }
}

#[allow(clippy::type_complexity)]
fn sync_detect_client<T: Component + Reflect>(
    mut push: ResMut<SyncTrackerRes>,
    q: Query<(&SyncUp, &T), (With<SyncUp>, Without<SyncExclude<T>>, Changed<T>)>,
) {
    for (sup, component) in q.iter() {
        push.signal_component_changed(sup.server_entity_id, component.clone_value());
    }
}

impl SyncComponent for App {
    fn sync_component<
        T: Component + TypePath + DynamicTypePath + Reflect + FromReflect + GetTypeRegistration,
    >(
        &mut self,
    ) -> &mut Self {
        self.register_type::<T>();
        self.register_type_data::<T, ReflectFromReflect>();
        let c_id = self.world.init_component::<T>();
        let c_exclude_id = self.world.init_component::<SyncExclude<T>>();
        let mut track = self.world.resource_mut::<SyncTrackerRes>();
        track.registered_componets_for_sync.insert(c_id);
        track
            .sync_exclude_cid_of_component_cid
            .insert(c_id, c_exclude_id);
        self.add_systems(Update, sync_detect_server::<T>);
        self.add_systems(Update, sync_detect_client::<T>);

        setup_cascade_registrations::<T>(self);

        self
    }

    fn sync_materials(&mut self, enable: bool) {
        let mut tracker = self.world.resource_mut::<SyncTrackerRes>();
        tracker.sync_materials = enable;
    }

    fn sync_meshes(&mut self, enable: bool) {
        let mut tracker = self.world.resource_mut::<SyncTrackerRes>();
        tracker.sync_meshes = enable;
    }
}

fn setup_cascade_registrations<T: Component + Reflect + FromReflect + GetTypeRegistration>(
    app: &mut App,
) {
    if TypeId::of::<T>() == TypeId::of::<Handle<StandardMaterial>>() {
        app.register_type_data::<StandardMaterial, ReflectFromReflect>();
        app.register_type::<Color>();
        app.register_type::<Image>();
        app.register_type::<Handle<Image>>();
        app.register_type::<Option<Handle<Image>>>();
        app.register_type::<AlphaMode>();
        app.register_type::<ParallaxMappingMethod>();
        app.register_type::<OpaqueRendererMethod>();
    }

    if TypeId::of::<T>() == TypeId::of::<PointLight>() {
        app.register_type::<Color>();
    }
}

#[derive(Component)]
pub(crate) struct SyncClientGeneratedEntity {
    pub(crate) client_id: ClientId,
    pub(crate) client_entity_id: Entity,
}

impl Plugin for SyncPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<SyncMark>();
        app.init_resource::<SyncTrackerRes>();
        app.add_plugins(BundleFixPlugin);
    }
}

impl Plugin for ServerPlugin {
    fn build(&self, app: &mut App) {
        crate::networking::setup_server(app, self.ip, self.port, self.web_port, self.max_transfer);
        app.add_plugins(ServerSyncPlugin);
    }
}

impl Plugin for ClientPlugin {
    fn build(&self, app: &mut App) {
        crate::networking::setup_client(app, self.ip, self.port, self.web_port, self.max_transfer);
        app.add_plugins(ClientSyncPlugin);
    }
}