Import Windows client and LAN simulation
This commit is contained in:
1 parent
ccc251758c
commit
c72c388fe9
5 files changed
+2967
No files matched your search
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
struct ScreenPoint {
|
||||
double x;
|
||||
double y;
|
||||
};
|
||||
|
||||
class IsometricCamera {
|
||||
public:
|
||||
[[nodiscard]] double scale() const noexcept { return scale_; }
|
||||
[[nodiscard]] ScreenPoint offset() const noexcept { return offset_; }
|
||||
|
||||
[[nodiscard]] ScreenPoint to_scene(ScreenPoint screen) const noexcept {
|
||||
return {(screen.x - offset_.x) / scale_, (screen.y - offset_.y) / scale_};
|
||||
}
|
||||
|
||||
void zoom_at(ScreenPoint cursor, double steps) noexcept {
|
||||
const double next_scale = std::clamp(scale_ * std::pow(1.25, steps), 0.65, 4.0);
|
||||
if (next_scale == scale_) return;
|
||||
const ScreenPoint anchor = to_scene(cursor);
|
||||
scale_ = next_scale;
|
||||
offset_ = {cursor.x - anchor.x * scale_, cursor.y - anchor.y * scale_};
|
||||
}
|
||||
|
||||
void pan(double dx, double dy) noexcept {
|
||||
offset_.x += dx;
|
||||
offset_.y += dy;
|
||||
}
|
||||
|
||||
private:
|
||||
double scale_ = 1.0;
|
||||
ScreenPoint offset_{0.0, 0.0};
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
|
||||
inline constexpr std::uint16_t colony_lan_port = 41727;
|
||||
|
||||
class LanSession {
|
||||
public:
|
||||
LanSession();
|
||||
~LanSession();
|
||||
LanSession(const LanSession&) = delete;
|
||||
LanSession& operator=(const LanSession&) = delete;
|
||||
|
||||
void host(std::uint16_t port = colony_lan_port, bool loopback_only = false);
|
||||
void join(std::string address, std::string code, std::uint16_t port = colony_lan_port);
|
||||
void reconnect();
|
||||
void leave() noexcept;
|
||||
[[nodiscard]] LanState state() const noexcept;
|
||||
[[nodiscard]] bool is_guest() const noexcept;
|
||||
[[nodiscard]] std::string join_code() const;
|
||||
[[nodiscard]] std::uint16_t port() const noexcept;
|
||||
[[nodiscard]] const std::string& detail() const noexcept;
|
||||
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
|
||||
GridPosition destination = {}, AgentId resident = 0);
|
||||
[[nodiscard]] std::optional<CommandStatus> take_rejection() noexcept;
|
||||
[[nodiscard]] std::unique_ptr<World> poll(World& world);
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string local_lan_addresses();
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,508 @@
|
||||
#define NOMINMAX
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <bcrypt.h>
|
||||
#include <iphlpapi.h>
|
||||
|
||||
#include "lan_session.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
constexpr std::uint32_t protocol_version = 7;
|
||||
constexpr std::size_t frame_limit = 4 * 1024 * 1024;
|
||||
constexpr auto poll_budget = 16;
|
||||
constexpr std::size_t command_queue_limit = 32;
|
||||
enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping };
|
||||
|
||||
struct Socket {
|
||||
SOCKET handle = INVALID_SOCKET;
|
||||
|
||||
Socket() = default;
|
||||
explicit Socket(SOCKET raw) : handle(raw) {}
|
||||
~Socket() { reset(); }
|
||||
Socket(const Socket&) = delete;
|
||||
Socket& operator=(const Socket&) = delete;
|
||||
Socket(Socket&& other) noexcept : handle(std::exchange(other.handle, INVALID_SOCKET)) {}
|
||||
Socket& operator=(Socket&& other) noexcept {
|
||||
if (this != &other) {
|
||||
reset();
|
||||
handle = std::exchange(other.handle, INVALID_SOCKET);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
explicit operator bool() const noexcept { return handle != INVALID_SOCKET; }
|
||||
void reset() noexcept {
|
||||
if (*this) closesocket(std::exchange(handle, INVALID_SOCKET));
|
||||
}
|
||||
};
|
||||
|
||||
void set_nonblocking(SOCKET socket) {
|
||||
u_long enabled = 1;
|
||||
if (ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) != 0) {
|
||||
throw std::runtime_error("Could not configure the socket.");
|
||||
}
|
||||
}
|
||||
|
||||
void tune_stream(SOCKET socket) {
|
||||
const int enabled = 1;
|
||||
setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&enabled), sizeof(enabled));
|
||||
}
|
||||
|
||||
void append_number(std::string& bytes, std::uint64_t value, unsigned length) {
|
||||
for (unsigned i = 0; i < length; ++i) {
|
||||
bytes.push_back(std::bit_cast<char>(static_cast<std::uint8_t>(value)));
|
||||
value >>= 8U;
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t number(std::string_view bytes) noexcept {
|
||||
std::uint64_t value = 0;
|
||||
for (std::size_t i = 0; i < bytes.size(); ++i) {
|
||||
value |= static_cast<std::uint64_t>(static_cast<unsigned char>(bytes[i])) << (8U * i);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string frame(Message message, std::string_view payload = {}) {
|
||||
if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play.");
|
||||
std::string bytes;
|
||||
bytes.reserve(5 + payload.size());
|
||||
append_number(bytes, 1 + payload.size(), 4);
|
||||
bytes.push_back(static_cast<char>(message));
|
||||
bytes.append(payload);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
Socket socket;
|
||||
std::string input;
|
||||
std::string output;
|
||||
std::size_t sent = 0;
|
||||
Clock::time_point opened = Clock::now();
|
||||
Clock::time_point last_received = Clock::now();
|
||||
|
||||
Channel() = default;
|
||||
explicit Channel(Socket incoming) : socket(std::move(incoming)) {}
|
||||
|
||||
bool pending() const noexcept { return sent < output.size(); }
|
||||
|
||||
void queue(Message message, std::string_view payload = {}) {
|
||||
if (sent != 0) {
|
||||
output.erase(0, sent);
|
||||
sent = 0;
|
||||
}
|
||||
if (output.size() + payload.size() + 5 > frame_limit + 1024) {
|
||||
throw std::runtime_error("The peer is not receiving data fast enough.");
|
||||
}
|
||||
output += frame(message, payload);
|
||||
}
|
||||
|
||||
void flush() {
|
||||
if (!pending()) return;
|
||||
const int size = static_cast<int>(std::min(output.size() - sent, std::size_t{64 * 1024}));
|
||||
const int written = send(socket.handle, output.data() + sent, size, 0);
|
||||
if (written == SOCKET_ERROR) {
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted.");
|
||||
return;
|
||||
}
|
||||
if (written == 0) throw std::runtime_error("Connection closed.");
|
||||
sent += static_cast<std::size_t>(written);
|
||||
if (sent == output.size()) {
|
||||
output.clear();
|
||||
sent = 0;
|
||||
}
|
||||
}
|
||||
|
||||
template<class Deliver>
|
||||
void receive(Deliver on_message) {
|
||||
std::array<char, 8192> bytes{};
|
||||
for (int read = 0; read < poll_budget; ++read) {
|
||||
const int count = recv(socket.handle, bytes.data(), static_cast<int>(bytes.size()), 0);
|
||||
if (count == SOCKET_ERROR) {
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted.");
|
||||
break;
|
||||
}
|
||||
if (count == 0) throw std::runtime_error("Connection closed.");
|
||||
last_received = Clock::now();
|
||||
input.append(bytes.data(), static_cast<std::size_t>(count));
|
||||
std::size_t cursor = 0;
|
||||
while (input.size() - cursor >= 4) {
|
||||
const std::string_view remaining(input.data() + cursor, input.size() - cursor);
|
||||
const auto length = number(remaining.substr(0, 4));
|
||||
if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size.");
|
||||
const auto end = 4 + static_cast<std::size_t>(length);
|
||||
if (remaining.size() < end) break;
|
||||
on_message(static_cast<Message>(static_cast<unsigned char>(remaining[4])),
|
||||
remaining.substr(5, static_cast<std::size_t>(length - 1)));
|
||||
cursor += end;
|
||||
}
|
||||
if (cursor != 0) input.erase(0, cursor);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
std::uint64_t parse_code(std::string_view code) {
|
||||
std::uint64_t key = 0;
|
||||
const auto end = code.data() + code.size();
|
||||
const auto result = std::from_chars(code.data(), end, key, 16);
|
||||
if (code.size() != 16 || result.ec != std::errc{} || result.ptr != end || key == 0) {
|
||||
throw std::invalid_argument("Enter the 16-character game code from the host.");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
std::string format_code(std::uint64_t key) {
|
||||
std::array<char, 16> digits{};
|
||||
const auto result = std::to_chars(digits.data(), digits.data() + digits.size(), key, 16);
|
||||
const auto size = static_cast<std::size_t>(result.ptr - digits.data());
|
||||
return std::string(16 - size, '0') + std::string(digits.data(), size);
|
||||
}
|
||||
|
||||
struct Action {
|
||||
CommandKind kind;
|
||||
GridPosition cell;
|
||||
std::uint8_t value;
|
||||
GridPosition destination;
|
||||
AgentId resident;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
struct LanSession::Impl {
|
||||
bool winsock = false;
|
||||
Socket listener;
|
||||
Channel peer;
|
||||
bool guest = false;
|
||||
bool connecting = false;
|
||||
bool authenticated = false;
|
||||
bool reject_pending = false;
|
||||
bool waiting_reply = false;
|
||||
std::uint16_t network_port = 0;
|
||||
std::uint64_t key = 0;
|
||||
std::string host_address;
|
||||
std::string notice;
|
||||
std::deque<Action> actions;
|
||||
std::optional<CommandStatus> rejected_command;
|
||||
std::uint64_t guest_sequence = 0;
|
||||
Clock::time_point last_ping{};
|
||||
Clock::time_point last_snapshot{};
|
||||
std::uint64_t sent_tick = 0;
|
||||
std::uint64_t sent_host_sequence = 0;
|
||||
std::uint64_t sent_guest_sequence = 0;
|
||||
|
||||
Impl() {
|
||||
WSADATA data{};
|
||||
winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0;
|
||||
}
|
||||
~Impl() {
|
||||
peer.socket.reset();
|
||||
listener.reset();
|
||||
if (winsock) WSACleanup();
|
||||
}
|
||||
|
||||
void drop_peer() noexcept {
|
||||
peer = Channel{};
|
||||
connecting = authenticated = reject_pending = waiting_reply = false;
|
||||
guest_sequence = 0;
|
||||
actions.clear();
|
||||
rejected_command.reset();
|
||||
last_snapshot = {};
|
||||
last_ping = {};
|
||||
}
|
||||
|
||||
void accept_guest() {
|
||||
if (peer.socket) return;
|
||||
Socket socket(accept(listener.handle, nullptr, nullptr));
|
||||
if (!socket) return;
|
||||
set_nonblocking(socket.handle);
|
||||
tune_stream(socket.handle);
|
||||
drop_peer();
|
||||
peer = Channel(std::move(socket));
|
||||
}
|
||||
|
||||
void finish_connection() {
|
||||
fd_set write{}, error{};
|
||||
FD_SET(peer.socket.handle, &write);
|
||||
FD_SET(peer.socket.handle, &error);
|
||||
timeval instant{};
|
||||
const int ready = select(0, nullptr, &write, &error, &instant);
|
||||
if (ready == SOCKET_ERROR) throw std::runtime_error("Could not connect to the host.");
|
||||
if (ready == 0) return;
|
||||
int code = 0;
|
||||
int length = sizeof(code);
|
||||
if (FD_ISSET(peer.socket.handle, &error) ||
|
||||
getsockopt(peer.socket.handle, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&code), &length) != 0 ||
|
||||
code != 0) {
|
||||
throw std::runtime_error("Could not connect to the host.");
|
||||
}
|
||||
connecting = false;
|
||||
}
|
||||
|
||||
void handle_host(World& world, Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
if (reject_pending) return;
|
||||
if (message != Message::Hello || payload.size() != 12 ||
|
||||
number(payload.substr(0, 4)) != protocol_version || number(payload.substr(4)) != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
if (message != Message::Command || payload.size() != 34) throw std::runtime_error("Invalid guest command.");
|
||||
const PlayerCommand command{2, number(payload.substr(0, 8)),
|
||||
static_cast<CommandKind>(static_cast<unsigned char>(payload[8])),
|
||||
{std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(9, 4)))),
|
||||
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(13, 4))))},
|
||||
static_cast<std::uint8_t>(payload[17]),
|
||||
{std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(18, 4)))),
|
||||
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(22, 4))))},
|
||||
number(payload.substr(26, 8))};
|
||||
const auto result = world.apply_command(command);
|
||||
std::string reply;
|
||||
append_number(reply, static_cast<std::uint8_t>(result.status), 1);
|
||||
append_number(reply, world.next_command_sequence(2), 8);
|
||||
peer.queue(Message::Receipt, reply);
|
||||
}
|
||||
|
||||
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
|
||||
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
|
||||
if (message == Message::Snapshot) {
|
||||
std::istringstream data(std::string(payload), std::ios::binary);
|
||||
latest = World::read_save(data);
|
||||
if (!latest->scenario_active() || latest->width() != first_colony_map_size ||
|
||||
latest->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("The host sent an unsupported colony.");
|
||||
}
|
||||
if (!authenticated) guest_sequence = latest->next_command_sequence(2);
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
return;
|
||||
}
|
||||
if (message != Message::Receipt || payload.size() != 9 || !waiting_reply) {
|
||||
throw std::runtime_error("Invalid message from the host.");
|
||||
}
|
||||
const auto status = static_cast<CommandStatus>(static_cast<unsigned char>(payload[0]));
|
||||
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
|
||||
if (status != CommandStatus::Accepted) rejected_command = status;
|
||||
guest_sequence = number(payload.substr(1));
|
||||
waiting_reply = false;
|
||||
}
|
||||
|
||||
void send_snapshot(const World& world, Clock::time_point now) {
|
||||
if (peer.pending()) return;
|
||||
const auto host_seq = world.next_command_sequence(1);
|
||||
const auto guest_seq = world.next_command_sequence(2);
|
||||
const bool changed = world.tick() != sent_tick || host_seq != sent_host_sequence || guest_seq != sent_guest_sequence;
|
||||
const auto elapsed = now - last_snapshot;
|
||||
if (last_snapshot != Clock::time_point{} && elapsed < 2s &&
|
||||
(!changed || (elapsed < 120ms && host_seq == sent_host_sequence && guest_seq == sent_guest_sequence))) return;
|
||||
std::ostringstream data(std::ios::binary);
|
||||
world.write_save(data);
|
||||
peer.queue(Message::Snapshot, data.str());
|
||||
last_snapshot = now;
|
||||
sent_tick = world.tick();
|
||||
sent_host_sequence = host_seq;
|
||||
sent_guest_sequence = guest_seq;
|
||||
}
|
||||
|
||||
void send_action() {
|
||||
if (waiting_reply || actions.empty() || guest_sequence == 0 || peer.pending()) return;
|
||||
const Action action = actions.front();
|
||||
std::string payload;
|
||||
append_number(payload, guest_sequence, 8);
|
||||
append_number(payload, static_cast<std::uint8_t>(action.kind), 1);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.cell.x), 4);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.cell.y), 4);
|
||||
append_number(payload, action.value, 1);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.destination.x), 4);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.destination.y), 4);
|
||||
append_number(payload, action.resident, 8);
|
||||
peer.queue(Message::Command, payload);
|
||||
actions.pop_front();
|
||||
waiting_reply = true;
|
||||
}
|
||||
};
|
||||
|
||||
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
|
||||
LanSession::~LanSession() = default;
|
||||
|
||||
void LanSession::host(std::uint16_t port, bool loopback_only) {
|
||||
if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable.");
|
||||
Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
|
||||
if (!socket) throw std::runtime_error("Could not open the LAN listener.");
|
||||
const int exclusive = 1;
|
||||
setsockopt(socket.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
|
||||
reinterpret_cast<const char*>(&exclusive), sizeof(exclusive));
|
||||
sockaddr_in local{};
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_addr.s_addr = htonl(loopback_only ? INADDR_LOOPBACK : INADDR_ANY);
|
||||
local.sin_port = htons(port);
|
||||
if (bind(socket.handle, reinterpret_cast<const sockaddr*>(&local), sizeof(local)) != 0 ||
|
||||
listen(socket.handle, 1) != 0) {
|
||||
throw std::runtime_error("Could not listen on the selected LAN port.");
|
||||
}
|
||||
int length = sizeof(local);
|
||||
if (getsockname(socket.handle, reinterpret_cast<sockaddr*>(&local), &length) != 0) {
|
||||
throw std::runtime_error("Could not determine the local LAN port.");
|
||||
}
|
||||
std::uint64_t key = 0;
|
||||
if (BCryptGenRandom(nullptr, reinterpret_cast<PUCHAR>(&key), sizeof(key), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0 ||
|
||||
key == 0) throw std::runtime_error("Could not generate a join code.");
|
||||
set_nonblocking(socket.handle);
|
||||
leave();
|
||||
impl_->listener = std::move(socket);
|
||||
impl_->key = key;
|
||||
impl_->network_port = ntohs(local.sin_port);
|
||||
}
|
||||
|
||||
void LanSession::join(std::string address, std::string code, std::uint16_t port) {
|
||||
if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable.");
|
||||
const auto key = parse_code(code);
|
||||
sockaddr_in remote{};
|
||||
remote.sin_family = AF_INET;
|
||||
remote.sin_port = htons(port);
|
||||
if (InetPtonA(AF_INET, address.c_str(), &remote.sin_addr) != 1 || port == 0) {
|
||||
throw std::invalid_argument("Enter a valid IPv4 address for the host.");
|
||||
}
|
||||
Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
|
||||
if (!socket) throw std::runtime_error("Could not open the guest connection.");
|
||||
set_nonblocking(socket.handle);
|
||||
tune_stream(socket.handle);
|
||||
const bool pending = connect(socket.handle, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0;
|
||||
if (pending && WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Could not connect to the host.");
|
||||
std::string identity;
|
||||
append_number(identity, protocol_version, 4);
|
||||
append_number(identity, key, 8);
|
||||
Channel channel(std::move(socket));
|
||||
channel.queue(Message::Hello, identity);
|
||||
leave();
|
||||
impl_->guest = true;
|
||||
impl_->connecting = pending;
|
||||
impl_->network_port = port;
|
||||
impl_->key = key;
|
||||
impl_->host_address = std::move(address);
|
||||
impl_->peer = std::move(channel);
|
||||
}
|
||||
|
||||
void LanSession::reconnect() {
|
||||
if (state() == LanState::GuestDisconnected) join(impl_->host_address, join_code(), impl_->network_port);
|
||||
}
|
||||
|
||||
void LanSession::leave() noexcept {
|
||||
impl_->drop_peer();
|
||||
impl_->listener.reset();
|
||||
impl_->guest = false;
|
||||
impl_->notice.clear();
|
||||
impl_->network_port = 0;
|
||||
impl_->key = 0;
|
||||
impl_->host_address.clear();
|
||||
}
|
||||
|
||||
LanState LanSession::state() const noexcept {
|
||||
if (impl_->listener) return impl_->authenticated ? LanState::HostConnected : LanState::Hosting;
|
||||
if (!impl_->guest) return LanState::Offline;
|
||||
if (!impl_->peer.socket) return LanState::GuestDisconnected;
|
||||
return impl_->authenticated ? LanState::GuestConnected : LanState::Connecting;
|
||||
}
|
||||
|
||||
bool LanSession::is_guest() const noexcept { return impl_->guest; }
|
||||
std::string LanSession::join_code() const { return format_code(impl_->key); }
|
||||
std::uint16_t LanSession::port() const noexcept { return impl_->network_port; }
|
||||
const std::string& LanSession::detail() const noexcept { return impl_->notice; }
|
||||
|
||||
bool LanSession::submit(CommandKind kind, GridPosition cell, std::uint8_t value, GridPosition destination,
|
||||
AgentId resident) {
|
||||
if (state() != LanState::GuestConnected || impl_->guest_sequence == 0 || kind == CommandKind::SetPaused ||
|
||||
impl_->actions.size() >= command_queue_limit) return false;
|
||||
impl_->actions.push_back({kind, cell, value, destination, resident});
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<CommandStatus> LanSession::take_rejection() noexcept {
|
||||
return std::exchange(impl_->rejected_command, std::nullopt);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll(World& world) {
|
||||
auto& connection = *impl_;
|
||||
std::unique_ptr<World> latest;
|
||||
try {
|
||||
if (connection.listener) connection.accept_guest();
|
||||
if (!connection.peer.socket) return nullptr;
|
||||
const auto now = Clock::now();
|
||||
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
|
||||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connection.connecting) connection.finish_connection();
|
||||
if (connection.connecting) return nullptr;
|
||||
connection.peer.receive([&](Message message, std::string_view payload) {
|
||||
if (connection.guest) connection.handle_guest(latest, message, payload);
|
||||
else connection.handle_host(world, message, payload);
|
||||
});
|
||||
if (connection.authenticated && connection.guest) {
|
||||
connection.send_action();
|
||||
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
|
||||
connection.peer.queue(Message::Ping);
|
||||
connection.last_ping = now;
|
||||
}
|
||||
} else if (connection.authenticated) {
|
||||
connection.send_snapshot(world, now);
|
||||
}
|
||||
connection.peer.flush();
|
||||
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
latest.reset();
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
std::string local_lan_addresses() {
|
||||
constexpr ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
|
||||
ULONG size = 15 * 1024;
|
||||
std::vector<std::byte> buffer(size);
|
||||
auto* addresses = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data());
|
||||
auto result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size);
|
||||
if (result == ERROR_BUFFER_OVERFLOW) {
|
||||
buffer.resize(size);
|
||||
addresses = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data());
|
||||
result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size);
|
||||
}
|
||||
std::string usable;
|
||||
if (result != NO_ERROR) return usable;
|
||||
for (auto* adapter = addresses; adapter != nullptr; adapter = adapter->Next) {
|
||||
if (adapter->OperStatus != IfOperStatusUp || adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
|
||||
for (auto* addr = adapter->FirstUnicastAddress; addr != nullptr; addr = addr->Next) {
|
||||
if (addr->Address.lpSockaddr == nullptr || addr->Address.lpSockaddr->sa_family != AF_INET) continue;
|
||||
const auto* ipv4 = reinterpret_cast<const sockaddr_in*>(addr->Address.lpSockaddr);
|
||||
std::array<char, INET_ADDRSTRLEN> digits{};
|
||||
if (!InetNtopA(AF_INET, &ipv4->sin_addr, digits.data(), digits.size())) continue;
|
||||
if (!usable.empty()) usable += ", ";
|
||||
usable += digits.data();
|
||||
}
|
||||
}
|
||||
return usable;
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
#include "settlement/core/deterministic_rng.hpp"
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Options {
|
||||
std::uint64_t seed = 42;
|
||||
std::uint64_t agent_count = 50;
|
||||
std::uint64_t job_count = 3000;
|
||||
std::uint64_t ticks = 2000;
|
||||
std::uint64_t warmup_ticks = 100;
|
||||
std::uint64_t map_size = 160;
|
||||
std::uint64_t blocked_percent = 8;
|
||||
std::uint64_t workers = [] {
|
||||
return static_cast<std::uint64_t>(std::min(8U,
|
||||
std::max(static_cast<unsigned>(settlement::min_worker_count), std::thread::hardware_concurrency())));
|
||||
}();
|
||||
std::string svg_path;
|
||||
};
|
||||
|
||||
bool parse_u64(std::string_view text, std::uint64_t& value) {
|
||||
const char* const begin = text.data();
|
||||
const char* const end = begin + text.size();
|
||||
const auto result = std::from_chars(begin, end, value);
|
||||
return result.ec == std::errc{} && result.ptr == end;
|
||||
}
|
||||
|
||||
bool parse_options(int argc, char** argv, Options& options) {
|
||||
for (int index = 1; index < argc; ++index) {
|
||||
const std::string_view flag(argv[index]);
|
||||
if (index + 1 >= argc) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string_view value_text(argv[++index]);
|
||||
if (flag == "--svg") {
|
||||
options.svg_path = std::string(value_text);
|
||||
continue;
|
||||
}
|
||||
|
||||
std::uint64_t value = 0;
|
||||
if (!parse_u64(value_text, value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (flag == "--seed") {
|
||||
options.seed = value;
|
||||
} else if (flag == "--agents") {
|
||||
options.agent_count = value;
|
||||
} else if (flag == "--jobs") {
|
||||
options.job_count = value;
|
||||
} else if (flag == "--ticks") {
|
||||
options.ticks = value;
|
||||
} else if (flag == "--warmup") {
|
||||
options.warmup_ticks = value;
|
||||
} else if (flag == "--map-size") {
|
||||
options.map_size = value;
|
||||
} else if (flag == "--blocked-percent") {
|
||||
options.blocked_percent = value;
|
||||
} else if (flag == "--workers") {
|
||||
options.workers = value;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr std::uint64_t max_ticks = 1000000;
|
||||
constexpr std::uint64_t max_agent_ticks = 100000000;
|
||||
if (options.agent_count > 100000 || options.job_count > 100000 ||
|
||||
options.map_size < 32 || options.map_size > 512 || options.blocked_percent > 30 ||
|
||||
options.ticks > max_ticks || options.warmup_ticks > max_ticks ||
|
||||
options.ticks > max_ticks - options.warmup_ticks ||
|
||||
options.workers < settlement::min_worker_count || options.workers > 32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::uint64_t total_ticks = options.ticks + options.warmup_ticks;
|
||||
const std::uint64_t map_cells = options.map_size * options.map_size;
|
||||
const std::uint64_t open_cells = map_cells - map_cells * options.blocked_percent / 100;
|
||||
return (options.agent_count == 0 || total_ticks <= max_agent_ticks / options.agent_count) &&
|
||||
options.job_count <= open_cells;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
Options options;
|
||||
if (!parse_options(argc, argv, options)) {
|
||||
std::cerr << "Usage: settlement_sim [--seed N] [--agents N] [--jobs N] [--ticks N] "
|
||||
"[--warmup N] [--map-size N] [--blocked-percent N] [--workers 2..32] [--svg PATH]\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
try {
|
||||
const auto map_size = static_cast<std::int32_t>(options.map_size);
|
||||
settlement::World world(options.seed, map_size, map_size,
|
||||
static_cast<std::size_t>(options.workers));
|
||||
settlement::DeterministicRng terrain_rng(options.seed ^ 0x5445525241494E31ULL);
|
||||
settlement::DeterministicRng agent_rng(options.seed ^ 0x4147454E545F3031ULL);
|
||||
settlement::DeterministicRng job_rng(options.seed ^ 0x4A4F42535F303031ULL);
|
||||
|
||||
const std::uint64_t map_cells = options.map_size * options.map_size;
|
||||
const std::uint64_t blocked_cell_count = map_cells * options.blocked_percent / 100;
|
||||
std::uint64_t blocked_cells = 0;
|
||||
while (blocked_cells < blocked_cell_count) {
|
||||
const std::uint64_t cell = terrain_rng.bounded(map_cells);
|
||||
const auto x = static_cast<std::int32_t>(cell % options.map_size);
|
||||
const auto y = static_cast<std::int32_t>(cell / options.map_size);
|
||||
const settlement::GridPosition position{x, y};
|
||||
if (world.is_walkable(position)) {
|
||||
world.set_blocked(position);
|
||||
++blocked_cells;
|
||||
}
|
||||
}
|
||||
|
||||
const settlement::GridPosition town_center{map_size / 2, map_size / 2};
|
||||
const std::int32_t camp_radius = 5;
|
||||
const std::int32_t job_min_distance = std::max(8, map_size / 10);
|
||||
std::vector<settlement::GridPosition> camp_spawn_cells;
|
||||
std::vector<settlement::GridPosition> job_spawn_cells;
|
||||
for (std::int32_t y = 0; y < map_size; ++y) {
|
||||
for (std::int32_t x = 0; x < map_size; ++x) {
|
||||
const settlement::GridPosition position{x, y};
|
||||
if (!world.is_walkable(position)) {
|
||||
continue;
|
||||
}
|
||||
const std::int32_t dx = x > town_center.x ? x - town_center.x : town_center.x - x;
|
||||
const std::int32_t dy = y > town_center.y ? y - town_center.y : town_center.y - y;
|
||||
const std::int32_t distance_from_center = dx + dy;
|
||||
if (distance_from_center <= camp_radius) {
|
||||
camp_spawn_cells.push_back(position);
|
||||
}
|
||||
if (distance_from_center >= job_min_distance) {
|
||||
job_spawn_cells.push_back(position);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (camp_spawn_cells.empty() || options.job_count > job_spawn_cells.size()) {
|
||||
throw std::runtime_error("map has too few open cells for the selected camp and jobs");
|
||||
}
|
||||
|
||||
for (std::size_t index = job_spawn_cells.size(); index > 1; --index) {
|
||||
const auto other = static_cast<std::size_t>(job_rng.bounded(static_cast<std::uint64_t>(index)));
|
||||
std::swap(job_spawn_cells[index - 1], job_spawn_cells[other]);
|
||||
}
|
||||
|
||||
for (std::uint64_t index = 0; index < options.agent_count; ++index) {
|
||||
const auto camp_index = static_cast<std::size_t>(
|
||||
agent_rng.bounded(static_cast<std::uint64_t>(camp_spawn_cells.size())));
|
||||
static_cast<void>(world.spawn_agent(camp_spawn_cells[camp_index]));
|
||||
}
|
||||
for (std::uint64_t index = 0; index < options.job_count; ++index) {
|
||||
const std::uint32_t work_required = static_cast<std::uint32_t>(20 + job_rng.bounded(61));
|
||||
const auto job_index = static_cast<std::size_t>(index);
|
||||
static_cast<void>(world.add_job(job_spawn_cells[job_index], work_required));
|
||||
}
|
||||
|
||||
for (std::uint64_t tick = 0; tick < options.warmup_ticks; ++tick) {
|
||||
world.step();
|
||||
}
|
||||
if (!options.svg_path.empty()) {
|
||||
world.write_svg(options.svg_path);
|
||||
}
|
||||
|
||||
std::vector<double> tick_times_microseconds;
|
||||
tick_times_microseconds.reserve(static_cast<std::size_t>(options.ticks));
|
||||
const auto benchmark_start = std::chrono::steady_clock::now();
|
||||
for (std::uint64_t tick = 0; tick < options.ticks; ++tick) {
|
||||
const auto tick_start = std::chrono::steady_clock::now();
|
||||
world.step();
|
||||
const auto tick_end = std::chrono::steady_clock::now();
|
||||
const std::chrono::duration<double, std::micro> elapsed = tick_end - tick_start;
|
||||
tick_times_microseconds.push_back(elapsed.count());
|
||||
}
|
||||
const auto benchmark_end = std::chrono::steady_clock::now();
|
||||
|
||||
std::sort(tick_times_microseconds.begin(), tick_times_microseconds.end());
|
||||
const auto percentile = [&tick_times_microseconds](double fraction) {
|
||||
if (tick_times_microseconds.empty()) {
|
||||
return 0.0;
|
||||
}
|
||||
const auto index = static_cast<std::size_t>(
|
||||
fraction * static_cast<double>(tick_times_microseconds.size() - 1));
|
||||
return tick_times_microseconds[index];
|
||||
};
|
||||
const std::chrono::duration<double, std::milli> total_elapsed = benchmark_end - benchmark_start;
|
||||
const double average_microseconds = options.ticks == 0
|
||||
? 0.0
|
||||
: total_elapsed.count() * 1000.0 / static_cast<double>(options.ticks);
|
||||
|
||||
const auto active_agents = std::count_if(
|
||||
world.agents().begin(), world.agents().end(),
|
||||
[](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; });
|
||||
|
||||
std::cout << "scenario=work_and_astar\n"
|
||||
<< "seed=" << world.seed() << '\n'
|
||||
<< "map=" << world.width() << 'x' << world.height() << '\n'
|
||||
<< "agents=" << world.agents().size() << '\n'
|
||||
<< "workers=" << world.worker_count() << '\n'
|
||||
<< "jobs=" << world.jobs().size() << '\n'
|
||||
<< "blocked_percent=" << options.blocked_percent << '\n'
|
||||
<< "warmup_ticks=" << options.warmup_ticks << '\n'
|
||||
<< "measured_ticks=" << options.ticks << '\n'
|
||||
<< "world_ticks=" << world.tick() << '\n'
|
||||
<< "active_agents=" << active_agents << '\n'
|
||||
<< "completed_jobs=" << world.jobs_completed() << '\n'
|
||||
<< "path_searches=" << world.path_searches() << '\n'
|
||||
<< "path_nodes_visited=" << world.path_nodes_visited() << '\n'
|
||||
<< "total_ms=" << total_elapsed.count() << '\n'
|
||||
<< "avg_tick_us=" << average_microseconds << '\n'
|
||||
<< "p50_tick_us=" << percentile(0.50) << '\n'
|
||||
<< "p95_tick_us=" << percentile(0.95) << '\n';
|
||||
if (!options.svg_path.empty()) {
|
||||
std::cout << "svg=" << options.svg_path << '\n';
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Simulation failed: " << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user