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
//! Contains the plugins, systems, and components for the bevy app.

use crate::sync::{CNetDir, NetCompMsg, SNetDir};
use crate::sync::{NetComp, NetEntity};
use bevy::prelude::*;
use carrier_pigeon::net::{CIdSpec, NetMsg};
use carrier_pigeon::{Client, MsgRegError, MsgTable, Server, SortedMsgTable, Transport};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::any::Any;
use std::marker::PhantomData;

/// An event that forces a sync of component `T`.
///
/// This can be used if you need to force a sync of component `T` with message type `M`. This is
/// most useful if you are using the change detection; you may want to force a sync of components
/// when a new client joins.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug, Default)]
pub struct SyncC<T> {
    _pd: PhantomData<T>,
}

/// A label that is applied to all networking systems.
#[derive(SystemLabel, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Default, Hash)]
pub struct NetLabel;

/// The client plugin.
///
/// Automatically clears client's message buffer and receive new messages at the start of every
/// frame.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Default, Hash)]
pub struct ClientPlugin;

/// The server plugin.
///
/// Automatically clears server's message buffer and receive new messages at the start of every
/// frame.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Default, Hash)]
pub struct ServerPlugin;

impl Plugin for ClientPlugin {
    fn build(&self, app: &mut App) {
        app.add_system_to_stage(CoreStage::First, client_tick.label(NetLabel));
    }
}

impl Plugin for ServerPlugin {
    fn build(&self, app: &mut App) {
        app.add_system_to_stage(CoreStage::First, server_tick.label(NetLabel));
    }
}

/// Clears client's message buffer and receive new messages.
pub fn client_tick(client: Option<ResMut<Client>>) {
    if let Some(mut client) = client {
        client.clear_msgs();
        client.recv_msgs();
    }
}

/// Clears server's message buffer and receive new messages.
pub fn server_tick(server: Option<ResMut<Server>>) {
    if let Some(mut server) = server {
        server.clear_msgs();
        server.recv_msgs();
    }
}

/// An extension trait for easy registering [`NetComp`] types.
pub trait AppExt {
    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Registers the type `NetCompMsg<M>` into `table` and adds the system required to sync
    /// components of type `T`, using type `M` to send.
    ///
    /// Types `T` and `M` ***can*** be the same type; if the component `T` implements all the
    /// required traits, you may use it as `M`.
    ///
    /// ### Panics
    /// panics if `NetCompMsg<M>` is already registered in the table
    /// (If you call this method twice with the same `M`).
    fn sync_comp<T, M>(&mut self, table: &mut MsgTable, transport: Transport) -> &mut Self
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned;

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Same as [`sync_comp()`](App::sync_comp), but doesn't panic in the event of a [`MsgRegError`].
    fn try_sync_comp<T, M>(
        &mut self,
        table: &mut MsgTable,
        transport: Transport,
    ) -> Result<&mut Self, MsgRegError>
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned;

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Registers the type `NetCompMsg<M>` into `table` and adds the system required to sync
    /// components of type `T`, using type `M` to send.
    ///
    /// Types `T` and `M` ***can*** be the same type; if the component `T` implements all the
    /// required traits, you may use it as `M`.
    ///
    /// ### Panics
    /// panics if `NetCompMsg<M>` is already registered in the table
    /// (If you call this method twice with the same `M`).
    fn sync_comp_sorted<T, M>(
        &mut self,
        table: &mut SortedMsgTable,
        transport: Transport,
    ) -> &mut Self
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned;

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Same as [`sync_comp()`](App::sync_comp), but doesn't panic in the event of a [`MsgRegError`].
    fn try_sync_comp_sorted<T, M>(
        &mut self,
        table: &mut SortedMsgTable,
        transport: Transport,
    ) -> Result<&mut Self, MsgRegError>
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned;
}

impl AppExt for App {
    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Registers the type `NetCompMsg<M>` into `table` and adds the system required to sync
    /// components of type `T`, using type `M` to send.
    ///
    /// Types `T` and `M` ***can*** be the same type; if the component `T` implements all the
    /// required traits, you may use it as `M`.
    ///
    /// ### Panics
    /// panics if `NetCompMsg<M>` is already registered in the table
    /// (If you call this method twice with the same `M`).
    fn sync_comp<T, M>(&mut self, table: &mut MsgTable, transport: Transport) -> &mut Self
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned,
    {
        table.register::<NetCompMsg<M>>(transport).unwrap();

        self.add_event::<SyncC<T>>();
        self.add_system(send_on_event::<T, M>.label(NetLabel));
        self.add_system(comp_send::<T, M>.label(NetLabel));
        self.add_system(comp_recv::<T, M>.label(NetLabel));
        self
    }

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Same as [`sync_comp()`](App::sync_comp), but doesn't panic in the event of a [`MsgRegError`].
    fn try_sync_comp<T, M>(
        &mut self,
        table: &mut MsgTable,
        transport: Transport,
    ) -> Result<&mut Self, MsgRegError>
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned,
    {
        table.register::<NetCompMsg<M>>(transport)?;

        self.add_event::<SyncC<T>>();
        self.add_system(send_on_event::<T, M>.label(NetLabel));
        self.add_system(comp_send::<T, M>.label(NetLabel));
        self.add_system(comp_recv::<T, M>.label(NetLabel));
        Ok(self)
    }

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Registers the type `NetCompMsg<M>` into `table` and adds the system required to sync
    /// components of type `T`, using type `M` to send.
    ///
    /// Types `T` and `M` ***can*** be the same type; if the component `T` implements all the
    /// required traits, you may use it as `M`.
    ///
    /// ### Panics
    /// panics if `NetCompMsg<M>` is already registered in the table
    /// (If you call this method twice with the same `M`).
    fn sync_comp_sorted<T, M>(
        &mut self,
        table: &mut SortedMsgTable,
        transport: Transport,
    ) -> &mut Self
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned,
    {
        let id = "bevy-pigeon::".to_owned() + std::any::type_name::<M>();
        table.register::<NetCompMsg<M>>(transport, &*id).unwrap();

        self.add_event::<SyncC<T>>();
        self.add_system(send_on_event::<T, M>.label(NetLabel));
        self.add_system(comp_send::<T, M>.label(NetLabel));
        self.add_system(comp_recv::<T, M>.label(NetLabel));
        self
    }

    /// Adds everything needed to sync component `T` using message type `M`.
    ///
    /// Same as [`sync_comp()`](App::sync_comp), but doesn't panic in the event of a [`MsgRegError`].
    fn try_sync_comp_sorted<T, M>(
        &mut self,
        table: &mut SortedMsgTable,
        transport: Transport,
    ) -> Result<&mut Self, MsgRegError>
    where
        T: Clone + Into<M> + Component,
        M: Clone + Into<T> + Any + Send + Sync + Serialize + DeserializeOwned,
    {
        let id = "bevy-pigeon::".to_owned() + std::any::type_name::<M>();
        table.register::<NetCompMsg<M>>(transport, &*id)?;

        self.add_event::<SyncC<T>>();
        self.add_system(send_on_event::<T, M>.label(NetLabel));
        self.add_system(comp_send::<T, M>.label(NetLabel));
        self.add_system(comp_recv::<T, M>.label(NetLabel));
        Ok(self)
    }
}

/// A system that forces a sync of a certain component.
fn send_on_event<T, M>(
    mut er: EventReader<SyncC<T>>,
    server: Option<ResMut<Server>>,
    client: Option<ResMut<Client>>,
    q: Query<(&NetEntity, &NetComp<T, M>, &T)>,
) where
    T: Clone + Into<M> + Component,
    M: Clone + Into<T> + Any + Send + Sync,
{
    if er.iter().count() == 0 {
        return;
    }
    trace!("Force Syncing {}", std::any::type_name::<T>());

    // Almost copy-paste from [`comp_send`] ignoring change detection
    if let Some(server) = server {
        for (net_e, net_c, comp) in q.iter() {
            if let Some(to_spec) = net_c.s_dir.to() {
                if let Err(e) = server.send_spec(
                    *to_spec,
                    &NetCompMsg::<M>::new(net_e.id, comp.clone().into()),
                ) {
                    error!("{}", e);
                }
            }
        }
    } else if let Some(client) = client {
        for (net_e, net_c, comp) in q.iter() {
            if let CNetDir::To = net_c.c_dir {
                if let Err(e) = client.send(&NetCompMsg::<M>::new(net_e.id, comp.clone().into())) {
                    error!("{}", e);
                }
            }
        }
    }
}

/// A system that sends component `T` using messages of type `M`.
///
/// Most of the time, you will call [`sync_comp`](AppExt::sync_comp) which will add this system.
/// Only add it manually if you know what you are doing and want custom control over when it runs.
pub fn comp_send<T, M>(
    server: Option<ResMut<Server>>,
    client: Option<ResMut<Client>>,
    q: Query<(&NetEntity, &NetComp<T, M>, &T, ChangeTrackers<T>)>,
) where
    T: Clone + Into<M> + Component,
    M: Clone + Into<T> + Any + Send + Sync,
{
    if let Some(server) = server {
        for (net_e, net_c, comp, ct) in q.iter() {
            // If we are using change detection, and the component hasn't been changed, skip.
            if net_c.cd && !ct.is_changed() {
                continue;
            }

            if let Some(to_spec) = net_c.s_dir.to() {
                if let Err(e) = server.send_spec(
                    *to_spec,
                    &NetCompMsg::<M>::new(net_e.id, comp.clone().into()),
                ) {
                    error!("{}", e);
                }
            }
        }
    } else if let Some(client) = client {
        for (net_e, net_c, comp, ct) in q.iter() {
            // If we are using change detection, and the component hasn't been changed, skip.
            if net_c.cd && !ct.is_changed() {
                continue;
            }

            if let CNetDir::To = net_c.c_dir {
                if let Err(e) = client.send(&NetCompMsg::<M>::new(net_e.id, comp.clone().into())) {
                    error!("{}", e);
                }
            }
        }
    }
}

/// A system that receives messages of type `M` and applies it to component `T`.
///
/// Most of the time, you will call [`sync_comp`](AppExt::sync_comp) which will add this system.
/// Only add it manually if you know what you are doing and want custom control over when it runs.
pub fn comp_recv<T, M>(
    server: Option<ResMut<Server>>,
    client: Option<ResMut<Client>>,
    mut q: Query<(&NetEntity, &mut NetComp<T, M>, &mut T)>,
) where
    T: Clone + Into<M> + Component,
    M: Clone + Into<T> + Any + Send + Sync,
{
    if let Some(server) = server {
        // Cache messages
        let msgs: Vec<NetMsg<NetCompMsg<M>>> = server.recv::<NetCompMsg<M>>().collect();
        for (net_e, mut net_c, mut comp) in q.iter_mut() {
            if let Some(&spec) = net_c.s_dir.from() {
                if let Some(valid_msg) = get_latest_msg(&msgs, net_c.last, spec, net_e.id) {
                    net_c.last = valid_msg.time;
                    *comp = valid_msg.msg.clone().into();
                }
            }
            // Warn on overlap
            if let SNetDir::ToFrom(to_spec, from_spec) = net_c.s_dir {
                if to_spec.overlaps(from_spec) {
                    warn!("NetEntity {{ id: {} }} has overlapping `CIdSpec`s in NetDirection::ToFrom. Applying anyway.", net_e.id);
                }
            }
        }
    } else if let Some(client) = client {
        // Cache messages
        let msgs: Vec<NetMsg<NetCompMsg<M>>> = client.recv::<NetCompMsg<M>>().collect();
        for (net_e, mut net_c, mut comp) in q.iter_mut() {
            if net_c.c_dir == CNetDir::From {
                if let Some(valid_msg) = get_latest_msg(&msgs, net_c.last, CIdSpec::All, net_e.id) {
                    net_c.last = valid_msg.time;
                    *comp = valid_msg.msg.clone().into();
                }

                if let Some(valid_msg) = msgs.iter().filter(|msg| msg.id == net_e.id).last() {
                    *comp = valid_msg.msg.clone().into();
                }
            }
        }
    }
}

/// Helper function that gets the most recent message that matches `from_spec` for entity with `id`
/// if it is sent later that current.
fn get_latest_msg<'a, M: Any + Send + Sync>(
    msgs: &'a Vec<NetMsg<NetCompMsg<M>>>,
    current: Option<u32>,
    spec: CIdSpec,
    id: u64,
) -> Option<&'a NetMsg<'a, NetCompMsg<M>>> {
    let mut latest_time = current.unwrap_or(0);
    let mut latest = None;
    for m in msgs.iter().filter(|m| spec.matches(m.cid) && m.id == id) {
        if let Some(time) = m.time {
            // If this packet has a send time, get the last.
            if time > latest_time {
                latest_time = time;
                latest = Some(m);
            }
        } else {
            // If this does not have a send time, just get the last one received.
            latest = Some(m);
        }
    }
    latest
}