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