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