R-Type
Distributed multiplayer game engine in C++
Loading...
Searching...
No Matches
GameLoop Class Reference

Main game loop orchestrating all subsystems. More...

#include <GameLoop.hpp>

Collaboration diagram for GameLoop:
Collaboration graph

Public Member Functions

 GameLoop (EventBus &eventBus, Replicator &replicator, const std::string &playerName)
 Constructor with shared EventBus and Replicator.
 
 ~GameLoop ()
 Destructor.
 
bool initialize ()
 Initialize all game subsystems.
 
void run ()
 Start the main game loop.
 
void shutdown ()
 Stop and clean up all subsystems.
 
void stop ()
 Stop the game loop.
 
void setReconciliationThreshold (float threshold)
 Set the reconciliation threshold for client-side prediction.
 
float getReconciliationThreshold () const
 Get the current reconciliation threshold.
 

Private Member Functions

void update (float deltaTime)
 Update game logic (variable timestep)
 
void fixedUpdate (float fixedDeltaTime)
 Update physics simulation (fixed timestep)
 
void render ()
 Perform rendering of current frame.
 
void processInput ()
 Process player inputs.
 
float calculateDeltaTime ()
 Calculate time elapsed since last frame.
 
void handleNetworkMessage (const NetworkEvent &event)
 Handle incoming network messages.
 
void handleUIEvent (const UIEvent &event)
 
void handleGameStart (const std::vector< uint8_t > &payload)
 
void handleGameState (const std::vector< uint8_t > &payload)
 
void handleGameruleUpdate (const std::vector< uint8_t > &payload)
 
void handleRoomList (const std::vector< uint8_t > &payload)
 
void handleRoomState (const std::vector< uint8_t > &payload)
 
void handleEntityDestroyed (const std::vector< uint8_t > &payload)
 
void handleChatMessage (const std::vector< uint8_t > &payload)
 
void handleLeftRoom (const std::vector< uint8_t > &payload)
 
void handleGameOver (const std::vector< uint8_t > &payload)
 
void processServerReconciliation (const RType::Messages::S2C::EntityState &entity)
 
void simulateInputHistory (float &x, float &y)
 

Private Attributes

EventBus_eventBus
 
std::unique_ptr< InputBuffer_inputBuffer
 
Replicator_replicator
 
std::unique_ptr< Rendering_rendering
 
bool _running = false
 
bool _initialized = false
 
float _fixedTimestep = 1.0f / 60.0f
 
float _accumulator = 0.0f
 
uint32_t _currentFrame = 0
 
uint32_t _inputSequenceId = 0
 
std::deque< RType::Messages::C2S::PlayerInput::InputSnapshot_inputHistory
 
std::optional< uint32_t > _myEntityId
 
uint32_t _myPlayerId = 0
 
bool _entityInitialized = false
 
bool _justCreatedRoom
 
std::string _playerName
 
bool _isMoving = false
 
float _playerSpeed = 300.0f
 
bool _clientSidePredictionEnabled = true
 
float _gameSpeedMultiplier = 1.0f
 
std::unordered_set< uint32_t > _knownEntityIds
 

Static Private Attributes

static constexpr size_t INPUT_HISTORY_SIZE = 12
 

Detailed Description

Main game loop orchestrating all subsystems.

GameLoop is the conductor of the R-Type client. It coordinates and synchronizes all components:

Temporal architecture:

Frame N:
1. ProcessInput() - Capture keyboard/mouse
2. FixedUpdate() x N - Physics simulation (60 FPS fixed)
3. Update(deltaTime) - Variable game logic
4. Render() - Display (VSync)

Fixed timestep:

  • Physics runs at constant 60 FPS (16.67ms per frame)
  • Decoupled from display framerate
  • Guarantees deterministic behavior
  • Essential for client prediction and network synchronization

Definition at line 57 of file GameLoop.hpp.

Constructor & Destructor Documentation

◆ GameLoop()

GameLoop::GameLoop ( EventBus eventBus,
Replicator replicator,
const std::string &  playerName 
)

Constructor with shared EventBus and Replicator.

Uses the provided EventBus and Replicator from Client. Call initialize() to start other subsystems.

Parameters
eventBusShared EventBus instance
replicatorShared Replicator instance
playerNameLocal player's display name (for host detection)

Definition at line 15 of file GameLoop.cpp.

◆ ~GameLoop()

GameLoop::~GameLoop ( )

Destructor.

Properly stops all subsystems and frees resources.

Definition at line 18 of file GameLoop.cpp.

References shutdown().

Here is the call graph for this function:

Member Function Documentation

◆ calculateDeltaTime()

float GameLoop::calculateDeltaTime ( )
private

Calculate time elapsed since last frame.

Returns
Delta time in seconds

Definition at line 482 of file GameLoop.cpp.

Referenced by run().

◆ fixedUpdate()

void GameLoop::fixedUpdate ( float  fixedDeltaTime)
private

Update physics simulation (fixed timestep)

Called N times per frame to guarantee 60 FPS simulation.

Parameters
fixedDeltaTimeFixed simulation time (1/60 = 0.0167s)

Definition at line 338 of file GameLoop.cpp.

Referenced by run().

◆ getReconciliationThreshold()

float GameLoop::getReconciliationThreshold ( ) const

Get the current reconciliation threshold.

Returns
Current threshold in pixels
Note
Delegates to Rendering -> EntityRenderer

Definition at line 291 of file GameLoop.cpp.

References _rendering.

◆ handleChatMessage()

void GameLoop::handleChatMessage ( const std::vector< uint8_t > &  payload)
private

Definition at line 806 of file GameLoop.cpp.

References _rendering, RType::Messages::S2C::S2CChatMessage::deserialize(), LOG_ERROR, and LOG_INFO.

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleEntityDestroyed()

void GameLoop::handleEntityDestroyed ( const std::vector< uint8_t > &  payload)
private

Definition at line 654 of file GameLoop.cpp.

References _entityInitialized, _myEntityId, _rendering, RType::Messages::S2C::EntityDestroyed::deserialize(), LOG_ERROR, LOG_INFO, and LOG_WARNING.

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleGameOver()

void GameLoop::handleGameOver ( const std::vector< uint8_t > &  payload)
private

Definition at line 855 of file GameLoop.cpp.

References _rendering, RType::Messages::S2C::GameOver::deserialize(), LOG_ERROR, and LOG_INFO.

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleGameruleUpdate()

void GameLoop::handleGameruleUpdate ( const std::vector< uint8_t > &  payload)
private

◆ handleGameStart()

void GameLoop::handleGameStart ( const std::vector< uint8_t > &  payload)
private

Definition at line 529 of file GameLoop.cpp.

References _entityInitialized, _myEntityId, _rendering, RType::Messages::S2C::GameStart::deserialize(), LOG_ERROR, and LOG_INFO.

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleGameState()

void GameLoop::handleGameState ( const std::vector< uint8_t > &  payload)
private

◆ handleLeftRoom()

void GameLoop::handleLeftRoom ( const std::vector< uint8_t > &  payload)
private

Definition at line 822 of file GameLoop.cpp.

References _eventBus, _myPlayerId, _rendering, BACK_TO_ROOM_LIST, LOG_ERROR, LOG_INFO, and EventBus::publish().

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleNetworkMessage()

◆ handleRoomList()

void GameLoop::handleRoomList ( const std::vector< uint8_t > &  payload)
private

◆ handleRoomState()

void GameLoop::handleRoomState ( const std::vector< uint8_t > &  payload)
private

Definition at line 606 of file GameLoop.cpp.

References _myPlayerId, _rendering, RType::Messages::S2C::RoomState::deserialize(), LOG_ERROR, and LOG_INFO.

Referenced by handleNetworkMessage().

Here is the call graph for this function:

◆ handleUIEvent()

◆ initialize()

bool GameLoop::initialize ( )

Initialize all game subsystems.

Initializes in order:

  1. EventBus
  2. InputBuffer
  3. Replicator
  4. Rendering (window, textures)
  5. ECS (future)
Returns
true if all systems initialize correctly
false if a system fails (error logged)
Note
On failure, automatically calls shutdown()
Must be called before run()

Definition at line 22 of file GameLoop.cpp.

References _eventBus, _initialized, _inputBuffer, _rendering, handleNetworkMessage(), handleUIEvent(), LOG_INFO, and EventBus::subscribe().

Here is the call graph for this function:

◆ processInput()

◆ processServerReconciliation()

◆ render()

void GameLoop::render ( )
private

Perform rendering of current frame.

Delegates to Rendering system.

Definition at line 347 of file GameLoop.cpp.

References _rendering, shutdown(), and stop().

Referenced by run().

Here is the call graph for this function:

◆ run()

void GameLoop::run ( )

Start the main game loop.

Launches the game loop that runs until:

  • Window closed by user
  • stop() called
  • Critical error

Loop structure:

while (running) {
float deltaTime = calculateDeltaTime();
accumulator += deltaTime;
// Fixed timestep for physics
while (accumulator >= fixedTimestep) {
fixedUpdate(fixedTimestep);
accumulator -= fixedTimestep;
currentFrame++;
}
update(deltaTime);
render();
}
void processInput()
Process player inputs.
Definition GameLoop.cpp:362
void update(float deltaTime)
Update game logic (variable timestep)
Definition GameLoop.cpp:298
void render()
Perform rendering of current frame.
Definition GameLoop.cpp:347
float calculateDeltaTime()
Calculate time elapsed since last frame.
Definition GameLoop.cpp:482
void fixedUpdate(float fixedDeltaTime)
Update physics simulation (fixed timestep)
Definition GameLoop.cpp:338
Note
Blocking until game stops
Uses fixed timestep for simulation

Definition at line 161 of file GameLoop.cpp.

References _accumulator, _currentFrame, _fixedTimestep, _initialized, _myEntityId, _myPlayerId, _rendering, _replicator, _running, calculateDeltaTime(), fixedUpdate(), Replicator::getMyPlayerId(), LOG_ERROR, LOG_INFO, LOG_WARNING, processInput(), Replicator::processMessages(), render(), Replicator::sendChatMessage(), and update().

Here is the call graph for this function:

◆ setReconciliationThreshold()

void GameLoop::setReconciliationThreshold ( float  threshold)

Set the reconciliation threshold for client-side prediction.

Parameters
thresholdDistance in pixels before server correction is applied

Adjusts how tolerant the client-side prediction is before reconciling with the server's authoritative position. This should be tuned based on observed network conditions:

  • Low latency (<50ms): 3.0f - 5.0f pixels (tight sync, minimal drift)
  • Medium latency (50-150ms): 5.0f - 10.0f pixels (default, balanced)
  • High latency (>150ms): 10.0f - 20.0f pixels (loose sync, smoother visuals)

Call this method when you detect network latency changes or based on user preferences/settings.

Note
Default is 5.0f pixels (suitable for medium latency)
Delegates to Rendering -> EntityRenderer

Definition at line 284 of file GameLoop.cpp.

References _rendering, and LOG_INFO.

◆ shutdown()

void GameLoop::shutdown ( )

Stop and clean up all subsystems.

Stops in reverse initialization order:

  1. Rendering
  2. Replicator (clean disconnection)
  3. InputBuffer
  4. EventBus
Note
Called automatically by destructor
Idempotent (can be called multiple times)

Definition at line 258 of file GameLoop.cpp.

References _initialized, _inputBuffer, _rendering, _running, and LOG_INFO.

Referenced by render(), and ~GameLoop().

◆ simulateInputHistory()

void GameLoop::simulateInputHistory ( float &  x,
float &  y 
)
private

◆ stop()

void GameLoop::stop ( )

Stop the game loop.

Requests game loop to stop at next iteration. Game will terminate cleanly after current frame.

Note
Non-blocking
Loop terminates after render() of current frame

Definition at line 279 of file GameLoop.cpp.

References _running, and LOG_INFO.

Referenced by handleUIEvent(), and render().

◆ update()

void GameLoop::update ( float  deltaTime)
private

Update game logic (variable timestep)

Called once per frame for non-critical logic.

Parameters
deltaTimeTime elapsed since last call (in seconds)

Definition at line 298 of file GameLoop.cpp.

References _playerSpeed, _rendering, _replicator, and Replicator::getLatency().

Referenced by run().

Here is the call graph for this function:

Member Data Documentation

◆ _accumulator

float GameLoop::_accumulator = 0.0f
private

Definition at line 256 of file GameLoop.hpp.

Referenced by run().

◆ _clientSidePredictionEnabled

bool GameLoop::_clientSidePredictionEnabled = true
private

Definition at line 275 of file GameLoop.hpp.

Referenced by handleGameState(), and processInput().

◆ _currentFrame

uint32_t GameLoop::_currentFrame = 0
private

Definition at line 257 of file GameLoop.hpp.

Referenced by run().

◆ _entityInitialized

bool GameLoop::_entityInitialized = false
private

Definition at line 269 of file GameLoop.hpp.

Referenced by handleEntityDestroyed(), handleGameStart(), and processInput().

◆ _eventBus

EventBus* GameLoop::_eventBus
private

Definition at line 247 of file GameLoop.hpp.

Referenced by handleLeftRoom(), and initialize().

◆ _fixedTimestep

float GameLoop::_fixedTimestep = 1.0f / 60.0f
private

Definition at line 255 of file GameLoop.hpp.

Referenced by processInput(), and run().

◆ _gameSpeedMultiplier

float GameLoop::_gameSpeedMultiplier = 1.0f
private

Definition at line 276 of file GameLoop.hpp.

Referenced by handleGameruleUpdate(), processInput(), and simulateInputHistory().

◆ _initialized

bool GameLoop::_initialized = false
private

Definition at line 253 of file GameLoop.hpp.

Referenced by initialize(), run(), and shutdown().

◆ _inputBuffer

std::unique_ptr<InputBuffer> GameLoop::_inputBuffer
private

Definition at line 248 of file GameLoop.hpp.

Referenced by initialize(), and shutdown().

◆ _inputHistory

std::deque<RType::Messages::C2S::PlayerInput::InputSnapshot> GameLoop::_inputHistory
private

Definition at line 264 of file GameLoop.hpp.

Referenced by processInput(), processServerReconciliation(), and simulateInputHistory().

◆ _inputSequenceId

uint32_t GameLoop::_inputSequenceId = 0
private

Definition at line 260 of file GameLoop.hpp.

Referenced by processInput().

◆ _isMoving

bool GameLoop::_isMoving = false
private

Definition at line 273 of file GameLoop.hpp.

Referenced by processInput().

◆ _justCreatedRoom

bool GameLoop::_justCreatedRoom
private
Initial value:
=
false

Definition at line 270 of file GameLoop.hpp.

Referenced by handleUIEvent().

◆ _knownEntityIds

std::unordered_set<uint32_t> GameLoop::_knownEntityIds
private

Definition at line 279 of file GameLoop.hpp.

Referenced by handleGameState().

◆ _myEntityId

std::optional<uint32_t> GameLoop::_myEntityId
private

◆ _myPlayerId

uint32_t GameLoop::_myPlayerId = 0
private

Definition at line 268 of file GameLoop.hpp.

Referenced by handleLeftRoom(), handleRoomState(), and run().

◆ _playerName

std::string GameLoop::_playerName
private

Definition at line 272 of file GameLoop.hpp.

◆ _playerSpeed

float GameLoop::_playerSpeed = 300.0f
private

Definition at line 274 of file GameLoop.hpp.

Referenced by handleGameruleUpdate(), processInput(), simulateInputHistory(), and update().

◆ _rendering

◆ _replicator

Replicator* GameLoop::_replicator
private

Definition at line 249 of file GameLoop.hpp.

Referenced by handleUIEvent(), processInput(), run(), and update().

◆ _running

bool GameLoop::_running = false
private

Definition at line 252 of file GameLoop.hpp.

Referenced by run(), shutdown(), and stop().

◆ INPUT_HISTORY_SIZE

constexpr size_t GameLoop::INPUT_HISTORY_SIZE = 12
staticconstexprprivate

Definition at line 263 of file GameLoop.hpp.

Referenced by processInput().


The documentation for this class was generated from the following files: