Debian Codegraph @

code/server/sv_snapshot.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22
23 #include "server.h"
24
25
26 /*
27 =============================================================================
28
29 Delta encode a client frame onto the network channel
30
31 A normal server packet will look like:
32
33 4 sequence number (high bit set if an oversize fragment)
34 <optional reliable commands>
35 1 svc_snapshot
36 4 last client reliable command
37 4 serverTime
38 1 lastframe for delta compression
39 1 snapFlags
40 1 areaBytes
41 <areabytes>
42 <playerstate>
43 <packetentities>
44
45 =============================================================================
46 */
47
48 /*
49 =============
50 SV_EmitPacketEntities
51
52 Writes a delta update of an entityState_t list to the message.
53 =============
54 */
55 static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) {
56 entityState_t *oldent, *newent;
57 int oldindex, newindex;
58 int oldnum, newnum;
59 int from_num_entities;
60
61 // generate the delta update
62 if ( !from ) {
63 from_num_entities = 0;
64 } else {
65 from_num_entities = from->num_entities;
66 }
67
68 newent = NULL;
69 oldent = NULL;
70 newindex = 0;
71 oldindex = 0;
72 while ( newindex < to->num_entities || oldindex < from_num_entities ) {
73 if ( newindex >= to->num_entities ) {
74 newnum = 9999;
75 } else {
76 newent = &svs.snapshotEntities[(to->first_entity+newindex) % svs.numSnapshotEntities];
77 newnum = newent->number;
78 }
79
80 if ( oldindex >= from_num_entities ) {
81 oldnum = 9999;
82 } else {
83 oldent = &svs.snapshotEntities[(from->first_entity+oldindex) % svs.numSnapshotEntities];
84 oldnum = oldent->number;
85 }
86
87 if ( newnum == oldnum ) {
88 // delta update from old position
89 // because the force parm is qfalse, this will not result
90 // in any bytes being emitted if the entity has not changed at all
91 MSG_WriteDeltaEntity (msg, oldent, newent, qfalse );
92 oldindex++;
93 newindex++;
94 continue;
95 }
96
97 if ( newnum < oldnum ) {
98 // this is a new entity, send it from the baseline
99 MSG_WriteDeltaEntity (msg, &sv.svEntities[newnum].baseline, newent, qtrue );
100 newindex++;
101 continue;
102 }
103
104 if ( newnum > oldnum ) {
105 // the old entity isn't present in the new message
106 MSG_WriteDeltaEntity (msg, oldent, NULL, qtrue );
107 oldindex++;
108 continue;
109 }
110 }
111
112 MSG_WriteBits( msg, (MAX_GENTITIES-1), GENTITYNUM_BITS ); // end of packetentities
113 }
114
115
116
117 /*
118 ==================
119 SV_WriteSnapshotToClient
120 ==================
121 */
122 static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) {
123 clientSnapshot_t *frame, *oldframe;
124 int lastframe;
125 int i;
126 int snapFlags;
127
128 // this is the snapshot we are creating
129 frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
130
131 // try to use a previous frame as the source for delta compressing the snapshot
132 if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) {
133 // client is asking for a retransmit
134 oldframe = NULL;
135 lastframe = 0;
136 } else if ( client->netchan.outgoingSequence - client->deltaMessage
137 >= (PACKET_BACKUP - 3) ) {
138 // client hasn't gotten a good message through in a long time
139 Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name);
140 oldframe = NULL;
141 lastframe = 0;
142 } else {
143 // we have a valid snapshot to delta from
144 oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ];
145 lastframe = client->netchan.outgoingSequence - client->deltaMessage;
146
147 // the snapshot's entities may still have rolled off the buffer, though
148 if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) {
149 Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name);
150 oldframe = NULL;
151 lastframe = 0;
152 }
153 }
154
155 MSG_WriteByte (msg, svc_snapshot);
156
157 // NOTE, MRE: now sent at the start of every message from server to client
158 // let the client know which reliable clientCommands we have received
159 //MSG_WriteLong( msg, client->lastClientCommand );
160
161 // send over the current server time so the client can drift
162 // its view of time to try to match
163 if( client->oldServerTime ) {
164 // The server has not yet got an acknowledgement of the
165 // new gamestate from this client, so continue to send it
166 // a time as if the server has not restarted. Note from
167 // the client's perspective this time is strictly speaking
168 // incorrect, but since it'll be busy loading a map at
169 // the time it doesn't really matter.
170 MSG_WriteLong (msg, sv.time + client->oldServerTime);
171 } else {
172 MSG_WriteLong (msg, sv.time);
173 }
174
175 // what we are delta'ing from
176 MSG_WriteByte (msg, lastframe);
177
178 snapFlags = svs.snapFlagServerBit;
179 if ( client->rateDelayed ) {
180 snapFlags |= SNAPFLAG_RATE_DELAYED;
181 }
182 if ( client->state != CS_ACTIVE ) {
183 snapFlags |= SNAPFLAG_NOT_ACTIVE;
184 }
185
186 MSG_WriteByte (msg, snapFlags);
187
188 // send over the areabits
189 MSG_WriteByte (msg, frame->areabytes);
190 MSG_WriteData (msg, frame->areabits, frame->areabytes);
191
192 // delta encode the playerstate
193 if ( oldframe ) {
194 MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps );
195 } else {
196 MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps );
197 }
198
199 // delta encode the entities
200 SV_EmitPacketEntities (oldframe, frame, msg);
201
202 // padding for rate debugging
203 if ( sv_padPackets->integer ) {
204 for ( i = 0 ; i < sv_padPackets->integer ; i++ ) {
205 MSG_WriteByte (msg, svc_nop);
206 }
207 }
208 }
209
210
211 /*
212 ==================
213 SV_UpdateServerCommandsToClient
214
215 (re)send all server commands the client hasn't acknowledged yet
216 ==================
217 */
218 void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) {
219 int i;
220
221 // write any unacknowledged serverCommands
222 for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
223 MSG_WriteByte( msg, svc_serverCommand );
224 MSG_WriteLong( msg, i );
225 MSG_WriteString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
226 }
227 client->reliableSent = client->reliableSequence;
228 }
229
230 /*
231 =============================================================================
232
233 Build a client snapshot structure
234
235 =============================================================================
236 */
237
238 typedef struct {
239 int numSnapshotEntities;
240 int snapshotEntities[MAX_SNAPSHOT_ENTITIES];
241 } snapshotEntityNumbers_t;
242
243 /*
244 =======================
245 SV_QsortEntityNumbers
246 =======================
247 */
248 static int QDECL SV_QsortEntityNumbers( const void *a, const void *b ) {
249 int *ea, *eb;
250
251 ea = (int *)a;
252 eb = (int *)b;
253
254 if ( *ea == *eb ) {
255 Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" );
256 }
257
258 if ( *ea < *eb ) {
259 return -1;
260 }
261
262 return 1;
263 }
264
265
266 /*
267 ===============
268 SV_AddEntToSnapshot
269 ===============
270 */
271 static void SV_AddEntToSnapshot( svEntity_t *svEnt, sharedEntity_t *gEnt, snapshotEntityNumbers_t *eNums ) {
272 // if we have already added this entity to this snapshot, don't add again
273 if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
274 return;
275 }
276 svEnt->snapshotCounter = sv.snapshotCounter;
277
278 // if we are full, silently discard entities
279 if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) {
280 return;
281 }
282
283 eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number;
284 eNums->numSnapshotEntities++;
285 }
286
287 /*
288 ===============
289 SV_AddEntitiesVisibleFromPoint
290 ===============
291 */
292 static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *frame,
293 snapshotEntityNumbers_t *eNums, qboolean portal ) {
294 int e, i;
295 sharedEntity_t *ent;
296 svEntity_t *svEnt;
297 int l;
298 int clientarea, clientcluster;
299 int leafnum;
300 byte *clientpvs;
301 byte *bitvector;
302
303 // during an error shutdown message we may need to transmit
304 // the shutdown message after the server has shutdown, so
305 // specfically check for it
306 if ( !sv.state ) {
307 return;
308 }
309
310 leafnum = CM_PointLeafnum (origin);
311 clientarea = CM_LeafArea (leafnum);
312 clientcluster = CM_LeafCluster (leafnum);
313
314 // calculate the visible areas
315 frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea );
316
317 clientpvs = CM_ClusterPVS (clientcluster);
318
319 for ( e = 0 ; e < sv.num_entities ; e++ ) {
320 ent = SV_GentityNum(e);
321
322 // never send entities that aren't linked in
323 if ( !ent->r.linked ) {
324 continue;
325 }
326
327 if (ent->s.number != e) {
328 Com_DPrintf ("FIXING ENT->S.NUMBER!!!\n");
329 ent->s.number = e;
330 }
331
332 // entities can be flagged to explicitly not be sent to the client
333 if ( ent->r.svFlags & SVF_NOCLIENT ) {
334 continue;
335 }
336
337 // entities can be flagged to be sent to only one client
338 if ( ent->r.svFlags & SVF_SINGLECLIENT ) {
339 if ( ent->r.singleClient != frame->ps.clientNum ) {
340 continue;
341 }
342 }
343 // entities can be flagged to be sent to everyone but one client
344 if ( ent->r.svFlags & SVF_NOTSINGLECLIENT ) {
345 if ( ent->r.singleClient == frame->ps.clientNum ) {
346 continue;
347 }
348 }
349 // entities can be flagged to be sent to a given mask of clients
350 if ( ent->r.svFlags & SVF_CLIENTMASK ) {
351 if (frame->ps.clientNum >= 32)
352 Com_Error( ERR_DROP, "SVF_CLIENTMASK: clientNum >= 32" );
353 if (~ent->r.singleClient & (1 << frame->ps.clientNum))
354 continue;
355 }
356
357 svEnt = SV_SvEntityForGentity( ent );
358
359 // don't double add an entity through portals
360 if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
361 continue;
362 }
363
364 // broadcast entities are always sent
365 if ( ent->r.svFlags & SVF_BROADCAST ) {
366 SV_AddEntToSnapshot( svEnt, ent, eNums );
367 continue;
368 }
369
370 // ignore if not touching a PV leaf
371 // check area
372 if ( !CM_AreasConnected( clientarea, svEnt->areanum ) ) {
373 // doors can legally straddle two areas, so
374 // we may need to check another one
375 if ( !CM_AreasConnected( clientarea, svEnt->areanum2 ) ) {
376 continue; // blocked by a door
377 }
378 }
379
380 bitvector = clientpvs;
381
382 // check individual leafs
383 if ( !svEnt->numClusters ) {
384 continue;
385 }
386 l = 0;
387 for ( i=0 ; i < svEnt->numClusters ; i++ ) {
388 l = svEnt->clusternums[i];
389 if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
390 break;
391 }
392 }
393
394 // if we haven't found it to be visible,
395 // check overflow clusters that coudln't be stored
396 if ( i == svEnt->numClusters ) {
397 if ( svEnt->lastCluster ) {
398 for ( ; l <= svEnt->lastCluster ; l++ ) {
399 if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
400 break;
401 }
402 }
403 if ( l == svEnt->lastCluster ) {
404 continue; // not visible
405 }
406 } else {
407 continue;
408 }
409 }
410
411 // add it
412 SV_AddEntToSnapshot( svEnt, ent, eNums );
413
414 // if it's a portal entity, add everything visible from its camera position
415 if ( ent->r.svFlags & SVF_PORTAL ) {
416 if ( ent->s.generic1 ) {
417 vec3_t dir;
418 VectorSubtract(ent->s.origin, origin, dir);
419 if ( VectorLengthSquared(dir) > (float) ent->s.generic1 * ent->s.generic1 ) {
420 continue;
421 }
422 }
423 SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue );
424 }
425
426 }
427 }
428
429 /*
430 =============
431 SV_BuildClientSnapshot
432
433 Decides which entities are going to be visible to the client, and
434 copies off the playerstate and areabits.
435
436 This properly handles multiple recursive portals, but the render
437 currently doesn't.
438
439 For viewing through other player's eyes, clent can be something other than client->gentity
440 =============
441 */
442 static void SV_BuildClientSnapshot( client_t *client ) {
443 vec3_t org;
444 clientSnapshot_t *frame;
445 snapshotEntityNumbers_t entityNumbers;
446 int i;
447 sharedEntity_t *ent;
448 entityState_t *state;
449 svEntity_t *svEnt;
450 sharedEntity_t *clent;
451 int clientNum;
452 playerState_t *ps;
453
454 // bump the counter used to prevent double adding
455 sv.snapshotCounter++;
456
457 // this is the frame we are creating
458 frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];
459
460 // clear everything in this snapshot
461 entityNumbers.numSnapshotEntities = 0;
462 Com_Memset( frame->areabits, 0, sizeof( frame->areabits ) );
463
464 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=62
465 frame->num_entities = 0;
466
467 clent = client->gentity;
468 if ( !clent || client->state == CS_ZOMBIE ) {
469 return;
470 }
471
472 // grab the current playerState_t
473 ps = SV_GameClientNum( client - svs.clients );
474 frame->ps = *ps;
475
476 // never send client's own entity, because it can
477 // be regenerated from the playerstate
478 clientNum = frame->ps.clientNum;
479 if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) {
480 Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" );
481 }
482 svEnt = &sv.svEntities[ clientNum ];
483
484 svEnt->snapshotCounter = sv.snapshotCounter;
485
486 // find the client's viewpoint
487 VectorCopy( ps->origin, org );
488 org[2] += ps->viewheight;
489
490 // add all the entities directly visible to the eye, which
491 // may include portal entities that merge other viewpoints
492 SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse );
493
494 // if there were portals visible, there may be out of order entities
495 // in the list which will need to be resorted for the delta compression
496 // to work correctly. This also catches the error condition
497 // of an entity being included twice.
498 qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities,
499 sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers );
500
501 // now that all viewpoint's areabits have been OR'd together, invert
502 // all of them to make it a mask vector, which is what the renderer wants
503 for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) {
504 ((int *)frame->areabits)[i] = ((int *)frame->areabits)[i] ^ -1;
505 }
506
507 // copy the entity states out
508 frame->num_entities = 0;
509 frame->first_entity = svs.nextSnapshotEntities;
510 for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) {
511 ent = SV_GentityNum(entityNumbers.snapshotEntities[i]);
512 state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities];
513 *state = ent->s;
514 svs.nextSnapshotEntities++;
515 // this should never hit, map should always be restarted first in SV_Frame
516 if ( svs.nextSnapshotEntities >= 0x7FFFFFFE ) {
517 Com_Error(ERR_FATAL, "svs.nextSnapshotEntities wrapped");
518 }
519 frame->num_entities++;
520 }
521 }
522
523 #ifdef USE_VOIP
524 /*
525 ==================
526 SV_WriteVoipToClient
527
528 Check to see if there is any VoIP queued for a client, and send if there is.
529 ==================
530 */
531 static void SV_WriteVoipToClient(client_t *cl, msg_t *msg)
532 {
533 int totalbytes = 0;
534 int i;
535 voipServerPacket_t *packet;
536
537 if(cl->queuedVoipPackets)
538 {
539 // Write as many VoIP packets as we reasonably can...
540 for(i = 0; i < cl->queuedVoipPackets; i++)
541 {
542 packet = cl->voipPacket[(i + cl->queuedVoipIndex) % ARRAY_LEN(cl->voipPacket)];
543
544 if(!*cl->downloadName)
545 {
546 totalbytes += packet->len;
547 if (totalbytes > (msg->maxsize - msg->cursize) / 2)
548 break;
549
550 MSG_WriteByte(msg, svc_voipOpus);
551 MSG_WriteShort(msg, packet->sender);
552 MSG_WriteByte(msg, (byte) packet->generation);
553 MSG_WriteLong(msg, packet->sequence);
554 MSG_WriteByte(msg, packet->frames);
555 MSG_WriteShort(msg, packet->len);
556 MSG_WriteBits(msg, packet->flags, VOIP_FLAGCNT);
557 MSG_WriteData(msg, packet->data, packet->len);
558 }
559
560 Z_Free(packet);
561 }
562
563 cl->queuedVoipPackets -= i;
564 cl->queuedVoipIndex += i;
565 cl->queuedVoipIndex %= ARRAY_LEN(cl->voipPacket);
566 }
567 }
568 #endif
569
570 /*
571 =======================
572 SV_SendMessageToClient
573
574 Called by SV_SendClientSnapshot and SV_SendClientGameState
575 =======================
576 */
577 void SV_SendMessageToClient(msg_t *msg, client_t *client)
578 {
579 // record information about the message
580 client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSize = msg->cursize;
581 client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSent = svs.time;
582 client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1;
583
584 // send the datagram
585 SV_Netchan_Transmit(client, msg);
586 }
587
588
589 /*
590 =======================
591 SV_SendClientSnapshot
592
593 Also called by SV_FinalMessage
594
595 =======================
596 */
597 void SV_SendClientSnapshot( client_t *client ) {
598 byte msg_buf[MAX_MSGLEN];
599 msg_t msg;
600
601 // build the snapshot
602 SV_BuildClientSnapshot( client );
603
604 // bots need to have their snapshots build, but
605 // the query them directly without needing to be sent
606 if ( client->gentity && client->gentity->r.svFlags & SVF_BOT ) {
607 return;
608 }
609
610 MSG_Init (&msg, msg_buf, sizeof(msg_buf));
611 msg.allowoverflow = qtrue;
612
613 // NOTE, MRE: all server->client messages now acknowledge
614 // let the client know which reliable clientCommands we have received
615 MSG_WriteLong( &msg, client->lastClientCommand );
616
617 // (re)send any reliable server commands
618 SV_UpdateServerCommandsToClient( client, &msg );
619
620 // send over all the relevant entityState_t
621 // and the playerState_t
622 SV_WriteSnapshotToClient( client, &msg );
623
624 #ifdef USE_VOIP
625 SV_WriteVoipToClient( client, &msg );
626 #endif
627
628 // check for overflow
629 if ( msg.overflowed ) {
630 Com_Printf ("WARNING: msg overflowed for %s\n", client->name);
631 MSG_Clear (&msg);
632 }
633
634 SV_SendMessageToClient( &msg, client );
635 }
636
637
638 /*
639 =======================
640 SV_SendClientMessages
641 =======================
642 */
643 void SV_SendClientMessages(void)
644 {
645 int i;
646 client_t *c;
647
648 // send a message to each connected client
649 for(i=0; i < sv_maxclients->integer; i++)
650 {
651 c = &svs.clients[i];
652
653 if(!c->state)
654 continue; // not connected
655
656 if(svs.time - c->lastSnapshotTime < c->snapshotMsec * com_timescale->value)
657 continue; // It's not time yet
658
659 if(*c->downloadName)
660 continue; // Client is downloading, don't send snapshots
661
662 if(c->netchan.unsentFragments || c->netchan_start_queue)
663 {
664 c->rateDelayed = qtrue;
665 continue; // Drop this snapshot if the packet queue is still full or delta compression will break
666 }
667
668 if(!(c->netchan.remoteAddress.type == NA_LOOPBACK ||
669 (sv_lanForceRate->integer && Sys_IsLANAddress(c->netchan.remoteAddress))))
670 {
671 // rate control for clients not on LAN
672 if(SV_RateMsec(c) > 0)
673 {
674 // Not enough time since last packet passed through the line
675 c->rateDelayed = qtrue;
676 continue;
677 }
678 }
679
680 // generate and send a new message
681 SV_SendClientSnapshot(c);
682 c->lastSnapshotTime = svs.time;
683 c->rateDelayed = qfalse;
684 }
685 }