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