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