1 /*
2 Copyright (C) 1997-2001 Id Software, Inc.
3 
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8 
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 
13 See the GNU General Public License for more details.
14 
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 
19 */
20 
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 
25 #include "server.h"
26 
27 static size_t szr; // just for quieting unused result warnings
28 
29 /*
30 =============================================================================
31 
32 Encode a client frame onto the network channel
33 
34 =============================================================================
35 */
36 
37 
38 /*
39 =============
40 SV_EmitPacketEntities
41 
42 Writes a delta update of an entity_state_t list to the message.
43 =============
44 */
SV_EmitPacketEntities(client_frame_t * from,client_frame_t * to,sizebuf_t * msg)45 void SV_EmitPacketEntities (client_frame_t *from, client_frame_t *to, sizebuf_t *msg)
46 {
47 	entity_state_t	*oldent=NULL, *newent=NULL;
48 	int		oldindex, newindex;
49 	int		oldnum, newnum;
50 	int		from_num_entities;
51 	int		bits;
52 
53 #if 0
54 	if (numprojs)
55 		MSG_WriteByte (msg, svc_packetentities2);
56 	else
57 #endif
58 		MSG_WriteByte (msg, svc_packetentities);
59 
60 	if (!from)
61 		from_num_entities = 0;
62 	else
63 		from_num_entities = from->num_entities;
64 
65 	newindex = 0;
66 	oldindex = 0;
67 	while (newindex < to->num_entities || oldindex < from_num_entities)
68 	{
69 		if (newindex >= to->num_entities)
70 			newnum = 9999;
71 		else
72 		{
73 			newent = &svs.client_entities[(to->first_entity+newindex)%svs.num_client_entities];
74 			newnum = newent->number;
75 		}
76 
77 		if (oldindex >= from_num_entities)
78 			oldnum = 9999;
79 		else
80 		{
81 			oldent = &svs.client_entities[(from->first_entity+oldindex)%svs.num_client_entities];
82 			oldnum = oldent->number;
83 		}
84 
85 		if (newnum == oldnum)
86 		{	// delta update from old position
87 			// because the force parm is false, this will not result
88 			// in any bytes being emited if the entity has not changed at all
89 			// note that players are always 'newentities', this updates their oldorigin always
90 			// and prevents warping
91 			MSG_WriteDeltaEntity (oldent, newent, msg, false, newent->number <= maxclients->value);
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 (&sv.baselines[newnum], newent, msg, true, true);
100 			newindex++;
101 			continue;
102 		}
103 
104 		if (newnum > oldnum)
105 		{	// the old entity isn't present in the new message
106 			bits = U_REMOVE;
107 			if (oldnum >= 256)
108 				bits |= U_NUMBER16 | U_MOREBITS1;
109 
110 			MSG_WriteByte (msg,	bits&255 );
111 			if (bits & 0x0000ff00)
112 				MSG_WriteByte (msg,	(bits>>8)&255 );
113 
114 			if (bits & U_NUMBER16)
115 				MSG_WriteShort (msg, oldnum);
116 			else
117 				MSG_WriteByte (msg, oldnum);
118 
119 			oldindex++;
120 			continue;
121 		}
122 	}
123 
124 	MSG_WriteShort (msg, 0);	// end of packetentities
125 }
126 
127 
128 
129 /*
130 =============
131 SV_WritePlayerstateToClient
132 
133 =============
134 */
SV_WritePlayerstateToClient(client_frame_t * from,client_frame_t * to,sizebuf_t * msg)135 void SV_WritePlayerstateToClient (client_frame_t *from, client_frame_t *to, sizebuf_t *msg)
136 {
137 	int				i;
138 	int				pflags;
139 	player_state_t	*ps, *ops;
140 	player_state_t	dummy;
141 	int				statbits;
142 
143 	ps = &to->ps;
144 	if (!from)
145 	{
146 		memset (&dummy, 0, sizeof(dummy));
147 		ops = &dummy;
148 	}
149 	else
150 		ops = &from->ps;
151 
152 	//
153 	// determine what needs to be sent
154 	//
155 	pflags = 0;
156 
157 	if (ps->pmove.pm_type != ops->pmove.pm_type)
158 		pflags |= PS_M_TYPE;
159 
160 	if (ps->pmove.origin[0] != ops->pmove.origin[0]
161 		|| ps->pmove.origin[1] != ops->pmove.origin[1]
162 		|| ps->pmove.origin[2] != ops->pmove.origin[2] )
163 		pflags |= PS_M_ORIGIN;
164 
165 	if (ps->pmove.velocity[0] != ops->pmove.velocity[0]
166 		|| ps->pmove.velocity[1] != ops->pmove.velocity[1]
167 		|| ps->pmove.velocity[2] != ops->pmove.velocity[2] )
168 		pflags |= PS_M_VELOCITY;
169 
170 	if (ps->pmove.pm_time != ops->pmove.pm_time)
171 		pflags |= PS_M_TIME;
172 
173 	if (ps->pmove.pm_flags != ops->pmove.pm_flags)
174 		pflags |= PS_M_FLAGS;
175 
176 	if (ps->pmove.gravity != ops->pmove.gravity)
177 		pflags |= PS_M_GRAVITY;
178 
179 	if (ps->pmove.delta_angles[0] != ops->pmove.delta_angles[0]
180 		|| ps->pmove.delta_angles[1] != ops->pmove.delta_angles[1]
181 		|| ps->pmove.delta_angles[2] != ops->pmove.delta_angles[2] )
182 		pflags |= PS_M_DELTA_ANGLES;
183 
184 
185 	if (ps->viewoffset[0] != ops->viewoffset[0]
186 		|| ps->viewoffset[1] != ops->viewoffset[1]
187 		|| ps->viewoffset[2] != ops->viewoffset[2] )
188 		pflags |= PS_VIEWOFFSET;
189 
190 	if (ps->viewangles[0] != ops->viewangles[0]
191 		|| ps->viewangles[1] != ops->viewangles[1]
192 		|| ps->viewangles[2] != ops->viewangles[2] )
193 		pflags |= PS_VIEWANGLES;
194 
195 	if (ps->kick_angles[0] != ops->kick_angles[0]
196 		|| ps->kick_angles[1] != ops->kick_angles[1]
197 		|| ps->kick_angles[2] != ops->kick_angles[2] )
198 		pflags |= PS_KICKANGLES;
199 
200 	if (ps->blend[0] != ops->blend[0]
201 		|| ps->blend[1] != ops->blend[1]
202 		|| ps->blend[2] != ops->blend[2]
203 		|| ps->blend[3] != ops->blend[3] )
204 		pflags |= PS_BLEND;
205 
206 	if (ps->fov != ops->fov)
207 		pflags |= PS_FOV;
208 
209 	if (ps->rdflags != ops->rdflags)
210 		pflags |= PS_RDFLAGS;
211 
212 	if (ps->gunframe != ops->gunframe
213 		|| (int)(ops->gunoffset[0]*4) != (int)(ps->gunoffset[0]*4)
214 		|| (int)(ops->gunoffset[1]*4) != (int)(ps->gunoffset[1]*4)
215 		|| (int)(ops->gunoffset[2]*4) != (int)(ps->gunoffset[2]*4)
216 		|| (int)(ops->gunangles[0]*4) != (int)(ps->gunangles[0]*4)
217 		|| (int)(ops->gunangles[1]*4) != (int)(ps->gunangles[1]*4)
218 		|| (int)(ops->gunangles[2]*4) != (int)(ps->gunangles[2]*4) )
219 		pflags |= PS_WEAPONFRAME;
220 
221 	pflags |= PS_WEAPONINDEX;
222 
223 	//
224 	// write it
225 	//
226 	MSG_WriteByte (msg, svc_playerinfo);
227 	MSG_WriteShort (msg, pflags);
228 
229 	//
230 	// write the pmove_state_t
231 	//
232 	if (pflags & PS_M_TYPE)
233 		MSG_WriteByte (msg, ps->pmove.pm_type);
234 
235 	if (pflags & PS_M_ORIGIN)
236 	{
237 		MSG_WriteSizeInt (msg, coord_bytes, ps->pmove.origin[0]);
238 		MSG_WriteSizeInt (msg, coord_bytes, ps->pmove.origin[1]);
239 		MSG_WriteSizeInt (msg, coord_bytes, ps->pmove.origin[2]);
240 	}
241 
242 	if (pflags & PS_M_VELOCITY)
243 	{
244 		MSG_WriteShort (msg, ps->pmove.velocity[0]);
245 		MSG_WriteShort (msg, ps->pmove.velocity[1]);
246 		MSG_WriteShort (msg, ps->pmove.velocity[2]);
247 	}
248 
249 	if (pflags & PS_M_TIME)
250 		MSG_WriteByte (msg, ps->pmove.pm_time);
251 
252 	if (pflags & PS_M_FLAGS)
253 		MSG_WriteByte (msg, ps->pmove.pm_flags);
254 
255 	if (pflags & PS_M_GRAVITY)
256 		MSG_WriteShort (msg, ps->pmove.gravity);
257 
258 	if (pflags & PS_M_DELTA_ANGLES)
259 	{
260 		MSG_WriteShort (msg, ps->pmove.delta_angles[0]);
261 		MSG_WriteShort (msg, ps->pmove.delta_angles[1]);
262 		MSG_WriteShort (msg, ps->pmove.delta_angles[2]);
263 	}
264 
265 	//
266 	// write the rest of the player_state_t
267 	//
268 	if (pflags & PS_VIEWOFFSET)
269 	{
270 		MSG_WriteChar (msg, ps->viewoffset[0]*4);
271 		MSG_WriteChar (msg, ps->viewoffset[1]*4);
272 		MSG_WriteChar (msg, ps->viewoffset[2]*4);
273 	}
274 
275 	if (pflags & PS_VIEWANGLES)
276 	{
277 		MSG_WriteAngle16 (msg, ps->viewangles[0]);
278 		MSG_WriteAngle16 (msg, ps->viewangles[1]);
279 		MSG_WriteAngle16 (msg, ps->viewangles[2]);
280 	}
281 
282 	if (pflags & PS_KICKANGLES)
283 	{
284 		MSG_WriteChar (msg, ps->kick_angles[0]*4);
285 		MSG_WriteChar (msg, ps->kick_angles[1]*4);
286 		MSG_WriteChar (msg, ps->kick_angles[2]*4);
287 	}
288 
289 	if (pflags & PS_WEAPONINDEX)
290 	{
291 		MSG_WriteByte (msg, ps->gunindex);
292 	}
293 
294 	if (pflags & PS_WEAPONFRAME)
295 	{
296 		MSG_WriteByte (msg, ps->gunframe);
297 		MSG_WriteChar (msg, ps->gunoffset[0]*4);
298 		MSG_WriteChar (msg, ps->gunoffset[1]*4);
299 		MSG_WriteChar (msg, ps->gunoffset[2]*4);
300 		MSG_WriteChar (msg, ps->gunangles[0]*4);
301 		MSG_WriteChar (msg, ps->gunangles[1]*4);
302 		MSG_WriteChar (msg, ps->gunangles[2]*4);
303 	}
304 
305 	if (pflags & PS_BLEND)
306 	{
307 		MSG_WriteByte (msg, ps->blend[0]*255);
308 		MSG_WriteByte (msg, ps->blend[1]*255);
309 		MSG_WriteByte (msg, ps->blend[2]*255);
310 		MSG_WriteByte (msg, ps->blend[3]*255);
311 	}
312 	if (pflags & PS_FOV)
313 		MSG_WriteByte (msg, ps->fov);
314 	if (pflags & PS_RDFLAGS)
315 		MSG_WriteByte (msg, ps->rdflags);
316 
317 	// send stats
318 	statbits = 0;
319 	for (i=0 ; i<MAX_STATS ; i++)
320 		if (ps->stats[i] != ops->stats[i])
321 			statbits |= 1<<i;
322 	MSG_WriteLong (msg, statbits);
323 	for (i=0 ; i<MAX_STATS ; i++)
324 		if (statbits & (1<<i) )
325 			MSG_WriteShort (msg, ps->stats[i]);
326 }
327 
328 
329 /*
330 ==================
331 SV_WriteFrameToClient
332 ==================
333 */
SV_WriteFrameToClient(client_t * client,sizebuf_t * msg)334 void SV_WriteFrameToClient (client_t *client, sizebuf_t *msg)
335 {
336 	client_frame_t		*frame, *oldframe;
337 	int					lastframe;
338 
339 //Com_Printf ("%i -> %i\n", client->lastframe, sv.framenum);
340 	// this is the frame we are creating
341 	frame = &client->frames[sv.framenum & UPDATE_MASK];
342 
343 	if (client->lastframe <= 0)
344 	{	// client is asking for a retransmit
345 		oldframe = NULL;
346 		lastframe = -1;
347 	}
348 	else if (sv.framenum - client->lastframe >= (UPDATE_BACKUP - 3) )
349 	{	// client hasn't gotten a good message through in a long time
350 //		Com_Printf ("%s: Delta request from out-of-date packet.\n", client->name);
351 		oldframe = NULL;
352 		lastframe = -1;
353 	}
354 	else
355 	{	// we have a valid message to delta from
356 		oldframe = &client->frames[client->lastframe & UPDATE_MASK];
357 		lastframe = client->lastframe;
358 	}
359 
360 	MSG_WriteByte (msg, svc_frame);
361 	MSG_WriteLong (msg, sv.framenum);
362 	MSG_WriteLong (msg, lastframe);	// what we are delta'ing from
363 	MSG_WriteByte (msg, client->surpressCount);	// rate dropped packets
364 	client->surpressCount = 0;
365 
366 	// send over the areabits
367 	MSG_WriteByte (msg, frame->areabytes);
368 	SZ_Write (msg, frame->areabits, frame->areabytes);
369 
370 	// delta encode the playerstate
371 	SV_WritePlayerstateToClient (oldframe, frame, msg);
372 
373 	// delta encode the entities
374 	SV_EmitPacketEntities (oldframe, frame, msg);
375 }
376 
377 
378 /*
379 =============================================================================
380 
381 Build a client frame structure
382 
383 =============================================================================
384 */
385 
386 byte		fatpvs[65536/8];	// 32767 is MAX_MAP_LEAFS
387 
388 /*
389 ============
390 SV_FatPVS
391 
392 The client will interpolate the view position,
393 so we can't use a single PVS point
394 ===========
395 */
SV_FatPVS(vec3_t org)396 void SV_FatPVS (vec3_t org)
397 {
398 	int		leafs[64];
399 	int		i, j, count;
400 	int		longs;
401 	byte	*src;
402 	vec3_t	mins, maxs;
403 
404 	for (i=0 ; i<3 ; i++)
405 	{
406 		mins[i] = org[i] - 8;
407 		maxs[i] = org[i] + 8;
408 	}
409 
410 	count = CM_BoxLeafnums (mins, maxs, leafs, 64, NULL);
411 	if (count < 1)
412 		Com_Error (ERR_FATAL, "SV_FatPVS: count < 1");
413 	longs = (CM_NumClusters()+31)>>5;
414 
415 	// convert leafs to clusters
416 	for (i=0 ; i<count ; i++)
417 		leafs[i] = CM_LeafCluster(leafs[i]);
418 
419 	memcpy (fatpvs, CM_ClusterPVS(leafs[0]), longs<<2);
420 	// or in all the other leaf bits
421 	for (i=1 ; i<count ; i++)
422 	{
423 		for (j=0 ; j<i ; j++)
424 			if (leafs[i] == leafs[j])
425 				break;
426 		if (j != i)
427 			continue;		// already have the cluster we want
428 		src = CM_ClusterPVS(leafs[i]);
429 		for (j=0 ; j<longs ; j++)
430 			((long *)fatpvs)[j] |= ((long *)src)[j];
431 	}
432 }
433 
434 
435 /*
436 =============
437 SV_BuildClientFrame
438 
439 Decides which entities are going to be visible to the client, and
440 copies off the playerstat and areabits.
441 =============
442 */
SV_BuildClientFrame(client_t * client)443 void SV_BuildClientFrame (client_t *client)
444 {
445 	int		e, i;
446 	vec3_t	org;
447 	edict_t	*ent;
448 	edict_t	*clent;
449 	edict_t	*orig_clent;
450 	client_frame_t	*frame;
451 	entity_state_t	*state;
452 	int		l;
453 	int		clientarea, clientcluster;
454 	int		leafnum;
455 	int		c_fullsend;
456 	byte	*clientphs;
457 	byte	*bitvector;
458 
459 	client_t	*redir_client;
460 	int			redir_num;
461 
462 	orig_clent = client->edict;
463 	if (!orig_clent->client)
464 		return;		// not in game yet
465 
466 	redir_num = client->edict->redirect_number;
467 	if (redir_num != client->edict->s.number)
468 	{
469 		for (i=0, redir_client = svs.clients ; i<maxclients->integer; i++, redir_client++)
470 			if (redir_num == redir_client->edict->s.number)
471 				break;
472 		if (i == maxclients->integer)
473 			redir_client = client;
474 	}
475 	else
476 		redir_client = client;
477 
478 	clent = redir_client->edict;
479 	if (!clent->client)
480 		return;		// not in game yet
481 
482 	// this is the frame we are creating
483 	frame = &client->frames[sv.framenum & UPDATE_MASK];
484 
485 	frame->senttime = svs.realtime; // save it for ping calc later
486 
487 	// find the client's PVS
488 	for (i=0 ; i<3 ; i++)
489 		org[i] = clent->client->ps.pmove.origin[i]*0.125 + clent->client->ps.viewoffset[i];
490 
491 	leafnum = CM_PointLeafnum (org);
492 	clientarea = CM_LeafArea (leafnum);
493 	clientcluster = CM_LeafCluster (leafnum);
494 
495 	// calculate the visible areas
496 	frame->areabytes = CM_WriteAreaBits (frame->areabits, clientarea);
497 
498 	// grab the current player_state_t
499 	frame->ps = clent->client->ps;
500 
501 	if (client != redir_client)
502 	{
503 		//some adjustments for ghost mode
504 		if (frame->ps.pmove.pm_type != PM_DEAD)
505 			frame->ps.pmove.pm_type = PM_FREEZE;
506 		frame->ps.fov = client->edict->client->ps.fov;
507 	}
508 
509 
510 	SV_FatPVS (org);
511 	clientphs = CM_ClusterPHS (clientcluster);
512 
513 	// build up the list of visible entities
514 	frame->num_entities = 0;
515 	frame->first_entity = svs.next_client_entities;
516 
517 	c_fullsend = 0;
518 
519 	for (e=1 ; e<ge->num_edicts ; e++)
520 	{
521 		ent = EDICT_NUM(e);
522 
523 		// ignore ents without visible models
524 		if (ent->svflags & SVF_NOCLIENT)
525 			continue;
526 
527 		// ignore ents without visible models unless they have an effect
528 		if (!ent->s.modelindex && !ent->s.effects && !ent->s.sound
529 			&& !ent->s.event)
530 			continue;
531 
532 		// ignore if not touching a PV leaf
533 		if (ent != clent)
534 		{
535 			// check area
536 			if (!CM_AreasConnected (clientarea, ent->areanum))
537 			{	// doors can legally straddle two areas, so
538 				// we may need to check another one
539 				if (!ent->areanum2
540 					|| !CM_AreasConnected (clientarea, ent->areanum2))
541 					continue;		// blocked by a door
542 			}
543 
544 			// FIXME: if an ent has a model and a sound, but isn't
545 			// in the PVS, only the PHS, clear the model
546 			if (ent->s.sound)
547 			{
548 				bitvector = fatpvs;	//clientphs;
549 			}
550 			else
551 				bitvector = fatpvs;
552 
553 			if (ent->num_clusters == -1)
554 			{	// too many leafs for individual check, go by headnode
555 				if (!CM_HeadnodeVisible (ent->headnode, bitvector))
556 					continue;
557 				c_fullsend++;
558 			}
559 			else
560 			{	// check individual leafs
561 				for (i=0 ; i < ent->num_clusters ; i++)
562 				{
563 					l = ent->clusternums[i];
564 					if (bitvector[l >> 3] & (1 << (l&7) ))
565 						break;
566 				}
567 				if (i == ent->num_clusters)
568 					continue;		// not visible
569 			}
570 
571 			if (!ent->s.modelindex)
572 			{	// don't send sounds if they will be attenuated away
573 				vec3_t	delta;
574 				float	len;
575 
576 				VectorSubtract (org, ent->s.origin, delta);
577 				len = VectorLength (delta);
578 				if (len > 400)
579 					continue;
580 			}
581 		}
582 
583 		if (ent->s.number != e)
584 		{ // note: server has limited info about entities
585 			Com_DPrintf("Fixing ent->s.number: %i to %i for a %s\n",
586 					ent->s.number, e, (ent->client ? "client" : "non-client") );
587 			ent->s.number = e;
588 		}
589 
590 		if (ent == orig_clent && orig_clent != clent)
591 		{
592 			Com_Printf ("CAN'T HAPPEN?\n");
593 			continue;
594 		}
595 
596 		// add it to the circular client_entities array
597 		state = &svs.client_entities[svs.next_client_entities%svs.num_client_entities];
598 		*state = ent->s;
599 		if (ent == clent && orig_clent != clent)
600 			state->number = orig_clent->s.number;
601 
602 		// don't mark players missiles as solid
603 		if (ent->owner == client->edict)
604 			state->solid = 0;
605 
606 		svs.next_client_entities++;
607 		frame->num_entities++;
608 	}
609 }
610 
611 
612 /*
613 ==================
614 SV_RecordDemoMessage
615 
616 Save everything in the world out without deltas.
617 Used for recording footage for merged or assembled demos
618 ==================
619 */
SV_RecordDemoMessage(void)620 void SV_RecordDemoMessage (void)
621 {
622 	int			e;
623 	edict_t		*ent;
624 	entity_state_t	nostate;
625 	sizebuf_t	buf;
626 	byte		buf_data[32768];
627 	int			len;
628 
629 	if (!svs.demofile)
630 		return;
631 
632 	memset (&nostate, 0, sizeof(nostate));
633 	SZ_Init (&buf, buf_data, sizeof(buf_data));
634 	SZ_SetName (&buf, "Demo message buffer", false);
635 
636 	// write a frame message that doesn't contain a player_state_t
637 	MSG_WriteByte (&buf, svc_frame);
638 	MSG_WriteLong (&buf, sv.framenum);
639 
640 	MSG_WriteByte (&buf, svc_packetentities);
641 
642 	e = 1;
643 	ent = EDICT_NUM(e);
644 	while (e < ge->num_edicts)
645 	{
646 		// ignore ents without visible models unless they have an effect
647 		if (ent->inuse &&
648 			ent->s.number &&
649 			(ent->s.modelindex || ent->s.effects || ent->s.sound || ent->s.event) &&
650 			!(ent->svflags & SVF_NOCLIENT))
651 			MSG_WriteDeltaEntity (&nostate, &ent->s, &buf, false, true);
652 
653 		e++;
654 		ent = EDICT_NUM(e);
655 	}
656 
657 	MSG_WriteShort (&buf, 0);		// end of packetentities
658 
659 	// now add the accumulated multicast information
660 	SZ_Write (&buf, svs.demo_multicast.data, svs.demo_multicast.cursize);
661 	SZ_Clear (&svs.demo_multicast);
662 
663 	// now write the entire message to the file, prefixed by the length
664 	len = LittleLong (buf.cursize);
665 	szr = fwrite (&len, 4, 1, svs.demofile);
666 	szr = fwrite (buf.data, buf.cursize, 1, svs.demofile);
667 }
668 
669