upgraded network protocol to DP5, now sends precise entity angles (except for EF_LOWP...
[divverent/darkplaces.git] / sv_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sv_main.c -- server main program
21
22 #include "quakedef.h"
23
24 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "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_DARKPLACES5);
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                 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[0]*256;
809                 cs.light[0] = (unsigned short)bound(0, f, 65535);
810                 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[1]*256;
811                 cs.light[1] = (unsigned short)bound(0, f, 65535);
812                 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[2]*256;
813                 cs.light[2] = (unsigned short)bound(0, f, 65535);
814                 f = GETEDICTFIELDVALUE(ent, eval_light_lev)->_float;
815                 cs.light[3] = (unsigned short)bound(0, f, 65535);
816                 cs.lightstyle = (qbyte)GETEDICTFIELDVALUE(ent, eval_style)->_float;
817                 cs.lightpflags = (qbyte)GETEDICTFIELDVALUE(ent, eval_pflags)->_float;
818
819                 cs.specialvisibilityradius = cs.light[3];
820                 if (cs.glowsize)
821                         cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.glowsize * 4);
822                 if (cs.flags & RENDER_GLOWTRAIL)
823                         cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
824                 if (cs.effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
825                 {
826                         if (cs.effects & EF_BRIGHTFIELD)
827                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 80);
828                         if (cs.effects & EF_MUZZLEFLASH)
829                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
830                         if (cs.effects & EF_BRIGHTLIGHT)
831                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 400);
832                         if (cs.effects & EF_DIMLIGHT)
833                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
834                         if (cs.effects & EF_RED)
835                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
836                         if (cs.effects & EF_BLUE)
837                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
838                         if (cs.effects & EF_FLAME)
839                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 250);
840                         if (cs.effects & EF_STARDUST)
841                                 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
842                 }
843
844                 if (numsendentities >= MAX_EDICTS)
845                         continue;
846                 // we can omit invisible entities with no effects that are not clients
847                 // LordHavoc: this could kill tags attached to an invisible entity, I
848                 // just hope we never have to support that case
849                 if (cs.number > svs.maxclients && ((cs.effects & EF_NODRAW) || (!cs.modelindex && !cs.specialvisibilityradius)))
850                         continue;
851                 sendentitiesindex[e] = sendentities + numsendentities;
852                 sendentities[numsendentities++] = cs;
853         }
854 }
855
856 static int sententitiesmark = 0;
857 static int sententities[MAX_EDICTS];
858 static int sententitiesconsideration[MAX_EDICTS];
859 static int sv_writeentitiestoclient_culled_pvs;
860 static int sv_writeentitiestoclient_culled_trace;
861 static int sv_writeentitiestoclient_visibleentities;
862 static int sv_writeentitiestoclient_totalentities;
863 //static entity_frame_t sv_writeentitiestoclient_entityframe;
864 static int sv_writeentitiestoclient_clentnum;
865 static vec3_t sv_writeentitiestoclient_testeye;
866 static client_t *sv_writeentitiestoclient_client;
867
868 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
869 {
870         vec3_t entmins, entmaxs, lightmins, lightmaxs, testorigin;
871         model_t *model;
872         trace_t trace;
873         if (sententitiesconsideration[s->number] == sententitiesmark)
874                 return;
875         sententitiesconsideration[s->number] = sententitiesmark;
876         // viewmodels don't have visibility checking
877         if (s->viewmodelforclient)
878         {
879                 if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
880                         return;
881         }
882         // never reject player
883         else if (s->number != sv_writeentitiestoclient_clentnum)
884         {
885                 // check various rejection conditions
886                 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
887                         return;
888                 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
889                         return;
890                 if (s->effects & EF_NODRAW)
891                         return;
892                 // LordHavoc: only send entities with a model or important effects
893                 if (!s->modelindex && s->specialvisibilityradius == 0)
894                         return;
895                 if (s->tagentity)
896                 {
897                         // tag attached entities simply check their parent
898                         if (!sendentitiesindex[s->tagentity])
899                                 return;
900                         SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
901                         if (sententities[s->tagentity] != sententitiesmark)
902                                 return;
903                 }
904                 // always send world submodels, they don't generate much traffic
905                 else if ((model = sv.models[s->modelindex]) == NULL || model->name[0] != '*')
906                 {
907                         Mod_CheckLoaded(model);
908                         // entity has survived every check so far, check if visible
909                         // enlarged box to account for prediction (not that there is
910                         // any currently, but still helps the 'run into a room and
911                         // watch items pop up' problem)
912                         entmins[0] = s->origin[0] - 32.0f;
913                         entmins[1] = s->origin[1] - 32.0f;
914                         entmins[2] = s->origin[2] - 32.0f;
915                         entmaxs[0] = s->origin[0] + 32.0f;
916                         entmaxs[1] = s->origin[1] + 32.0f;
917                         entmaxs[2] = s->origin[2] + 32.0f;
918                         // using the model's bounding box to ensure things are visible regardless of their physics box
919                         if (model)
920                         {
921                                 if (s->angles[0] || s->angles[2]) // pitch and roll
922                                 {
923                                         VectorAdd(entmins, model->rotatedmins, entmins);
924                                         VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
925                                 }
926                                 else if (s->angles[1])
927                                 {
928                                         VectorAdd(entmins, model->yawmins, entmins);
929                                         VectorAdd(entmaxs, model->yawmaxs, entmaxs);
930                                 }
931                                 else
932                                 {
933                                         VectorAdd(entmins, model->normalmins, entmins);
934                                         VectorAdd(entmaxs, model->normalmaxs, entmaxs);
935                                 }
936                         }
937                         lightmins[0] = min(entmins[0], s->origin[0] - s->specialvisibilityradius);
938                         lightmins[1] = min(entmins[1], s->origin[1] - s->specialvisibilityradius);
939                         lightmins[2] = min(entmins[2], s->origin[2] - s->specialvisibilityradius);
940                         lightmaxs[0] = min(entmaxs[0], s->origin[0] + s->specialvisibilityradius);
941                         lightmaxs[1] = min(entmaxs[1], s->origin[1] + s->specialvisibilityradius);
942                         lightmaxs[2] = min(entmaxs[2], s->origin[2] + s->specialvisibilityradius);
943                         sv_writeentitiestoclient_totalentities++;
944                         // if not touching a visible leaf
945                         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))
946                         {
947                                 sv_writeentitiestoclient_culled_pvs++;
948                                 return;
949                         }
950                         // or not seen by random tracelines
951                         if (sv_cullentities_trace.integer)
952                         {
953                                 // LordHavoc: test center first
954                                 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
955                                 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
956                                 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
957                                 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
958                                 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
959                                         sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
960                                 else
961                                 {
962                                         // LordHavoc: test random offsets, to maximize chance of detection
963                                         testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
964                                         testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
965                                         testorigin[2] = lhrandom(entmins[2], entmaxs[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                                         else
970                                         {
971                                                 if (s->specialvisibilityradius)
972                                                 {
973                                                         // LordHavoc: test random offsets, to maximize chance of detection
974                                                         testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
975                                                         testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
976                                                         testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
977                                                         sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
978                                                         if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
979                                                                 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
980                                                 }
981                                         }
982                                 }
983                                 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
984                                 {
985                                         sv_writeentitiestoclient_culled_trace++;
986                                         return;
987                                 }
988                         }
989                         sv_writeentitiestoclient_visibleentities++;
990                 }
991         }
992         // this just marks it for sending
993         // FIXME: it would be more efficient to send here, but the entity
994         // compressor isn't that flexible
995         sententities[s->number] = sententitiesmark;
996 }
997
998 void SV_WriteEntitiesToClient(client_t *client, edict_t *clent, sizebuf_t *msg)
999 {
1000         int i;
1001         vec3_t testorigin;
1002         entity_state_t *s;
1003         entity_database4_t *d;
1004         int n, startnumber;
1005         entity_state_t *e, inactiveentitystate;
1006         sizebuf_t buf;
1007         qbyte data[128];
1008
1009         // if there isn't enough space to accomplish anything, skip it
1010         if (msg->cursize + 24 > msg->maxsize)
1011                 return;
1012
1013         // prepare the buffer
1014         memset(&buf, 0, sizeof(buf));
1015         buf.data = data;
1016         buf.maxsize = sizeof(data);
1017
1018         d = client->entitydatabase4;
1019
1020         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1021                 if (!d->commit[i].numentities)
1022                         break;
1023         // if commit buffer full, just don't bother writing an update this frame
1024         if (i == MAX_ENTITY_HISTORY)
1025                 return;
1026         d->currentcommit = d->commit + i;
1027
1028         // this state's number gets played around with later
1029         ClearStateToDefault(&inactiveentitystate);
1030         //inactiveentitystate = defaultstate;
1031
1032         sv_writeentitiestoclient_client = client;
1033
1034         sv_writeentitiestoclient_culled_pvs = 0;
1035         sv_writeentitiestoclient_culled_trace = 0;
1036         sv_writeentitiestoclient_visibleentities = 0;
1037         sv_writeentitiestoclient_totalentities = 0;
1038
1039         Mod_CheckLoaded(sv.worldmodel);
1040
1041 // find the client's PVS
1042         // the real place being tested from
1043         VectorAdd(clent->v->origin, clent->v->view_ofs, sv_writeentitiestoclient_testeye);
1044         sv_writeentitiestoclient_pvsbytes = 0;
1045         if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1046                 sv_writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv_writeentitiestoclient_testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
1047
1048         sv_writeentitiestoclient_clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1049
1050         sententitiesmark++;
1051
1052         // the place being reported (to consider the fact the client still
1053         // applies the view_ofs[2], so we have to only send the fractional part
1054         // of view_ofs[2], undoing what the client will redo)
1055         VectorCopy(sv_writeentitiestoclient_testeye, testorigin);
1056         i = (int) clent->v->view_ofs[2] & 255;
1057         if (i >= 128)
1058                 i -= 256;
1059         testorigin[2] -= (float) i;
1060
1061         for (i = 0;i < numsendentities;i++)
1062                 SV_MarkWriteEntityStateToClient(sendentities + i);
1063
1064         d->currentcommit->numentities = 0;
1065         d->currentcommit->framenum = ++client->entityframenumber;
1066         MSG_WriteByte(msg, svc_entities);
1067         MSG_WriteLong(msg, d->referenceframenum);
1068         MSG_WriteLong(msg, d->currentcommit->framenum);
1069         if (developer_networkentities.integer >= 1)
1070         {
1071                 Con_Printf("send svc_entities ref:%i num:%i (database: ref:%i commits:", d->referenceframenum, d->currentcommit->framenum, d->referenceframenum);
1072                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1073                         if (d->commit[i].numentities)
1074                                 Con_Printf(" %i", d->commit[i].framenum);
1075                 Con_Printf(")\n");
1076         }
1077         if (d->currententitynumber >= sv.max_edicts)
1078                 startnumber = 1;
1079         else
1080                 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1081         MSG_WriteShort(msg, startnumber);
1082         // reset currententitynumber so if the loop does not break it we will
1083         // start at beginning next frame (if it does break, it will set it)
1084         d->currententitynumber = 1;
1085         for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1086         {
1087                 // find the old state to delta from
1088                 e = EntityFrame4_GetReferenceEntity(d, n);
1089                 // prepare the buffer
1090                 SZ_Clear(&buf);
1091                 // make the message
1092                 if (sententities[n] == sententitiesmark)
1093                 {
1094                         // entity exists, build an update (if empty there is no change)
1095                         // find the state in the list
1096                         for (;i < numsendentities && sendentities[i].number < n;i++);
1097                         s = sendentities + i;
1098                         if (s->number != n)
1099                                 Sys_Error("SV_WriteEntitiesToClient: s->number != n\n");
1100                         // build the update
1101                         if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1102                         {
1103                                 s->flags |= RENDER_EXTERIORMODEL;
1104                                 EntityState_Write(s, &buf, e);
1105                                 s->flags &= ~RENDER_EXTERIORMODEL;
1106                         }
1107                         else
1108                                 EntityState_Write(s, &buf, e);
1109                 }
1110                 else
1111                 {
1112                         s = &inactiveentitystate;
1113                         s->number = n;
1114                         if (e->active)
1115                         {
1116                                 // entity used to exist but doesn't anymore, send remove
1117                                 MSG_WriteShort(&buf, n | 0x8000);
1118                         }
1119                 }
1120                 // if the commit is full, we're done this frame
1121                 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1122                 {
1123                         // next frame we will continue where we left off
1124                         break;
1125                 }
1126                 // add the entity to the commit
1127                 EntityFrame4_AddCommitEntity(d, s);
1128                 // if the message is empty, skip out now
1129                 if (buf.cursize)
1130                 {
1131                         // write the message to the packet
1132                         SZ_Write(msg, buf.data, buf.cursize);
1133                 }
1134         }
1135         d->currententitynumber = n;
1136
1137         // remove world message (invalid, and thus a good terminator)
1138         MSG_WriteShort(msg, 0x8000);
1139         // write the number of the end entity
1140         MSG_WriteShort(msg, d->currententitynumber);
1141         // just to be sure
1142         d->currentcommit = NULL;
1143
1144         if (sv_cullentities_stats.integer)
1145                 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);
1146 }
1147 #endif
1148
1149 /*
1150 =============
1151 SV_CleanupEnts
1152
1153 =============
1154 */
1155 void SV_CleanupEnts (void)
1156 {
1157         int             e;
1158         edict_t *ent;
1159
1160         ent = NEXT_EDICT(sv.edicts);
1161         for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1162                 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1163 }
1164
1165 /*
1166 ==================
1167 SV_WriteClientdataToMessage
1168
1169 ==================
1170 */
1171 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1172 {
1173         int             bits;
1174         int             i;
1175         edict_t *other;
1176         int             items;
1177         eval_t  *val;
1178         vec3_t  punchvector;
1179         qbyte   viewzoom;
1180
1181 //
1182 // send a damage message
1183 //
1184         if (ent->v->dmg_take || ent->v->dmg_save)
1185         {
1186                 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1187                 MSG_WriteByte (msg, svc_damage);
1188                 MSG_WriteByte (msg, ent->v->dmg_save);
1189                 MSG_WriteByte (msg, ent->v->dmg_take);
1190                 for (i=0 ; i<3 ; i++)
1191                         MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1192
1193                 ent->v->dmg_take = 0;
1194                 ent->v->dmg_save = 0;
1195         }
1196
1197 //
1198 // send the current viewpos offset from the view entity
1199 //
1200         SV_SetIdealPitch ();            // how much to look up / down ideally
1201
1202 // a fixangle might get lost in a dropped packet.  Oh well.
1203         if ( ent->v->fixangle )
1204         {
1205                 MSG_WriteByte (msg, svc_setangle);
1206                 for (i=0 ; i < 3 ; i++)
1207                         MSG_WriteAngle (msg, ent->v->angles[i] );
1208                 ent->v->fixangle = 0;
1209         }
1210
1211         bits = 0;
1212
1213         if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1214                 bits |= SU_VIEWHEIGHT;
1215
1216         if (ent->v->idealpitch)
1217                 bits |= SU_IDEALPITCH;
1218
1219 // stuff the sigil bits into the high bits of items for sbar, or else
1220 // mix in items2
1221         val = GETEDICTFIELDVALUE(ent, eval_items2);
1222
1223         if (val)
1224                 items = (int)ent->v->items | ((int)val->_float << 23);
1225         else
1226                 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1227
1228         bits |= SU_ITEMS;
1229
1230         if ( (int)ent->v->flags & FL_ONGROUND)
1231                 bits |= SU_ONGROUND;
1232
1233         if ( ent->v->waterlevel >= 2)
1234                 bits |= SU_INWATER;
1235
1236         // PROTOCOL_DARKPLACES
1237         VectorClear(punchvector);
1238         if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1239                 VectorCopy(val->vector, punchvector);
1240
1241         i = 255;
1242         if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1243         {
1244                 i = val->_float * 255.0f;
1245                 if (i == 0)
1246                         i = 255;
1247                 else
1248                         i = bound(0, i, 255);
1249         }
1250         viewzoom = i;
1251
1252         if (viewzoom != 255)
1253                 bits |= SU_VIEWZOOM;
1254
1255         for (i=0 ; i<3 ; i++)
1256         {
1257                 if (ent->v->punchangle[i])
1258                         bits |= (SU_PUNCH1<<i);
1259                 if (punchvector[i]) // PROTOCOL_DARKPLACES
1260                         bits |= (SU_PUNCHVEC1<<i); // PROTOCOL_DARKPLACES
1261                 if (ent->v->velocity[i])
1262                         bits |= (SU_VELOCITY1<<i);
1263         }
1264
1265         if (ent->v->weaponframe)
1266                 bits |= SU_WEAPONFRAME;
1267
1268         if (ent->v->armorvalue)
1269                 bits |= SU_ARMOR;
1270
1271         bits |= SU_WEAPON;
1272
1273         if (bits >= 65536)
1274                 bits |= SU_EXTEND1;
1275         if (bits >= 16777216)
1276                 bits |= SU_EXTEND2;
1277
1278 // send the data
1279
1280         MSG_WriteByte (msg, svc_clientdata);
1281         MSG_WriteShort (msg, bits);
1282         if (bits & SU_EXTEND1)
1283                 MSG_WriteByte(msg, bits >> 16);
1284         if (bits & SU_EXTEND2)
1285                 MSG_WriteByte(msg, bits >> 24);
1286
1287         if (bits & SU_VIEWHEIGHT)
1288                 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1289
1290         if (bits & SU_IDEALPITCH)
1291                 MSG_WriteChar (msg, ent->v->idealpitch);
1292
1293         for (i=0 ; i<3 ; i++)
1294         {
1295                 if (bits & (SU_PUNCH1<<i))
1296                         MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // PROTOCOL_DARKPLACES
1297                 if (bits & (SU_PUNCHVEC1<<i)) // PROTOCOL_DARKPLACES
1298                         MSG_WriteFloat(msg, punchvector[i]); // PROTOCOL_DARKPLACES
1299                 if (bits & (SU_VELOCITY1<<i))
1300                         MSG_WriteFloat(msg, ent->v->velocity[i]);
1301         }
1302
1303 // [always sent]        if (bits & SU_ITEMS)
1304         MSG_WriteLong (msg, items);
1305
1306         if (bits & SU_WEAPONFRAME)
1307                 MSG_WriteByte (msg, ent->v->weaponframe);
1308         if (bits & SU_ARMOR)
1309                 MSG_WriteByte (msg, ent->v->armorvalue);
1310         if (bits & SU_WEAPON)
1311                 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1312
1313         MSG_WriteShort (msg, ent->v->health);
1314         MSG_WriteByte (msg, ent->v->currentammo);
1315         MSG_WriteByte (msg, ent->v->ammo_shells);
1316         MSG_WriteByte (msg, ent->v->ammo_nails);
1317         MSG_WriteByte (msg, ent->v->ammo_rockets);
1318         MSG_WriteByte (msg, ent->v->ammo_cells);
1319
1320         if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1321         {
1322                 for(i=0;i<32;i++)
1323                 {
1324                         if ( ((int)ent->v->weapon) & (1<<i) )
1325                         {
1326                                 MSG_WriteByte (msg, i);
1327                                 break;
1328                         }
1329                 }
1330         }
1331         else
1332         {
1333                 MSG_WriteByte (msg, ent->v->weapon);
1334         }
1335
1336         if (bits & SU_VIEWZOOM)
1337                 MSG_WriteByte (msg, viewzoom);
1338 }
1339
1340 /*
1341 =======================
1342 SV_SendClientDatagram
1343 =======================
1344 */
1345 static qbyte sv_sendclientdatagram_buf[NET_MAXMESSAGE]; // FIXME?
1346 qboolean SV_SendClientDatagram (client_t *client)
1347 {
1348         sizebuf_t       msg;
1349
1350         msg.data = sv_sendclientdatagram_buf;
1351         msg.maxsize = (int)bound(50.0, client->netconnection->rate * host_realframetime, (double)sizeof(sv_sendclientdatagram_buf));
1352         msg.cursize = 0;
1353
1354         MSG_WriteByte (&msg, svc_time);
1355         MSG_WriteFloat (&msg, sv.time);
1356
1357         // add the client specific data to the datagram
1358         SV_WriteClientdataToMessage (client->edict, &msg);
1359
1360         SV_WriteEntitiesToClient (client, client->edict, &msg);
1361
1362         // copy the server datagram if there is space
1363         // FIXME: put in delayed queue of effects to send
1364         if (msg.cursize + sv.datagram.cursize <= msg.maxsize)
1365                 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1366
1367 // send the datagram
1368         if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1369         {
1370                 SV_DropClient (true);// if the message couldn't send, kick off
1371                 return false;
1372         }
1373
1374         return true;
1375 }
1376
1377 /*
1378 =======================
1379 SV_UpdateToReliableMessages
1380 =======================
1381 */
1382 void SV_UpdateToReliableMessages (void)
1383 {
1384         int i, j;
1385         client_t *client;
1386         eval_t *val;
1387         char *s;
1388
1389 // check for changes to be sent over the reliable streams
1390         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1391         {
1392                 // update the host_client fields we care about according to the entity fields
1393                 sv_player = EDICT_NUM(i+1);
1394                 s = PR_GetString(sv_player->v->netname);
1395                 if (s != host_client->name)
1396                 {
1397                         if (s == NULL)
1398                                 s = "";
1399                         // point the string back at host_client->name to keep it safe
1400                         strlcpy (host_client->name, s, sizeof (host_client->name));
1401                         sv_player->v->netname = PR_SetString(host_client->name);
1402                 }
1403                 if ((val = GETEDICTFIELDVALUE(sv_player, eval_clientcolors)) && host_client->colors != val->_float)
1404                         host_client->colors = val->_float;
1405                 host_client->frags = sv_player->v->frags;
1406                 if (gamemode == GAME_NEHAHRA)
1407                         if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)) && host_client->pmodel != val->_float)
1408                                 host_client->pmodel = val->_float;
1409
1410                 // if the fields changed, send messages about the changes
1411                 if (strcmp(host_client->old_name, host_client->name))
1412                 {
1413                         strcpy(host_client->old_name, host_client->name);
1414                         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1415                         {
1416                                 if (!client->spawned || !client->netconnection)
1417                                         continue;
1418                                 MSG_WriteByte (&client->message, svc_updatename);
1419                                 MSG_WriteByte (&client->message, i);
1420                                 MSG_WriteString (&client->message, host_client->name);
1421                         }
1422                 }
1423                 if (host_client->old_colors != host_client->colors)
1424                 {
1425                         host_client->old_colors = host_client->colors;
1426                         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1427                         {
1428                                 if (!client->spawned || !client->netconnection)
1429                                         continue;
1430                                 MSG_WriteByte (&client->message, svc_updatecolors);
1431                                 MSG_WriteByte (&client->message, i);
1432                                 MSG_WriteByte (&client->message, host_client->colors);
1433                         }
1434                 }
1435                 if (host_client->old_frags != host_client->frags)
1436                 {
1437                         host_client->old_frags = host_client->frags;
1438                         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1439                         {
1440                                 if (!client->spawned || !client->netconnection)
1441                                         continue;
1442                                 MSG_WriteByte (&client->message, svc_updatefrags);
1443                                 MSG_WriteByte (&client->message, i);
1444                                 MSG_WriteShort (&client->message, host_client->frags);
1445                         }
1446                 }
1447         }
1448
1449         for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1450                 if (client->netconnection)
1451                         SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1452
1453         SZ_Clear (&sv.reliable_datagram);
1454 }
1455
1456
1457 /*
1458 =======================
1459 SV_SendNop
1460
1461 Send a nop message without trashing or sending the accumulated client
1462 message buffer
1463 =======================
1464 */
1465 void SV_SendNop (client_t *client)
1466 {
1467         sizebuf_t       msg;
1468         qbyte           buf[4];
1469
1470         msg.data = buf;
1471         msg.maxsize = sizeof(buf);
1472         msg.cursize = 0;
1473
1474         MSG_WriteChar (&msg, svc_nop);
1475
1476         if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1477                 SV_DropClient (true);   // if the message couldn't send, kick off
1478         client->last_message = realtime;
1479 }
1480
1481 /*
1482 =======================
1483 SV_SendClientMessages
1484 =======================
1485 */
1486 void SV_SendClientMessages (void)
1487 {
1488         int i, prepared = false;
1489
1490 // update frags, names, etc
1491         SV_UpdateToReliableMessages();
1492
1493 // build individual updates
1494         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1495         {
1496                 if (!host_client->active)
1497                         continue;
1498                 if (!host_client->netconnection)
1499                 {
1500                         SZ_Clear(&host_client->message);
1501                         continue;
1502                 }
1503
1504                 if (host_client->deadsocket || host_client->message.overflowed)
1505                 {
1506                         SV_DropClient (true);   // if the message couldn't send, kick off
1507                         continue;
1508                 }
1509
1510                 if (host_client->spawned)
1511                 {
1512                         if (!prepared)
1513                         {
1514                                 prepared = true;
1515                                 // only prepare entities once per frame
1516                                 SV_PrepareEntitiesForSending();
1517                         }
1518                         if (!SV_SendClientDatagram (host_client))
1519                                 continue;
1520                 }
1521                 else
1522                 {
1523                 // the player isn't totally in the game yet
1524                 // send small keepalive messages if too much time has passed
1525                 // send a full message when the next signon stage has been requested
1526                 // some other message data (name changes, etc) may accumulate
1527                 // between signon stages
1528                         if (!host_client->sendsignon)
1529                         {
1530                                 if (realtime - host_client->last_message > 5)
1531                                         SV_SendNop (host_client);
1532                                 continue;       // don't send out non-signon messages
1533                         }
1534                 }
1535
1536                 if (host_client->message.cursize || host_client->dropasap)
1537                 {
1538                         if (!NetConn_CanSendMessage (host_client->netconnection))
1539                                 continue;
1540
1541                         if (host_client->dropasap)
1542                                 SV_DropClient (false);  // went to another level
1543                         else
1544                         {
1545                                 if (NetConn_SendReliableMessage (host_client->netconnection, &host_client->message) == -1)
1546                                         SV_DropClient (true);   // if the message couldn't send, kick off
1547                                 SZ_Clear (&host_client->message);
1548                                 host_client->last_message = realtime;
1549                                 host_client->sendsignon = false;
1550                         }
1551                 }
1552         }
1553
1554 // clear muzzle flashes
1555         SV_CleanupEnts();
1556 }
1557
1558
1559 /*
1560 ==============================================================================
1561
1562 SERVER SPAWNING
1563
1564 ==============================================================================
1565 */
1566
1567 /*
1568 ================
1569 SV_ModelIndex
1570
1571 ================
1572 */
1573 int SV_ModelIndex (const char *name)
1574 {
1575         int i;
1576
1577         if (!name || !name[0])
1578                 return 0;
1579
1580         for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1581                 if (!strcmp(sv.model_precache[i], name))
1582                         return i;
1583         if (i==MAX_MODELS || !sv.model_precache[i])
1584                 Host_Error ("SV_ModelIndex: model %s not precached", name);
1585         return i;
1586 }
1587
1588 #ifdef SV_QUAKEENTITIES
1589 /*
1590 ================
1591 SV_CreateBaseline
1592
1593 ================
1594 */
1595 void SV_CreateBaseline (void)
1596 {
1597         int i, entnum, large;
1598         edict_t *svent;
1599
1600         // LordHavoc: clear *all* states (note just active ones)
1601         for (entnum = 0;entnum < sv.max_edicts;entnum++)
1602         {
1603                 // get the current server version
1604                 svent = EDICT_NUM(entnum);
1605
1606                 // LordHavoc: always clear state values, whether the entity is in use or not
1607                 ClearStateToDefault(&svent->e->baseline);
1608
1609                 if (svent->e->free)
1610                         continue;
1611                 if (entnum > svs.maxclients && !svent->v->modelindex)
1612                         continue;
1613
1614                 // create entity baseline
1615                 VectorCopy (svent->v->origin, svent->e->baseline.origin);
1616                 VectorCopy (svent->v->angles, svent->e->baseline.angles);
1617                 svent->e->baseline.frame = svent->v->frame;
1618                 svent->e->baseline.skin = svent->v->skin;
1619                 if (entnum > 0 && entnum <= svs.maxclients)
1620                 {
1621                         svent->e->baseline.colormap = entnum;
1622                         svent->e->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1623                 }
1624                 else
1625                 {
1626                         svent->e->baseline.colormap = 0;
1627                         svent->e->baseline.modelindex = svent->v->modelindex;
1628                 }
1629
1630                 large = false;
1631                 if (svent->e->baseline.modelindex & 0xFF00 || svent->e->baseline.frame & 0xFF00)
1632                         large = true;
1633
1634                 // add to the message
1635                 if (large)
1636                         MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1637                 else
1638                         MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1639                 MSG_WriteShort (&sv.signon, entnum);
1640
1641                 if (large)
1642                 {
1643                         MSG_WriteShort (&sv.signon, svent->e->baseline.modelindex);
1644                         MSG_WriteShort (&sv.signon, svent->e->baseline.frame);
1645                 }
1646                 else
1647                 {
1648                         MSG_WriteByte (&sv.signon, svent->e->baseline.modelindex);
1649                         MSG_WriteByte (&sv.signon, svent->e->baseline.frame);
1650                 }
1651                 MSG_WriteByte (&sv.signon, svent->e->baseline.colormap);
1652                 MSG_WriteByte (&sv.signon, svent->e->baseline.skin);
1653                 for (i=0 ; i<3 ; i++)
1654                 {
1655                         MSG_WriteDPCoord(&sv.signon, svent->e->baseline.origin[i]);
1656                         MSG_WriteAngle(&sv.signon, svent->e->baseline.angles[i]);
1657                 }
1658         }
1659 }
1660 #endif
1661
1662
1663 /*
1664 ================
1665 SV_SendReconnect
1666
1667 Tell all the clients that the server is changing levels
1668 ================
1669 */
1670 void SV_SendReconnect (void)
1671 {
1672         char    data[128];
1673         sizebuf_t       msg;
1674
1675         msg.data = data;
1676         msg.cursize = 0;
1677         msg.maxsize = sizeof(data);
1678
1679         MSG_WriteChar (&msg, svc_stufftext);
1680         MSG_WriteString (&msg, "reconnect\n");
1681         NetConn_SendToAll (&msg, 5);
1682
1683         if (cls.state != ca_dedicated)
1684                 Cmd_ExecuteString ("reconnect\n", src_command);
1685 }
1686
1687
1688 /*
1689 ================
1690 SV_SaveSpawnparms
1691
1692 Grabs the current state of each client for saving across the
1693 transition to another level
1694 ================
1695 */
1696 void SV_SaveSpawnparms (void)
1697 {
1698         int             i, j;
1699
1700         svs.serverflags = pr_global_struct->serverflags;
1701
1702         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1703         {
1704                 if (!host_client->active)
1705                         continue;
1706
1707         // call the progs to get default spawn parms for the new client
1708                 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1709                 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1710                 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1711                         host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1712         }
1713 }
1714
1715 void SV_IncreaseEdicts(void)
1716 {
1717         int i;
1718         edict_t *ent;
1719         int oldmax_edicts = sv.max_edicts;
1720         void *oldedictsengineprivate = sv.edictsengineprivate;
1721         void *oldedictsfields = sv.edictsfields;
1722         void *oldmoved_edicts = sv.moved_edicts;
1723
1724         if (sv.max_edicts >= MAX_EDICTS)
1725                 return;
1726
1727         // links don't survive the transition, so unlink everything
1728         for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1729         {
1730                 if (!ent->e->free)
1731                         SV_UnlinkEdict(sv.edicts + i);
1732                 memset(&ent->e->areagrid, 0, sizeof(ent->e->areagrid));
1733         }
1734         SV_ClearWorld();
1735
1736         sv.max_edicts   = min(sv.max_edicts + 256, MAX_EDICTS);
1737         sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1738         sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1739         sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1740
1741         memcpy(sv.edictsengineprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
1742         memcpy(sv.edictsfields, oldedictsfields, oldmax_edicts * pr_edict_size);
1743
1744         for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1745         {
1746                 ent->e = sv.edictsengineprivate + i;
1747                 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1748                 // link every entity except world
1749                 if (!ent->e->free)
1750                         SV_LinkEdict(ent, false);
1751         }
1752
1753         Mem_Free(oldedictsengineprivate);
1754         Mem_Free(oldedictsfields);
1755         Mem_Free(oldmoved_edicts);
1756 }
1757
1758 /*
1759 ================
1760 SV_SpawnServer
1761
1762 This is called at the start of each level
1763 ================
1764 */
1765 extern float            scr_centertime_off;
1766
1767 void SV_SpawnServer (const char *server)
1768 {
1769         edict_t *ent;
1770         int i;
1771         qbyte *entities;
1772
1773         // let's not have any servers with no name
1774         if (hostname.string[0] == 0)
1775                 Cvar_Set ("hostname", "UNNAMED");
1776         scr_centertime_off = 0;
1777
1778         Con_DPrintf ("SpawnServer: %s\n",server);
1779         svs.changelevel_issued = false;         // now safe to issue another
1780
1781 //
1782 // tell all connected clients that we are going to a new level
1783 //
1784         if (sv.active)
1785                 SV_SendReconnect();
1786         else
1787         {
1788                 // make sure cvars have been checked before opening the ports
1789                 NetConn_ServerFrame();
1790                 NetConn_OpenServerPorts(true);
1791         }
1792
1793 //
1794 // make cvars consistant
1795 //
1796         if (coop.integer)
1797                 Cvar_SetValue ("deathmatch", 0);
1798         current_skill = bound(0, (int)(skill.value + 0.5), 3);
1799
1800         Cvar_SetValue ("skill", (float)current_skill);
1801
1802 //
1803 // set up the new server
1804 //
1805         Host_ClearMemory ();
1806
1807         memset (&sv, 0, sizeof(sv));
1808
1809         strlcpy (sv.name, server, sizeof (sv.name));
1810
1811 // load progs to get entity field count
1812         PR_LoadProgs ();
1813
1814 // allocate server memory
1815         // start out with just enough room for clients and a reasonable estimate of entities
1816         sv.max_edicts = max(svs.maxclients + 1, 512);
1817         sv.max_edicts = min(sv.max_edicts, MAX_EDICTS);
1818
1819         // clear the edict memory pool
1820         Mem_EmptyPool(sv_edicts_mempool);
1821         // edict_t structures (hidden from progs)
1822         sv.edicts = Mem_Alloc(sv_edicts_mempool, MAX_EDICTS * sizeof(edict_t));
1823         // engine private structures (hidden from progs)
1824         sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1825         // progs fields, often accessed by server
1826         sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1827         // used by PushMove to move back pushed entities
1828         sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1829         for (i = 0;i < sv.max_edicts;i++)
1830         {
1831                 ent = sv.edicts + i;
1832                 ent->e = sv.edictsengineprivate + i;
1833                 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1834         }
1835
1836         sv.datagram.maxsize = sizeof(sv.datagram_buf);
1837         sv.datagram.cursize = 0;
1838         sv.datagram.data = sv.datagram_buf;
1839
1840         sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1841         sv.reliable_datagram.cursize = 0;
1842         sv.reliable_datagram.data = sv.reliable_datagram_buf;
1843
1844         sv.signon.maxsize = sizeof(sv.signon_buf);
1845         sv.signon.cursize = 0;
1846         sv.signon.data = sv.signon_buf;
1847
1848 // leave slots at start for clients only
1849         sv.num_edicts = svs.maxclients+1;
1850
1851         sv.state = ss_loading;
1852         sv.paused = false;
1853
1854         sv.time = 1.0;
1855
1856         Mod_ClearUsed();
1857
1858         strlcpy (sv.name, server, sizeof (sv.name));
1859         snprintf (sv.modelname, sizeof (sv.modelname), "maps/%s.bsp", server);
1860         sv.worldmodel = Mod_ForName(sv.modelname, false, true, true);
1861         if (!sv.worldmodel)
1862         {
1863                 Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
1864                 sv.active = false;
1865                 return;
1866         }
1867         sv.models[1] = sv.worldmodel;
1868
1869 //
1870 // clear world interaction links
1871 //
1872         SV_ClearWorld ();
1873
1874         sv.sound_precache[0] = "";
1875
1876         sv.model_precache[0] = "";
1877         sv.model_precache[1] = sv.modelname;
1878         for (i = 1;i < sv.worldmodel->brush.numsubmodels;i++)
1879         {
1880                 sv.model_precache[i+1] = localmodels[i];
1881                 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1882         }
1883
1884 //
1885 // load the rest of the entities
1886 //
1887         ent = EDICT_NUM(0);
1888         memset (ent->v, 0, progs->entityfields * 4);
1889         ent->e->free = false;
1890         ent->v->model = PR_SetString(sv.modelname);
1891         ent->v->modelindex = 1;         // world model
1892         ent->v->solid = SOLID_BSP;
1893         ent->v->movetype = MOVETYPE_PUSH;
1894
1895         if (coop.value)
1896                 pr_global_struct->coop = coop.integer;
1897         else
1898                 pr_global_struct->deathmatch = deathmatch.integer;
1899
1900         pr_global_struct->mapname = PR_SetString(sv.name);
1901
1902 // serverflags are for cross level information (sigils)
1903         pr_global_struct->serverflags = svs.serverflags;
1904
1905         // load replacement entity file if found
1906         entities = NULL;
1907         if (sv_entpatch.integer)
1908                 entities = FS_LoadFile(va("maps/%s.ent", sv.name), true);
1909         if (entities)
1910         {
1911                 Con_Printf("Loaded maps/%s.ent\n", sv.name);
1912                 ED_LoadFromFile (entities);
1913                 Mem_Free(entities);
1914         }
1915         else
1916                 ED_LoadFromFile (sv.worldmodel->brush.entities);
1917
1918
1919         // LordHavoc: clear world angles (to fix e3m3.bsp)
1920         VectorClear(sv.edicts->v->angles);
1921
1922         sv.active = true;
1923
1924 // all setup is completed, any further precache statements are errors
1925         sv.state = ss_active;
1926
1927 // run two frames to allow everything to settle
1928         for (i = 0;i < 2;i++)
1929         {
1930                 sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1931                 SV_Physics ();
1932         }
1933
1934         Mod_PurgeUnused();
1935
1936 #ifdef QUAKEENTITIES
1937 // create a baseline for more efficient communications
1938         SV_CreateBaseline ();
1939 #endif
1940
1941 // send serverinfo to all connected clients
1942         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1943                 if (host_client->netconnection)
1944                         SV_SendServerinfo(host_client);
1945
1946         Con_DPrintf ("Server spawned.\n");
1947         NetConn_Heartbeat (2);
1948 }
1949