GekkoNet 1.0
C/C++ Peer to Peer Game Networking SDK
Loading...
Searching...
No Matches
game_session.cpp
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cassert>
5#include <cstring>
6
24
26{
27 _host = nullptr;
28
29 _started = false;
30
32
33 // get given configs
34 std::memcpy(&_config, config, sizeof(GekkoConfig));
35
36 _config.max_input_prediction_window = std::min(_config.max_input_prediction_window, (u8)(InputBuffer::DEFAULT_BUFF_SIZE / 2));
37 _input_prediction_window = _config.max_input_prediction_window;
38
39 // setup input buffer for the players
40 _sync.Init(_config.num_players, _config.input_size);
41
42 // setup message system.
43 _msg.Init(_config.num_players, _config.input_size, _config.state_size);
44
45 // setup game event system
46 _game_events.Init(_config.input_size * _config.num_players);
47
48 // setup state storage
49 _storage.Init(_config.max_input_prediction_window, _config.state_size, _config.limited_saving);
50
51 _spectator_state.state = std::make_unique<u8[]>(_config.state_size);
52 _spectator_state.state_len = _config.state_size;
53
54 // setup disconnected input for disconnected player within the session
55 _disconnected_input = std::make_unique<u8[]>(_config.input_size);
56 std::memset(_disconnected_input.get(), 0, _config.input_size);
57
58 _health_state.state = std::make_unique<u8[]>(_config.state_size);
59 _health_state.state_len = _config.state_size;
60}
61
63{
64 _runahead_frames = runahead;
65}
66
68{
69 if (IsLockstepActive()) {
70 return;
71 }
72
73 _input_prediction_window = std::min(window, _config.max_input_prediction_window);
74
75 for (auto& remote : _msg.remotes) {
76 _sync.SetInputPredictionWindow(remote->handle, _input_prediction_window);
77 }
78}
79
81{
82 for (u32 i = 0; i < _msg.locals.size(); i++) {
83 if (_msg.locals[i]->handle == player) {
84 _sync.SetLocalDelay(player, delay);
85 }
86 }
87}
88
90{
91 _host = adapter;
92}
93
95{
96 const i32 ERR = -1;
97 std::unique_ptr<NetAddress> address;
98
99 if (addr) {
100 address = std::make_unique<NetAddress>(addr->data, addr->size);
101 }
102
103 if (type == GekkoSpectator) {
104 if (_started && _config.state_size == 0) {
105 return ERR;
106 }
107
108 // Disconnected spectators no longer occupy a slot. Their remaining
109 // disconnect retries are retained outside the active routing records.
110 _msg.ReclaimDisconnectedSpectators();
111
112 if (_msg.spectators.size() >= _config.max_spectators) {
113 return ERR;
114 }
115
116 Handle new_handle = _config.num_players;
117 const Handle end_handle = _config.num_players + _config.max_spectators;
118 for (; new_handle < end_handle; new_handle++) {
119 const bool in_use = std::any_of(
120 _msg.spectators.begin(),
121 _msg.spectators.end(),
122 [new_handle](const std::unique_ptr<Player>& player) {
123 return player->handle == new_handle;
124 }
125 );
126
127 if (!in_use) {
128 break;
129 }
130 }
131
132 auto spectator = std::make_unique<Player>(new_handle, type, address.get());
133 spectator->requires_spectator_state = _started;
134 spectator->spectator_state_acked = !_started;
135 _msg.spectators.push_back(std::move(spectator));
136
137 return new_handle;
138 }
139 else {
140 if (_started || _msg.locals.size() + _msg.remotes.size() >= _config.num_players) {
141 return ERR;
142 }
143
144 u32 new_handle = (u32)(_msg.locals.size() + _msg.remotes.size());
145
146 if (type == GekkoLocalPlayer) {
147 _msg.locals.push_back(std::make_unique<Player>(new_handle, type, address.get()));
148 }
149 else {
150 // require an address when specifing a remote player
151 if (addr == nullptr) {
152 return ERR;
153 }
154
155 _msg.remotes.push_back(std::make_unique<Player>(new_handle, type, address.get()));
156 _sync.SetInputPredictionWindow(new_handle, _input_prediction_window);
157 }
158
159 return new_handle;
160 }
161}
162
164{
165 if (!_msg.DisconnectActor(actor)) {
166 return false;
167 }
168
169 // flush right away so the disconnect gets sent even
170 // when the session isnt updated after this call.
171 if (_host) {
172 _msg.SendPendingOutput(_host);
173 }
174
175 return true;
176}
177
179{
180 _msg.SetDisconnectTimeout(timeout);
181}
182
183void Gekko::GameSession::AddLocalInput(i32 player, void* input)
184{
185 u8* inp = (u8*)input;
186
187 for (u32 i = 0; i < _msg.locals.size(); i++) {
188 if (_msg.locals[i]->handle == player) {
189 _sync.AddLocalInput(player, inp);
190 break;
191 }
192 }
193}
194
196{
197 // reset session events
198 _msg.session_events.Reset();
199
200 // connection Handling
201 Poll();
202
203 // clear GameEvents
204 _game_events.Clear();
205
206 // gameplay
207 if (AllActorsValid()) {
208 // reset the game event buffer before doing anything else
209 _game_events.Reset();
210
211 // send a healthcheck if applicable
213
214 // add inputs so we can continue the session.
216
217 // rewind any runahead frames from the previous tick
219
220 // store the frames that went by for the replay
222
223 // check if we need to rollback
225
226 // check if we need to save the confirmed frame
228
229 // check if the session is still doing alright.
231
232 // Sessions which do not hold a recent enough rollback save create one
233 // on demand when a spectator joins late.
235
236 // then advance the session
237 if (ShouldStallAdvance() || !_game_events.AddAdvanceEvent(_sync, false, _runahead_frames > 0)) {
238 _rollback_stats.stalls++;
239 }
240 else {
241 if (!_config.limited_saving) {
243 }
244 CaptureHealthState(_sync.GetCurrentFrame());
245 CaptureChecksumState(_sync.GetCurrentFrame());
246 _sync.IncrementFrame();
247 }
248
249 // run ahead if configured
251 }
252
253 *count = _game_events.Count();
254 return _game_events.Data();
255}
256
258{
259 *count = (i32)_msg.session_events.GetRecentEvents().size();
260 return _msg.session_events.GetRecentEvents().data();
261}
262
264{
265 if (!_started) {
266 return 0.f;
267 }
268
269 bool found = false;
270 f32 ahead = 0.f;
271 for (auto& remote : _msg.remotes) {
272 if (remote->GetStatus() == Connected) {
273 const f32 adv = remote->adv_history.GetAverageAdvantage();
274 ahead = found ? std::max(ahead, adv) : adv;
275 found = true;
276 }
277 }
278 return ahead;
279}
280
282{
283 std::vector<std::unique_ptr<Player>>* current = &_msg.remotes;
284
285 for (u32 i = 0; i < 2; i++)
286 {
287 if (i == 1) {
288 current = &_msg.spectators;
289 }
290
291 for (auto& actor : *current) {
292 if (actor->handle == player) {
293 actor->stats.UpdateBandwidth();
294 stats->kb_sent = actor->stats.kb_sent_per_sec;
295 stats->kb_received = actor->stats.kb_received_per_sec;
296 stats->last_ping = actor->stats.LastRTT();
297 stats->jitter = actor->stats.CalculateJitter();
298 stats->avg_ping = actor->stats.CalculateAvgRTT();
299 return;
300 }
301 }
302 }
303}
304
306{
307 stats->total_count = _rollback_stats.count;
308 stats->last_frames = _rollback_stats.last_frames;
309 stats->avg_frames = _rollback_stats.count > 0
310 ? (f32)_rollback_stats.total_frames / (f32)_rollback_stats.count : 0.f;
311 stats->max_frames = _rollback_stats.max_frames;
312 stats->total_stalls = _rollback_stats.stalls;
313}
314
316{
317 Poll();
318}
319
320bool Gekko::GameSession::StartRecording(bool save_initial_state, bool disable_compression)
321{
324
325 return _replay.StartRecording(_config, _sync.GetCurrentFrame(), save_initial_state, disable_compression);
326}
327
329{
331
332 return _replay.StopRecording(length);
333}
334
336{
338
339 return _replay.PeekRecording(length);
340}
341
343{
344 // the game handled the events of the last update by now, keep what they confirmed.
345 if (_replay.IsRecording() && !_replay.NeedsState()) {
346 _replay.RecordInputs(_sync);
348 }
349}
350
352{
353 return _replay.SetChecksumInterval(interval);
354}
355
357{
358 return _replay.SetUserData(data, length);
359}
360
362{
363 if (!_replay.IsRecording()) {
364 return;
365 }
366
367 if (_replay.NeedsState()) {
369 }
370
371 _replay.RecordInputs(_sync);
372
374}
375
377{
378 if (_config.limited_saving) {
379 // the checksums of the frames captured for the recording, in frame order.
380 for (u32 i = 0; i < _checksum_captures; i++) {
381 _replay.RecordChecksum(_checksum_states[i]->frame, _checksum_states[i]->checksum);
382 }
384 return;
385 }
386
387 // a saved frame is final once its inputs are confirmed and no rollback is pending before it.
388 Frame up_to = std::min(GetConfirmedFrame(), _sync.GetCurrentFrame() - 1);
389
390 const Frame incorrect = _sync.GetMinIncorrectFrame();
391 if (incorrect != GameInput::NULL_FRAME) {
392 up_to = std::min(up_to, incorrect - 1);
393 }
394
395 _replay.RecordChecksums(_storage, up_to);
396}
397
399{
400 const Frame current = _sync.GetCurrentFrame();
401 const Frame confirmed = GetConfirmedFrame();
402 const Frame incorrect = _sync.GetMinIncorrectFrame();
403
404 Frame stored = confirmed;
405
406 if (incorrect != GameInput::NULL_FRAME) {
407 stored = std::min(stored, incorrect - 1);
408 }
409
410 if (_config.limited_saving) {
411 stored = std::min(stored, _last_saved_frame);
412 }
413
414 if (stored >= 0) {
415 auto saved = _storage.GetState(stored);
416
417 if (saved->frame == stored && saved->state_len > 0) {
418 _replay.RecordState(saved->state.get(), saved->state_len, stored);
419 return;
420 }
421 }
422
423 if (current - 1 > confirmed || incorrect != GameInput::NULL_FRAME) {
424 return;
425 }
426
427 _game_events.AddStateSaveEvent(current - 1, _replay.PendingState());
428}
429
431{
432 // without limited saving the rollback saves already hold every frame.
433 if (!_config.limited_saving || frame <= _last_checksum_capture ||
434 frame > GetConfirmedFrame() || !_replay.WantsChecksum(frame)) {
435 return;
436 }
437
438 if (_checksum_captures == _checksum_states.size()) {
439 auto entry = std::make_unique<StateEntry>();
440 entry->state = std::make_unique<u8[]>(_config.state_size);
441 entry->state_len = _config.state_size;
442 _checksum_states.push_back(std::move(entry));
443 }
444
445 _game_events.AddStateSaveEvent(frame, _checksum_states[_checksum_captures].get());
448}
449
451{
452 if (!ConfirmedSaveDue()) {
453 return;
454 }
455
456 const Frame confirmed_frame = GetConfirmedFrame();
457 const Frame current = _sync.GetCurrentFrame();
458
459 assert(_last_saved_frame < confirmed_frame);
460
461 const Frame sync_frame = _last_saved_frame;
462 const Frame frame_to_save = std::min(current - 1, confirmed_frame);
463
464 _sync.SetCurrentFrame(sync_frame);
465 _game_events.AddLoadEvent(_sync, _storage);
466 _sync.IncrementFrame();
467
468 for (Frame frame = sync_frame + 1; frame < current; frame++) {
469 _game_events.AddAdvanceEvent(_sync, true);
470 if (frame == frame_to_save) {
472 }
473 CaptureHealthState(frame);
475 _sync.IncrementFrame();
476 }
477
478 // make sure that we are back where we started.
479 assert(_sync.GetCurrentFrame() == current);
480}
481
483{
484 if (!_config.desync_detection) {
485 return;
486 }
487
488 Frame confirmed = GameInput::NULL_FRAME;
489 u32 checksum = 0;
490
491 if (_config.limited_saving) {
492 if (!_health_captured) {
494 return;
495 }
496
497 confirmed = _health_state.frame;
498 checksum = _health_state.checksum;
499
500 _health_captured = false;
503 }
504 else {
505 const Frame current = _sync.GetCurrentFrame();
506 confirmed = (current - _config.max_input_prediction_window) - 1;
507
508 if (confirmed <= GameInput::NULL_FRAME) {
509 return;
510 }
511
512 if (confirmed <= _last_sent_healthcheck) {
513 return;
514 }
515
516 auto sav = _storage.GetState(confirmed);
517
518 assert(sav->frame == confirmed);
519
520 checksum = sav->checksum;
521 }
522
523 _last_sent_healthcheck = confirmed;
524
525 _msg.local_health[confirmed] = checksum;
526
527 _msg.SendSessionHealth(confirmed, checksum);
528
529 for (auto iter = _msg.local_health.begin();
530 iter != _msg.local_health.end(); ) {
531 if (iter->first < (confirmed - 100)) {
532 iter = _msg.local_health.erase(iter);
533 }
534 else {
535 ++iter;
536 }
537 }
538}
539
541{
542 if (!_config.desync_detection || !_config.limited_saving || _health_captured ||
543 frame != _health_frame || frame > GetConfirmedFrame()) {
544 return;
545 }
546
547 _game_events.AddStateSaveEvent(frame, &_health_state);
548 _health_captured = true;
549}
550
552{
553 const Frame current = _sync.GetCurrentFrame();
554 const bool resimulates = !IsLockstepActive() && !IsPlayingLocally();
555
556 if (_health_frame >= current || (resimulates && _health_frame > _last_saved_frame)) {
557 return;
558 }
559
561}
562
564{
565 _msg.SendNetworkHealth();
566}
567
569{
570 if (!_config.desync_detection) {
571 return;
572 }
573
574 for (auto iter = _msg.local_health.begin();
575 iter != _msg.local_health.end(); ) {
576
577 for (auto& player : _msg.remotes) {
578 if (player->session_health.count(iter->first)) {
579 if (player->session_health[iter->first] != iter->second) {
580 _msg.session_events.AddDesyncDetectedEvent(
581 iter->first,
582 player->handle,
583 iter->second,
584 player->session_health[iter->first]
585 );
586 }
587 player->session_health.erase(iter->first);
588 }
589 }
590
591 ++iter;
592 }
593}
594
596{
597 const Frame current = _sync.GetCurrentFrame();
598
599 for (auto& player : _msg.remotes) {
600 if (player->GetStatus() != Disconnected) {
601 continue;
602 }
603
604 const Handle handle = player->handle;
605 const Frame disc_frame = player->disconnect_frame;
606
607 auto& input_q = _msg.GetNetPlayerQueue(handle);
608 const Frame last_added = _msg.GetLastAddedInputFrom(handle);
609 const Frame oldest = last_added - (Frame)input_q.size() + 1;
610
611 // when a claim raised the agreed frame, replace the neutral inputs the
612 // session already used with the real ones so a rollback corrects it.
613 if (player->applied_disconnect_frame != INT32_MAX &&
614 player->applied_disconnect_frame < disc_frame) {
615 const Frame received = _sync.GetLastReceivedFrom(handle);
616 const Frame raised_up_to = std::min(disc_frame, received);
617 for (Frame frame = player->applied_disconnect_frame + 1; frame <= raised_up_to; frame++) {
618 if (frame >= oldest && frame <= last_added) {
619 _sync.OverwriteInput(handle, input_q[frame - oldest].get(), frame);
620 }
621 }
622 }
623 player->applied_disconnect_frame = disc_frame;
624
625 // use the inputs we hold up to the agreed frame, neutral input afterwards.
626 // include the current frame itself, lockstep cant predict its way past it.
627 const Frame last_recv = _sync.GetLastReceivedFrom(handle) + 1;
628
629 for (Frame frame = last_recv; frame <= current; frame++) {
630 if (frame <= disc_frame && frame >= oldest && frame <= last_added) {
631 _sync.AddRemoteInput(handle, input_q[frame - oldest].get(), frame);
632 }
633 else {
634 _sync.AddRemoteInput(handle, _disconnected_input.get(), frame);
635 }
636 }
637 }
638}
639
641{
642 const Frame current = _msg.GetLastAddedInput(true) + 1;
643 const Frame confirmed = GetConfirmedFrame();
644
645 std::unique_ptr<u8[]> inputs;
646 for (Frame frame = current; frame <= confirmed; frame++) {
647 if (!_sync.GetSpectatorInputs(inputs, frame)) {
648 break;
649 }
650 _msg.AddSpectatorInput(frame, inputs.get());
651 }
652}
653
655{
656 if (!_started || _config.state_size == 0) {
657 return;
658 }
659
660 const Frame oldest_input = _msg.GetOldestSpectatorInput();
661
662 for (auto& spectator : _msg.spectators) {
663 if (spectator->GetStatus() != Connected ||
664 !spectator->requires_spectator_state || spectator->spectator_state_acked) {
665 continue;
666 }
667
668 const bool state_too_old = spectator->spectator_state_configured &&
669 spectator->spectator_state_frame + 1 < oldest_input;
670 if (spectator->spectator_state_configured && !state_too_old) {
671 continue;
672 }
673
674 // states from the earliest mispredicted frame on are not rolled back yet.
675 Frame newest_correct = GetConfirmedFrame();
676 const Frame incorrect = _sync.GetMinIncorrectFrame();
677 if (incorrect != GameInput::NULL_FRAME) {
678 newest_correct = std::min(newest_correct, incorrect - 1);
679 }
680
681 Frame state_frame = _config.limited_saving ? _last_saved_frame : newest_correct;
682 const Frame oldest_state = _config.limited_saving
683 ? state_frame
684 : std::max((Frame)-1, state_frame - (Frame)_config.max_input_prediction_window - 1);
685
686 StateEntry* state = nullptr;
687 for (Frame frame = state_frame; frame >= oldest_state; frame--) {
688 auto candidate = _storage.GetState(frame);
689 if (candidate->frame == frame && candidate->state_len > 0 &&
690 candidate->state_len <= _config.state_size) {
691 state_frame = frame;
692 state = candidate;
693 break;
694 }
695 }
696
697 const Frame confirmed = GetConfirmedFrame();
698 if (_spectator_state.frame >= oldest_state &&
699 _spectator_state.frame <= confirmed && _spectator_state.state_len > 0 &&
700 _spectator_state.state_len <= _config.state_size &&
701 (!state || _spectator_state.frame > state_frame)) {
702 state_frame = _spectator_state.frame;
703 state = &_spectator_state;
704 }
705
706 if (!state || state_frame + 1 < oldest_input ||
707 (spectator->spectator_state_configured &&
708 state_frame <= spectator->spectator_state_frame)) {
709 continue;
710 }
711
712 _msg.SetSpectatorState(
713 spectator->handle,
714 state_frame,
715 state->state.get(),
716 state->state_len
717 );
718 }
719}
720
722{
723 if (_config.state_size == 0) {
724 return;
725 }
726
727 const Frame oldest_input = _msg.GetOldestSpectatorInput();
728 bool state_needed = false;
729 for (auto& spectator : _msg.spectators) {
730 if (spectator->GetStatus() != Connected ||
731 !spectator->requires_spectator_state || spectator->spectator_state_acked) {
732 continue;
733 }
734
735 if (!spectator->spectator_state_configured ||
736 spectator->spectator_state_frame + 1 < oldest_input) {
737 state_needed = true;
738 break;
739 }
740 }
741
742 const Frame current = _sync.GetCurrentFrame();
743 const Frame state_frame = std::min(current - 1, GetConfirmedFrame());
744 if (!state_needed || state_frame + 1 < oldest_input ||
745 state_frame <= _spectator_state.frame) {
746 return;
747 }
748
749 // Lockstep and local sessions are already sitting on the confirmed state.
750 if (state_frame == current - 1) {
751 _game_events.AddStateSaveEvent(state_frame, &_spectator_state, true);
752 return;
753 }
754
755 // A rollback session may be ahead of its confirmed frame. Re-simulate from
756 // its latest persistent save, capture the confirmed state along the way,
757 // and finish back at the state where this update started.
758 const Frame sync_frame = _last_saved_frame;
759 if (sync_frame >= state_frame) {
760 return;
761 }
762
763 auto saved = _storage.GetState(sync_frame);
764 if (saved->frame != sync_frame || saved->state_len == 0) {
765 return;
766 }
767
768 _sync.SetCurrentFrame(sync_frame);
769 _game_events.AddLoadEvent(_sync, _storage);
770 _sync.IncrementFrame();
771
772 for (Frame frame = sync_frame + 1; frame < current; frame++) {
773 _game_events.AddAdvanceEvent(_sync, true);
774 if (frame == state_frame) {
775 _game_events.AddStateSaveEvent(frame, &_spectator_state, true);
776 }
777 CaptureHealthState(frame);
779 _sync.IncrementFrame();
780 }
781
782 assert(_sync.GetCurrentFrame() == current);
783}
784
786{
787 Frame current = _sync.GetCurrentFrame();
789 _sync.SetCurrentFrame(current - 1);
791 _sync.IncrementFrame();
792 }
793
794 if (!RollbackPending()) {
795 return;
796 }
797
798 current = _sync.GetCurrentFrame();
799 const Frame min = _sync.GetMinIncorrectFrame();
800
801 const Frame sync_frame = _config.limited_saving ? _last_saved_frame : min - 1;
802 // never keep a save beyond the confirmed frame, a disconnect claim may
803 // still change inputs past it and the save would bake in the wrong ones.
804 const Frame frame_to_save = std::min(std::min(current - 1, min), GetConfirmedFrame());
805
806 // load the sync frame
807 _sync.SetCurrentFrame(sync_frame);
808 _game_events.AddLoadEvent(_sync, _storage);
809 _sync.IncrementFrame();
810
811 for (Frame frame = sync_frame + 1; frame < current; frame++) {
812 _game_events.AddAdvanceEvent(_sync, true);
813 if (!_config.limited_saving || frame == frame_to_save) {
815 }
816 CaptureHealthState(frame);
818 _sync.IncrementFrame();
819 }
820
821 const u32 resimulated = (u32)(current - sync_frame - 1);
822 _rollback_stats.count++;
823 _rollback_stats.last_frames = resimulated;
824 _rollback_stats.max_frames = std::max(_rollback_stats.max_frames, resimulated);
825 _rollback_stats.total_frames += resimulated;
826
827 // clear the marked mispredictions up to this point in the input buffer
828 _sync.ClearIncorrectFramesUpTo(current);
829
830 // make sure that we are back where we started.
831 assert(_sync.GetCurrentFrame() == current);
832}
833
835{
836 // return if no host is defined.
837 if (!_host) {
838 return;
839 }
840
841 // fetch data from network
842 int length = 0;
843 auto data = _host->receive_data(&length);
844
845 // process the data we received
846 _msg.HandleData(_host, data, length);
847
848 // Existing sessions continue handshaking newly added spectators.
849 _msg.CheckStatusActors();
850
851 // handle received inputs
853
854 // add local input for the network
856
857 // send inputs to spectators
859
860 // Late spectators start from a confirmed state and receive only later inputs.
862
863 // send network health update
865
866 // now send data
867 _msg.SendPendingOutput(_host);
868}
869
871{
872 if (!_started) {
873 if (!_msg.CheckStatusActors()) {
874 return false;
875 }
876
877 // if none returned that the session is ready!
878 _msg.session_events.AddSessionStartedEvent();
879
880 _started = true;
881
882 return true;
883 }
884
885 return true;
886}
887
889{
890 for (auto& remote : _msg.remotes) {
891 if (remote->GetStatus() != Connected) continue;
892
893 {
894 auto handle = remote->handle;
895 const Frame last_recv = _sync.GetLastReceivedFrom(handle) + 1;
896 const Frame last_added = _msg.GetLastAddedInputFrom(handle);
897
898 assert(last_added - last_recv <= 128); // more then 128 frames behind sounds incorrect.
899
900 auto& input_q = _msg.GetNetPlayerQueue(handle);
901 const Frame min_frame = last_added - (i32)input_q.size() + 1;
902 const Frame current_frame = _sync.GetCurrentFrame();
903 const Frame local_delay = (Frame)GetMinLocalDelay();
904 for (int i = last_recv; i <= last_added; i++) {
905 if (i >= min_frame) {
906 int current_idx = i - min_frame;
907 u8* input = input_q[current_idx].get();
908 _sync.AddRemoteInput(handle, input, i);
909 // + delay: each peer then rolls back latency - own delay
910 const i8 local_adv = (i8)(current_frame - i + local_delay);
911 _msg.SendInputAck(handle, i, local_adv);
912 }
913 }
914 }
915 }
916}
917
919{
920 if (!_msg.locals.empty() && _started) {
921 const Frame current = _msg.GetLastAddedInput(false) + 1;
922 const Frame delay = GetMinLocalDelay();
923
924 auto input = std::make_unique<u8[]>(_config.input_size);
925 for (Frame frame = current; frame <= current + delay; frame++) {
926 for (auto& player : _msg.locals) {
927 if (!_sync.GetLocalInput(player->handle, input, frame)) {
928 return;
929 }
930 _msg.AddInput(frame, player->handle, input.get());
931 }
932 // Record per-peer advantage snapshot once per actual game frame
933 if (frame == current) {
934 const Frame current_frame = _sync.GetCurrentFrame();
935 for (auto& remote : _msg.remotes) {
936 if (remote->GetStatus() == Connected) {
937 const i8 local_adv = (i8)(current_frame - _sync.GetLastReceivedFrom(remote->handle) + (Frame)delay);
938 remote->adv_history.SetLocalAdvantage(local_adv);
939 remote->adv_history.Update(frame);
940 }
941 }
942 }
943 }
944 }
945}
946
948{
949 u8 min = UINT8_MAX;
950 for (auto& player : _msg.locals) {
951 min = std::min(_sync.GetLocalDelay(player->handle), min);
952 }
953 return min;
954}
955
957{
958 return _msg.remotes.empty() && !_msg.locals.empty();
959}
960
962{
963 return _config.max_input_prediction_window == 0;
964}
965
967{
969 return false;
970 }
971
972 return _sync.GetMinIncorrectFrame() != GameInput::NULL_FRAME;
973}
974
976{
977 if (IsLockstepActive() || !_config.limited_saving || IsPlayingLocally()) {
978 return false;
979 }
980
981 const Frame diff = _sync.GetCurrentFrame() - (_last_saved_frame + 1);
982 return diff > _config.max_input_prediction_window;
983}
984
986{
987 // hold back confirmation while a disconnected players inputs may still grow.
988 return std::min(_msg.GetDisconnectHoldFrame(), _sync.GetMinReceivedFrame());
989}
990
992{
993 // while the claims for a disconnected player are settling a peer may still
994 // carry more inputs, dont outrun what the session can roll back to.
995 const Frame hold = _msg.GetDisconnectHoldFrame();
996
997 if (hold == INT32_MAX) {
998 return false;
999 }
1000
1001 return _sync.GetCurrentFrame() - hold > (Frame)_input_prediction_window;
1002}
1003
1005{
1007 return;
1008 }
1009
1011
1012 // a rollback or confirmed save will load+resim this frame, so dont load twice.
1013 if (RollbackPending() || ConfirmedSaveDue()) {
1014 return;
1015 }
1016
1017 _game_events.AddRunaheadLoadEvent(_storage);
1018}
1019
1021{
1022 if ((IsLockstepActive() && !IsPlayingLocally()) || _runahead_frames == 0) {
1023 return;
1024 }
1025
1026 _runahead_start_frame = _sync.GetCurrentFrame();
1027 _game_events.AddRunaheadSaveEvent(_sync, _storage);
1028
1029 _sync.SetRunaheadMode(true);
1030 for (u8 i = 0; i < _runahead_frames; i++) {
1031 const bool is_display_frame = (i == _runahead_frames - 1);
1032 if (!_game_events.AddAdvanceEvent(_sync, false, !is_display_frame)) {
1033 break;
1034 }
1035 _sync.IncrementFrame();
1036 }
1037 _sync.SetRunaheadMode(false);
1038
1039 // Reset back to the real frame so AddLocalInput and network logic see the correct frame
1040 _sync.SetCurrentFrame(_runahead_start_frame);
1041}
i32 AddActor(GekkoPlayerType type, GekkoNetAddress *addr) override
MessageSystem _msg
GameEventSystem _game_events
void SetInputPredictionWindow(u8 window) override
void SetRunahead(u8 runahead) override
ReplaySystem _replay
void NetworkStats(i32 player, GekkoNetworkStats *stats) override
void SetLocalDelay(i32 player, u8 delay) override
std::unique_ptr< u8[]> _disconnected_input
bool IsLockstepActive() const
void SetDisconnectTimeout(u32 timeout) override
void AddLocalInput(i32 player, void *input) override
RollbackCounters _rollback_stats
bool StartRecording(bool save_initial_state, bool disable_compression) override
static const Frame HEALTH_CHECK_INTERVAL
void HandleSavingConfirmedFrame()
f32 FramesAhead() override
GekkoGameEvent ** UpdateSession(i32 *count) override
void CaptureHealthState(Frame frame)
void RollbackStats(GekkoRollbackStats *stats) override
GekkoNetAdapter * _host
void Init(GekkoConfig *config) override
void NetworkPoll() override
void AddDisconnectedPlayerInputs()
GekkoConfig _config
void CaptureChecksumState(Frame frame)
GekkoSessionEvent ** Events(i32 *count) override
StateEntry _spectator_state
bool DisconnectActor(i32 actor) override
void SkipUnreachableHealthFrame()
std::vector< std::unique_ptr< StateEntry > > _checksum_states
void SetNetAdapter(GekkoNetAdapter *adapter) override
bool RecordChecksums(u32 interval) override
const u8 * StopRecording(u32 &length) override
bool SetReplayUserData(const u8 *data, u32 length) override
StateEntry _health_state
const u8 * PeekRecording(u32 &length) override
StateStorage _storage
int32_t i32
Definition gekko_types.h:12
float f32
Definition gekko_types.h:15
int32_t Handle
Definition gekko_types.h:19
int32_t Frame
Definition gekko_types.h:18
uint8_t u8
Definition gekko_types.h:5
int8_t i8
Definition gekko_types.h:10
uint32_t u32
Definition gekko_types.h:7
struct GekkoConfig GekkoConfig
GekkoPlayerType
Definition gekkonet.h:77
@ GekkoSpectator
Definition gekkonet.h:80
@ GekkoLocalPlayer
Definition gekkonet.h:78
@ Connected
Definition backend.h:22
@ Disconnected
Definition backend.h:23
unsigned int size
Definition gekkonet.h:85
unsigned short last_ping
Definition gekkonet.h:184
unsigned int max_frames
Definition gekkonet.h:193
unsigned int total_count
Definition gekkonet.h:190
unsigned int last_frames
Definition gekkonet.h:191
unsigned int total_stalls
Definition gekkonet.h:194
static const i32 NULL_FRAME
Definition input.h:21
static const u32 DEFAULT_BUFF_SIZE
Definition input.h:31
std::unique_ptr< u8[]> state
Definition storage.h:12