Air-Trap 1.0.0
A multiplayer R-Type clone game engine built with C++23 and ECS architecture
Loading...
Searching...
No Matches
Packet.hpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2025
3** R-Type
4** File description:
5** Packet.hpp, Packet
6 * declaration
7*/
8
14#ifndef RTYPE_NETWORK_PACKET_HPP_
15 #define RTYPE_NETWORK_PACKET_HPP_
16
18 #include "RType/Math/Vec2.hpp"
19
20 #include <bit>
21 #include <cstdint>
22 #include <cstring>
23 #include <span>
24 #include <stdexcept>
25 #include <string>
26 #include <string_view>
27 #include <utility>
28 #include <vector>
29 #include <asio/buffer.hpp>
30 #include <array>
31 #include <type_traits>
32
37namespace rtp::net
38{
39
41 // Constants and Enums
43
47 constexpr std::endian NATIVE_ENDIAN = std::endian::native;
48
52 constexpr uint16_t MAGIC_NUMBER = 0xA1B2;
53
57 constexpr size_t MTU_SIZE = 1400;
58
62 constexpr uint32_t MAX_STRING_SIZE = 2048;
63
67 constexpr uint32_t MAX_VECTOR_SIZE = 8192;
68
72 constexpr uint32_t MAX_BODY_SIZE = 64 * 1024;
73
78 enum class OpCode : uint8_t {
79 None = 0x00,
81 // Connection Management
82 Hello = 0x01,
83 Welcome = 0x02,
84 Disconnect = 0x03,
86 // Authentication
87 LoginRequest = 0x1A,
88 RegisterRequest = 0x1B,
89 LoginResponse = 0x9A,
90 RegisterResponse = 0x9B,
92 // Lobby Management
93 ListRooms = 0x04,
94 RoomList = 0x05,
95 CreateRoom = 0x06,
96 JoinRoom = 0x07,
97 LeaveRoom = 0x08,
98 RoomUpdate = 0x09,
99 SetReady = 0x0A,
100 RoomChatSended = 0x0B,
101 RoomChatReceived = 0x0C,
102 StartGame = 0x0D,
104 // Gameplay (C -> S)
105 InputTick = 0x10,
106 UpdateSelectedWeapon = 0x11,
108 // Game State (S -> C)
109 // RoomUpdate = 0x20, /**< Entity state snapshot */
110 EntitySpawn = 0x21,
111 EntityDeath = 0x22,
112 AmmoUpdate = 0x23,
113 Ping = 0x24,
114 Pong = 0x25,
115 DebugModeUpdate = 0x26,
116 Kicked = 0x27
117 ,
118 BeamState = 0x28,
119 ScoreUpdate = 0x29,
120 GameOver = 0x2A,
121 HealthUpdate = 0x2B
122 };
123
124 #pragma pack(push, 1)
125
130 struct Header {
131 uint16_t magic = MAGIC_NUMBER;
132 uint16_t sequenceId = 0;
133 uint32_t bodySize = 0;
134 uint16_t ackId = 0;
136 uint8_t reserved = 0;
137 uint32_t sessionId = 0;
138 };
139
144 enum class EntityType : uint8_t {
145 Player = 1,
146 Scout = 2,
147 Tank = 3,
148 Boss = 4,
149 Bullet = 5,
150 PowerupHeal = 6, // Red - Health regen
151 PowerupSpeed = 7, // (unused for now)
152 Obstacle = 8,
153 EnemyBullet = 9,
154 ObstacleSolid = 10,
155 ChargedBullet = 11,
156 PowerupDoubleFire = 12, // Yellow/White - Double fire for 20s
157 PowerupShield = 13, // Green - Shield (absorb 1 hit)
158 BossShield = 14,
159 Boss2 = 15, // Kraken Alien Boss (r-typesheet35.gif)
160 Boss2Bullet = 16 // Kraken's boomerang projectile
161 };
162
164 // Payload Structures
166
167 /***** Connection Management *****/
175 uint32_t sessionId;
176 };
177
183 uint8_t status;
184 };
185
186 /***** Authentication *****/
194 char username[32];
195 char password[32];
196 uint8_t weaponKind;
197 };
198
206 char username[32];
207 char password[32];
208 };
209
217 uint8_t success;
218 char username[32];
219 };
220
228 uint8_t success;
229 char username[32];
230 };
231
232 /***** Lobby Management *****/
233 enum class roomType : uint8_t {
234 Lobby = 0,
235 Public = 1,
236 Private = 2
237 };
244 struct RoomInfo {
245 uint32_t roomId;
246 char roomName[64];
247 uint32_t currentPlayers;
248 uint32_t maxPlayers;
249 uint8_t inGame;
251 float speed;
252 uint32_t duration;
253 uint32_t seed;
254 uint32_t levelId;
255 uint8_t roomType;
256 };
257
265 char roomName[64];
266 uint32_t maxPlayers;
268 float speed;
269 uint32_t levelId; // not used
270 uint32_t seed; // not used
271 uint32_t duration; // not used
272 uint8_t roomType;
273 };
274
282 uint32_t roomId;
283 uint8_t isSpectator;
284 };
285
293 uint32_t roomId;
294 uint32_t currentPlayers;
295 uint32_t serverTick;
296 uint16_t entityCount;
297 uint8_t inGame;
298 };
299
307 uint8_t isReady;
308 };
309
317 char message[256];
318 };
319
327 uint32_t sessionId;
328 char username[32];
329 char message[256];
330 };
331
332 /***** Gameplay *****/
343
349 uint32_t netId;
350 uint8_t type;
351 float posX;
352 float posY;
353 float sizeX{0.0f};
354 float sizeY{0.0f};
355 uint8_t weaponKind{0};
356 };
357
363 uint32_t netId;
364 uint8_t type;
366 };
367
375 uint16_t current;
376 uint16_t max;
377 uint8_t isReloading;
379 };
380
386 uint32_t ownerNetId;
387 uint8_t active;
389 float length;
390 float offsetY;
391 };
392
398 int32_t score;
399 };
400
406 char bestPlayer[32];
407 int32_t bestScore;
408 int32_t playerScore;
409 };
410
416 int32_t current;
417 int32_t max;
418 };
419
426 struct PingPayload {
427 uint64_t clientTimeMs;
428 };
429
437 uint8_t enabled;
438 };
439
440 #pragma pack(pop)
441
443 // Packet Class
445
454 using BufferSequence = std::array<asio::const_buffer, 2>;
455
461 uint8_t inputMask;
462 };
463
471 class Packet {
472 public:
474 std::vector<uint8_t> body;
479 Packet() = default;
480
485 explicit Packet(OpCode op);
486
490 void resetRead(void);
491
497
504 template <typename T>
505 static inline T to_network(T v)
506 {
507 if constexpr (std::is_enum_v<T>) {
508 using U = std::underlying_type_t<T>;
509 return static_cast<T>(to_network(static_cast<U>(v)));
510 } else if constexpr (std::is_integral_v<T>) {
511 if constexpr (sizeof(T) > 1 && NATIVE_ENDIAN == std::endian::little)
512 return std::byteswap(v);
513 return v;
514 } else if constexpr (std::is_same_v<T, float>) {
515 if constexpr (NATIVE_ENDIAN == std::endian::little) {
516 uint32_t u = std::bit_cast<uint32_t>(v);
517 u = std::byteswap(u);
518 return std::bit_cast<float>(u);
519 }
520 return v;
521 }
522 return v;
523 }
524
531 template <typename T>
532 static inline T from_network(T value) {
533 return to_network(value);
534 };
535
542 template <typename T>
543 auto operator<<(T data) -> Packet &;
544
551 template <typename T>
552 auto operator<<(const std::vector<T> &vec) -> Packet &;
553
559 auto operator<<(std::string_view str) -> Packet &;
560
567 template <typename T>
568 auto operator>>(T &data) -> Packet &;
569
576 template <typename T>
577 auto operator>>(std::vector<T> &vec) -> Packet &;
578
584 auto operator>>(std::string &str) -> Packet &;
585
586 private:
589 size_t _readPos = 0;
592 };
593}
594
595#include "Packet.tpp"
596
597#endif /* !RTYPE_NETWORK_PACKET_HPP_ */
Concepts for validating component types in the ECS.
Declaration of the 2-dimensional vector class.
Network packet with header and serializable body.
Definition Packet.hpp:471
static T to_network(T v)
Converts a primitive type (integer, float) from machine endianness to Big-Endian (network).
Definition Packet.hpp:505
size_t _readPos
Current read position in body.
Definition Packet.hpp:589
auto operator<<(std::string_view str) -> Packet &
Serialize string into packet body.
void _bumpBodySizeOrThrow()
Increment body size and check for overflow.
void resetRead(void)
Reset read position to beginning of body.
Definition Packet.cpp:31
auto operator>>(T &data) -> Packet &
Deserialize data from packet body.
Header _cacheHeader
Cached header with network endianness.
Definition Packet.hpp:591
auto operator<<(const std::vector< T > &vec) -> Packet &
Serialize vector into packet body.
auto operator>>(std::vector< T > &vec) -> Packet &
Deserialize vector from packet body.
BufferSequence getBufferSequence(void) const
Get buffer sequence for network transmission.
Definition Packet.cpp:36
std::vector< uint8_t > body
Packet body/payload.
Definition Packet.hpp:474
auto operator>>(std::string &str) -> Packet &
Deserialize string from packet body.
Packet()=default
Default constructor.
auto operator<<(T data) -> Packet &
Serialize data into packet body.
Header header
Packet header.
Definition Packet.hpp:473
static T from_network(T value)
Converts a primitive type (integer, float) from Big-Endian (network) to machine endianness.
Definition Packet.hpp:532
File : IEventPublisher.hpp License: MIT Author : Elias Josué HAJJAR LLAUQUEN elias-josue....
@ Lobby
Lobby room (system)
@ Public
Public room.
@ Private
Private room.
constexpr std::endian NATIVE_ENDIAN
Native endianness of the machine.
Definition Packet.hpp:47
constexpr uint32_t MAX_VECTOR_SIZE
Maximum size for serialized vectors.
Definition Packet.hpp:67
constexpr uint16_t MAGIC_NUMBER
Magic number for packet validation.
Definition Packet.hpp:52
constexpr uint32_t MAX_STRING_SIZE
Maximum sizes for strings, vectors, and packet bodies.
Definition Packet.hpp:62
EntityType
Types of entities in the game.
Definition Packet.hpp:144
OpCode
Operation codes for different packet types.
Definition Packet.hpp:78
@ DebugModeUpdate
Debug mode toggle.
@ SetReady
Set player readiness status.
@ LoginRequest
Client login request.
@ ListRooms
Request for room list.
@ BeamState
Beam start/stop notification.
@ Disconnect
Disconnect notification.
@ RoomChatReceived
Chat message received in room.
@ LeaveRoom
Request to leave a room.
@ Pong
Ping response.
@ RegisterResponse
Incorrect password notification.
@ LoginResponse
Successful connection notification.
@ UpdateSelectedWeapon
Client selected weapon changed.
@ JoinRoom
Request to join a room.
@ RoomList
Response with room list.
@ RegisterRequest
Server login response.
@ AmmoUpdate
Ammo update notification.
@ RoomChatSended
Chat message in room.
@ None
No operation.
@ Welcome
Server welcome response.
@ StartGame
Notification to start the game.
@ Hello
Client hello packet.
@ GameOver
Game over summary.
@ CreateRoom
Request to create a room.
@ HealthUpdate
Player health update.
@ RoomUpdate
Notification of room update.
@ EntitySpawn
Entity spawn notification.
@ ScoreUpdate
Player score update.
@ Kicked
Player kicked notification.
@ Ping
Ping request.
@ InputTick
Client input state.
@ EntityDeath
Entity death notification.
constexpr size_t MTU_SIZE
Safe UDP payload size to avoid fragmentation.
Definition Packet.hpp:57
std::array< asio::const_buffer, 2 > BufferSequence
@using BufferSequence
Definition Packet.hpp:454
constexpr uint32_t MAX_BODY_SIZE
Maximum size for packet body.
Definition Packet.hpp:72
Ammo update notification data Server OpCode.
Definition Packet.hpp:374
uint16_t current
Current ammo.
Definition Packet.hpp:375
uint16_t max
Max ammo.
Definition Packet.hpp:376
uint8_t isReloading
1 if reloading
Definition Packet.hpp:377
float cooldownRemaining
Remaining reload time.
Definition Packet.hpp:378
Notify clients that an entity's beam started or stopped.
Definition Packet.hpp:385
float length
Visual length of the beam in pixels.
Definition Packet.hpp:389
uint32_t ownerNetId
Network id of the player owning the beam.
Definition Packet.hpp:386
float timeRemaining
Remaining beam active time (seconds)
Definition Packet.hpp:388
uint8_t active
1 if beam active, 0 if stopped
Definition Packet.hpp:387
float offsetY
Vertical offset relative to owner (px)
Definition Packet.hpp:390
Generic boolean response payload.
Definition Packet.hpp:182
uint8_t status
Status code.
Definition Packet.hpp:183
Player connection data sended Client OpCode.
Definition Packet.hpp:174
uint32_t sessionId
Session identifier.
Definition Packet.hpp:175
Data for creating a new room Client OpCode.
Definition Packet.hpp:264
uint32_t seed
Seed for random generation.
Definition Packet.hpp:270
uint32_t duration
Duration of the game session.
Definition Packet.hpp:271
float difficulty
Difficulty level.
Definition Packet.hpp:267
uint32_t maxPlayers
Maximum number of players.
Definition Packet.hpp:266
uint8_t roomType
Room type (public/private)
Definition Packet.hpp:272
char roomName[64]
Desired room name.
Definition Packet.hpp:265
float speed
Speed multiplier.
Definition Packet.hpp:268
uint32_t levelId
Level identifier.
Definition Packet.hpp:269
Debug mode toggle data Server OpCode.
Definition Packet.hpp:436
uint8_t enabled
1 if debug mode enabled
Definition Packet.hpp:437
Entity death notification data.
Definition Packet.hpp:362
uint32_t netId
Network entity identifier.
Definition Packet.hpp:363
uint8_t type
Entity type.
Definition Packet.hpp:364
Vec2f position
Death position.
Definition Packet.hpp:365
Entity state snapshot data.
Definition Packet.hpp:337
uint32_t netId
Network entity identifier.
Definition Packet.hpp:338
Vec2f position
Entity position.
Definition Packet.hpp:339
Vec2f velocity
Entity velocity.
Definition Packet.hpp:340
float rotation
Entity rotation.
Definition Packet.hpp:341
Entity spawn notification data.
Definition Packet.hpp:348
uint8_t type
Entity type from EntityType.
Definition Packet.hpp:350
uint32_t netId
Network entity identifier.
Definition Packet.hpp:349
uint8_t weaponKind
Optional weapon kind for player entities.
Definition Packet.hpp:355
float posX
Spawn X position.
Definition Packet.hpp:351
float posY
Spawn Y position.
Definition Packet.hpp:352
float sizeY
Optional height for static entities.
Definition Packet.hpp:354
float sizeX
Optional width for static entities.
Definition Packet.hpp:353
Game over summary data.
Definition Packet.hpp:405
int32_t playerScore
Receiver player score.
Definition Packet.hpp:408
char bestPlayer[32]
Best player username.
Definition Packet.hpp:406
int32_t bestScore
Best score.
Definition Packet.hpp:407
Packet header with sequencing and acknowledgment support.
Definition Packet.hpp:130
uint16_t ackId
Last acknowledged packet.
Definition Packet.hpp:134
uint16_t magic
Magic number for validation.
Definition Packet.hpp:131
uint16_t sequenceId
Packet sequence number.
Definition Packet.hpp:132
uint8_t reserved
Reserved for future use.
Definition Packet.hpp:136
uint32_t sessionId
Session identifier.
Definition Packet.hpp:137
uint32_t bodySize
Size of the packet body.
Definition Packet.hpp:133
OpCode opCode
Operation code.
Definition Packet.hpp:135
Player health update data.
Definition Packet.hpp:415
int32_t max
Max health.
Definition Packet.hpp:417
int32_t current
Current health.
Definition Packet.hpp:416
Client input state data.
Definition Packet.hpp:460
uint8_t inputMask
Bitmask of input states.
Definition Packet.hpp:461
Data for joining an existing room Client OpCode.
Definition Packet.hpp:281
uint8_t isSpectator
1 if joining as spectator
Definition Packet.hpp:283
uint32_t roomId
Room identifier to join.
Definition Packet.hpp:282
char password[32]
Player password.
Definition Packet.hpp:195
uint8_t weaponKind
Selected weapon kind.
Definition Packet.hpp:196
char username[32]
Player username.
Definition Packet.hpp:194
Login response data sent by server for LoginResponse Server OpCode.
Definition Packet.hpp:216
uint8_t success
Login success flag.
Definition Packet.hpp:217
char username[32]
Player username.
Definition Packet.hpp:218
Ping request/response payload Client/Server /Pong OpCodes.
Definition Packet.hpp:426
uint64_t clientTimeMs
Client timestamp in ms.
Definition Packet.hpp:427
Player registration data sended by client Client OpCode.
Definition Packet.hpp:205
char password[32]
Player password.
Definition Packet.hpp:207
char username[32]
Player username.
Definition Packet.hpp:206
Registration response data sent by server for RegisterResponse Server OpCode.
Definition Packet.hpp:227
uint8_t success
Registration success flag.
Definition Packet.hpp:228
char username[32]
Player username.
Definition Packet.hpp:229
Data for sending chat messages in a room Client OpCode.
Definition Packet.hpp:316
char message[256]
Chat message content.
Definition Packet.hpp:317
Data for receiving chat messages in a room Server OpCode.
Definition Packet.hpp:326
char username[32]
Sender's username.
Definition Packet.hpp:328
char message[256]
Chat message content.
Definition Packet.hpp:329
uint32_t sessionId
Sender's session identifier.
Definition Packet.hpp:327
Information about a game room Server OpCode.
Definition Packet.hpp:244
uint32_t seed
Seed for random generation.
Definition Packet.hpp:253
uint32_t duration
Duration of the game session.
Definition Packet.hpp:252
uint8_t inGame
Is the game in progress.
Definition Packet.hpp:249
uint8_t roomType
Room type (public/private)
Definition Packet.hpp:255
float difficulty
Difficulty level.
Definition Packet.hpp:250
uint32_t roomId
Room identifier.
Definition Packet.hpp:245
uint32_t maxPlayers
Maximum number of players.
Definition Packet.hpp:248
float speed
Speed multiplier.
Definition Packet.hpp:251
uint32_t levelId
Level identifier.
Definition Packet.hpp:254
char roomName[64]
Room name.
Definition Packet.hpp:246
uint32_t currentPlayers
Current number of players.
Definition Packet.hpp:247
uint32_t roomId
Room identifier.
Definition Packet.hpp:293
uint8_t inGame
Is the game in progress.
Definition Packet.hpp:297
uint32_t currentPlayers
Current number of players.
Definition Packet.hpp:294
uint16_t entityCount
Entity position.
Definition Packet.hpp:296
uint32_t serverTick
Network entity identifier.
Definition Packet.hpp:295
Player score update notification data.
Definition Packet.hpp:397
int32_t score
Player score.
Definition Packet.hpp:398
Data for setting player readiness status Client OpCode.
Definition Packet.hpp:306
uint8_t isReady
Player readiness status.
Definition Packet.hpp:307