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
//! Module for the main game loop, in the [run] function.

use crate::gameplay_socket::GameplaySocket;
use crate::login_server::LoginServer;
use crate::{map_loader, secure_rand};
use common::{
    ChunkUpdate, ClientAction, Effect, PcHandle, PlayerCharacter, Point, ServerAction, World,
    CHUNKS_X, CHUNKS_Y, CHUNK_HEIGHT, CHUNK_WIDTH,
};
use rand::Rng;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{Duration, Instant};

// Used in docs.
#[allow(unused_imports)]
use common::Chunk;

/// The amount of time one frame should take.
///
/// If processing a frame takes less time, the thread sleeps to compensate, and
/// if processing a frame takes too long, a warning is logged.
const FRAME_DURATION: Duration = Duration::from_micros(33_333);

/// Tracked state for a specific peer.
struct PeerState {
    pc_handle: PcHandle,
    loaded_chunk_indices: Vec<usize>,
}

/// Runs the game loop and blocks until it returns an error (or the process is
/// terminated).
///
/// One loop consists of the following:
///
/// 1. Spawn newly logged in player characters if any are reported by [LoginServer].
/// 2. Gather up the new [ClientAction]s from players.
/// 3. Process the [ClientAction]s into [Effect]s.
/// 4. Apply the [Effect]s to the [World].
/// 5. Despawn players that haven't sent a message in a while (= have disconnected).
/// 6. Send out relevant [ChunkUpdate]s to the players (may include entire [Chunk]s, if needed).
/// 7. Run [World::update] (i.e. simulate one timestep).
pub fn run() -> anyhow::Result<()> {
    let mut world = map_loader::load_map(include_str!("worldmap/tutorial-fort.tmx"))?;
    let mut players = HashMap::new();
    let mut taken_handles = HashSet::new();

    let mut rng = rand::thread_rng();
    let spawn_chunks = world
        .chunks
        .iter()
        .enumerate()
        .filter_map(|(i, chunk)| Some((i, chunk.as_ref()?)))
        .filter(|(_, chunk)| !chunk.spawns.is_empty())
        .map(|(i, _)| i)
        .collect::<Vec<_>>();

    let mut login_server = LoginServer::new()?;
    let mut gameplay_socket = GameplaySocket::new()?;

    let mut previous_poll_end = Instant::now();
    loop {
        let prev_frame = Instant::now() - previous_poll_end;
        if let Some(to_wait) = FRAME_DURATION.checked_sub(prev_frame) {
            thread::sleep(to_wait);
        } else {
            log::warn!("Frame took {prev_frame:.2?}, more than the expected {FRAME_DURATION:.2?}!");
        }
        previous_poll_end = Instant::now();

        let mut chunks_effects = vec![Vec::new(); world.chunks.len()];

        // Spawn charcters for any new peers
        while let Some((peer_id, encryption_key)) = login_server.try_recv_new_peers() {
            let handle = loop {
                let potential_handle = PcHandle(secure_rand::gen_u64());
                if taken_handles.insert(potential_handle) {
                    break potential_handle;
                }
            };
            players.insert(
                peer_id,
                PeerState {
                    pc_handle: handle,
                    loaded_chunk_indices: vec![],
                },
            );
            gameplay_socket.add_peer(peer_id, encryption_key);

            let spawn_chunk_index = spawn_chunks[rng.gen_range(0..spawn_chunks.len())];
            let spawn_points = &world.chunks[spawn_chunk_index].as_ref().unwrap().spawns;
            let position = spawn_points[rng.gen_range(0..spawn_points.len())];
            chunks_effects[spawn_chunk_index]
                .push(Effect::SpawnPlayerCharacter { handle, position });
        }

        // Poll for new Actions
        gameplay_socket.transport();

        // Get the actions
        let mut frame_actions = HashMap::new();
        while let Some((peer_id, action)) = gameplay_socket.recv_actions() {
            frame_actions.insert(peer_id, action);
        }

        // Make effects out of the actions
        for (peer, action) in frame_actions {
            if matches!(action, ClientAction::Hello) {
                if let Some(PeerState { pc_handle, .. }) = players.get(&peer) {
                    gameplay_socket.send_action(peer, ServerAction::Welcome(*pc_handle));
                }
            }
            if let Some(PeerState { pc_handle, .. }) = players.get(&peer) {
                if let Some((chunk, player)) = world.get_player_character(*pc_handle) {
                    let player = (*pc_handle, player);
                    for (i, effect) in make_effects(action, &world, player, chunk) {
                        chunks_effects[i].push(effect);
                    }
                }
            }
        }

        // Despawn disconnected players
        let peer_ids = gameplay_socket.refresh();
        players.retain(|peer_id, PeerState { pc_handle, .. }| {
            if peer_ids.contains(peer_id) {
                true
            } else {
                if let Some((chunk_index, _)) = world.get_player_character(*pc_handle) {
                    let despawn_effect = Effect::DespawnPlayerCharacter(*pc_handle);
                    chunks_effects[chunk_index].push(despawn_effect);
                    log::debug!(
                        "Despawning character {:016x} of disconnected peer {:032x}",
                        pc_handle.0,
                        peer_id.0,
                    );
                }
                false
            }
        });

        // Apply the effects
        for (i, chunk_effects) in chunks_effects.iter().enumerate() {
            // Safety: the server always has all chunks loaded.
            assert!(world.apply_effects(i, chunk_effects.clone()));
        }

        // Distribute the effects among the peers
        for peer in &peer_ids {
            if let Some((loaded_chunk_indices, player_chunk_index)) =
                players.get_mut(peer).and_then(|peer_state| {
                    let (chunk_index, _) = world.get_player_character(peer_state.pc_handle)?;
                    Some((&mut peer_state.loaded_chunk_indices, chunk_index))
                })
            {
                // Get neighbor indices and send unloads for old chunks
                let neighbor_indices = get_neighbor_chunks_indices(player_chunk_index);
                let mut to_unload = Vec::with_capacity(3);
                for i in &*loaded_chunk_indices {
                    if !neighbor_indices.contains(i) {
                        to_unload.push(*i);
                    }
                }
                if !to_unload.is_empty() {
                    gameplay_socket.send_action(*peer, ServerAction::UnloadChunks(to_unload));
                }

                // Send out effects or entire chunks depending on neighbors are new
                let mut chunk_updates = Vec::with_capacity(9);
                for i in &neighbor_indices {
                    let effects = &chunks_effects[*i];
                    let synced_chunk = loaded_chunk_indices.contains(i);
                    if effects.is_empty() && synced_chunk {
                        continue;
                    }
                    let update = if synced_chunk {
                        ChunkUpdate::Effects(effects.clone())
                    } else {
                        ChunkUpdate::ResetTo(world.chunks[*i].clone().unwrap())
                    };
                    chunk_updates.push((*i, update));
                }
                let effects_action = ServerAction::Effects {
                    time: world.time,
                    chunk_updates,
                };
                gameplay_socket.send_action(*peer, effects_action);

                // Update the "already loaded" list
                loaded_chunk_indices.clear();
                loaded_chunk_indices.extend_from_slice(&neighbor_indices);
            } else if log::log_enabled!(log::Level::Debug) {
                if players.contains_key(peer) {
                    log::debug!("Player character missing for peer {:032x}!", peer.0);
                } else {
                    // The peer id is just too new to have been added into `players`.
                }
            }
        }

        // Send out the Effects
        gameplay_socket.transport();

        // Finally, update the world state to the next value of `world.time`
        world.update();
    }
}

/// Returns the neighboring chunks to the given chunk index. There are 4-9
/// neighbors for every chunk, depending on if they're on the border of the
/// world.
fn get_neighbor_chunks_indices(player_chunk_index: usize) -> Vec<usize> {
    let x = (player_chunk_index % CHUNKS_X) as i32;
    let y = (player_chunk_index / CHUNKS_X) as i32;
    let offsets = [
        (-1, -1),
        (0, -1),
        (1, -1),
        (-1, 0),
        (0, 0),
        (1, 0),
        (-1, 1),
        (0, 1),
        (1, 1),
    ];
    offsets
        .into_iter()
        .filter_map(|(xo, yo)| {
            let new_x = x + xo;
            let new_y = y + yo;
            if new_x < 0 || new_y < 0 || new_x >= CHUNKS_X as i32 || new_y >= CHUNKS_Y as i32 {
                None
            } else {
                Some(new_x as usize + new_y as usize * CHUNKS_X)
            }
        })
        .collect::<Vec<_>>()
}

/// Takes a [ClientAction], the [PlayerCharacter] associated with the action,
/// and the [World], and comes up with the [Effect]s that the action causes. The
/// return value contains the appropriate chunk index for each [Effect].
fn make_effects(
    action: ClientAction,
    world: &World,
    (handle, player): (PcHandle, &PlayerCharacter),
    chunk_index: usize,
) -> Vec<(usize, Effect)> {
    let move_effects = |dx: i32, dy: i32| {
        if let Some(current_move) = &player.current_move {
            if world.time < current_move.start_frame + current_move.duration {
                return Vec::with_capacity(0);
            }
        }
        let Point(px, py) = player.position;
        let chunk_x = chunk_index % CHUNKS_X;
        let chunk_y = chunk_index / CHUNKS_X;
        let moving_against_border = (dx == -1 && px == 0 && chunk_x == 0)
            || (dx == 1 && px == CHUNK_WIDTH as i32 - 1 && chunk_x == CHUNKS_X - 1)
            || (dy == -1 && py == 0 && chunk_y == 0)
            || (dy == 1 && py == CHUNK_HEIGHT as i32 - 1 && chunk_y == CHUNKS_Y - 1);
        if moving_against_border {
            return Vec::with_capacity(0);
        }
        let new_x_offset_by_a_chunk = px as i32 + dx + CHUNK_WIDTH as i32;
        let new_y_offset_by_a_chunk = py as i32 + dy + CHUNK_HEIGHT as i32;
        let chunk_dx = new_x_offset_by_a_chunk / CHUNK_WIDTH as i32 - 1;
        let chunk_dy = new_y_offset_by_a_chunk / CHUNK_HEIGHT as i32 - 1;
        let new_chunk_x = chunk_x as i32 + chunk_dx;
        let new_chunk_y = chunk_y as i32 + chunk_dy;
        let new_chunk_i = (new_chunk_x + new_chunk_y * CHUNKS_X as i32) as usize;
        // Safety: the server always has all chunks loaded.
        let chunk = world.chunks[new_chunk_i].as_ref().unwrap();
        let new_x = new_x_offset_by_a_chunk % CHUNK_WIDTH as i32;
        let new_y = new_y_offset_by_a_chunk % CHUNK_WIDTH as i32;
        let move_effect = Effect::MovePlayerCharacter {
            handle,
            old_position: Point(
                px - chunk_dx * CHUNK_WIDTH as i32,
                py - chunk_dy * CHUNK_HEIGHT as i32,
            ),
            new_position: Point(new_x, new_y),
        };
        if chunk.is_wall(new_x, new_y) {
            Vec::with_capacity(0)
        } else if new_chunk_i != chunk_index {
            let despawn_effect = Effect::DespawnPlayerCharacter(handle);
            let spawn_effect = Effect::SpawnPlayerCharacter {
                handle,
                position: Point(new_x, new_y),
            };
            vec![
                (chunk_index, despawn_effect),
                (new_chunk_i, spawn_effect),
                (new_chunk_i, move_effect),
            ]
        } else {
            vec![(chunk_index, move_effect)]
        }
    };

    use ClientAction::*;
    match action {
        KeepAlive | Hello => vec![],
        MoveLeft => move_effects(-1, 0),
        MoveRight => move_effects(1, 0),
        MoveUp => move_effects(0, -1),
        MoveDown => move_effects(0, 1),
    }
}