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