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