]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sv_main.c
split out RecursiveHullCheck and related code into collision.c (shared by client...
[xonotic/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 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 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23
24 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "0"}; // fast but loose
25 static cvar_t sv_cullentities_portal = {0, "sv_cullentities_portal", "0"}; // extremely accurate visibility checking, but too slow
26 static cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "1"}; // tends to get false negatives, uses a timeout to keep entities visible a short time after becoming hidden
27 static cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0"};
28
29 server_t                sv;
30 server_static_t svs;
31
32 static char localmodels[MAX_MODELS][5];                 // inline model names for precache
33
34 static mempool_t *sv_edicts_mempool = NULL;
35
36 //============================================================================
37
38 extern void SV_Phys_Init (void);
39
40 /*
41 ===============
42 SV_Init
43 ===============
44 */
45 void SV_Init (void)
46 {
47         int i;
48
49         Cvar_RegisterVariable (&sv_maxvelocity);
50         Cvar_RegisterVariable (&sv_gravity);
51         Cvar_RegisterVariable (&sv_friction);
52         Cvar_RegisterVariable (&sv_edgefriction);
53         Cvar_RegisterVariable (&sv_stopspeed);
54         Cvar_RegisterVariable (&sv_maxspeed);
55         Cvar_RegisterVariable (&sv_accelerate);
56         Cvar_RegisterVariable (&sv_idealpitchscale);
57         Cvar_RegisterVariable (&sv_aim);
58         Cvar_RegisterVariable (&sv_nostep);
59         Cvar_RegisterVariable (&sv_predict);
60         Cvar_RegisterVariable (&sv_deltacompress);
61         Cvar_RegisterVariable (&sv_cullentities_pvs);
62         Cvar_RegisterVariable (&sv_cullentities_portal);
63         Cvar_RegisterVariable (&sv_cullentities_trace);
64         Cvar_RegisterVariable (&sv_cullentities_stats);
65
66         SV_Phys_Init();
67
68         for (i = 0;i < MAX_MODELS;i++)
69                 sprintf (localmodels[i], "*%i", i);
70
71         sv_edicts_mempool = Mem_AllocPool("edicts");
72 }
73
74 /*
75 =============================================================================
76
77 EVENT MESSAGES
78
79 =============================================================================
80 */
81
82 /*
83 ==================
84 SV_StartParticle
85
86 Make sure the event gets sent to all clients
87 ==================
88 */
89 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
90 {
91         int             i, v;
92
93         if (sv.datagram.cursize > MAX_DATAGRAM-16)
94                 return;
95         MSG_WriteByte (&sv.datagram, svc_particle);
96         MSG_WriteDPCoord (&sv.datagram, org[0]);
97         MSG_WriteDPCoord (&sv.datagram, org[1]);
98         MSG_WriteDPCoord (&sv.datagram, org[2]);
99         for (i=0 ; i<3 ; i++)
100         {
101                 v = dir[i]*16;
102                 if (v > 127)
103                         v = 127;
104                 else if (v < -128)
105                         v = -128;
106                 MSG_WriteChar (&sv.datagram, v);
107         }
108         MSG_WriteByte (&sv.datagram, count);
109         MSG_WriteByte (&sv.datagram, color);
110 }
111
112 /*
113 ==================
114 SV_StartEffect
115
116 Make sure the event gets sent to all clients
117 ==================
118 */
119 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
120 {
121         if (sv.datagram.cursize > MAX_DATAGRAM-18)
122                 return;
123         if (modelindex >= 256 || startframe >= 256)
124         {
125                 MSG_WriteByte (&sv.datagram, svc_effect2);
126                 MSG_WriteDPCoord (&sv.datagram, org[0]);
127                 MSG_WriteDPCoord (&sv.datagram, org[1]);
128                 MSG_WriteDPCoord (&sv.datagram, org[2]);
129                 MSG_WriteShort (&sv.datagram, modelindex);
130                 MSG_WriteShort (&sv.datagram, startframe);
131                 MSG_WriteByte (&sv.datagram, framecount);
132                 MSG_WriteByte (&sv.datagram, framerate);
133         }
134         else
135         {
136                 MSG_WriteByte (&sv.datagram, svc_effect);
137                 MSG_WriteDPCoord (&sv.datagram, org[0]);
138                 MSG_WriteDPCoord (&sv.datagram, org[1]);
139                 MSG_WriteDPCoord (&sv.datagram, org[2]);
140                 MSG_WriteByte (&sv.datagram, modelindex);
141                 MSG_WriteByte (&sv.datagram, startframe);
142                 MSG_WriteByte (&sv.datagram, framecount);
143                 MSG_WriteByte (&sv.datagram, framerate);
144         }
145 }
146
147 /*
148 ==================
149 SV_StartSound
150
151 Each entity can have eight independant sound sources, like voice,
152 weapon, feet, etc.
153
154 Channel 0 is an auto-allocate channel, the others override anything
155 already running on that entity/channel pair.
156
157 An attenuation of 0 will play full volume everywhere in the level.
158 Larger attenuations will drop off.  (max 4 attenuation)
159
160 ==================
161 */
162 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume,
163     float attenuation)
164 {
165     int         sound_num;
166     int field_mask;
167     int                 i;
168         int                     ent;
169
170         if (volume < 0 || volume > 255)
171                 Host_Error ("SV_StartSound: volume = %i", volume);
172
173         if (attenuation < 0 || attenuation > 4)
174                 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
175
176         if (channel < 0 || channel > 7)
177                 Host_Error ("SV_StartSound: channel = %i", channel);
178
179         if (sv.datagram.cursize > MAX_DATAGRAM-16)
180                 return;
181
182 // find precache number for sound
183     for (sound_num=1 ; sound_num<MAX_SOUNDS
184         && sv.sound_precache[sound_num] ; sound_num++)
185         if (!strcmp(sample, sv.sound_precache[sound_num]))
186             break;
187
188     if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
189     {
190         Con_Printf ("SV_StartSound: %s not precached\n", sample);
191         return;
192     }
193
194         ent = NUM_FOR_EDICT(entity);
195
196         channel = (ent<<3) | channel;
197
198         field_mask = 0;
199         if (volume != DEFAULT_SOUND_PACKET_VOLUME)
200                 field_mask |= SND_VOLUME;
201         if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
202                 field_mask |= SND_ATTENUATION;
203
204 // directed messages go only to the entity they are targeted on
205         if (sound_num >= 256)
206                 MSG_WriteByte (&sv.datagram, svc_sound2);
207         else
208                 MSG_WriteByte (&sv.datagram, svc_sound);
209         MSG_WriteByte (&sv.datagram, field_mask);
210         if (field_mask & SND_VOLUME)
211                 MSG_WriteByte (&sv.datagram, volume);
212         if (field_mask & SND_ATTENUATION)
213                 MSG_WriteByte (&sv.datagram, attenuation*64);
214         MSG_WriteShort (&sv.datagram, channel);
215         if (sound_num >= 256)
216                 MSG_WriteShort (&sv.datagram, sound_num);
217         else
218                 MSG_WriteByte (&sv.datagram, sound_num);
219         for (i=0 ; i<3 ; i++)
220                 MSG_WriteDPCoord (&sv.datagram, entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]));
221 }
222
223 /*
224 ==============================================================================
225
226 CLIENT SPAWNING
227
228 ==============================================================================
229 */
230
231 /*
232 ================
233 SV_SendServerinfo
234
235 Sends the first message from the server to a connected client.
236 This will be sent on the initial connection and upon each server load.
237 ================
238 */
239 void SV_SendServerinfo (client_t *client)
240 {
241         char                    **s;
242         char                    message[2048];
243
244         // LordHavoc: clear entityframe tracking
245         client->entityframenumber = 0;
246         EntityFrame_ClearDatabase(&client->entitydatabase);
247
248         MSG_WriteByte (&client->message, svc_print);
249         sprintf (message, "\002\nServer: %s build %s (progs %i crc)", gamename, buildstring, pr_crc);
250         MSG_WriteString (&client->message,message);
251
252         MSG_WriteByte (&client->message, svc_serverinfo);
253         MSG_WriteLong (&client->message, DPPROTOCOL_VERSION3);
254         MSG_WriteByte (&client->message, svs.maxclients);
255
256         if (!coop.integer && deathmatch.integer)
257                 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
258         else
259                 MSG_WriteByte (&client->message, GAME_COOP);
260
261         sprintf (message, pr_strings+sv.edicts->v.message);
262
263         MSG_WriteString (&client->message,message);
264
265         for (s = sv.model_precache+1 ; *s ; s++)
266                 MSG_WriteString (&client->message, *s);
267         MSG_WriteByte (&client->message, 0);
268
269         for (s = sv.sound_precache+1 ; *s ; s++)
270                 MSG_WriteString (&client->message, *s);
271         MSG_WriteByte (&client->message, 0);
272
273 // send music
274         MSG_WriteByte (&client->message, svc_cdtrack);
275         MSG_WriteByte (&client->message, sv.edicts->v.sounds);
276         MSG_WriteByte (&client->message, sv.edicts->v.sounds);
277
278 // set view
279         MSG_WriteByte (&client->message, svc_setview);
280         MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
281
282         MSG_WriteByte (&client->message, svc_signonnum);
283         MSG_WriteByte (&client->message, 1);
284
285         client->sendsignon = true;
286         client->spawned = false;                // need prespawn, spawn, etc
287 }
288
289 /*
290 ================
291 SV_ConnectClient
292
293 Initializes a client_t for a new net connection.  This will only be called
294 once for a player each game, not once for each level change.
295 ================
296 */
297 void SV_ConnectClient (int clientnum)
298 {
299         edict_t                 *ent;
300         client_t                *client;
301         int                             edictnum;
302         struct qsocket_s *netconnection;
303         int                             i;
304         float                   spawn_parms[NUM_SPAWN_PARMS];
305
306         client = svs.clients + clientnum;
307
308         Con_DPrintf ("Client %s connected\n", client->netconnection->address);
309
310         edictnum = clientnum+1;
311
312         ent = EDICT_NUM(edictnum);
313
314 // set up the client_t
315         netconnection = client->netconnection;
316
317         if (sv.loadgame)
318                 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
319         memset (client, 0, sizeof(*client));
320         client->netconnection = netconnection;
321
322         strcpy (client->name, "unconnected");
323         client->active = true;
324         client->spawned = false;
325         client->edict = ent;
326         client->message.data = client->msgbuf;
327         client->message.maxsize = sizeof(client->msgbuf);
328         client->message.allowoverflow = true;           // we can catch it
329
330         if (sv.loadgame)
331                 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
332         else
333         {
334         // call the progs to get default spawn parms for the new client
335                 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
336                 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
337                         client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
338         }
339
340 #if NOROUTINGFIX
341         SV_SendServerinfo (client);
342 #else
343         // send serverinfo on first nop
344         client->waitingforconnect = true;
345         client->sendsignon = true;
346         client->spawned = false;                // need prespawn, spawn, etc
347 #endif
348 }
349
350
351 /*
352 ===================
353 SV_CheckForNewClients
354
355 ===================
356 */
357 void SV_CheckForNewClients (void)
358 {
359         struct qsocket_s        *ret;
360         int                             i;
361
362 //
363 // check for new connections
364 //
365         while (1)
366         {
367                 ret = NET_CheckNewConnections ();
368                 if (!ret)
369                         break;
370
371         //
372         // init a new client structure
373         //
374                 for (i=0 ; i<svs.maxclients ; i++)
375                         if (!svs.clients[i].active)
376                                 break;
377                 if (i == svs.maxclients)
378                         Sys_Error ("Host_CheckForNewClients: no free clients");
379
380                 svs.clients[i].netconnection = ret;
381                 SV_ConnectClient (i);
382
383                 net_activeconnections++;
384         }
385 }
386
387
388
389 /*
390 ===============================================================================
391
392 FRAME UPDATES
393
394 ===============================================================================
395 */
396
397 /*
398 ==================
399 SV_ClearDatagram
400
401 ==================
402 */
403 void SV_ClearDatagram (void)
404 {
405         SZ_Clear (&sv.datagram);
406 }
407
408 /*
409 =============================================================================
410
411 The PVS must include a small area around the client to allow head bobbing
412 or other small motion on the client side.  Otherwise, a bob might cause an
413 entity that should be visible to not show up, especially when the bob
414 crosses a waterline.
415
416 =============================================================================
417 */
418
419 int             fatbytes;
420 qbyte   fatpvs[MAX_MAP_LEAFS/8];
421
422 void SV_AddToFatPVS (vec3_t org, mnode_t *node)
423 {
424         int             i;
425         qbyte   *pvs;
426         mplane_t        *plane;
427         float   d;
428
429         while (1)
430         {
431         // if this is a leaf, accumulate the pvs bits
432                 if (node->contents < 0)
433                 {
434                         if (node->contents != CONTENTS_SOLID)
435                         {
436                                 pvs = Mod_LeafPVS ( (mleaf_t *)node, sv.worldmodel);
437                                 for (i=0 ; i<fatbytes ; i++)
438                                         fatpvs[i] |= pvs[i];
439                         }
440                         return;
441                 }
442
443                 plane = node->plane;
444                 d = DotProduct (org, plane->normal) - plane->dist;
445                 if (d > 8)
446                         node = node->children[0];
447                 else if (d < -8)
448                         node = node->children[1];
449                 else
450                 {       // go down both
451                         SV_AddToFatPVS (org, node->children[0]);
452                         node = node->children[1];
453                 }
454         }
455 }
456
457 /*
458 =============
459 SV_FatPVS
460
461 Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the
462 given point.
463 =============
464 */
465 qbyte *SV_FatPVS (vec3_t org)
466 {
467         fatbytes = (sv.worldmodel->numleafs+31)>>3;
468         memset (fatpvs, 0, fatbytes);
469         SV_AddToFatPVS (org, sv.worldmodel->nodes);
470         return fatpvs;
471 }
472
473 //=============================================================================
474
475
476 int SV_BoxTouchingPVS (qbyte *pvs, vec3_t mins, vec3_t maxs, mnode_t *node)
477 {
478         int leafnum;
479 loc0:
480         if (node->contents < 0)
481         {
482                 // leaf
483                 if (node->contents == CONTENTS_SOLID)
484                         return false;
485                 leafnum = (mleaf_t *)node - sv.worldmodel->leafs - 1;
486                 return pvs[leafnum >> 3] & (1 << (leafnum & 7));
487         }
488
489         // node - recurse down the BSP tree
490         switch (BOX_ON_PLANE_SIDE(mins, maxs, node->plane))
491         {
492         case 1: // front
493                 node = node->children[0];
494                 goto loc0;
495         case 2: // back
496                 node = node->children[1];
497                 goto loc0;
498         default: // crossing
499                 if (node->children[0]->contents != CONTENTS_SOLID)
500                         if (SV_BoxTouchingPVS (pvs, mins, maxs, node->children[0]))
501                                 return true;
502                 node = node->children[1];
503                 goto loc0;
504         }
505         // never reached
506         return false;
507 }
508
509
510 /*
511 =============
512 SV_WriteEntitiesToClient
513
514 =============
515 */
516 #ifdef QUAKEENTITIES
517 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
518 {
519         int e, clentnum, bits, alpha, glowcolor, glowsize, scale, effects;
520         int culled_pvs, culled_portal, culled_trace, visibleentities, totalentities;
521         qbyte *pvs;
522         vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
523         float nextfullupdate;
524         edict_t *ent;
525         eval_t *val;
526         entity_state_t *baseline; // LordHavoc: delta or startup baseline
527         trace_t trace;
528         model_t *model;
529
530         Mod_CheckLoaded(sv.worldmodel);
531
532 // find the client's PVS
533         VectorAdd (clent->v.origin, clent->v.view_ofs, testeye);
534         pvs = SV_FatPVS (testeye);
535         /*
536         // dp protocol
537         MSG_WriteByte(msg, svc_playerposition);
538         MSG_WriteFloat(msg, testeye[0]);
539         MSG_WriteFloat(msg, testeye[1]);
540         MSG_WriteFloat(msg, testeye[2]);
541         */
542
543         culled_pvs = 0;
544         culled_portal = 0;
545         culled_trace = 0;
546         visibleentities = 0;
547         totalentities = 0;
548
549         clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
550         // send all entities that touch the pvs
551         ent = NEXT_EDICT(sv.edicts);
552         for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
553         {
554                 bits = 0;
555
556                 // prevent delta compression against this frame (unless actually sent, which will restore this later)
557                 nextfullupdate = client->nextfullupdate[e];
558                 client->nextfullupdate[e] = -1;
559
560                 if (ent != clent) // LordHavoc: always send player
561                 {
562                         if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
563                         {
564                                 if (val->edict != clentnum)
565                                 {
566                                         // don't show to anyone else
567                                         continue;
568                                 }
569                                 else
570                                         bits |= U_VIEWMODEL; // show relative to the view
571                         }
572                         else
573                         {
574                                 // LordHavoc: never draw something told not to display to this client
575                                 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
576                                         continue;
577                                 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
578                                         continue;
579                         }
580                 }
581
582                 glowsize = 0;
583
584                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
585                         glowsize = (int) val->_float >> 2;
586                 if (glowsize > 255) glowsize = 255;
587                 if (glowsize < 0) glowsize = 0;
588
589                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
590                 if (val->_float != 0)
591                         bits |= U_GLOWTRAIL;
592
593                 if (ent->v.modelindex >= 0 && ent->v.modelindex < MAX_MODELS && pr_strings[ent->v.model])
594                 {
595                         model = sv.models[(int)ent->v.modelindex];
596                         Mod_CheckLoaded(model);
597                 }
598                 else
599                 {
600                         model = NULL;
601                         if (ent != clent) // LordHavoc: always send player
602                                 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
603                                         continue;
604                 }
605
606                 VectorCopy(ent->v.angles, angles);
607                 if (DotProduct(ent->v.velocity, ent->v.velocity) >= 1.0f)
608                 {
609                         VectorMA(ent->v.origin, host_client->latency, ent->v.velocity, origin);
610                         // LordHavoc: trace predicted movement to avoid putting things in walls
611                         trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, origin, MOVE_NORMAL, ent);
612                         VectorCopy(trace.endpos, origin);
613                 }
614                 else
615                 {
616                         VectorCopy(ent->v.origin, origin);
617                 }
618
619                 // ent has survived every check so far, check if it is visible
620                 if (ent != clent && ((bits & U_VIEWMODEL) == 0))
621                 {
622                         // use the predicted origin
623                         entmins[0] = origin[0] - 1.0f;
624                         entmins[1] = origin[1] - 1.0f;
625                         entmins[2] = origin[2] - 1.0f;
626                         entmaxs[0] = origin[0] + 1.0f;
627                         entmaxs[1] = origin[1] + 1.0f;
628                         entmaxs[2] = origin[2] + 1.0f;
629                         // using the model's bounding box to ensure things are visible regardless of their physics box
630                         if (model)
631                         {
632                                 if (ent->v.angles[0] || ent->v.angles[2]) // pitch and roll
633                                 {
634                                         VectorAdd(entmins, model->rotatedmins, entmins);
635                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
636                                 }
637                                 else if (ent->v.angles[1])
638                                 {
639                                         VectorAdd(entmins, model->yawmins, entmins);
640                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
641                                 }
642                                 else
643                                 {
644                                         VectorAdd(entmins, model->normalmins, entmins);
645                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
646                                 }
647                         }
648
649                         totalentities++;
650
651                         // if not touching a visible leaf
652                         if (sv_cullentities_pvs.integer && !SV_BoxTouchingPVS(pvs, entmins, entmaxs, sv.worldmodel->nodes))
653                         {
654                                 culled_pvs++;
655                                 continue;
656                         }
657
658                         // or not visible through the portals
659                         if (sv_cullentities_portal.integer && !Portal_CheckBox(sv.worldmodel, testeye, entmins, entmaxs))
660                         {
661                                 culled_portal++;
662                                 continue;
663                         }
664
665                         // don't try to cull embedded brush models with this, they're sometimes huge (spanning several rooms)
666                         if (sv_cullentities_trace.integer && (model == NULL || model->type != mod_brush || model->name[0] != '*'))
667                         {
668                                 // LordHavoc: test random offsets, to maximize chance of detection
669                                 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
670                                 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
671                                 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
672
673                                 Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
674
675                                 if (trace.fraction == 1)
676                                         client->visibletime[e] = realtime + 1;
677                                 else
678                                 {
679                                         //test nearest point on bbox
680                                         testorigin[0] = bound(entmins[0], testeye[0], entmaxs[0]);
681                                         testorigin[1] = bound(entmins[1], testeye[1], entmaxs[1]);
682                                         testorigin[2] = bound(entmins[2], testeye[2], entmaxs[2]);
683
684                                         Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
685
686                                         if (trace.fraction == 1)
687                                                 client->visibletime[e] = realtime + 1;
688                                         else if (realtime > client->visibletime[e])
689                                         {
690                                                 culled_trace++;
691                                                 continue;
692                                         }
693                                 }
694                         }
695                         visibleentities++;
696                 }
697
698                 alpha = 255;
699                 scale = 16;
700                 glowcolor = 254;
701                 effects = ent->v.effects;
702
703                 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
704                 if (val->_float != 0)
705                         alpha = (int) (val->_float * 255.0);
706
707                 // HalfLife support
708                 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
709                 if (val->_float != 0)
710                         alpha = (int) val->_float;
711
712                 if (alpha == 0)
713                         alpha = 255;
714                 alpha = bound(0, alpha, 255);
715
716                 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
717                 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
718                 if (scale < 0) scale = 0;
719                 if (scale > 255) scale = 255;
720
721                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
722                 if (val->_float != 0)
723                         glowcolor = (int) val->_float;
724
725                 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
726                 if (val->_float != 0)
727                         effects |= EF_FULLBRIGHT;
728
729                 if (ent != clent)
730                 {
731                         if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
732                         {
733                                 if (model) // model
734                                 {
735                                         // don't send if flagged for NODRAW and there are no effects
736                                         if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
737                                                 continue;
738                                 }
739                                 else // no model and no effects
740                                         continue;
741                         }
742                 }
743
744                 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
745                 {
746                         Con_Printf ("packet overflow\n");
747                         // mark the rest of the entities so they can't be delta compressed against this frame
748                         for (;e < sv.num_edicts;e++)
749                         {
750                                 client->nextfullupdate[e] = -1;
751                                 client->visibletime[e] = -1;
752                         }
753                         return;
754                 }
755
756                 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
757                         bits = bits | U_EXTERIORMODEL;
758
759 // send an update
760                 baseline = &ent->baseline;
761
762                 if (((int)ent->v.effects & EF_DELTA) && sv_deltacompress.integer)
763                 {
764                         // every half second a full update is forced
765                         if (realtime < client->nextfullupdate[e])
766                         {
767                                 bits |= U_DELTA;
768                                 baseline = &ent->deltabaseline;
769                         }
770                         else
771                                 nextfullupdate = realtime + 0.5f;
772                 }
773                 else
774                         nextfullupdate = realtime + 0.5f;
775
776                 // restore nextfullupdate since this is being sent for real
777                 client->nextfullupdate[e] = nextfullupdate;
778
779                 if (e >= 256)
780                         bits |= U_LONGENTITY;
781
782                 if (ent->v.movetype == MOVETYPE_STEP)
783                         bits |= U_STEP;
784
785                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
786 //              if ((int)(origin[0]*8.0) != (int)(baseline->origin[0]*8.0))                                             bits |= U_ORIGIN1;
787 //              if ((int)(origin[1]*8.0) != (int)(baseline->origin[1]*8.0))                                             bits |= U_ORIGIN2;
788 //              if ((int)(origin[2]*8.0) != (int)(baseline->origin[2]*8.0))                                             bits |= U_ORIGIN3;
789                 if (origin[0] != baseline->origin[0])                                                                                   bits |= U_ORIGIN1;
790                 if (origin[1] != baseline->origin[1])                                                                                   bits |= U_ORIGIN2;
791                 if (origin[2] != baseline->origin[2])                                                                                   bits |= U_ORIGIN3;
792                 if (((int)(angles[0]*(256.0/360.0)) & 255) != ((int)(baseline->angles[0]*(256.0/360.0)) & 255)) bits |= U_ANGLE1;
793                 if (((int)(angles[1]*(256.0/360.0)) & 255) != ((int)(baseline->angles[1]*(256.0/360.0)) & 255)) bits |= U_ANGLE2;
794                 if (((int)(angles[2]*(256.0/360.0)) & 255) != ((int)(baseline->angles[2]*(256.0/360.0)) & 255)) bits |= U_ANGLE3;
795                 if (baseline->colormap != (qbyte) ent->v.colormap)                                                              bits |= U_COLORMAP;
796                 if (baseline->skin != (qbyte) ent->v.skin)                                                                              bits |= U_SKIN;
797                 if ((baseline->frame & 0x00FF) != ((int) ent->v.frame & 0x00FF))                                bits |= U_FRAME;
798                 if ((baseline->effects & 0x00FF) != ((int) ent->v.effects & 0x00FF))                    bits |= U_EFFECTS;
799                 if ((baseline->modelindex & 0x00FF) != ((int) ent->v.modelindex & 0x00FF))              bits |= U_MODEL;
800
801                 // LordHavoc: new stuff
802                 if (baseline->alpha != alpha)                                                                                                   bits |= U_ALPHA;
803                 if (baseline->scale != scale)                                                                                                   bits |= U_SCALE;
804                 if (((int) baseline->effects & 0xFF00) != ((int) ent->v.effects & 0xFF00))              bits |= U_EFFECTS2;
805                 if (baseline->glowsize != glowsize)                                                                                             bits |= U_GLOWSIZE;
806                 if (baseline->glowcolor != glowcolor)                                                                                   bits |= U_GLOWCOLOR;
807                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v.frame & 0xFF00))                  bits |= U_FRAME2;
808                 if (((int) baseline->frame & 0xFF00) != ((int) ent->v.modelindex & 0xFF00))             bits |= U_MODEL2;
809
810                 // update delta baseline
811                 VectorCopy(ent->v.origin, ent->deltabaseline.origin);
812                 VectorCopy(ent->v.angles, ent->deltabaseline.angles);
813                 ent->deltabaseline.colormap = ent->v.colormap;
814                 ent->deltabaseline.skin = ent->v.skin;
815                 ent->deltabaseline.frame = ent->v.frame;
816                 ent->deltabaseline.effects = ent->v.effects;
817                 ent->deltabaseline.modelindex = ent->v.modelindex;
818                 ent->deltabaseline.alpha = alpha;
819                 ent->deltabaseline.scale = scale;
820                 ent->deltabaseline.glowsize = glowsize;
821                 ent->deltabaseline.glowcolor = glowcolor;
822
823                 // write the message
824                 if (bits >= 16777216)
825                         bits |= U_EXTEND2;
826                 if (bits >= 65536)
827                         bits |= U_EXTEND1;
828                 if (bits >= 256)
829                         bits |= U_MOREBITS;
830                 bits |= U_SIGNAL;
831
832                 MSG_WriteByte (msg, bits);
833                 if (bits & U_MOREBITS)
834                         MSG_WriteByte (msg, bits>>8);
835                 // LordHavoc: extend bytes have to be written here due to delta compression
836                 if (bits & U_EXTEND1)
837                         MSG_WriteByte (msg, bits>>16);
838                 if (bits & U_EXTEND2)
839                         MSG_WriteByte (msg, bits>>24);
840
841                 // LordHavoc: old stuff
842                 if (bits & U_LONGENTITY)
843                         MSG_WriteShort (msg,e);
844                 else
845                         MSG_WriteByte (msg,e);
846                 if (bits & U_MODEL)             MSG_WriteByte (msg,     ent->v.modelindex);
847                 if (bits & U_FRAME)             MSG_WriteByte (msg, ent->v.frame);
848                 if (bits & U_COLORMAP)  MSG_WriteByte (msg, ent->v.colormap);
849                 if (bits & U_SKIN)              MSG_WriteByte (msg, ent->v.skin);
850                 if (bits & U_EFFECTS)   MSG_WriteByte (msg, ent->v.effects);
851                 if (bits & U_ORIGIN1)   MSG_WriteDPCoord (msg, origin[0]);
852                 if (bits & U_ANGLE1)    MSG_WriteAngle(msg, angles[0]);
853                 if (bits & U_ORIGIN2)   MSG_WriteDPCoord (msg, origin[1]);
854                 if (bits & U_ANGLE2)    MSG_WriteAngle(msg, angles[1]);
855                 if (bits & U_ORIGIN3)   MSG_WriteDPCoord (msg, origin[2]);
856                 if (bits & U_ANGLE3)    MSG_WriteAngle(msg, angles[2]);
857
858                 // LordHavoc: new stuff
859                 if (bits & U_ALPHA)             MSG_WriteByte(msg, alpha);
860                 if (bits & U_SCALE)             MSG_WriteByte(msg, scale);
861                 if (bits & U_EFFECTS2)  MSG_WriteByte(msg, (int)ent->v.effects >> 8);
862                 if (bits & U_GLOWSIZE)  MSG_WriteByte(msg, glowsize);
863                 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
864                 if (bits & U_FRAME2)    MSG_WriteByte(msg, (int)ent->v.frame >> 8);
865                 if (bits & U_MODEL2)    MSG_WriteByte(msg, (int)ent->v.modelindex >> 8);
866         }
867
868         if (sv_cullentities_stats.integer)
869                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d portal %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_portal + culled_trace, culled_pvs, culled_portal, culled_trace);
870 }
871 #else
872 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
873 {
874         int e, clentnum, flags, alpha, glowcolor, glowsize, scale, effects;
875         int culled_pvs, culled_portal, culled_trace, visibleentities, totalentities;
876         qbyte *pvs;
877         vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
878         edict_t *ent;
879         eval_t *val;
880         trace_t trace;
881         model_t *model;
882         entity_frame_t entityframe;
883         entity_state_t *s;
884
885         if (client->sendsignon)
886                 return;
887
888         Mod_CheckLoaded(sv.worldmodel);
889
890 // find the client's PVS
891         VectorAdd (clent->v.origin, clent->v.view_ofs, testeye);
892         pvs = SV_FatPVS (testeye);
893         EntityFrame_Clear(&entityframe, testeye);
894
895         culled_pvs = 0;
896         culled_portal = 0;
897         culled_trace = 0;
898         visibleentities = 0;
899         totalentities = 0;
900
901         clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
902         // send all entities that touch the pvs
903         ent = NEXT_EDICT(sv.edicts);
904         for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
905         {
906                 flags = 0;
907
908                 if (ent != clent) // LordHavoc: always send player
909                 {
910                         if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
911                         {
912                                 if (val->edict == clentnum)
913                                         flags |= RENDER_VIEWMODEL; // show relative to the view
914                                 else
915                                 {
916                                         // don't show to anyone else
917                                         continue;
918                                 }
919                         }
920                         else
921                         {
922                                 // LordHavoc: never draw something told not to display to this client
923                                 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
924                                         continue;
925                                 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
926                                         continue;
927                         }
928                 }
929
930                 glowsize = 0;
931
932                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
933                         glowsize = (int) val->_float >> 2;
934                 glowsize = bound(0, glowsize, 255);
935
936                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
937                 if (val->_float != 0)
938                         flags |= RENDER_GLOWTRAIL;
939
940                 if (ent->v.modelindex >= 0 && ent->v.modelindex < MAX_MODELS && pr_strings[ent->v.model])
941                 {
942                         model = sv.models[(int)ent->v.modelindex];
943                         Mod_CheckLoaded(model);
944                 }
945                 else
946                 {
947                         model = NULL;
948                         if (ent != clent) // LordHavoc: always send player
949                                 if (glowsize == 0 && (flags & RENDER_GLOWTRAIL) == 0) // no effects
950                                         continue;
951                 }
952
953                 VectorCopy(ent->v.angles, angles);
954                 if (DotProduct(ent->v.velocity, ent->v.velocity) >= 1.0f && host_client->latency >= 0.01f)
955                 {
956                         VectorMA(ent->v.origin, host_client->latency, ent->v.velocity, origin);
957                         // LordHavoc: trace predicted movement to avoid putting things in walls
958                         trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, origin, MOVE_NORMAL, ent);
959                         VectorCopy(trace.endpos, origin);
960                 }
961                 else
962                 {
963                         VectorCopy(ent->v.origin, origin);
964                 }
965
966                 // ent has survived every check so far, check if it is visible
967                 // always send embedded brush models, they don't generate much traffic
968                 if (ent != clent && ((flags & RENDER_VIEWMODEL) == 0) && (model == NULL || model->type != mod_brush || model->name[0] != '*'))
969                 {
970                         // use the predicted origin
971                         entmins[0] = origin[0] - 1.0f;
972                         entmins[1] = origin[1] - 1.0f;
973                         entmins[2] = origin[2] - 1.0f;
974                         entmaxs[0] = origin[0] + 1.0f;
975                         entmaxs[1] = origin[1] + 1.0f;
976                         entmaxs[2] = origin[2] + 1.0f;
977                         // using the model's bounding box to ensure things are visible regardless of their physics box
978                         if (model)
979                         {
980                                 if (ent->v.angles[0] || ent->v.angles[2]) // pitch and roll
981                                 {
982                                         VectorAdd(entmins, model->rotatedmins, entmins);
983                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
984                                 }
985                                 else if (ent->v.angles[1])
986                                 {
987                                         VectorAdd(entmins, model->yawmins, entmins);
988                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
989                                 }
990                                 else
991                                 {
992                                         VectorAdd(entmins, model->normalmins, entmins);
993                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
994                                 }
995                         }
996
997                         totalentities++;
998
999                         // if not touching a visible leaf
1000                         if (sv_cullentities_pvs.integer && !SV_BoxTouchingPVS(pvs, entmins, entmaxs, sv.worldmodel->nodes))
1001                         {
1002                                 culled_pvs++;
1003                                 continue;
1004                         }
1005
1006                         // or not visible through the portals
1007                         if (sv_cullentities_portal.integer && !Portal_CheckBox(sv.worldmodel, testeye, entmins, entmaxs))
1008                         {
1009                                 culled_portal++;
1010                                 continue;
1011                         }
1012
1013                         if (sv_cullentities_trace.integer)
1014                         {
1015                                 // LordHavoc: test random offsets, to maximize chance of detection
1016                                 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
1017                                 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
1018                                 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
1019
1020                                 Collision_ClipTrace(&trace, NULL, sv.worldmodel, vec3_origin, vec3_origin, vec3_origin, vec3_origin, testeye, vec3_origin, vec3_origin, testorigin);
1021
1022                                 if (trace.fraction == 1)
1023                                         client->visibletime[e] = realtime + 1;
1024                                 else
1025                                 {
1026                                         if (realtime > client->visibletime[e])
1027                                         {
1028                                                 culled_trace++;
1029                                                 continue;
1030                                         }
1031                                 }
1032                         }
1033                         visibleentities++;
1034                 }
1035
1036                 alpha = 255;
1037                 scale = 16;
1038                 glowcolor = 254;
1039                 effects = ent->v.effects;
1040
1041                 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
1042                 if (val->_float != 0)
1043                         alpha = (int) (val->_float * 255.0);
1044
1045                 // HalfLife support
1046                 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
1047                 if (val->_float != 0)
1048                         alpha = (int) val->_float;
1049
1050                 if (alpha == 0)
1051                         alpha = 255;
1052                 alpha = bound(0, alpha, 255);
1053
1054                 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
1055                 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
1056                 if (scale < 0) scale = 0;
1057                 if (scale > 255) scale = 255;
1058
1059                 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
1060                 if (val->_float != 0)
1061                         glowcolor = (int) val->_float;
1062
1063                 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
1064                 if (val->_float != 0)
1065                         effects |= EF_FULLBRIGHT;
1066
1067                 if (ent != clent)
1068                 {
1069                         if (glowsize == 0 && (flags & RENDER_GLOWTRAIL) == 0) // no effects
1070                         {
1071                                 if (model) // model
1072                                 {
1073                                         // don't send if flagged for NODRAW and there are no effects
1074                                         if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
1075                                                 continue;
1076                                 }
1077                                 else // no model and no effects
1078                                         continue;
1079                         }
1080                 }
1081
1082                 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
1083                         flags |= RENDER_EXTERIORMODEL;
1084
1085                 if (ent->v.movetype == MOVETYPE_STEP)
1086                         flags |= RENDER_STEP;
1087                 // don't send an entity if it's coordinates would wrap around
1088                 if ((effects & EF_LOWPRECISION) && origin[0] >= -32768 && origin[1] >= -32768 && origin[2] >= -32768 && origin[0] <= 32767 && origin[1] <= 32767 && origin[2] <= 32767)
1089                         flags |= RENDER_LOWPRECISION;
1090
1091                 s = EntityFrame_NewEntity(&entityframe, e);
1092                 // if we run out of space, abort
1093                 if (!s)
1094                         break;
1095                 VectorCopy(origin, s->origin);
1096                 VectorCopy(angles, s->angles);
1097                 s->colormap = ent->v.colormap;
1098                 s->skin = ent->v.skin;
1099                 s->frame = ent->v.frame;
1100                 s->modelindex = ent->v.modelindex;
1101                 s->effects = effects;
1102                 s->alpha = alpha;
1103                 s->scale = scale;
1104                 s->glowsize = glowsize;
1105                 s->glowcolor = glowcolor;
1106                 s->flags = flags;
1107         }
1108         entityframe.framenum = ++client->entityframenumber;
1109         EntityFrame_Write(&client->entitydatabase, &entityframe, msg);
1110
1111         if (sv_cullentities_stats.integer)
1112                 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d portal %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_portal + culled_trace, culled_pvs, culled_portal, culled_trace);
1113 }
1114 #endif
1115
1116 /*
1117 =============
1118 SV_CleanupEnts
1119
1120 =============
1121 */
1122 void SV_CleanupEnts (void)
1123 {
1124         int             e;
1125         edict_t *ent;
1126
1127         ent = NEXT_EDICT(sv.edicts);
1128         for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1129                 ent->v.effects = (int)ent->v.effects & ~EF_MUZZLEFLASH;
1130 }
1131
1132 /*
1133 ==================
1134 SV_WriteClientdataToMessage
1135
1136 ==================
1137 */
1138 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1139 {
1140         int             bits;
1141         int             i;
1142         edict_t *other;
1143         int             items;
1144         eval_t  *val;
1145         vec3_t  punchvector;
1146         qbyte   viewzoom;
1147
1148 //
1149 // send a damage message
1150 //
1151         if (ent->v.dmg_take || ent->v.dmg_save)
1152         {
1153                 other = PROG_TO_EDICT(ent->v.dmg_inflictor);
1154                 MSG_WriteByte (msg, svc_damage);
1155                 MSG_WriteByte (msg, ent->v.dmg_save);
1156                 MSG_WriteByte (msg, ent->v.dmg_take);
1157                 for (i=0 ; i<3 ; i++)
1158                         MSG_WriteDPCoord (msg, other->v.origin[i] + 0.5*(other->v.mins[i] + other->v.maxs[i]));
1159
1160                 ent->v.dmg_take = 0;
1161                 ent->v.dmg_save = 0;
1162         }
1163
1164 //
1165 // send the current viewpos offset from the view entity
1166 //
1167         SV_SetIdealPitch ();            // how much to look up / down ideally
1168
1169 // a fixangle might get lost in a dropped packet.  Oh well.
1170         if ( ent->v.fixangle )
1171         {
1172                 MSG_WriteByte (msg, svc_setangle);
1173                 for (i=0 ; i < 3 ; i++)
1174                         MSG_WriteAngle (msg, ent->v.angles[i] );
1175                 ent->v.fixangle = 0;
1176         }
1177
1178         bits = 0;
1179
1180         //if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT)
1181                 bits |= SU_VIEWHEIGHT;
1182
1183         if (ent->v.idealpitch)
1184                 bits |= SU_IDEALPITCH;
1185
1186 // stuff the sigil bits into the high bits of items for sbar, or else
1187 // mix in items2
1188         val = GETEDICTFIELDVALUE(ent, eval_items2);
1189
1190         if (val)
1191                 items = (int)ent->v.items | ((int)val->_float << 23);
1192         else
1193                 items = (int)ent->v.items | ((int)pr_global_struct->serverflags << 28);
1194
1195         bits |= SU_ITEMS;
1196
1197         if ( (int)ent->v.flags & FL_ONGROUND)
1198                 bits |= SU_ONGROUND;
1199
1200         if ( ent->v.waterlevel >= 2)
1201                 bits |= SU_INWATER;
1202
1203         // dpprotocol
1204         VectorClear(punchvector);
1205         if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1206                 VectorCopy(val->vector, punchvector);
1207
1208         i = 255;
1209         if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1210         {
1211                 i = val->_float * 255.0f;
1212                 if (i == 0)
1213                         i = 255;
1214                 else
1215                         i = bound(0, i, 255);
1216         }
1217         viewzoom = i;
1218
1219         if (viewzoom != 255)
1220                 bits |= SU_VIEWZOOM;
1221
1222         for (i=0 ; i<3 ; i++)
1223         {
1224                 if (ent->v.punchangle[i])
1225                         bits |= (SU_PUNCH1<<i);
1226                 if (punchvector[i]) // dpprotocol
1227                         bits |= (SU_PUNCHVEC1<<i); // dpprotocol
1228                 if (ent->v.velocity[i])
1229                         bits |= (SU_VELOCITY1<<i);
1230         }
1231
1232         if (ent->v.weaponframe)
1233                 bits |= SU_WEAPONFRAME;
1234
1235         if (ent->v.armorvalue)
1236                 bits |= SU_ARMOR;
1237
1238 //      if (ent->v.weapon)
1239                 bits |= SU_WEAPON;
1240
1241         if (bits >= 65536)
1242                 bits |= SU_EXTEND1;
1243         if (bits >= 16777216)
1244                 bits |= SU_EXTEND2;
1245
1246 // send the data
1247
1248         MSG_WriteByte (msg, svc_clientdata);
1249         MSG_WriteShort (msg, bits);
1250         if (bits & SU_EXTEND1)
1251                 MSG_WriteByte(msg, bits >> 16);
1252         if (bits & SU_EXTEND2)
1253                 MSG_WriteByte(msg, bits >> 24);
1254
1255         if (bits & SU_VIEWHEIGHT)
1256                 //MSG_WriteChar (msg, ent->v.view_ofs[2]);
1257                 MSG_WriteChar (msg, 0);
1258
1259         if (bits & SU_IDEALPITCH)
1260                 MSG_WriteChar (msg, ent->v.idealpitch);
1261
1262         for (i=0 ; i<3 ; i++)
1263         {
1264                 if (bits & (SU_PUNCH1<<i))
1265                         MSG_WritePreciseAngle(msg, ent->v.punchangle[i]); // dpprotocol
1266                 if (bits & (SU_PUNCHVEC1<<i)) // dpprotocol
1267                         MSG_WriteDPCoord(msg, punchvector[i]); // dpprotocol
1268                 if (bits & (SU_VELOCITY1<<i))
1269                         MSG_WriteChar (msg, ent->v.velocity[i]/16);
1270         }
1271
1272 // [always sent]        if (bits & SU_ITEMS)
1273         MSG_WriteLong (msg, items);
1274
1275         if (bits & SU_WEAPONFRAME)
1276                 MSG_WriteByte (msg, ent->v.weaponframe);
1277         if (bits & SU_ARMOR)
1278                 MSG_WriteByte (msg, ent->v.armorvalue);
1279         if (bits & SU_WEAPON)
1280                 MSG_WriteByte (msg, SV_ModelIndex(pr_strings+ent->v.weaponmodel));
1281
1282         MSG_WriteShort (msg, ent->v.health);
1283         MSG_WriteByte (msg, ent->v.currentammo);
1284         MSG_WriteByte (msg, ent->v.ammo_shells);
1285         MSG_WriteByte (msg, ent->v.ammo_nails);
1286         MSG_WriteByte (msg, ent->v.ammo_rockets);
1287         MSG_WriteByte (msg, ent->v.ammo_cells);
1288
1289         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE)
1290         {
1291                 for(i=0;i<32;i++)
1292                 {
1293                         if ( ((int)ent->v.weapon) & (1<<i) )
1294                         {
1295                                 MSG_WriteByte (msg, i);
1296                                 break;
1297                         }
1298                 }
1299         }
1300         else
1301         {
1302                 MSG_WriteByte (msg, ent->v.weapon);
1303         }
1304
1305         if (bits & SU_VIEWZOOM)
1306                 MSG_WriteByte (msg, viewzoom);
1307 }
1308
1309 /*
1310 =======================
1311 SV_SendClientDatagram
1312 =======================
1313 */
1314 qboolean SV_SendClientDatagram (client_t *client)
1315 {
1316         qbyte           buf[MAX_DATAGRAM];
1317         sizebuf_t       msg;
1318
1319         msg.data = buf;
1320         msg.maxsize = sizeof(buf);
1321         msg.cursize = 0;
1322
1323         MSG_WriteByte (&msg, svc_time);
1324         MSG_WriteFloat (&msg, sv.time);
1325
1326         if (client->spawned)
1327         {
1328                 // add the client specific data to the datagram
1329                 SV_WriteClientdataToMessage (client->edict, &msg);
1330
1331                 SV_WriteEntitiesToClient (client, client->edict, &msg);
1332
1333                 // copy the server datagram if there is space
1334                 if (msg.cursize + sv.datagram.cursize < msg.maxsize)
1335                         SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1336         }
1337
1338 // send the datagram
1339         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
1340         {
1341                 SV_DropClient (true);// if the message couldn't send, kick off
1342                 return false;
1343         }
1344
1345         return true;
1346 }
1347
1348 /*
1349 =======================
1350 SV_UpdateToReliableMessages
1351 =======================
1352 */
1353 void SV_UpdateToReliableMessages (void)
1354 {
1355         int                     i, j;
1356         client_t *client;
1357
1358 // check for changes to be sent over the reliable streams
1359         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1360         {
1361                 if (host_client->old_frags != host_client->edict->v.frags)
1362                 {
1363                         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1364                         {
1365                                 if (!client->active || !client->spawned)
1366                                         continue;
1367                                 MSG_WriteByte (&client->message, svc_updatefrags);
1368                                 MSG_WriteByte (&client->message, i);
1369                                 MSG_WriteShort (&client->message, host_client->edict->v.frags);
1370                         }
1371
1372                         host_client->old_frags = host_client->edict->v.frags;
1373                 }
1374         }
1375
1376         for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
1377         {
1378                 if (!client->active)
1379                         continue;
1380                 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1381         }
1382
1383         SZ_Clear (&sv.reliable_datagram);
1384 }
1385
1386
1387 /*
1388 =======================
1389 SV_SendNop
1390
1391 Send a nop message without trashing or sending the accumulated client
1392 message buffer
1393 =======================
1394 */
1395 void SV_SendNop (client_t *client)
1396 {
1397         sizebuf_t       msg;
1398         qbyte           buf[4];
1399
1400         msg.data = buf;
1401         msg.maxsize = sizeof(buf);
1402         msg.cursize = 0;
1403
1404         MSG_WriteChar (&msg, svc_nop);
1405
1406         if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
1407                 SV_DropClient (true);   // if the message couldn't send, kick off
1408         client->last_message = realtime;
1409 }
1410
1411 /*
1412 =======================
1413 SV_SendClientMessages
1414 =======================
1415 */
1416 void SV_SendClientMessages (void)
1417 {
1418         int                     i;
1419
1420 // update frags, names, etc
1421         SV_UpdateToReliableMessages ();
1422
1423 // build individual updates
1424         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1425         {
1426                 if (!host_client->active)
1427                         continue;
1428
1429 #ifndef NOROUTINGFIX
1430                 if (host_client->sendserverinfo)
1431                 {
1432                         host_client->sendserverinfo = false;
1433                         SV_SendServerinfo (host_client);
1434                 }
1435 #endif
1436
1437                 if (host_client->spawned)
1438                 {
1439                         if (!SV_SendClientDatagram (host_client))
1440                                 continue;
1441                 }
1442                 else
1443                 {
1444                 // the player isn't totally in the game yet
1445                 // send small keepalive messages if too much time has passed
1446                 // send a full message when the next signon stage has been requested
1447                 // some other message data (name changes, etc) may accumulate
1448                 // between signon stages
1449                         if (!host_client->sendsignon)
1450                         {
1451                                 if (realtime - host_client->last_message > 5)
1452                                         SV_SendNop (host_client);
1453                                 continue;       // don't send out non-signon messages
1454                         }
1455                 }
1456
1457                 // check for an overflowed message.  Should only happen
1458                 // on a very fucked up connection that backs up a lot, then
1459                 // changes level
1460                 if (host_client->message.overflowed)
1461                 {
1462                         SV_DropClient (true);
1463                         host_client->message.overflowed = false;
1464                         continue;
1465                 }
1466
1467                 if (host_client->message.cursize || host_client->dropasap)
1468                 {
1469                         if (!NET_CanSendMessage (host_client->netconnection))
1470                         {
1471 //                              I_Printf ("can't write\n");
1472                                 continue;
1473                         }
1474
1475                         if (host_client->dropasap)
1476                                 SV_DropClient (false);  // went to another level
1477                         else
1478                         {
1479                                 if (NET_SendMessage (host_client->netconnection, &host_client->message) == -1)
1480                                         SV_DropClient (true);   // if the message couldn't send, kick off
1481                                 SZ_Clear (&host_client->message);
1482                                 host_client->last_message = realtime;
1483                                 host_client->sendsignon = false;
1484                         }
1485                 }
1486         }
1487
1488
1489 // clear muzzle flashes
1490         SV_CleanupEnts ();
1491 }
1492
1493
1494 /*
1495 ==============================================================================
1496
1497 SERVER SPAWNING
1498
1499 ==============================================================================
1500 */
1501
1502 /*
1503 ================
1504 SV_ModelIndex
1505
1506 ================
1507 */
1508 int SV_ModelIndex (char *name)
1509 {
1510         int             i;
1511
1512         if (!name || !name[0])
1513                 return 0;
1514
1515         for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1516                 if (!strcmp(sv.model_precache[i], name))
1517                         return i;
1518         if (i==MAX_MODELS || !sv.model_precache[i])
1519                 Host_Error ("SV_ModelIndex: model %s not precached", name);
1520         return i;
1521 }
1522
1523 #ifdef SV_QUAKEENTITIES
1524 /*
1525 ================
1526 SV_CreateBaseline
1527
1528 ================
1529 */
1530 void SV_CreateBaseline (void)
1531 {
1532         int i, entnum, large;
1533         edict_t *svent;
1534
1535         // LordHavoc: clear *all* states (note just active ones)
1536         for (entnum = 0; entnum < MAX_EDICTS ; entnum++)
1537         {
1538                 // get the current server version
1539                 svent = EDICT_NUM(entnum);
1540
1541                 // LordHavoc: always clear state values, whether the entity is in use or not
1542                 ClearStateToDefault(&svent->baseline);
1543
1544                 if (svent->free)
1545                         continue;
1546                 if (entnum > svs.maxclients && !svent->v.modelindex)
1547                         continue;
1548
1549                 // create entity baseline
1550                 VectorCopy (svent->v.origin, svent->baseline.origin);
1551                 VectorCopy (svent->v.angles, svent->baseline.angles);
1552                 svent->baseline.frame = svent->v.frame;
1553                 svent->baseline.skin = svent->v.skin;
1554                 if (entnum > 0 && entnum <= svs.maxclients)
1555                 {
1556                         svent->baseline.colormap = entnum;
1557                         svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1558                 }
1559                 else
1560                 {
1561                         svent->baseline.colormap = 0;
1562                         svent->baseline.modelindex = svent->v.modelindex; //SV_ModelIndex(pr_strings + svent->v.model);
1563                 }
1564
1565                 large = false;
1566                 if (svent->baseline.modelindex & 0xFF00 || svent->baseline.frame & 0xFF00)
1567                         large = true;
1568
1569                 // add to the message
1570                 if (large)
1571                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1572                 else
1573                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1574                 MSG_WriteShort (&sv.signon, entnum);
1575
1576                 if (large)
1577                 {
1578                         MSG_WriteShort (&sv.signon, svent->baseline.modelindex);
1579                         MSG_WriteShort (&sv.signon, svent->baseline.frame);
1580                 }
1581                 else
1582                 {
1583                         MSG_WriteByte (&sv.signon, svent->baseline.modelindex);
1584                         MSG_WriteByte (&sv.signon, svent->baseline.frame);
1585                 }
1586                 MSG_WriteByte (&sv.signon, svent->baseline.colormap);
1587                 MSG_WriteByte (&sv.signon, svent->baseline.skin);
1588                 for (i=0 ; i<3 ; i++)
1589                 {
1590                         MSG_WriteDPCoord(&sv.signon, svent->baseline.origin[i]);
1591                         MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]);
1592                 }
1593         }
1594 }
1595 #endif
1596
1597
1598 /*
1599 ================
1600 SV_SendReconnect
1601
1602 Tell all the clients that the server is changing levels
1603 ================
1604 */
1605 void SV_SendReconnect (void)
1606 {
1607         char    data[128];
1608         sizebuf_t       msg;
1609
1610         msg.data = data;
1611         msg.cursize = 0;
1612         msg.maxsize = sizeof(data);
1613
1614         MSG_WriteChar (&msg, svc_stufftext);
1615         MSG_WriteString (&msg, "reconnect\n");
1616         NET_SendToAll (&msg, 5);
1617         
1618         if (cls.state != ca_dedicated)
1619                 Cmd_ExecuteString ("reconnect\n", src_command);
1620 }
1621
1622
1623 /*
1624 ================
1625 SV_SaveSpawnparms
1626
1627 Grabs the current state of each client for saving across the
1628 transition to another level
1629 ================
1630 */
1631 void SV_SaveSpawnparms (void)
1632 {
1633         int             i, j;
1634
1635         svs.serverflags = pr_global_struct->serverflags;
1636
1637         for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1638         {
1639                 if (!host_client->active)
1640                         continue;
1641
1642         // call the progs to get default spawn parms for the new client
1643                 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1644                 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1645                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1646                         host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1647         }
1648 }
1649
1650 /*
1651 ================
1652 SV_SpawnServer
1653
1654 This is called at the start of each level
1655 ================
1656 */
1657 extern float            scr_centertime_off;
1658
1659 void SV_SpawnServer (char *server)
1660 {
1661         edict_t         *ent;
1662         int                     i;
1663
1664         // let's not have any servers with no name
1665         if (hostname.string[0] == 0)
1666                 Cvar_Set ("hostname", "UNNAMED");
1667         scr_centertime_off = 0;
1668
1669         Con_DPrintf ("SpawnServer: %s\n",server);
1670         svs.changelevel_issued = false;         // now safe to issue another
1671
1672 //
1673 // tell all connected clients that we are going to a new level
1674 //
1675         if (sv.active)
1676                 SV_SendReconnect ();
1677
1678 //
1679 // make cvars consistant
1680 //
1681         if (coop.integer)
1682                 Cvar_SetValue ("deathmatch", 0);
1683         current_skill = bound(0, (int)(skill.value + 0.5), 3);
1684
1685         Cvar_SetValue ("skill", (float)current_skill);
1686
1687 //
1688 // set up the new server
1689 //
1690         Host_ClearMemory ();
1691
1692         memset (&sv, 0, sizeof(sv));
1693
1694         strcpy (sv.name, server);
1695
1696 // load progs to get entity field count
1697         PR_LoadProgs ();
1698
1699 // allocate server memory
1700         sv.max_edicts = MAX_EDICTS;
1701
1702         // clear the edict memory pool
1703         Mem_EmptyPool(sv_edicts_mempool);
1704         sv.edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1705
1706         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1707         sv.datagram.cursize = 0;
1708         sv.datagram.data = sv.datagram_buf;
1709
1710         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1711         sv.reliable_datagram.cursize = 0;
1712         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1713
1714         sv.signon.maxsize = sizeof(sv.signon_buf);
1715         sv.signon.cursize = 0;
1716         sv.signon.data = sv.signon_buf;
1717
1718 // leave slots at start for clients only
1719         sv.num_edicts = svs.maxclients+1;
1720         for (i=0 ; i<svs.maxclients ; i++)
1721         {
1722                 ent = EDICT_NUM(i+1);
1723                 svs.clients[i].edict = ent;
1724         }
1725
1726         sv.state = ss_loading;
1727         sv.paused = false;
1728
1729         sv.time = 1.0;
1730
1731         Mod_ClearUsed();
1732
1733         strcpy (sv.name, server);
1734         sprintf (sv.modelname,"maps/%s.bsp", server);
1735         sv.worldmodel = Mod_ForName(sv.modelname, false, true, true);
1736         if (!sv.worldmodel)
1737         {
1738                 Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
1739                 sv.active = false;
1740                 return;
1741         }
1742         sv.models[1] = sv.worldmodel;
1743
1744 //
1745 // clear world interaction links
1746 //
1747         SV_ClearWorld ();
1748
1749         sv.sound_precache[0] = pr_strings;
1750
1751         sv.model_precache[0] = pr_strings;
1752         sv.model_precache[1] = sv.modelname;
1753         for (i = 1;i < sv.worldmodel->numsubmodels;i++)
1754         {
1755                 sv.model_precache[i+1] = localmodels[i];
1756                 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1757         }
1758
1759 //
1760 // load the rest of the entities
1761 //
1762         ent = EDICT_NUM(0);
1763         memset (&ent->v, 0, progs->entityfields * 4);
1764         ent->free = false;
1765         ent->v.model = sv.worldmodel->name - pr_strings;
1766         ent->v.modelindex = 1;          // world model
1767         ent->v.solid = SOLID_BSP;
1768         ent->v.movetype = MOVETYPE_PUSH;
1769
1770         if (coop.integer)
1771                 pr_global_struct->coop = coop.integer;
1772         else
1773                 pr_global_struct->deathmatch = deathmatch.integer;
1774
1775         pr_global_struct->mapname = sv.name - pr_strings;
1776
1777 // serverflags are for cross level information (sigils)
1778         pr_global_struct->serverflags = svs.serverflags;
1779
1780         ED_LoadFromFile (sv.worldmodel->entities);
1781         // LordHavoc: clear world angles (to fix e3m3.bsp)
1782         VectorClear(sv.edicts->v.angles);
1783
1784         sv.active = true;
1785
1786 // all setup is completed, any further precache statements are errors
1787         sv.state = ss_active;
1788
1789 // run two frames to allow everything to settle
1790         sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1791         SV_Physics ();
1792         sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1793         SV_Physics ();
1794
1795         Mod_PurgeUnused();
1796
1797 #ifdef QUAKEENTITIES
1798 // create a baseline for more efficient communications
1799         SV_CreateBaseline ();
1800 #endif
1801
1802 // send serverinfo to all connected clients
1803         for (i=0,host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
1804                 if (host_client->active)
1805                         SV_SendServerinfo (host_client);
1806
1807         Con_DPrintf ("Server spawned.\n");
1808 }