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