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
|
use anyhow::Result;
use arrayvec::ArrayVec;
use libtw2_event_loop::{
Addr, Application, Chunk, ConnlessChunk, Loop, PeerId, SocketLoop, Timeout,
};
use libtw2_gamenet_ddnet::{
enums::{Team, VERSION},
msg::{
self, Game, System, SystemOrGame,
game::{ClSetTeam, ClStartInfo},
system::{EnterGame, Info, MapChange, Ready, RequestMapData},
},
snap_obj::obj_size,
};
use libtw2_packer::{IntUnpacker, Unpacker, with_packer};
use libtw2_snapshot::Manager as SnapManager;
use log::{debug, info, warn};
use std::{
fmt::Debug,
fs::File,
io::Write,
net::{IpAddr, Ipv4Addr},
path::PathBuf,
sync::mpsc::{Receiver, Sender, channel},
thread::spawn,
};
use twsnap::{Snap, SnapObj};
pub struct Client {
pub incoming: Receiver<(i32, Snap)>,
}
impl Client {
pub fn new() -> Result<Self> {
let (incoming_tx, incoming_rx) = channel();
spawn(move || {
let mut sloop = SocketLoop::client();
sloop.connect(Addr {
ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
port: 8303,
});
sloop.run(ClientNetwork {
state: NetworkState::New,
events: incoming_tx,
});
});
Ok(Self {
incoming: incoming_rx,
})
}
}
pub struct ClientNetwork {
state: NetworkState,
events: Sender<(i32, Snap)>,
}
enum NetworkState {
New,
Downloading {
chunk: i32,
data: Vec<u8>,
path: PathBuf,
size: usize,
},
Ready,
Ingame {
snap_manager: SnapManager,
snap: twsnap::Snap,
},
}
impl<L: Loop> Application<L> for ClientNetwork {
fn needs_tick(&mut self) -> Timeout {
Timeout::inactive()
}
fn on_tick(&mut self, _loop_: &mut L) {}
fn on_packet(&mut self, loop_: &mut L, chunk: Chunk) {
let pid = chunk.pid;
let msg;
match msg::decode(&mut Warn(chunk.data), &mut Unpacker::new(chunk.data)) {
Ok(m) => msg = m,
Err(err) => {
warn!("decode error {:?}:", err);
return;
}
}
debug!("<- {msg:?}");
match msg {
SystemOrGame::System(System::MapChange(MapChange { name, crc, size })) => {
let path = map_cache_path(name, crc);
if path.exists() {
loop_.sends(pid, Ready);
self.state = NetworkState::Ready
} else {
loop_.sends(pid, RequestMapData { chunk: 0 });
self.state = NetworkState::Downloading {
chunk: 0,
data: Vec::new(),
path,
size: size as usize,
}
}
}
SystemOrGame::System(System::MapData(p)) => {
if let NetworkState::Downloading {
chunk,
data,
path,
size,
} = &mut self.state
{
data.extend(p.data);
info!("download {} / {}", data.len(), size);
assert_eq!(*chunk, p.chunk);
*chunk += 1;
if p.last != 0 {
File::create(path).unwrap().write_all(&data).unwrap();
self.state = NetworkState::Ready;
loop_.sends(pid, Ready);
} else {
loop_.sends(pid, RequestMapData { chunk: *chunk });
}
}
}
SystemOrGame::System(System::ConReady(..)) => {
if let NetworkState::Ready = &mut self.state {
loop_.sendg(pid, ClStartInfo {
name: b"testclient",
clan: b"metamuffin",
country: -1,
skin: b"limekittygirl",
use_custom_color: true,
color_body: 0xFF00FFFFu32 as i32,
color_feet: 0x550055FFu32 as i32,
});
self.state = NetworkState::Ingame {
snap: Snap::default(),
snap_manager: SnapManager::new(),
}
}
}
SystemOrGame::System(System::SnapSingle(p)) => {
if let NetworkState::Ingame { snap, snap_manager } = &mut self.state {
if let Some(new_snap) = snap_manager
.snap_single(&mut Warn(&[]), obj_size, p)
.unwrap()
{
let objs = new_snap
.items()
.filter_map(|i| {
let mut ints = IntUnpacker::new(i.data);
match SnapObj::decode_obj(&mut Warn(&[]), i.type_id, &mut ints) {
Ok(ob) => Some((ob, i.id)),
Err(e) => {
warn!("snap object decode error: {e:?} {:?}", i.type_id);
None
}
}
})
.collect::<Vec<_>>();
snap.process_next(objs.iter());
self.events.send((p.tick, snap.clone())).unwrap();
}
}
}
SystemOrGame::Game(Game::SvReadyToEnter(..)) => {
loop_.sends(pid, EnterGame);
loop_.sendg(pid, ClSetTeam { team: Team::Red });
}
_ => {}
}
}
fn on_connless_packet(&mut self, _loop_: &mut L, _chunk: ConnlessChunk) {}
fn on_connect(&mut self, _loop_: &mut L, _pid: PeerId) {
todo!()
}
fn on_ready(&mut self, loop_: &mut L, pid: PeerId) {
loop_.sends(pid, Info {
version: VERSION.as_bytes(),
password: Some(b""),
});
loop_.flush(pid);
}
fn on_disconnect(&mut self, _loop_: &mut L, _pid: PeerId, _remote: bool, _reason: &[u8]) {}
}
// Adapted from from libtw2/downloader/src/main.rs by heinrich5991, MIT-or-Apache-2.0
trait LoopExt: Loop {
fn sends<'a, S: Into<System<'a>> + Debug>(&mut self, pid: PeerId, msg: S) {
debug!("-> System({msg:?})");
fn inner<L: Loop + ?Sized>(msg: System, pid: PeerId, loop_: &mut L) {
let mut buf: ArrayVec<[u8; 2048]> = ArrayVec::new();
with_packer(&mut buf, |p| msg.encode(p).unwrap());
loop_.send(Chunk {
pid,
vital: true,
data: &buf,
})
}
inner(msg.into(), pid, self)
}
fn sendg<'a, G: Into<Game<'a>> + Debug>(&mut self, pid: PeerId, msg: G) {
debug!("-> System({msg:?})");
fn inner<L: Loop + ?Sized>(msg: Game, pid: PeerId, loop_: &mut L) {
let mut buf: ArrayVec<[u8; 2048]> = ArrayVec::new();
with_packer(&mut buf, |p| msg.encode(p).unwrap());
loop_.send(Chunk {
pid,
vital: true,
data: &buf,
})
}
inner(msg.into(), pid, self)
}
}
impl<L: Loop> LoopExt for L {}
struct Warn<'a>(#[allow(unused)] &'a [u8]);
impl<'a, W: Debug> warn::Warn<W> for Warn<'a> {
fn warn(&mut self, w: W) {
warn!("{:?}", w);
}
}
fn map_cache_path(name: &[u8], crc: i32) -> PathBuf {
xdg::BaseDirectories::with_prefix("twclient")
.unwrap()
.create_cache_directory("maps")
.unwrap()
.join(format!(
"{}_{:08x}",
String::from_utf8_lossy(name)
.replace("/", "")
.replace(".", ""),
crc as u32
))
}
|