GekkoNet 1.0
C/C++ Peer to Peer Game Networking SDK
Loading...
Searching...
No Matches
spectator_session.cpp
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cstring>
5
17
19{
20 _host = nullptr;
21
22 _started = false;
23
24 // get given configs
25 std::memcpy(&_config, config, sizeof(GekkoConfig));
26
27 // setup input buffer for the players (room for the spectator delay and for falling behind)
28 _sync.Init(_config.num_players, _config.input_size, InputBufferSize());
29
30 // setup message system.
31 _msg.Init(_config.num_players, _config.input_size, _config.state_size, true);
32
33 // setup game event system
34 _game_events.Init(_config.input_size * _config.num_players);
35
36 _checksum_state.state = std::make_unique<u8[]>(_config.state_size);
37 _checksum_state.state_len = _config.state_size;
38 _checksum_pending = false;
39
40 // start paused so the buffer fills before playback begins
41 _delay_spectator = (_config.spectator_delay > 0);
42}
43
48
50{
51 const i32 ERR = -1;
52 std::unique_ptr<NetAddress> address;
53
54 // only accept a single remote player (the host)
55 if (type != GekkoRemotePlayer) {
56 return ERR;
57 }
58
59 if (addr == nullptr) {
60 return ERR;
61 }
62
63 if (!_msg.remotes.empty()) {
64 return ERR;
65 }
66
67 address = std::make_unique<NetAddress>(addr->data, addr->size);
68
69 u32 new_handle = (u32)_msg.remotes.size();
70 _msg.remotes.push_back(std::make_unique<Player>(new_handle, type, address.get()));
71
72 return new_handle;
73}
74
76{
77 // disconnecting the host stops the spectating session.
78 if (!_msg.DisconnectActor(actor)) {
79 return false;
80 }
81
82 // flush right away so the disconnect gets sent even
83 // when the session isnt updated after this call.
84 if (_host) {
85 _msg.SendPendingOutput(_host);
86 }
87
88 return true;
89}
90
92{
93 _msg.SetDisconnectTimeout(timeout);
94}
95
97{
98 // reset session events
99 _msg.session_events.Reset();
100
101 // connection handling
102 Poll();
103
104 // clear GameEvents
105 _game_events.Clear();
106
107 // gameplay
108 if (AllActorsValid()) {
109 // reset the game event buffer before doing anything else
110 _game_events.Reset();
111
113 _game_events.AddStateLoadEvent(
115 _spectator_state.data(),
116 (u32)_spectator_state.size()
117 );
119 }
120
121 // store the frames that went by for the replay
123
124 // spectator session buffer
125 if (ShouldDelaySpectator()) {
126 *count = _game_events.Count();
127 return _game_events.Data();
128 }
129
130 // then advance the session
131 if (_game_events.AddAdvanceEvent(_sync, false)) {
132 const Frame frame = _sync.GetCurrentFrame();
133 if (_replay.WantsChecksum(frame)) {
134 _game_events.AddStateSaveEvent(frame, &_checksum_state);
135 _checksum_pending = true;
136 }
137 _sync.IncrementFrame();
138 }
139 }
140
141 *count = _game_events.Count();
142 return _game_events.Data();
143}
144
149
151{
152 const Frame received = _sync.GetMinReceivedFrame();
153 if (received == GameInput::NULL_FRAME) {
154 return 0;
155 }
156
157 return std::max(0, (i32)(received - _sync.GetCurrentFrame() + 1));
158}
159
161{
162 *count = (i32)_msg.session_events.GetRecentEvents().size();
163 return _msg.session_events.GetRecentEvents().data();
164}
165
167{
168 for (auto& actor : _msg.remotes) {
169 if (actor->handle == player) {
170 actor->stats.UpdateBandwidth();
171 stats->kb_sent = actor->stats.kb_sent_per_sec;
172 stats->kb_received = actor->stats.kb_received_per_sec;
173 stats->last_ping = actor->stats.LastRTT();
174 stats->jitter = actor->stats.CalculateJitter();
175 stats->avg_ping = actor->stats.CalculateAvgRTT();
176 return;
177 }
178 }
179}
180
185
186bool Gekko::SpectatorSession::StartRecording(bool save_initial_state, bool disable_compression)
187{
188 return _replay.StartRecording(_config, _sync.GetCurrentFrame(), save_initial_state, disable_compression);
189}
190
192{
194
195 return _replay.StopRecording(length);
196}
197
199{
201
202 return _replay.PeekRecording(length);
203}
204
206{
207 // the game handled the events of the last update by now, keep what they confirmed.
208 if (_replay.IsRecording() && !_replay.NeedsState()) {
209 _replay.RecordInputs(_sync);
211 }
212}
213
215{
216 return _replay.SetChecksumInterval(interval);
217}
218
220{
221 return _replay.SetUserData(data, length);
222}
223
225{
226 if (!_checksum_pending) {
227 return;
228 }
229
230 _checksum_pending = false;
231
232 _replay.RecordChecksum(_checksum_state.frame, _checksum_state.checksum);
233}
234
236{
237 if (!_replay.IsRecording()) {
238 return;
239 }
240
241 if (_replay.NeedsState()) {
242 _game_events.AddStateSaveEvent(_sync.GetCurrentFrame() - 1, _replay.PendingState());
243 }
244
245 _replay.RecordInputs(_sync);
246
247 // spectators only play confirmed inputs, so the frame saved last update is final.
249}
250
252{
253 // return if no host is defined.
254 if (!_host) {
255 return;
256 }
257
258 // fetch data from network
259 int length = 0;
260 auto data = _host->receive_data(&length);
261
262 // process the data we received
263 _msg.HandleData(_host, data, length);
264
265 _msg.CheckStatusActors();
266
267 Frame state_frame = GameInput::NULL_FRAME;
268 std::vector<u8> state;
269 if (_msg.TakeSpectatorState(state_frame, state)) {
270 // The snapshot contains the state after this frame, so playback starts
271 // with the next input frame.
272 _sync.Init(_config.num_players, _config.input_size, InputBufferSize());
273 _sync.SetCurrentFrame(state_frame + 1);
274 _sync.SetLastReceivedFrame(state_frame);
275
276 _spectator_state_frame = state_frame;
277 _spectator_state = std::move(state);
279 _delay_spectator = (_config.spectator_delay > 0);
280 }
281
282 // handle received inputs
284
285 // send network health update
286 _msg.SendNetworkHealth();
287
288 // now send data
289 _msg.SendPendingOutput(_host);
290}
291
293{
294 if (!_started) {
295 if (!_msg.CheckStatusActors()) {
296 return false;
297 }
298
299 // if none returned that the session is ready!
300 _msg.session_events.AddSessionStartedEvent();
301 if (_config.spectator_delay > 0) {
302 _msg.session_events.AddSpectatorPausedEvent();
303 }
304 _started = true;
305
306 return true;
307 }
308
309 return true;
310}
311
313{
314 for (auto& remote : _msg.remotes) {
315 if (remote->GetStatus() != Connected) continue;
316
317 // spectators receive combined inputs for ALL players from the host
318 std::vector<Handle> handles;
319 for (u32 i = 0; i < _config.num_players; i++) {
320 handles.push_back(i);
321 }
322
323 for (u32 i = 0; i < handles.size(); i++) {
324 auto handle = handles[i];
325 const Frame last_recv = _sync.GetLastReceivedFrom(handle) + 1;
326 const Frame last_added = _msg.GetLastAddedInputFrom(handle);
327
328 auto& input_q = _msg.GetNetPlayerQueue(handle);
329 const Frame min_frame = last_added - (i32)input_q.size() + 1;
330 for (int i = last_recv; i <= last_added; i++) {
331 if (i >= min_frame) {
332 int current_idx = i - min_frame;
333 u8* input = input_q[current_idx].get();
334 _sync.AddRemoteInput(handle, input, i);
335 _msg.SendInputAck(handle, i, 0);
336 }
337 }
338 }
339 }
340}
341
343{
344 if (_config.spectator_delay == 0) {
345 return false;
346 }
347
348 const u32 delay = _config.spectator_delay;
349 const Frame current = _sync.GetCurrentFrame();
350 const Frame min = _sync.GetMinReceivedFrame();
351 const u32 diff = std::abs(min - current);
352
353 if (_delay_spectator) {
354 if (diff >= delay) {
355 _delay_spectator = false;
356 _msg.session_events.AddSpectatorUnpausedEvent();
357 return false;
358 }
359 return true;
360 }
361
362 // Re-pause only when the buffer is completely exhausted
363 if (diff == 0) {
364 _delay_spectator = true;
365 _msg.session_events.AddSpectatorPausedEvent();
366 return true;
367 }
368
369 return false;
370}
bool SetReplayUserData(const u8 *data, u32 length) override
const u8 * PeekRecording(u32 &length) override
static const u32 CATCH_UP_FRAMES
bool StartRecording(bool save_initial_state, bool disable_compression) override
const u8 * StopRecording(u32 &length) override
i32 AddActor(GekkoPlayerType type, GekkoNetAddress *addr) override
void NetworkStats(i32 player, GekkoNetworkStats *stats) override
GekkoSessionEvent ** Events(i32 *count) override
i32 SpectatorBufferedFrames() override
GekkoGameEvent ** UpdateSession(i32 *count) override
void SetNetAdapter(GekkoNetAdapter *adapter) override
void SetDisconnectTimeout(u32 timeout) override
bool RecordChecksums(u32 interval) override
bool DisconnectActor(i32 actor) override
std::vector< u8 > _spectator_state
void Init(GekkoConfig *config) override
int32_t i32
Definition gekko_types.h:12
int32_t Frame
Definition gekko_types.h:18
uint8_t u8
Definition gekko_types.h:5
uint32_t u32
Definition gekko_types.h:7
struct GekkoConfig GekkoConfig
GekkoPlayerType
Definition gekkonet.h:77
@ GekkoRemotePlayer
Definition gekkonet.h:79
@ Connected
Definition backend.h:22
unsigned int size
Definition gekkonet.h:85
unsigned short last_ping
Definition gekkonet.h:184
static const i32 NULL_FRAME
Definition input.h:21
static const u32 DEFAULT_BUFF_SIZE
Definition input.h:31