forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathConnection.cpp
More file actions
407 lines (338 loc) · 11.7 KB
/
Connection.cpp
File metadata and controls
407 lines (338 loc) · 11.7 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#include "GameNetwork/Connection.h"
#include "GameNetwork/networkutil.h"
#include "GameLogic/GameLogic.h"
enum { MaxQuitFlushTime = 30000 }; // wait this many milliseconds at most to retry things before quitting
/**
* The constructor.
*/
Connection::Connection() {
m_transport = nullptr;
m_user = nullptr;
m_netCommandList = nullptr;
m_retryTime = 2000; // set retry time to 2 seconds.
m_lastTimeSent = 0;
m_frameGrouping = 1;
m_isQuitting = false;
m_quitTime = 0;
m_averageLatency = 0.0f;
Int i;
for(i = 0; i < CONNECTION_LATENCY_HISTORY_LENGTH; i++)
{
m_latencies[i] = 0.0f;
}
}
/**
* The destructor.
*/
Connection::~Connection() {
deleteInstance(m_user);
m_user = nullptr;
deleteInstance(m_netCommandList);
m_netCommandList = nullptr;
}
/**
* Initialize the connection and any subsystems.
*/
void Connection::init() {
m_transport = nullptr;
deleteInstance(m_user);
m_user = nullptr;
if (m_netCommandList == nullptr) {
m_netCommandList = newInstance(NetCommandList);
m_netCommandList->init();
}
m_netCommandList->reset();
m_lastTimeSent = 0;
m_frameGrouping = 1;
m_numRetries = 0;
m_retryMetricsTime = 0;
for (Int i = 0; i < CONNECTION_LATENCY_HISTORY_LENGTH; ++i) {
m_latencies[i] = 0;
}
m_averageLatency = 0;
m_isQuitting = FALSE;
m_quitTime = 0;
}
/**
* Take the connection back to the initial state.
*/
void Connection::reset() {
init();
}
/**
* Doesn't really do anything.
*/
void Connection::update() {
}
/**
* Attach the transport object that this connection should use.
*/
void Connection::attachTransport(Transport *transport) {
m_transport = transport;
}
/**
* Assign this connection a user. This is the user to whome we send all our packetized goodies.
*/
void Connection::setUser(User *user) {
deleteInstance(m_user);
m_user = user;
}
/**
* Return the user object.
*/
User * Connection::getUser() {
return m_user;
}
/**
* Add this network command to the send queue for this connection.
* The relay is the mask specifying the people the person we are sending to should send to.
* The relay mostly has to do with the packet router.
*/
void Connection::sendNetCommandMsg(NetCommandMsg *msg, UnsignedByte relay) {
if (m_isQuitting)
return;
if (m_netCommandList != nullptr) {
// this is done so we don't have to allocate and delete a packet every time we send a message.
static NetPacket* packet = newInstance(NetPacket);
// check to see if this command will fit in a packet. If not, we need to split it up.
// we are splitting up the command here so that the retry logic will not try to
// resend the ENTIRE command (i.e. multiple packets work of data) and only do the retry
// one wrapper command at a time.
packet->reset();
NetCommandRef *tempref = NEW_NETCOMMANDREF(msg);
Bool msgFits = packet->addCommand(tempref);
deleteInstance(tempref); // delete the temporary reference.
tempref = nullptr;
if (!msgFits) {
NetCommandRef *origref = NEW_NETCOMMANDREF(msg);
origref->setRelay(relay);
// the message doesn't fit in a single packet, need to split it up.
NetPacketList packetList = NetPacket::ConstructBigCommandPacketList(origref);
NetPacketListIter tempPacketPtr = packetList.begin();
while (tempPacketPtr != packetList.end()) {
NetPacket *tempPacket = (*tempPacketPtr);
NetCommandList *list = tempPacket->getCommandList();
NetCommandRef *ref1 = list->getFirstMessage();
while (ref1 != nullptr) {
NetCommandRef *ref2 = m_netCommandList->addMessage(ref1->getCommand());
ref2->setRelay(relay);
ref1 = ref1->getNext();
}
deleteInstance(tempPacket);
tempPacket = nullptr;
++tempPacketPtr;
deleteInstance(list);
list = nullptr;
}
deleteInstance(origref);
origref = nullptr;
return;
}
// the message fits in a packet, add to the command list normally.
NetCommandRef *ref = m_netCommandList->addMessage(msg);
if (ref != nullptr) {
/*
#if defined(RTS_DEBUG)
if (msg->getNetCommandType() == NETCOMMANDTYPE_GAMECOMMAND) {
DEBUG_LOG(("Connection::sendNetCommandMsg - added game command %d to net command list for frame %d.",
msg->getID(), msg->getExecutionFrame()));
} else if (msg->getNetCommandType() == NETCOMMANDTYPE_FRAMEINFO) {
DEBUG_LOG(("Connection::sendNetCommandMsg - added frame info for frame %d", msg->getExecutionFrame()));
}
#endif // RTS_DEBUG
*/
ref->setRelay(relay);
}
}
}
void Connection::clearCommandsExceptFrom( Int playerIndex )
{
NetCommandRef *tmp = m_netCommandList->getFirstMessage();
while (tmp)
{
NetCommandRef *next = tmp->getNext();
NetCommandMsg *msg = tmp->getCommand();
if (msg->getPlayerID() != playerIndex)
{
DEBUG_LOG(("Connection::clearCommandsExceptFrom(%d) - clearing a command from player %d for frame %d",
playerIndex, tmp->getCommand()->getPlayerID(), tmp->getCommand()->getExecutionFrame()));
m_netCommandList->removeMessage(tmp);
deleteInstance(tmp);
}
tmp = next;
}
}
Bool Connection::isQueueEmpty() {
if (m_netCommandList->getFirstMessage() == nullptr) {
return TRUE;
}
return FALSE;
}
void Connection::setQuitting()
{
m_isQuitting = TRUE;
m_quitTime = timeGetTime();
DEBUG_LOG(("Connection::setQuitting() at time %d", m_quitTime));
}
/**
* This is the good part. We take all the network commands queued up for this connection,
* packetize them and put them on the transport's send queue for actual sending.
*/
UnsignedInt Connection::doSend() {
Int numpackets = 0;
time_t curtime = timeGetTime();
Bool couldQueue = TRUE;
// Do this check first, since it's an important fail-safe
if (m_isQuitting && curtime > m_quitTime + MaxQuitFlushTime)
{
DEBUG_LOG(("Timed out a quitting connection. Deleting all %d messages", m_netCommandList->length()));
m_netCommandList->reset();
return 0;
}
if ((curtime - m_lastTimeSent) < m_frameGrouping) {
// DEBUG_LOG(("not sending packet, time = %d, m_lastFrameSent = %d, m_frameGrouping = %d", curtime, m_lastTimeSent, m_frameGrouping));
return 0;
}
// iterate through all the messages and put them into a packet(s).
NetCommandRef *msg = m_netCommandList->getFirstMessage();
// this is done so we don't have to allocate and delete a packet every time we send a message.
static NetPacket* packet = newInstance(NetPacket);
while ((msg != nullptr) && couldQueue) {
packet->reset();
packet->setAddress(m_user->GetIPAddr(), m_user->GetPort());
Bool notDone = TRUE;
// add the command messages until either we run out of messages or the packet is full.
while ((msg != nullptr) && notDone) {
NetCommandRef *next = msg->getNext(); // Need this since msg could be deleted
time_t timeLastSent = msg->getTimeLastSent();
if (((curtime - timeLastSent) > m_retryTime) || (timeLastSent == -1)) {
notDone = packet->addCommand(msg);
if (notDone) {
// the msg command was added to the packet.
if (CommandRequiresAck(msg->getCommand())) {
if (timeLastSent != -1) {
++m_numRetries;
}
doRetryMetrics();
msg->setTimeLastSent(curtime);
} else {
m_netCommandList->removeMessage(msg);
deleteInstance(msg);
}
}
}
msg = next;
}
if (msg != nullptr) {
DEBUG_LOG(("didn't finish sending all commands in connection"));
}
++numpackets;
/// @todo Make the act of giving the transport object a packet to send more efficient. Make the transport take a NetPacket object rather than the raw data, thus avoiding an extra memcpy.
if (packet->getNumCommands() > 0) {
// If the packet actually has any information to give, give it to the transport object
// for transmission.
couldQueue = m_transport->queueSend(packet->getAddr(), packet->getPort(), packet->getData(), packet->getLength());
m_lastTimeSent = curtime;
}
}
return numpackets;
}
NetCommandRef * Connection::processAck(NetAckStage1CommandMsg *msg) {
return processAck(msg->getCommandID(), msg->getOriginalPlayerID());
}
NetCommandRef * Connection::processAck(NetAckBothCommandMsg *msg) {
return processAck(msg->getCommandID(), msg->getOriginalPlayerID());
}
NetCommandRef * Connection::processAck(NetCommandMsg *msg) {
if (msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE1) {
NetAckStage1CommandMsg *ackmsg = (NetAckStage1CommandMsg *)msg;
return processAck(ackmsg);
}
if (msg->getNetCommandType() == NETCOMMANDTYPE_ACKBOTH) {
NetAckBothCommandMsg *ackmsg = (NetAckBothCommandMsg *)msg;
return processAck(ackmsg);
}
return nullptr;
}
/**
* The person we are sending to has ack'd one of the messages we sent him.
* Take that message off the list of commands to send.
*/
NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte originalPlayerID) {
NetCommandRef *temp = m_netCommandList->getFirstMessage();
while ((temp != nullptr) && ((temp->getCommand()->getID() != commandID) || (temp->getCommand()->getPlayerID() != originalPlayerID))) {
// cycle through the commands till we find the one we need to remove.
// Need to check for both the command ID and the player ID.
temp = temp->getNext();
}
if (temp == nullptr) {
return nullptr;
}
#if defined(RTS_DEBUG)
Bool doDebug = FALSE;
if (temp->getCommand()->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) {
doDebug = TRUE;
}
#endif
Int index = temp->getCommand()->getID() % CONNECTION_LATENCY_HISTORY_LENGTH;
m_averageLatency -= ((Real)(m_latencies[index])) / CONNECTION_LATENCY_HISTORY_LENGTH;
Real lat = timeGetTime() - temp->getTimeLastSent();
m_averageLatency += lat / CONNECTION_LATENCY_HISTORY_LENGTH;
m_latencies[index] = lat;
#if defined(RTS_DEBUG)
if (doDebug == TRUE) {
DEBUG_LOG(("Connection::processAck - disconnect frame command %d found, removing from command list.", commandID));
}
#endif
m_netCommandList->removeMessage(temp);
return temp;
}
void Connection::setFrameGrouping(time_t frameGrouping) {
m_frameGrouping = frameGrouping;
// m_retryTime = frameGrouping * 4;
}
void Connection::doRetryMetrics() {
static Int numSeconds = 0;
time_t curTime = timeGetTime();
if ((curTime - m_retryMetricsTime) > 10000) {
m_retryMetricsTime = curTime;
++numSeconds;
// DEBUG_LOG(("Retries in the last 10 seconds = %d, average latency = %fms", m_numRetries, m_averageLatency));
m_numRetries = 0;
// m_retryTime = m_averageLatency * 1.5;
}
}
#if defined(RTS_DEBUG)
void Connection::debugPrintCommands() {
NetCommandRef *ref = m_netCommandList->getFirstMessage();
while (ref != nullptr) {
DEBUG_LOG(("Connection::debugPrintCommands - ID: %d\tType: %s\tRelay: 0x%X for frame %d",
ref->getCommand()->getID(), GetNetCommandTypeAsString(ref->getCommand()->getNetCommandType()),
ref->getRelay(), ref->getCommand()->getExecutionFrame()));
ref = ref->getNext();
}
}
#endif