Set up basic deterministic lockstep

This commit is contained in:
Vladislav Khorev committed 2026-11-05 23:02:53 +06:00
1 parent 28c6e83eda
commit 23fef6f349
26 files changed
+1172 -239

No files matched your search

+131 -18
View File
@@ -3,6 +3,7 @@
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <atomic>
#include <deque>
#include <iostream>
#include <mutex>
#include <thread>
@@ -28,6 +29,8 @@ public:
, port_(std::move(port))
, path_(std::move(path))
{
std::cout << "[network] Resolving ws://" << host_ << ':' << port_
<< path_ << std::endl;
resolve();
thread_ = std::thread([this]() { io_.run(); });
}
@@ -49,6 +52,16 @@ public:
bool connected() const { return connected_.load(); }
bool connectionFailed() const { return connectionFailed_.load(); }
void send(std::string message)
{
asio::post(io_, [this, message = std::move(message)]() mutable {
if (!connected_.load()) return;
const bool writeInProgress = !outbound_.empty();
outbound_.push_back(std::move(message));
if (!writeInProgress) write();
});
}
private:
void resolve()
{
@@ -56,11 +69,15 @@ private:
host_, port_,
[this](beast::error_code error, tcp::resolver::results_type results) {
if (error) return fail("resolve", error);
std::cout << "[network] WebSocket host resolved; connecting"
<< std::endl;
asio::async_connect(
socket_.next_layer(), results,
[this](beast::error_code connectError,
const tcp::endpoint&) {
if (connectError) return fail("connect", connectError);
std::cout << "[network] TCP connected; starting WebSocket handshake"
<< std::endl;
socket_.set_option(
websocket::stream_base::timeout::suggested(
beast::role_type::client));
@@ -72,7 +89,7 @@ private:
connected_.store(true);
std::cout
<< "[network] Connected to ws://"
<< host_ << ':' << port_ << path_ << '\n';
<< host_ << ':' << port_ << path_ << std::endl;
read();
});
});
@@ -99,6 +116,17 @@ private:
});
}
void write()
{
socket_.async_write(
asio::buffer(outbound_.front()),
[this](beast::error_code error, std::size_t) {
if (error) return fail("write", error);
outbound_.pop_front();
if (!outbound_.empty()) write();
});
}
void fail(const char* operation, beast::error_code error)
{
connected_.store(false);
@@ -119,6 +147,7 @@ private:
std::atomic_bool connectionFailed_{false};
std::mutex messagesMutex_;
std::vector<std::string> messages_;
std::deque<std::string> outbound_;
};
WebsocketGameClient::WebsocketGameClient(
@@ -140,38 +169,122 @@ const std::string& WebsocketGameClient::localPlayerId() const
return replica_.localPlayerId();
}
void WebsocketGameClient::submit(const GameCommand&)
void WebsocketGameClient::submit(const GameCommand& command)
{
// Commands intentionally remain local no-ops in the first iteration.
if (!initialized_) return;
if (const auto* destination =
std::get_if<SetCharacterDestinationCommand>(&command)) {
impl_->send(makeDestinationInputMessage(
{nextClientSequence_++, destination->target}));
}
}
std::vector<GameServerEvent> WebsocketGameClient::drainEvents()
{
return {};
std::vector<GameServerEvent> result;
result.swap(pendingEvents_);
return result;
}
void WebsocketGameClient::update(std::int64_t)
{
std::vector<std::string> messages = impl_->takeMessages();
if (messages.empty()) return;
// State messages are complete snapshots; only the newest queued one matters.
for (auto it = messages.rbegin(); it != messages.rend(); ++it) {
nlohmann::json state;
for (const std::string& text : messages) {
std::string error;
if (!parseStateMessage(*it, state, error)) {
std::cerr << "[network] Ignoring WebSocket message: "
<< error << '\n';
InitialStateMessage initial;
if (parseInitialStateMessage(text, initial, error)) {
if (!expectedCompatibilityFingerprint_.empty() &&
initial.compatibilityFingerprint !=
expectedCompatibilityFingerprint_) {
std::cerr << "[network] Incompatible server content: expected "
<< expectedCompatibilityFingerprint_ << ", received "
<< initial.compatibilityFingerprint << '\n';
continue;
}
try {
replica_.load(initial.state);
replica_.setLocalPlayerId(initial.assignedPlayerId);
nextExpectedTick_ = initial.snapshotTick + 1;
compatibilityFingerprint_ =
std::move(initial.compatibilityFingerprint);
pendingTicks_.clear();
initialized_ = true;
std::cout << "[network] Applied initial state at tick "
<< initial.snapshotTick << " as player '"
<< initial.assignedPlayerId << "' (delay "
<< initial.inputDelayTicks << " ticks)" << std::endl;
} catch (const std::exception& exception) {
std::cerr << "[network] Invalid initial state: "
<< exception.what() << '\n';
}
continue;
}
try {
replica_.load(state);
} catch (const std::exception& exception) {
std::cerr << "[network] Ignoring invalid game state: "
<< exception.what() << '\n';
TickMessage tick;
if (parseTickMessage(text, tick, error)) {
if (initialized_ && tick.tickId >= nextExpectedTick_) {
if (!loggedFirstTick_) {
std::cout << "[network] Received first lockstep tick "
<< tick.tickId << std::endl;
loggedFirstTick_ = true;
}
pendingTicks_.emplace(tick.tickId, std::move(tick));
}
continue;
}
break;
std::string errorCode;
std::string errorDetail;
if (parseErrorMessage(text, errorCode, errorDetail)) {
std::cerr << "[network] Server rejected request (" << errorCode
<< "): " << errorDetail << '\n';
if (errorCode == "server_full" ||
errorCode == "incompatible")
rejected_ = true;
continue;
}
std::cerr << "[network] Ignoring WebSocket message: "
<< error << '\n';
}
while (initialized_) {
auto next = pendingTicks_.find(nextExpectedTick_);
if (next == pendingTicks_.end()) break;
TickMessage tick = std::move(next->second);
pendingTicks_.erase(next);
const std::string locationId =
replica_.snapshot()->currentLocationId;
for (const ScheduledDestinationCommand& command : tick.commands) {
replica_.submit(SetCharacterDestinationCommand{
locationId, command.playerId, command.target, {}});
}
replica_.update(kSimulationTickMs);
completedSimulationTicks_.push_back({
replica_.pendingSimulationLocationId_,
replica_.pendingSimulationEvents_});
std::vector<GameServerEvent> events = replica_.drainEvents();
pendingEvents_.insert(
pendingEvents_.end(),
std::make_move_iterator(events.begin()),
std::make_move_iterator(events.end()));
if (!tick.stateHash.empty()) {
nlohmann::json state;
replica_.save(state);
const std::string localHash = canonicalStateHash(std::move(state));
if (localHash != tick.stateHash) {
std::cerr << "[network] Lockstep divergence at tick "
<< tick.tickId << ": server=" << tick.stateHash
<< ", client=" << localHash << '\n';
}
}
++nextExpectedTick_;
}
}
std::vector<WebsocketGameClient::CompletedSimulationTick>
WebsocketGameClient::takeCompletedSimulationTicks()
{
std::vector<CompletedSimulationTick> result;
result.swap(completedSimulationTicks_);
return result;
}
void WebsocketGameClient::save(nlohmann::json&) const