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