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