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