File: sv_snapshot.c

package info (click to toggle)
openmohaa 0.81.1%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: trixie
  • size: 29,124 kB
  • sloc: ansic: 270,865; cpp: 250,173; sh: 234; asm: 141; xml: 64; makefile: 7
file content (1337 lines) | stat: -rw-r--r-- 34,659 bytes parent folder | download
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.

This file is part of Quake III Arena source code.

Quake III Arena source code 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 2 of the License,
or (at your option) any later version.

Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
===========================================================================
*/

#include "server.h"
#include "../qcommon/bg_compat.h"

#define	CULL_IN		0		// completely unclipped
#define	CULL_CLIP	1		// clipped by one or more planes
#define	CULL_OUT	2		// completely outside the clipping planes

/*
=============================================================================

Delta encode a client frame onto the network channel

A normal server packet will look like:

4	sequence number (high bit set if an oversize fragment)
<optional reliable commands>
1	svc_snapshot
4	last client reliable command
4	serverTime
1	lastframe for delta compression
1	snapFlags
1	areaBytes
<areabytes>
<playerstate>
<packetentities>

=============================================================================
*/

/*
=============
SV_EmitPacketEntities

Writes a delta update of an entityState_t list to the message.
=============
*/
static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) {
	entityState_t	*oldent, *newent;
	int		oldindex, newindex;
	int		oldnum, newnum;
	int		from_num_entities;

	// generate the delta update
	if ( !from ) {
		from_num_entities = 0;
	} else {
		from_num_entities = from->num_entities;
	}

	newent = NULL;
	oldent = NULL;
	newindex = 0;
	oldindex = 0;
	while ( newindex < to->num_entities || oldindex < from_num_entities ) {
		if ( newindex >= to->num_entities ) {
			newnum = 9999;
		} else {
			newent = &svs.snapshotEntities[(to->first_entity+newindex) % svs.numSnapshotEntities];
			newnum = newent->number;
		}

		if ( oldindex >= from_num_entities ) {
			oldnum = 9999;
		} else {
			oldent = &svs.snapshotEntities[(from->first_entity+oldindex) % svs.numSnapshotEntities];
			oldnum = oldent->number;
		}

		if ( newnum == oldnum ) {
			// delta update from old position
			// because the force parm is qfalse, this will not result
			// in any bytes being emitted if the entity has not changed at all
			MSG_WriteDeltaEntity (msg, oldent, newent, qfalse, sv.frameTime);
			oldindex++;
			newindex++;
			continue;
		}

		if ( newnum < oldnum ) {
			// this is a new entity, send it from the baseline
			MSG_WriteDeltaEntity (msg, &sv.svEntities[newnum].baseline, newent, qtrue, sv.frameTime);
			newindex++;
			continue;
		}

		if ( newnum > oldnum ) {
			// the old entity isn't present in the new message
			MSG_WriteDeltaEntity (msg, oldent, NULL, qtrue, sv.frameTime);
			oldindex++;
			continue;
		}
	}

	MSG_WriteEntityNum(msg, (MAX_GENTITIES - 1));	// end of packetentities
}



/*
==================
SV_WriteSnapshotToClient
==================
*/
static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) {
	clientSnapshot_t	*frame, *oldframe;
	int					lastframe;
	int					i;
	int					snapFlags;

	// this is the snapshot we are creating
	frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];

	// try to use a previous frame as the source for delta compressing the snapshot
	if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) {
		// client is asking for a retransmit
		oldframe = NULL;
		lastframe = 0;
	} else if ( client->netchan.outgoingSequence - client->deltaMessage 
		>= (PACKET_BACKUP - 3) ) {
		// client hasn't gotten a good message through in a long time
		Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name);
		oldframe = NULL;
		lastframe = 0;
	} else {
		// we have a valid snapshot to delta from
		oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ];
		lastframe = client->netchan.outgoingSequence - client->deltaMessage;

		// the snapshot's entities may still have rolled off the buffer, though
		if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) {
			Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name);
			oldframe = NULL;
			lastframe = 0;
		}
	}

	MSG_WriteSVC(msg, svc_snapshot);

	// NOTE, MRE: now sent at the start of every message from server to client
	// let the client know which reliable clientCommands we have received
	//MSG_WriteLong( msg, client->lastClientCommand );

	// send over the current server time so the client can drift
	// its view of time to try to match
	if( client->oldServerTime ) {
		// The server has not yet got an acknowledgement of the
		// new gamestate from this client, so continue to send it
		// a time as if the server has not restarted. Note from
		// the client's perspective this time is strictly speaking
		// incorrect, but since it'll be busy loading a map at
		// the time it doesn't really matter.
		MSG_WriteLong (msg, svs.time + client->oldServerTime);
	} else {
		// WOMBAT: note that MOHAA always goes into this else.
		// therefore we are deviating from the MOHAA protocol but i don't think this is a problem
		MSG_WriteLong (msg, svs.time);
	}

	if ( sv.timeResidual > 254 )
		MSG_WriteByte( msg, 255 );
	else MSG_WriteByte( msg, sv.timeResidual );

	// what we are delta'ing from
	MSG_WriteByte (msg, lastframe);

	snapFlags = svs.snapFlagServerBit;
	if ( client->rateDelayed ) {
		snapFlags |= SNAPFLAG_RATE_DELAYED;
	}
	if ( client->state != CS_ACTIVE ) {
		snapFlags |= SNAPFLAG_NOT_ACTIVE;
	}

	MSG_WriteByte (msg, snapFlags);

	// send over the areabits
	if ( frame->areabytes > 255 ) {
		Com_DPrintf( "WARNING: area bytes exceeds 255!  Bad!  Bad!" ); // 2015 actually had humour
		MSG_WriteByte( msg, 0 );
	} else {
		MSG_WriteByte (msg, frame->areabytes);
		MSG_WriteData (msg, frame->areabits, frame->areabytes);
	}

	// delta encode the playerstate
	if ( oldframe ) {
		MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps, sv.frameTime);
	} else {
		MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps, sv.frameTime);
	}

	// delta encode the entities
	SV_EmitPacketEntities (oldframe, frame, msg);

	MSG_WriteSounds( msg, client->server_sounds, client->number_of_server_sounds );

	if ( client->stringToPrint[0] ) {
		if ( client->locprint ) {
			MSG_WriteSVC( msg, svc_locprint );
			MSG_WriteShort( msg, client->XOffset );
			MSG_WriteShort( msg, client->YOffset );
			MSG_WriteScrambledString( msg, client->stringToPrint );
			client->locprint = qfalse;
		}
		else {
			MSG_WriteSVC( msg, svc_centerprint );
			MSG_WriteScrambledString( msg, client->stringToPrint);
		}
	}

	// padding for rate debugging
	if ( sv_padPackets->integer ) {
		for ( i = 0 ; i < sv_padPackets->integer ; i++ ) {
			MSG_WriteSVC(msg, svc_nop);
		}
	}
}


/*
==================
SV_UpdateServerCommandsToClient

(re)send all server commands the client hasn't acknowledged yet
==================
*/
void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) {
	int		i;

	// write any unacknowledged serverCommands
	for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) {
		MSG_WriteSVC( msg, svc_serverCommand );
		MSG_WriteLong( msg, i );
		MSG_WriteScrambledString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] );
	}
	client->reliableSent = client->reliableSequence;
}

/*
=============================================================================

Build a client snapshot structure

=============================================================================
*/

#define	MAX_SNAPSHOT_ENTITIES	1024
typedef struct {
	int		numSnapshotEntities;
	int		snapshotEntities[MAX_SNAPSHOT_ENTITIES];	
} snapshotEntityNumbers_t;

/*
=======================
SV_QsortEntityNumbers
=======================
*/
static int QDECL SV_QsortEntityNumbers( const void *a, const void *b ) {
	int	*ea, *eb;

	ea = (int *)a;
	eb = (int *)b;

	if ( *ea == *eb ) {
		Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" );
	}

	if ( *ea < *eb ) {
		return -1;
	}

	return 1;
}

/*
===============
SV_AddNonPVSSound
===============
*/
static void SV_AddNonPVSSound(client_t* client, gentity_t* ent) {
	int i;

    for (i = 0; i < ent->r.num_nonpvs_sounds; i++) {
		nonpvs_sound_t *npvs = &ent->r.nonpvs_sounds[i];

        SV_ClientSound(
            client,
            &ent->s.origin,
            ENTITYNUM_NONE,
            1,
            npvs->index,
            npvs->volume,
            npvs->minDist,
            npvs->pitch,
            npvs->maxDist,
            qfalse
        );
	}
}

/*
====================
SV_ClipMoveToBSPEntities

====================
*/
static qboolean SV_ClipMoveToBSPEntities(const vec3_t start, const vec3_t end, int mask) {
	int				i, num;
	int				touchlist[MAX_GENTITIES];
	gentity_t		*touch;
	trace_t			trace;
	clipHandle_t	clipHandle;
	vec3_t			boxmins, boxmaxs;

	for (i = 0; i < 3; i++) {
		if (end[i] > start[i]) {
			boxmins[i] = start[i] - 1;
			boxmaxs[i] = end[i] + 1;
		}
		else {
			boxmins[i] = end[i] - 1;
			boxmaxs[i] = start[i] + 1;
		}
	}

	num = SV_AreaEntities(boxmins, boxmaxs, touchlist, MAX_GENTITIES);

	for (i = 0; i < num; i++) {
		touch = SV_GentityNum(touchlist[i]);

		// skip non-solids and triggers
		if (touch->solid != SOLID_BSP) {
			continue;
		}

		// if it doesn't have any brushes of a type we
		// are looking for, ignore it
		if (!(mask & touch->r.contents)) {
			continue;
		}

		// might intersect, so do an exact clip
		clipHandle = SV_ClipHandleForEntity(touch);

		CM_TransformedBoxTrace(&trace, start, end,
			vec3_origin, vec3_origin, clipHandle, mask,
			touch->s.origin, touch->r.currentAngles, qfalse);

		if (trace.allsolid || trace.startsolid || trace.fraction != 1) {
			return qfalse;
		}
	}

	return qtrue;
}

/*
===============
SV_WorldTrace
===============
*/
qboolean SV_WorldTrace(const vec3_t start, const vec3_t end, int mask)
{
	trace_t trace = { 0 };

    CM_BoxTrace(&trace, start, end, vec3_origin, vec3_origin, 0, mask, qfalse);
	if (trace.fraction != 1) {
		return qfalse;
	}

	// Also test against brush models
	return SV_ClipMoveToBSPEntities(start, end, mask);
}

/*
===============
SV_ClientIsVisibleTrace
===============
*/
qboolean SV_ClientIsVisibleTrace(const vec3_t fromOrigin, const vec3_t toOrigin, float height, float dot) {
	vec3_t dir;
	vec3_t end;

	VectorSubtract(toOrigin, fromOrigin, dir);
    VectorNormalize(dir);
    //VectorMA(toOrigin, -height, dir, end);
	VectorCopy(toOrigin, end);

	if (SV_WorldTrace(fromOrigin, end, (CONTENTS_SLIME | CONTENTS_LAVA | CONTENTS_SOLID))) {
		return qtrue;
	}

	if (dot < 0) {
		return qfalse;
    }

	end[2] -= height;
	return SV_WorldTrace(fromOrigin, end, (CONTENTS_SLIME | CONTENTS_LAVA | CONTENTS_SOLID));
}

/*
===============
SV_ClientIsVisible
===============
*/
qboolean SV_ClientIsVisible(int toNum, int fromNum, int distCheck, const vec3_t forward, const vec3_t right) {
	client_t* fromClient;
	playerState_t *fromPs, *toPs;
	vec3_t dir;
	vec3_t fromOrigin, toOrigin;
	vec3_t toRight;
	float dot;
	float speed;
	
	if (!g_netoptimize->integer || !sv_netoptimize->integer) {
		return qtrue;
	}

	if (toNum >= svs.iNumClients) {
		return qtrue;
	}

	fromClient = &svs.clients[fromNum];
	if (sv_netoptimize->integer == NETO_CULLED && distCheck == CULL_IN) {
		fromClient->lastVisCheckTime[toNum] = svs.time + sv_netoptimize_vistime->integer;
		return qtrue;
	}

	if (fromClient->lastVisCheckTime[toNum] > svs.time) {
		return qtrue;
	}

    fromPs = SV_GameClientNum(fromNum);
    toPs = SV_GameClientNum(toNum);

	if (fromPs->fLeanAngle == 0) {
		VectorCopy(fromPs->vEyePos, fromOrigin);
	} else if (fromPs->fLeanAngle >= 0) {
		VectorMA(fromPs->vEyePos, 30, right, fromOrigin);
	} else {
		VectorMA(fromPs->vEyePos, -30, right, fromOrigin);
    }
    VectorCopy(fromPs->vEyePos, fromOrigin);

	if (toPs->fLeanAngle == 0) {
		VectorCopy(toPs->vEyePos, toOrigin);
	} else if (toPs->fLeanAngle >= 0) {
		AngleVectors(toPs->viewangles, toRight, NULL, NULL);
		VectorMA(toPs->vEyePos, 30, toRight, toOrigin);
	} else {
		AngleVectors(toPs->viewangles, toRight, NULL, NULL);
		VectorMA(toPs->vEyePos, -30, toRight, toOrigin);
    }
    VectorCopy(toPs->vEyePos, toOrigin);

	VectorSubtract(toOrigin, fromOrigin, dir);
	VectorNormalize(dir);

	dot = DotProduct(forward, dir);
	if (SV_ClientIsVisibleTrace(fromOrigin, toOrigin, toPs->viewheight / 2, dot)) {
		fromClient->lastVisCheckTime[toNum] = svs.time + sv_netoptimize_vistime->integer;
		return qtrue;
	}

	speed = VectorLength(toPs->velocity);
	if (speed <= 0) {
		return qfalse;
	}

	//
	// check with velocity prediction
	//
	VectorMA(fromOrigin, sv.frameTime * 3, fromPs->velocity, fromOrigin);
	VectorMA(toOrigin, sv.frameTime * 3, toPs->velocity, toOrigin);

	if (SV_ClientIsVisibleTrace(fromOrigin, toOrigin, toPs->viewheight / 2, dot)) {
        fromClient->lastVisCheckTime[toNum] = svs.time + sv_netoptimize_vistime->integer;
        return qtrue;
	}

	// not visible
	return qfalse;
}

/*
===============
SV_AddEntToSnapshot
===============
*/
static void SV_AddEntToSnapshot( svEntity_t *svEnt, gentity_t *gEnt, snapshotEntityNumbers_t *eNums, svEntity_t* portalEnt, qboolean portalsky) {
	// if we have already added this entity to this snapshot, don't add again
	if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
		gEnt->s.renderfx &= ~(RF_SHADOW_PLANE | RF_WRAP_FRAMES);
		gEnt->s.renderfx |= RF_WRAP_FRAMES;
		return;
	}
	svEnt->snapshotCounter = sv.snapshotCounter;

	// if we are full, silently discard entities
	if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) {
		return;
	}

	gEnt->s.renderfx &= ~(RF_SHADOW_PLANE | RF_WRAP_FRAMES | RF_SKYENTITY);

	if ( portalEnt ) {
		gEnt->s.renderfx |= RF_SHADOW_PLANE;
	} else if ( portalsky ) {
		gEnt->s.renderfx |= RF_SKYENTITY;
	}

	gEnt->r.lastNetTime = svs.time - svs.startTime;
	eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number;
	eNums->numSnapshotEntities++;
}

/*
===============
EntityDistCheck
===============
*/
int EntityDistCheck(const vec3_t origin, const vec3_t forward, const gentity_t* ent, float farplane, float fov) {
	vec3_t dir;
	float farplaneMax;
	float length;
	float fovCheck;
	float dot;

	VectorSubtract(origin, ent->r.centroid, dir);
	length = VectorNormalize(dir) - ent->r.radius;

	farplaneMax = farplane + 128;
	if (length >= farplaneMax) {
		return CULL_OUT;
	}

	fovCheck = fov / 80 * length;

	if (ent->s.number < svs.iNumClients && VectorLength(ent->s.pos.trDelta) < 5) {
		fovCheck *= 0.25f;
	}

	if (fovCheck <= 640) {
		return CULL_IN;
	}

	dot = DotProduct(forward, dir) + 0.5f;
	if (dot < 0) {
		dot = 0;
	}

	if (fovCheck * (dot * 2.f + 1.f) >= farplaneMax) {
		// outside the farplane
		return CULL_OUT;
	}

	return CULL_CLIP;
}

/*
===============
SV_AddEntitiesVisibleFromPoint
===============
*/
static void SV_AddEntitiesVisibleFromPoint(const vec3_t origin, clientSnapshot_t* frame, snapshotEntityNumbers_t* eNums, svEntity_t* portalEnt, qboolean portalsky, client_t* client, const vec3_t angles ) {
	int		e, i;
	gentity_t *ent;
	gentity_t *parentEnt;
	playerState_t *ps;
	svEntity_t	*svEnt, *svCheckEnt;
	int		l;
	int		clientarea, clientcluster;
	int		leafnum;
	int		c_fullsend;
	byte	*clientpvs;
	byte	*bitvector;
	gentity_t* skyorigin = NULL;
	int		num;
	int		check = 0;
	vec3_t	forward, right;

	// during an error shutdown message we may need to transmit
	// the shutdown message after the server has shutdown, so
	// specfically check for it
	if ( !sv.state ) {
		return;
	}

	ps = SV_GameClientNum(client - svs.clients);

	num = 1;
	if (sv_drawentities->integer) {
		num = sv.num_entities;
	}

	leafnum = CM_PointLeafnum (origin);
	clientarea = CM_LeafArea (leafnum);
	clientcluster = CM_LeafCluster (leafnum);

	// calculate the visible areas
	frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea );

	clientpvs = CM_ClusterPVS (clientcluster);

	AngleVectors(angles, forward, right, NULL);

	c_fullsend = 0;

	for ( e = 0 ; e < sv.num_entities ; e++ ) {
		ent = SV_GentityNum(e);

		// never send unused entities
		if (!ent->inuse) {
			continue;
		}

		// mark the entity as sent
		ent->r.svFlags |= SVF_SENT;

		// never send entities that aren't linked in
		if ( !ent->r.linked ) {
			continue;
		}
		// entities can be flagged to explicitly not be sent to the client
		if ( ent->r.svFlags & SVF_NOCLIENT ) {
			continue;
		}
		// entities can be flagged to be sent to only one client
		if ( ent->r.svFlags & SVF_SINGLECLIENT ) {
			if ( ent->r.singleClient != frame->ps.clientNum ) {
				continue;
			}
		}
		// entities can be flagged to be sent to everyone but one client
		if ( ent->r.svFlags & SVF_NOTSINGLECLIENT ) {
			if ( ent->r.singleClient == frame->ps.clientNum ) {
				continue;
			}
		}
		// entities can be flagged to be sent to a given mask of clients
		// Removed in OPM
		//  This doesn't make sense it it only supports half of the client
		/*
		if ( ent->r.svFlags & SVF_CLIENTMASK ) {
			if (frame->ps.clientNum >= 32)
				Com_Error( ERR_DROP, "SVF_CLIENTMASK: clientNum > 32\n" );
			if (~ent->r.singleClient & (1 << frame->ps.clientNum))
				continue;
		}
		*/

		parentEnt = NULL;
		if (ent->s.parent != ENTITYNUM_NONE) {
			parentEnt = SV_GentityNum(ent->s.parent);
			// parents that will not send to clients will be skipped
			if (parentEnt && parentEnt->r.svFlags & SVF_NOCLIENT) {
				continue;
			}
		}

		svEnt = SV_SvEntityForGentity( ent );

		// don't double add an entity through portals
		if ( svEnt->snapshotCounter == sv.snapshotCounter ) {
			continue;
		}

		if (ent->s.renderfx & RF_SKYORIGIN) {
			if (sv.skyportal && !portalsky && !portalEnt) {
				if (skyorigin) {
					Com_Error(ERR_DROP, "SV_AddEntitiesVisibleFromPoint: duplicate sky origin");
				}
				skyorigin = ent;
				SV_AddEntToSnapshot(svEnt, ent, eNums, NULL, qfalse);
			}
			continue;
		}

		// broadcast entities are always sent
		// or broadcast entities that are sent once
		if ( (ent->r.svFlags & SVF_BROADCAST) || (ent->r.svFlags & SVF_SENDONCE)  ) {
			SV_AddEntToSnapshot( svEnt, ent, eNums, portalEnt, portalsky);
			continue;
		}

		if (parentEnt) {
			svEntity_t* parentSvEnt = SV_SvEntityForGentity(parentEnt);
			if (parentSvEnt->snapshotCounter == sv.snapshotCounter) {
				SV_AddEntToSnapshot(svEnt, ent, eNums, portalEnt, portalsky);
				continue;
			} else if (g_gametype->integer != GT_SINGLE_PLAYER && ent->s.parent < svs.iNumClients) {
				SV_AddNonPVSSound(client, ent);
				continue;
			}

			svCheckEnt = parentSvEnt;
		} else {
			svCheckEnt = svEnt;
		}

		if (!(ent->r.svFlags & SVF_SENDPVS) && !ent->s.modelindex && !ent->s.loopSound) {
			// don't send entities that have nothing to draw
			continue;
		}

		if ((ent->s.loopSound && ent->s.loopSoundMinDist == LEVEL_WIDE_MIN_DIST) || ent->s.renderfx & RF_VIEWMODEL) {
            // loopsound entities should be sent regardless
			SV_AddEntToSnapshot(svEnt, ent, eNums, portalEnt, portalsky);
            continue;
		}

		// ignore if not touching a PV leaf
		// check area
		if ( !CM_AreasConnected( clientarea, svCheckEnt->areanum ) ) {
			// doors can legally straddle two areas, so
			// we may need to check another one
			if ( !CM_AreasConnected( clientarea, svCheckEnt->areanum2 ) ) {
				continue;		// blocked by a door
			}
		}

		if (g_gametype->integer != GT_SINGLE_PLAYER && !(ent->r.svFlags & SVF_NOFARPLANE)) {
			float farplane = sv.farplane;

			if (farplane < 1) farplane = 12000;
			if (farplane > 12000) farplane = 12000;

			check = EntityDistCheck(origin, forward, parentEnt ? parentEnt : ent, farplane, ps->fov);
			if (check == CULL_OUT) {
				continue;
			}
		}

		// check individual leafs
		if( !svEnt->numClusters ) {
			continue;
		}

		bitvector = clientpvs;

		l = 0;
		for ( i=0 ; i < svCheckEnt->numClusters ; i++ ) {
			l = svCheckEnt->clusternums[i];
			if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
				break;
			}
		}

		// if we haven't found it to be visible,
		// check overflow clusters that coudln't be stored
		if ( i == svCheckEnt->numClusters ) {
			if ( svCheckEnt->lastCluster ) {
				for ( ; l <= svCheckEnt->lastCluster ; l++ ) {
					if ( bitvector[l >> 3] & (1 << (l&7) ) ) {
						break;
					}
				}
				if ( l == svCheckEnt->lastCluster ) {
					continue;	// not visible
				}
			} else {
				continue;
			}
		}

		if (svEnt->snapshotCounter == sv.snapshotCounter) {
			ent->s.renderfx &= ~(RF_WRAP_FRAMES | RF_SHADOW_PLANE);
			ent->s.renderfx |= RF_WRAP_FRAMES;
			continue;
		}

		if (g_gametype->integer != GT_SINGLE_PLAYER && ent->s.number < svs.iNumClients) {
			if (!SV_ClientIsVisible(ent->s.number, client - svs.clients, check, forward, right)) {
				SV_AddNonPVSSound(client, ent);
				continue;
			}
		}

		// add it
		SV_AddEntToSnapshot( svEnt, ent, eNums, portalEnt, portalsky);

		// if its a portal entity, add everything visible from its camera position
		if ( ent->r.svFlags & SVF_PORTAL && svEnt != portalEnt ) {
			SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, svEnt, qfalse, client, angles  );
		}
	}

	if (!portalsky && skyorigin && !portalEnt) {
		SV_AddEntitiesVisibleFromPoint(skyorigin->s.origin, frame, eNums, NULL, qtrue, client, angles);
	}
}

/*
=============
SV_ClearNonPVSClient

Clears the client's radar.
=============
*/
void SV_ClearNonPVSClient(client_t* client) {
	client->radarInfo = client - svs.clients;
}

/*
=============
SV_InitRadar

Initializes radar for all clients.
=============
*/
void SV_InitRadar() {
	int i;

	for (i = 0; i < svs.iNumClients; i++) {
		SV_ClearNonPVSClient(&svs.clients[i]);
	}
}

/*
=============
SV_PackNonPVSClient

Pack radar information into a 32-bit integer for a client.
=============
*/
void SV_PackNonPVSClient(radarUnpacked_t* unpacked, int* packed) {
	float inv;
	float x, y;
	float length;
	int packedX, packedY;
	int valid;

	if (com_radar_range && com_radar_range->value) {
		inv = 1.f / com_radar_range->value;
	} else {
		inv = 0;
	}

	x = inv * unpacked->x;
	y = inv * unpacked->y;

	length = sqrt(x * x + y * y);
	if (length > 0) {
		valid = 1;
		x *= 1.f / length;
		y *= 1.f / length;
	} else {
		valid = 0;
	}

	packedX = (int)((x * 63.f) + 63.5f);
	packedY = (int)((y * 63.f) + 63.5f);
	if (packedX < 0) {
		packedX = 0;
	} else if (packedX > 126) {
		packedX = 126;
	}

	if (packedY < 0) {
		packedY = 0;
	} else if (packedY > 126) {
		packedY = 126;
	}

	*packed = (packedY << 13) | unpacked->clientNum | (packedX << 6) | (((valid << 5) | (int)(unpacked->yaw
		* 0.088f
		+ 32.5f) & 0x1F) << 20);
}

/*
=============
SV_SetNonPVSClient

Pack an invisible client (other) into the client's radar information.
=============
*/
void SV_SetNonPVSClient(client_t* client, client_t* other) {
	radarUnpacked_t radar;

	radar.clientNum = other - svs.clients;
	radar.x = other->gentity->s.origin[0] - client->gentity->s.origin[0];
	radar.y = other->gentity->s.origin[1] - client->gentity->s.origin[1];
	radar.yaw = other->gentity->s.angles[1];

	SV_PackNonPVSClient(&radar, &client->radarInfo);
	client->lastRadarTime[radar.clientNum] = svs.time;
}

/*
=============
SV_InTeamGame

Returns true if the client is in game and joined a team.
=============
*/
qboolean SV_InTeamGame(client_t* client) {
	return (client->state != CS_FREE && client->gentity && client->gentity->s.solid && client->gentity->s.eFlags & EF_ANY_TEAM);
}

/*
=============
SV_SameTeam

Returns true if both clients are on the same team.
=============
*/
qboolean SV_SameTeam(client_t* client1, client_t* client2) {
	return (client1->gentity->s.eFlags & EF_ANY_TEAM) == (client2->gentity->s.eFlags & EF_ANY_TEAM);
}

/*
=============
SV_IsTeamGame

Returns true if it's a team game.
=============
*/
qboolean SV_IsTeamGame() {
	return g_gametype->integer >= GT_TEAM;
}

/*
=============
SV_UpdateRadar

Updates the radar information for the specified client.
=============
*/
void SV_UpdateRadar(client_t* client) {
	client_t* other;
	client_t* mate;
	float deltaX, deltaY;
	float dist;
	int deltaTime;
	int bestTime;
	int i;

	mate = NULL;

	if (!SV_IsTeamGame()) {
		SV_ClearNonPVSClient(client);
		return;
	}

	if (!SV_InTeamGame(client)) {
		SV_ClearNonPVSClient(client);
		return;
	}

	bestTime = svs.time;

	for (i = 0; i < svs.iNumClients; i++) {
		other = &svs.clients[i];

		if (other == client) {
			continue;
		}

		if (!SV_InTeamGame(other)) {
			continue;
		}

		if (!SV_SameTeam(client, other)) {
			continue;
		}

		deltaX = other->gentity->s.origin[0] - client->gentity->s.origin[0];
		deltaY = other->gentity->s.origin[1] - client->gentity->s.origin[1];
		deltaTime = svs.time - client->lastRadarTime[i];
		dist = sqrt(deltaX * deltaX + deltaY * deltaY);

		if (dist > com_radar_range->value) {
			if (deltaTime < 1000) {
				continue;
			}

			deltaTime /= 2;
		}

		if (deltaTime > svs.time - bestTime) {
			bestTime = client->lastRadarTime[i];
			mate = other;
		}
	}

	if (!mate) {
		SV_ClearNonPVSClient(client);
		return;
	}

	SV_SetNonPVSClient(client, mate);
}

/*
=============
SV_BuildClientSnapshot

Decides which entities are going to be visible to the client, and
copies off the playerstate and areabits.

This properly handles multiple recursive portals, but the render
currently doesn't.

For viewing through other player's eyes, clent can be something other than client->gentity
=============
*/
static void SV_BuildClientSnapshot( client_t *client ) {
	vec3_t						org;
	vec3_t						ang;
	clientSnapshot_t			*frame;
	snapshotEntityNumbers_t		entityNumbers;
	int							i;
	gentity_t					*ent;
	entityState_t				*state;
	svEntity_t					*svEnt;
	gentity_t					*clent;
	int							clientNum;
	playerState_t				*ps;

	// bump the counter used to prevent double adding
	sv.snapshotCounter++;

	// this is the frame we are creating
	frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ];

	// clear everything in this snapshot
	entityNumbers.numSnapshotEntities = 0;
	Com_Memset( frame->areabits, 0, sizeof( frame->areabits ) );

  // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=62
	frame->num_entities = 0;
	
	clent = client->gentity;
	if ( !clent || client->state == CS_ZOMBIE ) {
		return;
	}

	// grab the current playerState_t
	ps = SV_GameClientNum( client - svs.clients );
	frame->ps = *ps;
    frame->ps.net_pm_flags = CPT_DenormalizePlayerStateFlags(ps->pm_flags);
    frame->ps.iNetViewModelAnim = CPT_DenormalizeViewModelAnim(ps->iViewModelAnim);

	//SV_SvEntityForGentity
	// never send client's own entity, because it can
	// be regenerated from the playerstate
	clientNum = frame->ps.clientNum;
	if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) {
		Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" );
	}
	svEnt = &sv.svEntities[ clientNum ];
	
	// su44: that's not done in MoHAA
	//svEnt->snapshotCounter = sv.snapshotCounter;

	// find the client's viewpoint
	if (ps->pm_flags & PMF_CAMERA_VIEW)
	{
		VectorCopy(ps->camera_origin, org);
		VectorCopy(ps->camera_angles, ang);
	}
	else
	{
		VectorCopy(ps->vEyePos, org);
		VectorCopy(ps->viewangles, ang);
	}

	SV_AddEntToSnapshot(svEnt, SV_GentityNum(client - svs.clients), &entityNumbers, NULL, qfalse);

	// add all the entities directly visible to the eye, which
	// may include portal entities that merge other viewpoints
	SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, NULL, qfalse, client, ang );

	// if there were portals visible, there may be out of order entities
	// in the list which will need to be resorted for the delta compression
	// to work correctly.  This also catches the error condition
	// of an entity being included twice.
	qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities, 
		sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers );

	// now that all viewpoint's areabits have been OR'd together, invert
	// all of them to make it a mask vector, which is what the renderer wants
	for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) {
		((int *)frame->areabits)[i] = ((int *)frame->areabits)[i] ^ -1;
	}

	
	// copy the entity states out
	frame->num_entities = 0;
	frame->first_entity = svs.nextSnapshotEntities;
	for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) {
		ent = SV_GentityNum(entityNumbers.snapshotEntities[i]);
		if (ent->client && ent->s.number < svs.iNumClients) {
			assert(ent->s.number < MAX_CLIENTS);
			client->lastRadarTime[ent->s.number] = svs.time;
		}

		state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities];
		*state = ent->s;
		svs.nextSnapshotEntities++;
		// this should never hit, map should always be restarted first in SV_Frame
		if ( svs.nextSnapshotEntities >= 0x7FFFFFFE ) {
			Com_Error(ERR_FATAL, "svs.nextSnapshotEntities wrapped");
		}
		frame->num_entities++;
	}

	SV_UpdateRadar(client);
    frame->ps.radarInfo = client->radarInfo;
}

#ifdef USE_VOIP
/*
==================
SV_WriteVoipToClient

Check to see if there is any VoIP queued for a client, and send if there is.
==================
*/
static void SV_WriteVoipToClient(client_t *cl, msg_t *msg)
{
	int totalbytes = 0;
	int i;
	voipServerPacket_t *packet;

	if(cl->queuedVoipPackets)
	{
		// Write as many VoIP packets as we reasonably can...
		for(i = 0; i < cl->queuedVoipPackets; i++)
		{
			packet = cl->voipPacket[(i + cl->queuedVoipIndex) % ARRAY_LEN(cl->voipPacket)];

			if(!*cl->downloadName)
			{
        			totalbytes += packet->len;
	        		if (totalbytes > (msg->maxsize - msg->cursize) / 2)
		        		break;

        			MSG_WriteByte(msg, svc_voipOpus);
        			MSG_WriteShort(msg, packet->sender);
	        		MSG_WriteByte(msg, (byte) packet->generation);
		        	MSG_WriteLong(msg, packet->sequence);
		        	MSG_WriteByte(msg, packet->frames);
        			MSG_WriteShort(msg, packet->len);
        			MSG_WriteBits(msg, packet->flags, VOIP_FLAGCNT);
	        		MSG_WriteData(msg, packet->data, packet->len);
                        }

			Z_Free(packet);
		}

		cl->queuedVoipPackets -= i;
		cl->queuedVoipIndex += i;
		cl->queuedVoipIndex %= ARRAY_LEN(cl->voipPacket);
	}
}
#endif

/*
=======================
SV_SendMessageToClient

Called by SV_SendClientSnapshot and SV_SendClientGameState
=======================
*/
void SV_SendMessageToClient(msg_t *msg, client_t *client)
{
	// record information about the message
	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSize = msg->cursize;
	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSent = svs.time;
	client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1;

	// send the datagram
	SV_Netchan_Transmit(client, msg);
}


/*
=======================
SV_SendClientSnapshot

Also called by SV_FinalMessage

=======================
*/
void SV_SendClientSnapshot( client_t *client ) {
	byte		msg_buf[MAX_MSGLEN];
	msg_t		msg;

	// build the snapshot
	SV_BuildClientSnapshot( client );

	// bots need to have their snapshots build, but
	// the query them directly without needing to be sent
	if ( client->gentity && client->gentity->r.svFlags & SVF_MONSTER ) {
		return;
	}

    MSG_Init(&msg, msg_buf, sizeof(msg_buf));
    msg.allowoverflow = qtrue;

    // NOTE, MRE: all server->client messages now acknowledge
    // let the client know which reliable clientCommands we have received
    MSG_WriteLong(&msg, client->lastClientCommand);

	if (g_gametype->integer <= GT_SINGLE_PLAYER || client->serverIdAcknowledge == sv.serverId || client->serverIdAcknowledge == sv.restartedServerId) {
		// (re)send any reliable server commands
		SV_UpdateServerCommandsToClient( client, &msg );

		// send over all the relevant entityState_t
		// and the playerState_t
		SV_WriteSnapshotToClient( client, &msg );

		// clear the sounds on the client, preventing them to be sent each at packet
		SV_ClearSounds( client );

		// clear center print, preventing it to be sent at each packet
		client->stringToPrint[ 0 ] = 0;

		// su44: write any pending MoHAA cg messages
		SV_WriteCGMToClient( client, &msg );

#ifdef USE_VOIP
		SV_WriteVoipToClient(client, &msg);
#endif
	} else {
		// Fixed in 2.0
		//  Don't send snapshots until the player has acknowledged the server id (which happens when the client enters the world).
		//  This also prevent sending CG messages while the client connects, as the cgame module is loaded when parsing the gamestate
		MSG_WriteSVC(&msg, svc_nop);
	}

	// check for overflow
	if ( msg.overflowed ) {
		Com_Printf ("WARNING: msg overflowed for %s\n", client->name);
		MSG_Clear (&msg);
	}

	SV_SendMessageToClient( &msg, client );
}

/*
=======================
SV_SendClientMessages
=======================
*/
void SV_SendClientMessages(void)
{
	int				i;
	int				rate;
	client_t		*c;

	// send a message to each connected client
	for(i=0; i < sv_maxclients->integer; i++)
	{
		c = &svs.clients[i];
		
		if(!c->state)
			continue;		// not connected

		if(svs.time - c->lastSnapshotTime < c->snapshotMsec * com_timescale->value)
			continue;		// It's not time yet

		if (!SV_IsValidSnapshotClient(c))
			continue; // not valid snapshot

		if(*c->downloadName)
			continue;		// Client is downloading, don't send snapshots

		if(c->netchan.unsentFragments || c->netchan_start_queue)
		{
			c->rateDelayed = qtrue;
			continue;		// Drop this snapshot if the packet queue is still full or delta compression will break
		}

		rate = SV_RateMsec(c);

		if(!(c->netchan.remoteAddress.type == NA_LOOPBACK ||
		     (sv_lanForceRate->integer && Sys_IsLANAddress(c->netchan.remoteAddress))))
		{
			// rate control for clients not on LAN 
			if(rate > 0)
			{
				// Not enough time since last packet passed through the line
				c->rateDelayed = qtrue;
				continue;
			}
		}

		// generate and send a new message
		SV_SendClientSnapshot(c);
		c->lastSnapshotTime = svs.time;
		c->rateDelayed = qfalse;
    }
}

qboolean SV_IsValidSnapshotClient(client_t* client) {
	if (client->deltaMessage <= 0) {
		return qtrue;
	}

	if (client->state != CS_ACTIVE) {
		return qtrue;
	}

	if (client->lastPacketTime >= svs.lastTime) {
		return qtrue;
	}

	if (client->netchan.outgoingSequence - client->deltaMessage < 29) {
		return qtrue;
	}

	return qfalse;
}