-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathnthread.cpp
256 lines (232 loc) · 6.5 KB
/
nthread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* @file nthread.cpp
*
* Implementation of functions for managing game ticks.
*/
#include "nthread.h"
#include <cstdint>
#include <fmt/core.h>
#include "diablo.h"
#include "engine/demomode.h"
#include "gmenu.h"
#include "storm/storm_net.hpp"
#include "utils/sdl_mutex.h"
#include "utils/sdl_thread.h"
#include "utils/str_cat.hpp"
namespace devilution {
uint8_t sgbNetUpdateRate;
size_t gdwMsgLenTbl[MAX_PLRS];
uint32_t gdwTurnsInTransit;
uintptr_t glpMsgTbl[MAX_PLRS];
uint32_t gdwLargestMsgSize;
uint32_t gdwNormalMsgSize;
int last_tick;
uint8_t ProgressToNextGameTick = 0;
namespace {
SdlMutex MemCrit;
bool nthread_should_run;
int8_t sgbSyncCountdown;
uint32_t turn_upper_bit;
bool sgbTicsOutOfSync;
int8_t sgbPacketCountdown;
bool sgbThreadIsRunning;
SdlThread Thread;
void NthreadHandler()
{
if (!nthread_should_run) {
return;
}
while (true) {
MemCrit.lock();
if (!nthread_should_run) {
MemCrit.unlock();
break;
}
nthread_send_and_recv_turn(0, 0);
int delta = gnTickDelay;
if (nthread_recv_turns())
delta = last_tick - SDL_GetTicks();
MemCrit.unlock();
if (delta > 0)
SDL_Delay(delta);
if (!nthread_should_run)
return;
}
}
} // namespace
void nthread_terminate_game(const char *pszFcn)
{
app_fatal(pszFcn);
gbGameDestroyed = true;
}
uint32_t nthread_send_and_recv_turn(uint32_t curTurn, int turnDelta)
{
uint32_t curTurnsInTransit;
if (!SNetGetTurnsInTransit(&curTurnsInTransit)) {
nthread_terminate_game("SNetGetTurnsInTransit");
return 0;
}
while (curTurnsInTransit++ < gdwTurnsInTransit) {
uint32_t turnTmp = turn_upper_bit | (curTurn & 0x7FFFFFFF);
turn_upper_bit = 0;
uint32_t turn = turnTmp;
if (!SNetSendTurn((char *)&turn, sizeof(turn))) {
nthread_terminate_game("SNetSendTurn");
return 0;
}
curTurn += turnDelta;
if (curTurn >= 0x7FFFFFFF)
curTurn &= 0xFFFF;
}
return curTurn;
}
bool nthread_recv_turns(bool *pfSendAsync)
{
if (pfSendAsync != nullptr)
*pfSendAsync = false;
sgbPacketCountdown--;
if (sgbPacketCountdown > 0) {
last_tick += gnTickDelay;
return true;
}
sgbSyncCountdown--;
sgbPacketCountdown = sgbNetUpdateRate;
if (sgbSyncCountdown != 0) {
if (pfSendAsync != nullptr)
*pfSendAsync = true;
last_tick += gnTickDelay;
return true;
}
if (!SNetReceiveTurns(MAX_PLRS, (char **)glpMsgTbl, gdwMsgLenTbl, &player_state[0])) {
sgbTicsOutOfSync = false;
sgbSyncCountdown = 1;
sgbPacketCountdown = 1;
return false;
}
if (!sgbTicsOutOfSync) {
sgbTicsOutOfSync = true;
last_tick = SDL_GetTicks();
}
sgbSyncCountdown = 4;
multi_msg_countdown();
if (pfSendAsync != nullptr)
*pfSendAsync = true;
last_tick += gnTickDelay;
return true;
}
void nthread_set_turn_upper_bit()
{
turn_upper_bit = 0x80000000;
}
void nthread_start(bool setTurnUpperBit)
{
last_tick = SDL_GetTicks();
sgbPacketCountdown = 1;
sgbSyncCountdown = 1;
sgbTicsOutOfSync = true;
if (setTurnUpperBit)
nthread_set_turn_upper_bit();
else
turn_upper_bit = 0;
_SNETCAPS caps;
caps.size = 36;
SNetGetProviderCaps(&caps);
gdwTurnsInTransit = caps.defaultturnsintransit;
if (gdwTurnsInTransit == 0)
gdwTurnsInTransit = 1;
if (caps.defaultturnssec <= 20 && caps.defaultturnssec != 0)
sgbNetUpdateRate = 20 / caps.defaultturnssec;
else
sgbNetUpdateRate = 1;
uint32_t largestMsgSize = 512;
if (caps.maxmessagesize < 0x200)
largestMsgSize = caps.maxmessagesize;
gdwLargestMsgSize = largestMsgSize;
gdwNormalMsgSize = caps.bytessec * sgbNetUpdateRate / 20;
gdwNormalMsgSize *= 3;
gdwNormalMsgSize >>= 2;
if (caps.maxplayers > MAX_PLRS)
caps.maxplayers = MAX_PLRS;
gdwNormalMsgSize /= caps.maxplayers;
while (gdwNormalMsgSize < 0x80) {
gdwNormalMsgSize *= 2;
sgbNetUpdateRate *= 2;
}
if (gdwNormalMsgSize > largestMsgSize)
gdwNormalMsgSize = largestMsgSize;
if (gbIsMultiplayer) {
sgbThreadIsRunning = false;
MemCrit.lock();
nthread_should_run = true;
Thread = SdlThread { NthreadHandler };
}
}
void nthread_cleanup()
{
nthread_should_run = false;
gdwTurnsInTransit = 0;
gdwNormalMsgSize = 0;
gdwLargestMsgSize = 0;
if (Thread.joinable() && Thread.get_id() != this_sdl_thread::get_id()) {
if (!sgbThreadIsRunning)
MemCrit.unlock();
Thread.join();
}
}
void nthread_ignore_mutex(bool bStart)
{
if (!Thread.joinable())
return;
if (bStart)
MemCrit.unlock();
else
MemCrit.lock();
sgbThreadIsRunning = bStart;
}
bool nthread_has_500ms_passed(bool *drawGame /*= nullptr*/)
{
int currentTickCount = SDL_GetTicks();
int ticksElapsed = currentTickCount - last_tick;
// Check if we missed multiple game ticks (> 10)
if (ticksElapsed > gnTickDelay * 10) {
bool resetLastTick = true;
if (gbIsMultiplayer) {
for (size_t i = 0; i < Players.size(); i++) {
if ((player_state[i] & PS_CONNECTED) != 0 && i != MyPlayerId) {
// Reset last tick is not allowed when other players are connected, because the elapsed time is needed to sync the game ticks between the clients
resetLastTick = false;
break;
}
}
}
if (resetLastTick) {
// Reset last tick to avoid catching up with all missed game ticks (game speed is dramatically increased for a short time)
last_tick = currentTickCount;
ticksElapsed = 0;
}
}
if (drawGame != nullptr) {
// Check if we missed a game tick.
// This can happen when we run a low-end device that can't render fast enough (typically 20fps).
// If this happens, try to speed-up the game by skipping the rendering.
// This avoids desyncs and hourglasses when running multiplayer and slowdowns in singleplayer.
*drawGame = ticksElapsed <= gnTickDelay;
}
return ticksElapsed >= 0;
}
void nthread_UpdateProgressToNextGameTick()
{
if (!gbRunGame || PauseMode != 0 || (!gbIsMultiplayer && gmenu_is_active()) || !gbProcessPlayers || demo::IsRunning()) // if game is not running or paused there is no next gametick in the near future
return;
int currentTickCount = SDL_GetTicks();
int ticksMissing = last_tick - currentTickCount;
if (ticksMissing <= 0) {
ProgressToNextGameTick = AnimationInfo::baseValueFraction; // game tick is due
return;
}
int ticksAdvanced = gnTickDelay - ticksMissing;
int32_t fraction = ticksAdvanced * AnimationInfo::baseValueFraction / gnTickDelay;
fraction = std::clamp<int32_t>(fraction, 0, AnimationInfo::baseValueFraction);
ProgressToNextGameTick = static_cast<uint8_t>(fraction);
}
} // namespace devilution