vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
net_session.h
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <string>
6#include <vector>
7
8#include "ecs/component/core/transform.h"
9#include "ecs/entity.h"
10#include "net/net_client.h"
11#include "net/net_server.h"
12#include "net/prediction/command.h"
13#include "net/transport/connection.h"
14#include "net/wire/bit_stream.h"
15#include "net/wire/protocol.h"
16#include "platform/net/udp_socket.h"
17
18namespace Vkm::Engine {
19
20class Clock;
21class EventBus;
22class Scene;
23class ResourceManager;
24
31constexpr float NET_SNAPSHOT_RATE = 64.0f;
32
39constexpr float NET_COMMAND_RATE = 64.0f;
40
49constexpr uint32_t NET_MAX_TICK_RATE = static_cast<uint32_t>(2.0f * NET_COMMAND_RATE);
50
55struct NetCore {
62 static constexpr size_t MAX_READS_PER_FRAME = 512;
63
64 UdpSocket socket;
65 uint32_t tickRate = 0;
66
67 uint32_t actionCount = 0;
68
71 uint64_t actionNames = 0;
72 bool ticked = false;
73
74 uint64_t world = 0;
75
78 uint32_t serverTick = 0;
79
80 std::string lastError;
81
82 std::vector<uint8_t> scratch;
83 std::vector<uint8_t> payload;
84 std::vector<uint8_t> datagram;
85 std::vector<uint16_t> acknowledged;
86};
87
96void sendBare(NetCore& core, NetConnection& connection, NetMessage message, uint64_t token);
97
107BitReader receivedPayload(const NetCore& core);
108
118class NetSession {
119 public:
128 class Drawn {
129 public:
137 Drawn(NetSession& session, Scene& scene, float deltaTime);
138 ~Drawn();
139
140 Drawn(const Drawn& other) = delete;
141 Drawn& operator=(const Drawn& other) = delete;
142
143 Drawn(Drawn && other) = delete;
144 Drawn& operator=(Drawn && other) = delete;
145
146 private:
147 NetSession& m_session;
148 Scene& m_scene;
149 };
150
158 class Rewind {
159 public:
172 Rewind(NetSession& session, Scene& scene, EntityId shooter);
173 ~Rewind();
174
175 Rewind(const Rewind& other) = delete;
176 Rewind& operator=(const Rewind& other) = delete;
177
178 Rewind(Rewind && other) = delete;
179 Rewind& operator=(Rewind && other) = delete;
180
181 private:
182 NetSession& m_session;
183 Scene& m_scene;
184 };
185
186 public:
187 NetSession();
188 ~NetSession();
189
190 NetSession(const NetSession& other) = delete;
191 NetSession& operator=(const NetSession& other) = delete;
192
193 NetSession(NetSession && other) = delete;
194 NetSession& operator=(NetSession && other) = delete;
195
196 public:
209 void setWorld(uint64_t fingerprint, const Scene& scene);
210
223 bool host(uint16_t port, uint32_t maxPlayers, uint32_t tickRate);
224
233 bool connect(const NetAddress& server, uint32_t tickRate);
234
240 void close();
241
244
245 public:
246 NetRole role() const { return m_role; }
247 bool isOffline() const { return m_role == NetRole::Offline; }
248
250 bool isDisconnected() const { return m_role == NetRole::Disconnected; }
251
258 bool isPlaying() const;
259
261 const std::string& lastError() const { return m_core.lastError; }
262
263 PlayerId localPlayer() const { return m_client.localPlayer(); }
264
270 NetAddress localAddress() const { return m_core.socket.localAddress(); }
271
277 EntityId localEntity() const { return m_client.localEntity(); }
278
280 float roundTrip() const;
281
291 size_t playerCount() const;
292
293 public:
308 bool simulates(const Scene& scene, EntityId entity) const;
309
323 void lease(const std::vector<EntityId>& entities) { m_client.lease(entities); }
324
340 bool sendMessage(const uint8_t* bytes, size_t size) {
341 return m_role == NetRole::Client && m_client.sendMessage(bytes, size);
342 }
343
349 size_t leaseCount() const { return m_client.leaseCount(); }
350
358 bool isMine(EntityId entity) const;
359
371 EntityId entityFor(const Scene& scene, uint32_t slot) const;
372
383 const InputCommand& commandFor(EntityId entity) const;
384
385 public:
395 void receive(Scene& scene, ResourceManager& resources);
396
404 void deliver(EventBus& events);
405
414 const std::vector<InputCommand>& replayCommands() const { return m_client.replayCommands(); }
415
423 void beginReplayTick(const InputCommand& command);
424
426 void endReplay(Scene& scene) { m_client.endReplay(scene); }
427
433 bool replaying() const { return m_client.replaying(); }
434
444 void endTick(Scene& scene, uint32_t tick);
445
459 uint32_t tick,
460 const InputCommand& command,
461 uint32_t actionCount,
462 uint64_t actionNames
463 );
464
466 void send(Scene& scene, uint32_t tick);
467
487 Scene& scene,
488 ResourceManager& resources,
489 const std::string& prefab,
490 const Transform& at
491 );
492
499 void advance(float seconds);
500
510 void interpolate(Scene& scene, float deltaTime);
511
518 float renderDelay() const;
519
534 double worldTime(const Clock& clock) const;
535
544 float pacing() const;
545
552 float predictionError() const { return m_client.predictionError(); }
553
554 public:
562 std::string describe() const;
563
564 private:
565 static constexpr uint64_t NO_WORLD = UINT64_MAX;
566
567 private:
574 bool acceptsTickRate(uint32_t tickRate);
575
582 void disconnect();
583
585 void hangUp();
586
594 void forgetWorld();
595
596 void beginRewind(Scene& scene, EntityId shooter);
597 void endRewind(Scene& scene);
598
599 private:
600 NetCore m_core;
601 NetServer m_server;
602 NetClient m_client;
603 NetRole m_role = NetRole::Offline;
604
606 InputCommand m_currentCommand;
607
609 float m_sendAccumulator = 1.0f;
610 bool m_tickOpen = false;
611
612 uint32_t m_rewindDepth = 0;
613 EntityId m_rewoundFor;
614
617 uint64_t m_worldEpoch = NO_WORLD;
618};
619
620} // namespace Vkm::Engine
Reads back what a BitWriter wrote, in the same order.
Definition bit_stream.h:145
The engine's frame clock: real + simulation time and the fixed-step accumulator.
Definition clock.h:18
Typed pub/sub event dispatcher.
Definition event_bus.h:22
A guest's half of a NetSession: joining, predicting what it owns, being corrected,...
Definition net_client.h:44
One end of one conversation: sequencing, acknowledgement and timing.
Definition connection.h:34
The authority's half of a NetSession: seats, the join handshake, commands in and snapshots out.
Definition net_server.h:35
std::function< void(Scene &, ResourceManager &, PlayerId, EntityId)> DespawnPlayer
Undo what SpawnPlayer did.
Definition net_server.h:49
std::function< EntityId(Scene &, ResourceManager &, PlayerId)> SpawnPlayer
What a joining player is given, decided by the game.
Definition net_server.h:42
Drawn(NetSession &session, Scene &scene, float deltaTime)
Works a little of the correction off and applies the rest.
Rewind(NetSession &session, Scene &scene, EntityId shooter)
Rewinds to the moment shooter was drawing when the running command was made.
void receive(Scene &scene, ResourceManager &resources)
Apply everything that has arrived.
bool isMine(EntityId entity) const
Whether entity belongs to the player at this end.
void beginTick(uint32_t tick, const InputCommand &command, uint32_t actionCount, uint64_t actionNames)
Take the command this tick runs under.
void setWorld(uint64_t fingerprint, const Scene &scene)
Say which world this end loaded, as loaded, before anything in it has run.
float pacing() const
How much faster than the wall clock this end should run its ticks.
size_t playerCount() const
How many players this end knows of.
bool host(uint16_t port, uint32_t maxPlayers, uint32_t tickRate)
Take players on port.
const std::vector< InputCommand > & replayCommands() const
The ticks a correction wants run again, oldest first.
Definition net_session.h:414
EntityId spawn(Scene &scene, ResourceManager &resources, const std::string &prefab, const Transform &at)
Build prefab at at, here and on every client.
void endTick(Scene &scene, uint32_t tick)
Record what this end predicted for the tick that just ran.
void interpolate(Scene &scene, float deltaTime)
Draw what this end is only told about where it was a moment ago.
EntityId localEntity() const
The entity this end drives; null on a server.
Definition net_session.h:277
void lease(const std::vector< EntityId > &entities)
Also simulate entities, for a while.
Definition net_session.h:323
double worldTime(const Clock &clock) const
The seconds of the authority's world this end is drawing.
void beginReplayTick(const InputCommand &command)
Take command for a tick being run a second time.
bool sendMessage(const uint8_t *bytes, size_t size)
Send the server something it must have: a move, a name, a choice in a lobby.
Definition net_session.h:340
void endReplay(Scene &scene)
Finish the replay and clear the request.
Definition net_session.h:426
NetAddress localAddress() const
The address this end is bound to; the real port after hosting on zero.
Definition net_session.h:270
float renderDelay() const
How far behind the server this end is drawing, in ticks; zero when it holds the present.
bool connect(const NetAddress &server, uint32_t tickRate)
Join the game at server.
const std::string & lastError() const
Why the last attempt to join ended, or an empty string.
Definition net_session.h:261
void onSpawn(NetServer::SpawnPlayer spawn, NetServer::DespawnPlayer despawn)
What the game does when a player joins and leaves. Set before host().
size_t leaseCount() const
How many bodies this end is simulating on top of its own.
Definition net_session.h:349
bool simulates(const Scene &scene, EntityId entity) const
Whether this end decides what happens to entity.
void advance(float seconds)
Wall-clock time passing, for the timers that must run while the simulation does not - a paused editor...
bool isDisconnected() const
True when a session was open and the other end has gone.
Definition net_session.h:250
void send(Scene &scene, uint32_t tick)
Send what this frame produced. Called once a frame, after the ticks.
void close()
Say goodbye and go back to Offline. Safe to call when already offline.
bool replaying() const
True while a tick that already happened is being run again.
Definition net_session.h:433
EntityId entityFor(const Scene &scene, uint32_t slot) const
What the server's slot names on this end.
const InputCommand & commandFor(EntityId entity) const
The input driving entity on the tick about to run.
std::string describe() const
One line describing the session, for a log or a readout.
void deliver(EventBus &events)
Hand what players sent since the last call to events, as PlayerMessageEvent.
bool isPlaying() const
True once this end can play: always for a server, and for a client from the Welcome until the connect...
float roundTrip() const
Round trip to the server, in seconds. Zero on a server or offline.
float predictionError() const
How far this end's prediction of its own entity was out, last time the server said.
Definition net_session.h:552
Type-erased resource registry with typed handles and generational lifetimes.
Definition resource_manager.h:46
Central registry managing entities and an open set of component types.
Definition scene.h:29
A non-blocking UDP socket, the same on Windows and Linux.
Definition udp_socket.h:17
Names one entity of one Scene, for as long as that slot holds it.
Definition entity.h:23
Everything one simulation tick was told to do, as a value.
Definition input_command.h:28
Where a datagram came from, or is going to: an IPv4 host and a port.
Definition net_address.h:13
What a session's server and client halves share: the socket, what the two ends agreed,...
Definition net_session.h:55
uint64_t world
Which world this end loaded, or zero for none.
Definition net_session.h:74
uint32_t tickRate
Fixed for the session.
Definition net_session.h:65
static constexpr size_t MAX_READS_PER_FRAME
Datagrams read in one frame.
Definition net_session.h:62
uint64_t actionNames
Definition net_session.h:71
bool ticked
A tick has run, so the count is real.
Definition net_session.h:72
std::vector< uint8_t > payload
What an outgoing message is written into.
Definition net_session.h:83
std::vector< uint8_t > datagram
The datagram last received, or last framed to send.
Definition net_session.h:84
uint32_t serverTick
Definition net_session.h:78
Local position, rotation and scale of an entity.
Definition transform.h:17