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