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
use std::time::Duration;
use naia_socket_shared::{LinkConditionerConfig, SocketConfig};
use crate::{
component::{component_kinds::ComponentKinds, replicate::Replicate},
connection::compression_config::CompressionConfig,
messages::{
channel::{Channel, ChannelDirection, ChannelMode, ChannelSettings},
channel_kinds::ChannelKinds,
default_channels::DefaultChannelsPlugin,
message::Message,
message_kinds::MessageKinds,
},
};
pub trait ProtocolPlugin {
fn build(&self, protocol: &mut Protocol);
}
pub struct Protocol {
pub channel_kinds: ChannelKinds,
pub message_kinds: MessageKinds,
pub component_kinds: ComponentKinds,
pub socket: SocketConfig,
pub tick_interval: Duration,
pub compression: Option<CompressionConfig>,
locked: bool,
}
impl Default for Protocol {
fn default() -> Self {
Self {
channel_kinds: ChannelKinds::new(),
message_kinds: MessageKinds::new(),
component_kinds: ComponentKinds::new(),
socket: SocketConfig::new(None, None),
tick_interval: Duration::from_millis(50),
compression: None,
locked: false,
}
}
}
impl Protocol {
pub fn builder() -> Self {
Self::default()
}
pub fn add_plugin<P: ProtocolPlugin>(&mut self, plugin: P) -> &mut Self {
self.check_lock();
plugin.build(self);
self
}
pub fn link_condition(&mut self, config: LinkConditionerConfig) -> &mut Self {
self.check_lock();
self.socket.link_condition = Some(config);
self
}
pub fn rtc_endpoint(&mut self, path: String) -> &mut Self {
self.check_lock();
self.socket.rtc_endpoint_path = path;
self
}
pub fn tick_interval(&mut self, duration: Duration) -> &mut Self {
self.check_lock();
self.tick_interval = duration;
self
}
pub fn compression(&mut self, config: CompressionConfig) -> &mut Self {
self.check_lock();
self.compression = Some(config);
self
}
pub fn add_default_channels(&mut self) -> &mut Self {
self.check_lock();
let plugin = DefaultChannelsPlugin;
plugin.build(self);
self
}
pub fn add_channel<C: Channel>(
&mut self,
direction: ChannelDirection,
mode: ChannelMode,
) -> &mut Self {
self.check_lock();
self.channel_kinds
.add_channel::<C>(ChannelSettings::new(mode, direction));
self
}
pub fn add_message<M: Message>(&mut self) -> &mut Self {
self.check_lock();
self.message_kinds.add_message::<M>();
self
}
pub fn add_component<C: Replicate>(&mut self) -> &mut Self {
self.check_lock();
self.component_kinds.add_component::<C>();
self
}
pub fn lock(&mut self) {
self.check_lock();
self.locked = true;
}
pub fn check_lock(&self) {
if self.locked {
panic!("Protocol already locked!");
}
}
pub fn build(&mut self) -> Self {
std::mem::take(self)
}
}