R-Type
Networked shoot'em up built on Aegis2D
Loading...
Searching...
No Matches
client_session.hpp
Go to the documentation of this file.
1
3#pragma once
4#include <aegis2d/core/clock.hpp>
5#include <aegis2d/ecs/components.hpp>
6#include <aegis2d/net/binary.hpp>
7#include <aegis2d/net/context.hpp>
8#include <aegis2d/net/endpoint.hpp>
9#include <aegis2d/net/packet.hpp>
10#include <aegis2d/net/reliability.hpp>
11#include <aegis2d/net/rtt.hpp>
12#include <aegis2d/net/tcp_connection.hpp>
13#include <aegis2d/net/traffic.hpp>
14#include <aegis2d/net/udp_socket.hpp>
15
16#include <rtype/chat_log.hpp>
18#include <rtype/input.hpp>
19#include <rtype/login.hpp>
21#include <rtype/rooms.hpp>
22#include <rtype/scores.hpp>
25#include <rtype/tuning.hpp>
26
27#include <chrono>
28#include <cstddef>
29#include <cstdint>
30#include <memory>
31#include <optional>
32#include <span>
33#include <string>
34#include <string_view>
35#include <vector>
36
37namespace rtype {
38
40enum class ClientState : std::uint8_t {
42 Idle,
48 Lobby,
50 InRoom,
52 Binding,
54 InGame,
56 Failed,
59 Lost,
61 Closed,
62};
63
67[[nodiscard]] std::string_view to_string(ClientState state) noexcept;
68
72 std::string host = "127.0.0.1";
74 std::uint16_t tcp_port = 4242;
76 std::string name = "player";
80 bool choose_room = false;
81};
82
104public:
106 using Clock = std::chrono::steady_clock;
107
109 static constexpr std::chrono::milliseconds connect_interval{250};
111 static constexpr std::chrono::seconds bind_timeout{5};
113 static constexpr std::chrono::seconds login_timeout{5};
115 static constexpr std::chrono::seconds server_timeout{5};
117 static constexpr std::chrono::seconds room_refresh{1};
119 static constexpr aegis2d::core::Duration input_interval =
120 aegis2d::core::step_from_rate(tuning::tick_rate);
121
125 ClientSession(aegis2d::net::NetworkContext& context, ClientSettings settings);
126
127 ClientSession(const ClientSession&) = delete;
133
137 void start();
138
144 void update(Clock::time_point now);
145
150 void set_input(aegis2d::ecs::PlayerInput input) noexcept;
151
155 void create_room(const CreateRoomRequest& request);
156
161 void join_room(std::uint8_t room);
162
165 void set_ready(bool ready);
166
169
177 bool send_chat(std::string_view text);
178
182 [[nodiscard]] ChatLog& chat() noexcept;
183
188 [[nodiscard]] const std::vector<ScoreRecord>& scores() const noexcept;
189
192 [[nodiscard]] bool ready() const noexcept;
193
196 [[nodiscard]] const RoomPlayers& room_players() const noexcept;
197
200 [[nodiscard]] const std::vector<RoomRecord>& rooms() const noexcept;
201
204 [[nodiscard]] const std::string& room_error() const noexcept;
205
209 void leave();
210
213 [[nodiscard]] ClientState state() const noexcept;
214
217 [[nodiscard]] const std::string& error() const noexcept;
218
221 [[nodiscard]] const std::optional<LoginAccepted>& login() const noexcept;
222
225 [[nodiscard]] const std::optional<aegis2d::net::Endpoint>& server_udp() const noexcept;
226
229 [[nodiscard]] std::uint64_t connects_sent() const noexcept;
230
235 [[nodiscard]] ClientWorld& world() noexcept;
236
238 [[nodiscard]] const ClientWorld& world() const noexcept;
239
244 [[nodiscard]] const SnapshotDecoder& snapshots() const noexcept;
245
256 [[nodiscard]] const ShipPrediction& prediction() const noexcept;
257
260 [[nodiscard]] std::uint64_t inputs_sent() const noexcept;
261
266 [[nodiscard]] std::optional<std::uint16_t> last_input() const noexcept;
267
273 [[nodiscard]] std::optional<std::uint16_t> acknowledged_input() const noexcept;
274
280 [[nodiscard]] const aegis2d::net::TrafficCounters& traffic() const noexcept;
281
289 [[nodiscard]] const aegis2d::net::RttEstimator& rtt() const noexcept;
290
295 [[nodiscard]] const NetworkStats& network_stats() const noexcept;
296
297private:
298 void fail(std::string reason);
299 void on_connected();
300 void on_message(std::span<const std::byte> message);
301 void on_datagram(const aegis2d::net::Endpoint& from, std::span<const std::byte> datagram);
302 void start_binding();
303 void on_room_message(std::span<const std::byte> message);
304 bool on_chat(std::span<const std::byte> message);
305 void send_request(std::vector<std::byte> message);
306 void send_connect(Clock::time_point now);
307 void send_input(Clock::time_point now);
308 void predict(const Snapshot& snapshot);
309 void on_game_datagram(const aegis2d::net::PacketHeader& header,
310 aegis2d::net::BinaryReader& payload, Clock::time_point now);
311
312 aegis2d::net::NetworkContext& context_;
313 ClientSettings settings_;
314 ClientState state_ = ClientState::Idle;
315 std::string error_;
316 std::unique_ptr<aegis2d::net::TcpConnection> connection_;
317 std::unique_ptr<aegis2d::net::UdpSocket> socket_;
318 aegis2d::net::ReliableChannel channel_;
319 std::optional<aegis2d::net::Endpoint> server_tcp_;
320 std::optional<aegis2d::net::Endpoint> server_udp_;
321 std::optional<LoginAccepted> login_;
322 Clock::time_point started_;
323 Clock::time_point accepted_;
324 Clock::time_point last_connect_;
325 Clock::time_point last_room_list_;
326 std::vector<RoomRecord> rooms_;
327 std::string room_error_;
328 RoomPlayers room_players_;
329 ChatLog chat_;
330 std::vector<ScoreRecord> scores_;
331 std::uint64_t connects_sent_ = 0;
332 std::uint8_t held_ = 0;
333 Clock::time_point next_input_;
334 std::uint64_t inputs_sent_ = 0;
335 // The last inputs sent, oldest first: each Input carries them all.
336 std::vector<InputRecord> recent_inputs_;
337 aegis2d::net::TrafficCounters traffic_;
338 NetworkStats network_stats_;
339 // Last valid datagram from the server, in game.
340 Clock::time_point last_heard_;
341 ClientWorld world_;
342 SnapshotDecoder snapshots_;
343 ShipPrediction prediction_;
344 // Lives of the player when the prediction started: one less means a respawn.
345 std::uint8_t predicted_lives_ = 0;
346 // Tick of the last snapshot the prediction started from or was reconciled with.
347 std::optional<std::uint32_t> reconciled_tick_;
348 // Time of the last update(), to smooth the corrections of the prediction.
349 std::optional<Clock::time_point> last_update_;
350 // Messages handed to the connection, to close it once they have left.
351 std::uint64_t sent_ = 0;
352 bool closing_ = false;
353 // Whether the player said it is ready, in its room.
354 bool ready_ = false;
355};
356
357} // namespace rtype
The last chat messages a client shows, each for a few seconds.
The chat messages to show, newest last, each for shown_for.
Definition chat_log.hpp:19
The client side of a session (RFC section 3).
Definition client_session.hpp:103
const std::vector< ScoreRecord > & scores() const noexcept
The best scores of the server, as the lobby shows them (RFC section 3.9).
std::uint64_t inputs_sent() const noexcept
Number of Input datagrams sent.
void join_room(std::uint8_t room)
Asks to join a room, in the lobby (JoinRoom, RFC section 3.7).
~ClientSession()
Closes the sockets, without Logout: call leave() first to say goodbye.
const SnapshotDecoder & snapshots() const noexcept
The snapshots rebuilt from the Snapshot datagrams, as baselines of the next.
std::optional< std::uint16_t > acknowledged_input() const noexcept
Sequence of the last Input of the player the server applied, from the player record of its own player...
void create_room(const CreateRoomRequest &request)
Asks the server for a new room, in the lobby (CreateRoom, RFC section 3.6).
static constexpr std::chrono::seconds login_timeout
Longest wait for the TCP connection and LoginAccepted.
Definition client_session.hpp:113
std::uint64_t connects_sent() const noexcept
Number of Connect datagrams sent.
std::optional< std::uint16_t > last_input() const noexcept
Sequence of the last Input sent (RFC section 4.2).
void leave_room()
Leaves the room for the lobby, where the rooms are listed again (LeaveRoom).
const ShipPrediction & prediction() const noexcept
The client's own ship, moved at once by each Input sent.
const std::string & room_error() const noexcept
Why the last room could not be created or joined.
ClientSession(aegis2d::net::NetworkContext &context, ClientSettings settings)
Creates a session, not started.
const std::vector< RoomRecord > & rooms() const noexcept
The rooms of the server, from its last RoomList.
static constexpr std::chrono::milliseconds connect_interval
Time between two Connect datagrams (RFC section 3.4).
Definition client_session.hpp:109
static constexpr std::chrono::seconds server_timeout
Longest silence of the server in game before the session is lost (RFC 5.5).
Definition client_session.hpp:115
bool ready() const noexcept
Whether the player said it is ready, in its room.
ClientState state() const noexcept
Where the session is.
void update(Clock::time_point now)
Runs the timers: Connect resent, the login and binding timeouts, and, in game, one Input every input_...
const NetworkStats & network_stats() const noexcept
Loss, snapshot interval and jitter of the server's datagrams.
bool send_chat(std::string_view text)
Sends a chat message to the players of the room, or of the lobby (ChatSend, RFC section 3....
const aegis2d::net::RttEstimator & rtt() const noexcept
Round trip time to the server, with its jitter.
const std::optional< LoginAccepted > & login() const noexcept
What the server gave at login.
const std::optional< aegis2d::net::Endpoint > & server_udp() const noexcept
The server's UDP endpoint, once logged in.
static constexpr std::chrono::seconds room_refresh
Time between two ListRooms in the lobby.
Definition client_session.hpp:117
static constexpr std::chrono::seconds bind_timeout
Longest wait for Accept after LoginAccepted (RFC section 3.4).
Definition client_session.hpp:111
std::chrono::steady_clock Clock
Clock of the timers.
Definition client_session.hpp:106
ChatLog & chat() noexcept
The last chat messages of the room, and why a message of this client was not sent,...
ClientSession(const ClientSession &)=delete
const std::string & error() const noexcept
Why the session failed or was lost.
ClientWorld & world() noexcept
The world as the server describes it, once in game.
ClientSession & operator=(const ClientSession &)=delete
const RoomPlayers & room_players() const noexcept
The players of the room joined, from the server's last RoomPlayers.
const aegis2d::net::TrafficCounters & traffic() const noexcept
Datagrams exchanged with the server, by direction and packet type.
void leave()
Leaves the server: sends Logout and closes once it has left.
void set_input(aegis2d::ecs::PlayerInput input) noexcept
Sets the actions the player holds, sent in every Input until the next call.
ClientSession & operator=(ClientSession &&)=delete
ClientSession(ClientSession &&)=delete
void set_ready(bool ready)
Says whether the player is ready to start, in a room (SetReady, RFC 3.7).
void start()
Connects to the server and logs in.
static constexpr aegis2d::core::Duration input_interval
Time between two Input datagrams: one per server tick (RFC section 4.2).
Definition client_session.hpp:119
The world as the server describes it (RFC sections 4.3 to 4.5).
Definition client_world.hpp:102
Measures the loss and the jitter of the server's datagrams over a sliding window.
Definition network_stats.hpp:35
Where the client's own ship is, before the server says so.
Definition ship_prediction.hpp:22
Rebuilds the snapshots of the server from the payloads of its Snapshot datagrams.
Definition snapshot_decoder.hpp:22
The client's copy of the server's world, built from snapshots and events.
Inputs of a player sent to the server (RFC section 4.2).
TCP messages of the session (RFC section 3.2): encoding, decoding and name rules; those of the rooms ...
constexpr std::uint32_t tick_rate
Simulation rate of the server, in ticks per second.
Definition tuning.hpp:15
R-Type game code, built on the Aegis2D engine.
Definition enemy_scripts.hpp:16
@ InGame
The player is in game: it plays in its room until its session ends.
ClientState
Where the client is in its session.
Definition client_session.hpp:40
@ Closed
The player left with leave().
@ Lobby
Logged in with ClientSettings::choose_room: choosing a room (RFC 3.6, 3.7).
@ LoggingIn
LoginRequest sent, waiting for the answer.
@ InRoom
In the room joined from the lobby, until all its players are ready (RFC 3.7).
@ Binding
Logged in, sending Connect until Accept arrives.
@ Lost
The session was running and ended: the server stopped, went silent, closed the connection or ended th...
@ Failed
The session could not start; error() says why.
@ Connecting
Opening the TCP connection.
@ Idle
Not started.
std::string_view to_string(ChatRejection reason) noexcept
Short name of a rejection, for logs.
Packet loss, snapshot interval and jitter of the datagrams the client receives.
TCP messages of the rooms (RFC sections 3.6 and 3.7): listing them, creating one, joining and leaving...
TCP messages of the scoreboard (RFC section 3.9): encoding and decoding.
The client's own ship, moved at once by its inputs (client-side prediction).
The client side of delta snapshots: each snapshot rebuilt from its baseline.
What the client needs to join a server.
Definition client_session.hpp:70
std::string host
Numeric IPv4 or IPv6 address of the server, or "localhost".
Definition client_session.hpp:72
std::string name
Player name, 1 to 16 bytes of UTF-8 without control characters.
Definition client_session.hpp:76
std::uint16_t tcp_port
TCP port of the server.
Definition client_session.hpp:74
bool choose_room
Stays in the lobby after the login, where the rooms are listed, created and joined,...
Definition client_session.hpp:80
Content of a CreateRoom.
Definition rooms.hpp:131
One input of the player: the actions held at one tick of the client.
Definition input.hpp:29
Content of a LoginAccepted.
Definition login.hpp:116
Content of a RoomPlayers.
Definition rooms.hpp:101
A room, as a RoomList describes it.
Definition rooms.hpp:113
One score of a ScoreList.
Definition scores.hpp:17
The state of the world at one tick.
Definition snapshot.hpp:94
Gameplay values of R-Type: play area, speeds, sizes, health, lives and scores.