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