2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // sv_main.c -- server main program
24 static cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1"}; // fast but loose
25 static cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "0"}; // tends to get false negatives, uses a timeout to keep entities visible a short time after becoming hidden
26 static cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0"};
27 static cvar_t sv_entpatch = {0, "sv_entpatch", "1"};
32 static char localmodels[MAX_MODELS][5]; // inline model names for precache
34 mempool_t *sv_edicts_mempool = NULL;
36 //============================================================================
38 extern void SV_Phys_Init (void);
39 extern void SV_World_Init (void);
40 static void SV_SaveEntFile_f(void);
51 Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f);
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_deltacompress);
63 Cvar_RegisterVariable (&sv_cullentities_pvs);
64 Cvar_RegisterVariable (&sv_cullentities_trace);
65 Cvar_RegisterVariable (&sv_cullentities_stats);
66 Cvar_RegisterVariable (&sv_entpatch);
71 for (i = 0;i < MAX_MODELS;i++)
72 sprintf (localmodels[i], "*%i", i);
74 sv_edicts_mempool = Mem_AllocPool("server edicts");
77 static void SV_SaveEntFile_f(void)
79 char basename[MAX_QPATH];
80 if (!sv.active || !sv.worldmodel)
82 Con_Print("Not running a server\n");
85 FS_StripExtension(sv.worldmodel->name, basename, sizeof(basename));
86 FS_WriteFile(va("%s.ent", basename), sv.worldmodel->brush.entities, strlen(sv.worldmodel->brush.entities));
90 =============================================================================
94 =============================================================================
101 Make sure the event gets sent to all clients
104 void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
108 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
110 MSG_WriteByte (&sv.datagram, svc_particle);
111 MSG_WriteDPCoord (&sv.datagram, org[0]);
112 MSG_WriteDPCoord (&sv.datagram, org[1]);
113 MSG_WriteDPCoord (&sv.datagram, org[2]);
114 for (i=0 ; i<3 ; i++)
121 MSG_WriteChar (&sv.datagram, v);
123 MSG_WriteByte (&sv.datagram, count);
124 MSG_WriteByte (&sv.datagram, color);
131 Make sure the event gets sent to all clients
134 void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
136 if (modelindex >= 256 || startframe >= 256)
138 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
140 MSG_WriteByte (&sv.datagram, svc_effect2);
141 MSG_WriteDPCoord (&sv.datagram, org[0]);
142 MSG_WriteDPCoord (&sv.datagram, org[1]);
143 MSG_WriteDPCoord (&sv.datagram, org[2]);
144 MSG_WriteShort (&sv.datagram, modelindex);
145 MSG_WriteShort (&sv.datagram, startframe);
146 MSG_WriteByte (&sv.datagram, framecount);
147 MSG_WriteByte (&sv.datagram, framerate);
151 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
153 MSG_WriteByte (&sv.datagram, svc_effect);
154 MSG_WriteDPCoord (&sv.datagram, org[0]);
155 MSG_WriteDPCoord (&sv.datagram, org[1]);
156 MSG_WriteDPCoord (&sv.datagram, org[2]);
157 MSG_WriteByte (&sv.datagram, modelindex);
158 MSG_WriteByte (&sv.datagram, startframe);
159 MSG_WriteByte (&sv.datagram, framecount);
160 MSG_WriteByte (&sv.datagram, framerate);
168 Each entity can have eight independant sound sources, like voice,
171 Channel 0 is an auto-allocate channel, the others override anything
172 already running on that entity/channel pair.
174 An attenuation of 0 will play full volume everywhere in the level.
175 Larger attenuations will drop off. (max 4 attenuation)
179 void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, float attenuation)
181 int sound_num, field_mask, i, ent;
183 if (volume < 0 || volume > 255)
184 Host_Error ("SV_StartSound: volume = %i", volume);
186 if (attenuation < 0 || attenuation > 4)
187 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
189 if (channel < 0 || channel > 7)
190 Host_Error ("SV_StartSound: channel = %i", channel);
192 if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
195 // find precache number for sound
196 for (sound_num=1 ; sound_num<MAX_SOUNDS && sv.sound_precache[sound_num] ; sound_num++)
197 if (!strcmp(sample, sv.sound_precache[sound_num]))
200 if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
202 Con_Printf("SV_StartSound: %s not precached\n", sample);
206 ent = NUM_FOR_EDICT(entity);
209 if (volume != DEFAULT_SOUND_PACKET_VOLUME)
210 field_mask |= SND_VOLUME;
211 if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
212 field_mask |= SND_ATTENUATION;
214 field_mask |= SND_LARGEENTITY;
215 if (sound_num >= 256 || channel >= 8)
216 field_mask |= SND_LARGESOUND;
218 // directed messages go only to the entity they are targeted on
219 MSG_WriteByte (&sv.datagram, svc_sound);
220 MSG_WriteByte (&sv.datagram, field_mask);
221 if (field_mask & SND_VOLUME)
222 MSG_WriteByte (&sv.datagram, volume);
223 if (field_mask & SND_ATTENUATION)
224 MSG_WriteByte (&sv.datagram, attenuation*64);
225 if (field_mask & SND_LARGEENTITY)
227 MSG_WriteShort (&sv.datagram, ent);
228 MSG_WriteByte (&sv.datagram, channel);
231 MSG_WriteShort (&sv.datagram, (ent<<3) | channel);
232 if (field_mask & SND_LARGESOUND)
233 MSG_WriteShort (&sv.datagram, sound_num);
235 MSG_WriteByte (&sv.datagram, sound_num);
236 for (i = 0;i < 3;i++)
237 MSG_WriteDPCoord (&sv.datagram, entity->v->origin[i]+0.5*(entity->v->mins[i]+entity->v->maxs[i]));
241 ==============================================================================
245 ==============================================================================
252 Sends the first message from the server to a connected client.
253 This will be sent on the initial connection and upon each server load.
256 void SV_SendServerinfo (client_t *client)
261 // edicts get reallocated on level changes, so we need to update it here
262 client->edict = EDICT_NUM(client->number + 1);
264 // LordHavoc: clear entityframe tracking
265 client->entityframenumber = 0;
266 if (client->entitydatabase4)
267 EntityFrame4_FreeDatabase(client->entitydatabase4);
268 client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_clients_mempool);
270 MSG_WriteByte (&client->message, svc_print);
271 snprintf (message, sizeof (message), "\002\nServer: %s build %s (progs %i crc)", gamename, buildstring, pr_crc);
272 MSG_WriteString (&client->message,message);
274 MSG_WriteByte (&client->message, svc_serverinfo);
275 MSG_WriteLong (&client->message, PROTOCOL_DARKPLACES5);
276 MSG_WriteByte (&client->message, svs.maxclients);
278 if (!coop.integer && deathmatch.integer)
279 MSG_WriteByte (&client->message, GAME_DEATHMATCH);
281 MSG_WriteByte (&client->message, GAME_COOP);
283 MSG_WriteString (&client->message,PR_GetString(sv.edicts->v->message));
285 for (s = sv.model_precache+1 ; *s ; s++)
286 MSG_WriteString (&client->message, *s);
287 MSG_WriteByte (&client->message, 0);
289 for (s = sv.sound_precache+1 ; *s ; s++)
290 MSG_WriteString (&client->message, *s);
291 MSG_WriteByte (&client->message, 0);
294 MSG_WriteByte (&client->message, svc_cdtrack);
295 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
296 MSG_WriteByte (&client->message, sv.edicts->v->sounds);
299 MSG_WriteByte (&client->message, svc_setview);
300 MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
302 MSG_WriteByte (&client->message, svc_signonnum);
303 MSG_WriteByte (&client->message, 1);
305 client->sendsignon = true;
306 client->spawned = false; // need prespawn, spawn, etc
313 Initializes a client_t for a new net connection. This will only be called
314 once for a player each game, not once for each level change.
317 void SV_ConnectClient (int clientnum, netconn_t *netconnection)
321 float spawn_parms[NUM_SPAWN_PARMS];
323 client = svs.clients + clientnum;
325 // set up the client_t
327 memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
328 memset (client, 0, sizeof(*client));
329 client->active = true;
330 client->netconnection = netconnection;
332 Con_DPrintf("Client %s connected\n", client->netconnection->address);
334 strcpy(client->name, "unconnected");
335 strcpy(client->old_name, "unconnected");
336 client->number = clientnum;
337 client->spawned = false;
338 client->edict = EDICT_NUM(clientnum+1);
339 client->message.data = client->msgbuf;
340 client->message.maxsize = sizeof(client->msgbuf);
341 client->message.allowoverflow = true; // we can catch it
344 memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
347 // call the progs to get default spawn parms for the new client
348 PR_ExecuteProgram (pr_global_struct->SetNewParms, "QC function SetNewParms is missing");
349 for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
350 client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
353 SV_SendServerinfo (client);
358 ===============================================================================
362 ===============================================================================
371 void SV_ClearDatagram (void)
373 SZ_Clear (&sv.datagram);
377 =============================================================================
379 The PVS must include a small area around the client to allow head bobbing
380 or other small motion on the client side. Otherwise, a bob might cause an
381 entity that should be visible to not show up, especially when the bob
384 =============================================================================
387 int sv_writeentitiestoclient_pvsbytes;
388 qbyte sv_writeentitiestoclient_pvs[MAX_MAP_LEAFS/8];
392 SV_WriteEntitiesToClient
397 void SV_WriteEntitiesToClient (client_t *client, edict_t *clent, sizebuf_t *msg)
399 int e, clentnum, bits, alpha, glowcolor, glowsize, scale, effects, lightsize;
400 int culled_pvs, culled_trace, visibleentities, totalentities;
402 vec3_t origin, angles, entmins, entmaxs, testorigin, testeye;
403 float nextfullupdate, alphaf;
406 entity_state_t *baseline; // LordHavoc: delta or startup baseline
409 Mod_CheckLoaded(sv.worldmodel);
411 // find the client's PVS
412 VectorAdd (clent->v->origin, clent->v->view_ofs, testeye);
414 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
415 fatbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
422 clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
423 // send all entities that touch the pvs
424 ent = NEXT_EDICT(sv.edicts);
425 for (e = 1;e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
429 // prevent delta compression against this frame (unless actually sent, which will restore this later)
430 nextfullupdate = client->nextfullupdate[e];
431 client->nextfullupdate[e] = -1;
433 if (ent != clent) // LordHavoc: always send player
435 if ((val = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)) && val->edict)
437 if (val->edict != clentnum)
439 // don't show to anyone else
443 bits |= U_VIEWMODEL; // show relative to the view
447 // LordHavoc: never draw something told not to display to this client
448 if ((val = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)) && val->edict == clentnum)
450 if ((val = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)) && val->edict && val->edict != clentnum)
457 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_size)))
458 glowsize = (int) val->_float >> 2;
459 if (glowsize > 255) glowsize = 255;
460 if (glowsize < 0) glowsize = 0;
462 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_trail)))
463 if (val->_float != 0)
466 if (ent->v->modelindex >= 0 && ent->v->modelindex < MAX_MODELS && *PR_GetString(ent->v->model))
468 model = sv.models[(int)ent->v->modelindex];
469 Mod_CheckLoaded(model);
474 if (ent != clent) // LordHavoc: always send player
475 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
479 VectorCopy(ent->v->angles, angles);
480 VectorCopy(ent->v->origin, origin);
482 // ent has survived every check so far, check if it is visible
483 if (ent != clent && ((bits & U_VIEWMODEL) == 0))
485 // use the predicted origin
486 entmins[0] = origin[0] - 1.0f;
487 entmins[1] = origin[1] - 1.0f;
488 entmins[2] = origin[2] - 1.0f;
489 entmaxs[0] = origin[0] + 1.0f;
490 entmaxs[1] = origin[1] + 1.0f;
491 entmaxs[2] = origin[2] + 1.0f;
492 // using the model's bounding box to ensure things are visible regardless of their physics box
495 if (ent->v->angles[0] || ent->v->angles[2]) // pitch and roll
497 VectorAdd(entmins, model->rotatedmins, entmins);
498 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
500 else if (ent->v->angles[1])
502 VectorAdd(entmins, model->yawmins, entmins);
503 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
507 VectorAdd(entmins, model->normalmins, entmins);
508 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
514 // if not touching a visible leaf
515 if (sv_cullentities_pvs.integer && fatbytes && sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, entmins, entmaxs))
521 // don't try to cull embedded brush models with this, they're sometimes huge (spanning several rooms)
522 if (sv_cullentities_trace.integer && (model == NULL || model->name[0] != '*'))
524 // LordHavoc: test random offsets, to maximize chance of detection
525 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
526 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
527 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
529 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
530 if (trace.fraction == 1)
531 client->visibletime[e] = realtime + 1;
534 //test nearest point on bbox
535 testorigin[0] = bound(entmins[0], testeye[0], entmaxs[0]);
536 testorigin[1] = bound(entmins[1], testeye[1], entmaxs[1]);
537 testorigin[2] = bound(entmins[2], testeye[2], entmaxs[2]);
539 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, testeye, testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
540 if (trace.fraction == 1)
541 client->visibletime[e] = realtime + 1;
542 else if (realtime > client->visibletime[e])
555 effects = ent->v->effects;
557 if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)))
558 if (val->_float != 0)
559 alphaf = val->_float * 255.0f;
562 if ((val = GETEDICTFIELDVALUE(ent, eval_renderamt)))
563 if (val->_float != 0)
564 alphaf = val->_float;
568 alpha = bound(0, alphaf, 255);
570 if ((val = GETEDICTFIELDVALUE(ent, eval_scale)))
571 if ((scale = (int) (val->_float * 16.0)) == 0) scale = 16;
572 if (scale < 0) scale = 0;
573 if (scale > 255) scale = 255;
575 if ((val = GETEDICTFIELDVALUE(ent, eval_glow_color)))
576 if (val->_float != 0)
577 glowcolor = (int) val->_float;
579 if ((val = GETEDICTFIELDVALUE(ent, eval_fullbright)))
580 if (val->_float != 0)
581 effects |= EF_FULLBRIGHT;
585 if (glowsize == 0 && (bits & U_GLOWTRAIL) == 0) // no effects
589 // don't send if flagged for NODRAW and there are no effects
590 if (model->flags == 0 && ((effects & EF_NODRAW) || scale <= 0 || alpha <= 0))
593 else // no model and no effects
598 if (msg->maxsize - msg->cursize < 32) // LordHavoc: increased check from 16 to 32
600 Con_Print("packet overflow\n");
601 // mark the rest of the entities so they can't be delta compressed against this frame
602 for (;e < sv.num_edicts;e++)
604 client->nextfullupdate[e] = -1;
605 client->visibletime[e] = -1;
610 if ((val = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)) && val->edict == clentnum)
611 bits = bits | U_EXTERIORMODEL;
614 baseline = &ent->e->baseline;
616 if (((int)ent->v->effects & EF_DELTA) && sv_deltacompress.integer)
618 // every half second a full update is forced
619 if (realtime < client->nextfullupdate[e])
622 baseline = &ent->e->deltabaseline;
625 nextfullupdate = realtime + 0.5f;
628 nextfullupdate = realtime + 0.5f;
630 // restore nextfullupdate since this is being sent for real
631 client->nextfullupdate[e] = nextfullupdate;
634 bits |= U_LONGENTITY;
636 if (ent->v->movetype == MOVETYPE_STEP)
639 // LordHavoc: old stuff, but rewritten to have more exact tolerances
640 if (origin[0] != baseline->origin[0]) bits |= U_ORIGIN1;
641 if (origin[1] != baseline->origin[1]) bits |= U_ORIGIN2;
642 if (origin[2] != baseline->origin[2]) bits |= U_ORIGIN3;
643 if (((int)(angles[0]*(256.0/360.0)) & 255) != ((int)(baseline->angles[0]*(256.0/360.0)) & 255)) bits |= U_ANGLE1;
644 if (((int)(angles[1]*(256.0/360.0)) & 255) != ((int)(baseline->angles[1]*(256.0/360.0)) & 255)) bits |= U_ANGLE2;
645 if (((int)(angles[2]*(256.0/360.0)) & 255) != ((int)(baseline->angles[2]*(256.0/360.0)) & 255)) bits |= U_ANGLE3;
646 if (baseline->colormap != (qbyte) ent->v->colormap) bits |= U_COLORMAP;
647 if (baseline->skin != (qbyte) ent->v->skin) bits |= U_SKIN;
648 if ((baseline->frame & 0x00FF) != ((int) ent->v->frame & 0x00FF)) bits |= U_FRAME;
649 if ((baseline->effects & 0x00FF) != ((int) ent->v->effects & 0x00FF)) bits |= U_EFFECTS;
650 if ((baseline->modelindex & 0x00FF) != ((int) ent->v->modelindex & 0x00FF)) bits |= U_MODEL;
652 // LordHavoc: new stuff
653 if (baseline->alpha != alpha) bits |= U_ALPHA;
654 if (baseline->scale != scale) bits |= U_SCALE;
655 if (((int) baseline->effects & 0xFF00) != ((int) ent->v->effects & 0xFF00)) bits |= U_EFFECTS2;
656 if (baseline->glowsize != glowsize) bits |= U_GLOWSIZE;
657 if (baseline->glowcolor != glowcolor) bits |= U_GLOWCOLOR;
658 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->frame & 0xFF00)) bits |= U_FRAME2;
659 if (((int) baseline->frame & 0xFF00) != ((int) ent->v->modelindex & 0xFF00)) bits |= U_MODEL2;
661 // update delta baseline
662 VectorCopy(ent->v->origin, ent->e->deltabaseline.origin);
663 VectorCopy(ent->v->angles, ent->e->deltabaseline.angles);
664 ent->e->deltabaseline.colormap = ent->v->colormap;
665 ent->e->deltabaseline.skin = ent->v->skin;
666 ent->e->deltabaseline.frame = ent->v->frame;
667 ent->e->deltabaseline.effects = ent->v->effects;
668 ent->e->deltabaseline.modelindex = ent->v->modelindex;
669 ent->e->deltabaseline.alpha = alpha;
670 ent->e->deltabaseline.scale = scale;
671 ent->e->deltabaseline.glowsize = glowsize;
672 ent->e->deltabaseline.glowcolor = glowcolor;
675 if (bits >= 16777216)
683 MSG_WriteByte (msg, bits);
684 if (bits & U_MOREBITS)
685 MSG_WriteByte (msg, bits>>8);
686 // LordHavoc: extend bytes have to be written here due to delta compression
687 if (bits & U_EXTEND1)
688 MSG_WriteByte (msg, bits>>16);
689 if (bits & U_EXTEND2)
690 MSG_WriteByte (msg, bits>>24);
692 // LordHavoc: old stuff
693 if (bits & U_LONGENTITY)
694 MSG_WriteShort (msg,e);
696 MSG_WriteByte (msg,e);
697 if (bits & U_MODEL) MSG_WriteByte(msg, ent->v->modelindex);
698 if (bits & U_FRAME) MSG_WriteByte(msg, ent->v->frame);
699 if (bits & U_COLORMAP) MSG_WriteByte(msg, ent->v->colormap);
700 if (bits & U_SKIN) MSG_WriteByte(msg, ent->v->skin);
701 if (bits & U_EFFECTS) MSG_WriteByte(msg, ent->v->effects);
702 if (bits & U_ORIGIN1) MSG_WriteDPCoord(msg, origin[0]);
703 if (bits & U_ANGLE1) MSG_WriteAngle(msg, angles[0]);
704 if (bits & U_ORIGIN2) MSG_WriteDPCoord(msg, origin[1]);
705 if (bits & U_ANGLE2) MSG_WriteAngle(msg, angles[1]);
706 if (bits & U_ORIGIN3) MSG_WriteDPCoord(msg, origin[2]);
707 if (bits & U_ANGLE3) MSG_WriteAngle(msg, angles[2]);
709 // LordHavoc: new stuff
710 if (bits & U_ALPHA) MSG_WriteByte(msg, alpha);
711 if (bits & U_SCALE) MSG_WriteByte(msg, scale);
712 if (bits & U_EFFECTS2) MSG_WriteByte(msg, (int)ent->v->effects >> 8);
713 if (bits & U_GLOWSIZE) MSG_WriteByte(msg, glowsize);
714 if (bits & U_GLOWCOLOR) MSG_WriteByte(msg, glowcolor);
715 if (bits & U_FRAME2) MSG_WriteByte(msg, (int)ent->v->frame >> 8);
716 if (bits & U_MODEL2) MSG_WriteByte(msg, (int)ent->v->modelindex >> 8);
719 if (sv_cullentities_stats.integer)
720 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, totalentities, visibleentities, culled_pvs + culled_trace, culled_pvs, culled_trace);
723 static int numsendentities;
724 static entity_state_t sendentities[MAX_EDICTS];
725 static entity_state_t *sendentitiesindex[MAX_EDICTS];
727 void SV_PrepareEntitiesForSending(void)
733 // send all entities that touch the pvs
735 sendentitiesindex[0] = NULL;
736 for (e = 1, ent = NEXT_EDICT(sv.edicts);e < sv.num_edicts;e++, ent = NEXT_EDICT(ent))
738 sendentitiesindex[e] = NULL;
742 ClearStateToDefault(&cs);
745 VectorCopy(ent->v->origin, cs.origin);
746 VectorCopy(ent->v->angles, cs.angles);
748 cs.effects = (int)ent->v->effects;
749 cs.colormap = (qbyte)ent->v->colormap;
750 cs.skin = (qbyte)ent->v->skin;
751 cs.frame = (qbyte)ent->v->frame;
752 cs.viewmodelforclient = GETEDICTFIELDVALUE(ent, eval_viewmodelforclient)->edict;
753 cs.exteriormodelforclient = GETEDICTFIELDVALUE(ent, eval_exteriormodeltoclient)->edict;
754 cs.nodrawtoclient = GETEDICTFIELDVALUE(ent, eval_nodrawtoclient)->edict;
755 cs.drawonlytoclient = GETEDICTFIELDVALUE(ent, eval_drawonlytoclient)->edict;
756 cs.tagentity = GETEDICTFIELDVALUE(ent, eval_tag_entity)->edict;
757 cs.tagindex = (qbyte)GETEDICTFIELDVALUE(ent, eval_tag_index)->_float;
758 i = (int)(GETEDICTFIELDVALUE(ent, eval_glow_size)->_float * 0.25f);
759 cs.glowsize = (qbyte)bound(0, i, 255);
760 if (GETEDICTFIELDVALUE(ent, eval_glow_trail)->_float)
761 cs.flags |= RENDER_GLOWTRAIL;
764 i = (int)ent->v->modelindex;
765 if (i >= 1 && i < MAX_MODELS && *PR_GetString(ent->v->model))
769 f = (GETEDICTFIELDVALUE(ent, eval_alpha)->_float * 255.0f);
773 cs.alpha = (qbyte)bound(0, i, 255);
776 f = (GETEDICTFIELDVALUE(ent, eval_renderamt)->_float);
780 cs.alpha = (qbyte)bound(0, i, 255);
784 f = (GETEDICTFIELDVALUE(ent, eval_scale)->_float * 16.0f);
788 cs.scale = (qbyte)bound(0, i, 255);
792 f = (GETEDICTFIELDVALUE(ent, eval_glow_color)->_float);
794 cs.glowcolor = (int)f;
796 if (GETEDICTFIELDVALUE(ent, eval_fullbright)->_float)
797 cs.effects |= EF_FULLBRIGHT;
799 if (ent->v->movetype == MOVETYPE_STEP)
800 cs.flags |= RENDER_STEP;
801 if ((cs.effects & EF_LOWPRECISION) && cs.origin[0] >= -32768 && cs.origin[1] >= -32768 && cs.origin[2] >= -32768 && cs.origin[0] <= 32767 && cs.origin[1] <= 32767 && cs.origin[2] <= 32767)
802 cs.flags |= RENDER_LOWPRECISION;
803 if (ent->v->colormap >= 1024)
804 cs.flags |= RENDER_COLORMAPPED;
805 if (cs.viewmodelforclient)
806 cs.flags |= RENDER_VIEWMODEL; // show relative to the view
808 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[0]*256;
809 cs.light[0] = (unsigned short)bound(0, f, 65535);
810 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[1]*256;
811 cs.light[1] = (unsigned short)bound(0, f, 65535);
812 f = GETEDICTFIELDVALUE(ent, eval_color)->vector[2]*256;
813 cs.light[2] = (unsigned short)bound(0, f, 65535);
814 f = GETEDICTFIELDVALUE(ent, eval_light_lev)->_float;
815 cs.light[3] = (unsigned short)bound(0, f, 65535);
816 cs.lightstyle = (qbyte)GETEDICTFIELDVALUE(ent, eval_style)->_float;
817 cs.lightpflags = (qbyte)GETEDICTFIELDVALUE(ent, eval_pflags)->_float;
819 if (gamemode == GAME_TENEBRAE)
821 // tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
825 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
827 // tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
835 cs.lightpflags |= PFLAGS_FULLDYNAMIC;
839 cs.specialvisibilityradius = 0;
840 if (cs.lightpflags & PFLAGS_FULLDYNAMIC)
841 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.light[3]);
843 cs.specialvisibilityradius = max(cs.specialvisibilityradius, cs.glowsize * 4);
844 if (cs.flags & RENDER_GLOWTRAIL)
845 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
846 if (cs.effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
848 if (cs.effects & EF_BRIGHTFIELD)
849 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 80);
850 if (cs.effects & EF_MUZZLEFLASH)
851 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
852 if (cs.effects & EF_BRIGHTLIGHT)
853 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 400);
854 if (cs.effects & EF_DIMLIGHT)
855 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
856 if (cs.effects & EF_RED)
857 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
858 if (cs.effects & EF_BLUE)
859 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 200);
860 if (cs.effects & EF_FLAME)
861 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 250);
862 if (cs.effects & EF_STARDUST)
863 cs.specialvisibilityradius = max(cs.specialvisibilityradius, 100);
866 if (numsendentities >= MAX_EDICTS)
868 // we can omit invisible entities with no effects that are not clients
869 // LordHavoc: this could kill tags attached to an invisible entity, I
870 // just hope we never have to support that case
871 if (cs.number > svs.maxclients && ((cs.effects & EF_NODRAW) || (!cs.modelindex && !cs.specialvisibilityradius)))
873 sendentitiesindex[e] = sendentities + numsendentities;
874 sendentities[numsendentities++] = cs;
878 static int sententitiesmark = 0;
879 static int sententities[MAX_EDICTS];
880 static int sententitiesconsideration[MAX_EDICTS];
881 static int sv_writeentitiestoclient_culled_pvs;
882 static int sv_writeentitiestoclient_culled_trace;
883 static int sv_writeentitiestoclient_visibleentities;
884 static int sv_writeentitiestoclient_totalentities;
885 //static entity_frame_t sv_writeentitiestoclient_entityframe;
886 static int sv_writeentitiestoclient_clentnum;
887 static vec3_t sv_writeentitiestoclient_testeye;
888 static client_t *sv_writeentitiestoclient_client;
890 void SV_MarkWriteEntityStateToClient(entity_state_t *s)
892 vec3_t entmins, entmaxs, lightmins, lightmaxs, testorigin;
895 if (sententitiesconsideration[s->number] == sententitiesmark)
897 sententitiesconsideration[s->number] = sententitiesmark;
898 // viewmodels don't have visibility checking
899 if (s->viewmodelforclient)
901 if (s->viewmodelforclient != sv_writeentitiestoclient_clentnum)
904 // never reject player
905 else if (s->number != sv_writeentitiestoclient_clentnum)
907 // check various rejection conditions
908 if (s->nodrawtoclient == sv_writeentitiestoclient_clentnum)
910 if (s->drawonlytoclient && s->drawonlytoclient != sv_writeentitiestoclient_clentnum)
912 if (s->effects & EF_NODRAW)
914 // LordHavoc: only send entities with a model or important effects
915 if (!s->modelindex && s->specialvisibilityradius == 0)
919 // tag attached entities simply check their parent
920 if (!sendentitiesindex[s->tagentity])
922 SV_MarkWriteEntityStateToClient(sendentitiesindex[s->tagentity]);
923 if (sententities[s->tagentity] != sententitiesmark)
926 // always send world submodels, they don't generate much traffic
927 else if ((model = sv.models[s->modelindex]) == NULL || model->name[0] != '*')
929 Mod_CheckLoaded(model);
930 // entity has survived every check so far, check if visible
931 // enlarged box to account for prediction (not that there is
932 // any currently, but still helps the 'run into a room and
933 // watch items pop up' problem)
934 entmins[0] = s->origin[0] - 32.0f;
935 entmins[1] = s->origin[1] - 32.0f;
936 entmins[2] = s->origin[2] - 32.0f;
937 entmaxs[0] = s->origin[0] + 32.0f;
938 entmaxs[1] = s->origin[1] + 32.0f;
939 entmaxs[2] = s->origin[2] + 32.0f;
940 // using the model's bounding box to ensure things are visible regardless of their physics box
943 if (s->angles[0] || s->angles[2]) // pitch and roll
945 VectorAdd(entmins, model->rotatedmins, entmins);
946 VectorAdd(entmaxs, model->rotatedmaxs, entmaxs);
948 else if (s->angles[1])
950 VectorAdd(entmins, model->yawmins, entmins);
951 VectorAdd(entmaxs, model->yawmaxs, entmaxs);
955 VectorAdd(entmins, model->normalmins, entmins);
956 VectorAdd(entmaxs, model->normalmaxs, entmaxs);
959 lightmins[0] = min(entmins[0], s->origin[0] - s->specialvisibilityradius);
960 lightmins[1] = min(entmins[1], s->origin[1] - s->specialvisibilityradius);
961 lightmins[2] = min(entmins[2], s->origin[2] - s->specialvisibilityradius);
962 lightmaxs[0] = min(entmaxs[0], s->origin[0] + s->specialvisibilityradius);
963 lightmaxs[1] = min(entmaxs[1], s->origin[1] + s->specialvisibilityradius);
964 lightmaxs[2] = min(entmaxs[2], s->origin[2] + s->specialvisibilityradius);
965 sv_writeentitiestoclient_totalentities++;
966 // if not touching a visible leaf
967 if (sv_cullentities_pvs.integer && sv_writeentitiestoclient_pvsbytes && sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv_writeentitiestoclient_pvs, lightmins, lightmaxs))
969 sv_writeentitiestoclient_culled_pvs++;
972 // or not seen by random tracelines
973 if (sv_cullentities_trace.integer)
975 // LordHavoc: test center first
976 testorigin[0] = (entmins[0] + entmaxs[0]) * 0.5f;
977 testorigin[1] = (entmins[1] + entmaxs[1]) * 0.5f;
978 testorigin[2] = (entmins[2] + entmaxs[2]) * 0.5f;
979 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
980 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
981 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
984 // LordHavoc: test random offsets, to maximize chance of detection
985 testorigin[0] = lhrandom(entmins[0], entmaxs[0]);
986 testorigin[1] = lhrandom(entmins[1], entmaxs[1]);
987 testorigin[2] = lhrandom(entmins[2], entmaxs[2]);
988 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
989 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
990 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
993 if (s->specialvisibilityradius)
995 // LordHavoc: test random offsets, to maximize chance of detection
996 testorigin[0] = lhrandom(lightmins[0], lightmaxs[0]);
997 testorigin[1] = lhrandom(lightmins[1], lightmaxs[1]);
998 testorigin[2] = lhrandom(lightmins[2], lightmaxs[2]);
999 sv.worldmodel->TraceBox(sv.worldmodel, 0, &trace, sv_writeentitiestoclient_testeye, sv_writeentitiestoclient_testeye, testorigin, testorigin, SUPERCONTENTS_SOLID);
1000 if (trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, entmins, entmaxs))
1001 sv_writeentitiestoclient_client->visibletime[s->number] = realtime + 1;
1005 if (realtime > sv_writeentitiestoclient_client->visibletime[s->number])
1007 sv_writeentitiestoclient_culled_trace++;
1011 sv_writeentitiestoclient_visibleentities++;
1014 // this just marks it for sending
1015 // FIXME: it would be more efficient to send here, but the entity
1016 // compressor isn't that flexible
1017 sententities[s->number] = sententitiesmark;
1020 void SV_WriteEntitiesToClient(client_t *client, edict_t *clent, sizebuf_t *msg)
1025 entity_database4_t *d;
1027 entity_state_t *e, inactiveentitystate;
1031 // if there isn't enough space to accomplish anything, skip it
1032 if (msg->cursize + 24 > msg->maxsize)
1035 // prepare the buffer
1036 memset(&buf, 0, sizeof(buf));
1038 buf.maxsize = sizeof(data);
1040 d = client->entitydatabase4;
1042 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1043 if (!d->commit[i].numentities)
1045 // if commit buffer full, just don't bother writing an update this frame
1046 if (i == MAX_ENTITY_HISTORY)
1048 d->currentcommit = d->commit + i;
1050 // this state's number gets played around with later
1051 ClearStateToDefault(&inactiveentitystate);
1052 //inactiveentitystate = defaultstate;
1054 sv_writeentitiestoclient_client = client;
1056 sv_writeentitiestoclient_culled_pvs = 0;
1057 sv_writeentitiestoclient_culled_trace = 0;
1058 sv_writeentitiestoclient_visibleentities = 0;
1059 sv_writeentitiestoclient_totalentities = 0;
1061 Mod_CheckLoaded(sv.worldmodel);
1063 // find the client's PVS
1064 // the real place being tested from
1065 VectorAdd(clent->v->origin, clent->v->view_ofs, sv_writeentitiestoclient_testeye);
1066 sv_writeentitiestoclient_pvsbytes = 0;
1067 if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
1068 sv_writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv_writeentitiestoclient_testeye, 8, sv_writeentitiestoclient_pvs, sizeof(sv_writeentitiestoclient_pvs));
1070 sv_writeentitiestoclient_clentnum = EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
1074 // the place being reported (to consider the fact the client still
1075 // applies the view_ofs[2], so we have to only send the fractional part
1076 // of view_ofs[2], undoing what the client will redo)
1077 VectorCopy(sv_writeentitiestoclient_testeye, testorigin);
1078 i = (int) clent->v->view_ofs[2] & 255;
1081 testorigin[2] -= (float) i;
1083 for (i = 0;i < numsendentities;i++)
1084 SV_MarkWriteEntityStateToClient(sendentities + i);
1086 d->currentcommit->numentities = 0;
1087 d->currentcommit->framenum = ++client->entityframenumber;
1088 MSG_WriteByte(msg, svc_entities);
1089 MSG_WriteLong(msg, d->referenceframenum);
1090 MSG_WriteLong(msg, d->currentcommit->framenum);
1091 if (developer_networkentities.integer >= 1)
1093 Con_Printf("send svc_entities ref:%i num:%i (database: ref:%i commits:", d->referenceframenum, d->currentcommit->framenum, d->referenceframenum);
1094 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1095 if (d->commit[i].numentities)
1096 Con_Printf(" %i", d->commit[i].framenum);
1099 if (d->currententitynumber >= sv.max_edicts)
1102 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1103 MSG_WriteShort(msg, startnumber);
1104 // reset currententitynumber so if the loop does not break it we will
1105 // start at beginning next frame (if it does break, it will set it)
1106 d->currententitynumber = 1;
1107 for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1109 // find the old state to delta from
1110 e = EntityFrame4_GetReferenceEntity(d, n);
1111 // prepare the buffer
1114 if (sententities[n] == sententitiesmark)
1116 // entity exists, build an update (if empty there is no change)
1117 // find the state in the list
1118 for (;i < numsendentities && sendentities[i].number < n;i++);
1119 s = sendentities + i;
1121 Sys_Error("SV_WriteEntitiesToClient: s->number != n\n");
1123 if (s->exteriormodelforclient && s->exteriormodelforclient == sv_writeentitiestoclient_clentnum)
1125 s->flags |= RENDER_EXTERIORMODEL;
1126 EntityState_Write(s, &buf, e);
1127 s->flags &= ~RENDER_EXTERIORMODEL;
1130 EntityState_Write(s, &buf, e);
1134 s = &inactiveentitystate;
1138 // entity used to exist but doesn't anymore, send remove
1139 MSG_WriteShort(&buf, n | 0x8000);
1142 // if the commit is full, we're done this frame
1143 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1145 // next frame we will continue where we left off
1148 // add the entity to the commit
1149 EntityFrame4_AddCommitEntity(d, s);
1150 // if the message is empty, skip out now
1153 // write the message to the packet
1154 SZ_Write(msg, buf.data, buf.cursize);
1157 d->currententitynumber = n;
1159 // remove world message (invalid, and thus a good terminator)
1160 MSG_WriteShort(msg, 0x8000);
1161 // write the number of the end entity
1162 MSG_WriteShort(msg, d->currententitynumber);
1164 d->currentcommit = NULL;
1166 if (sv_cullentities_stats.integer)
1167 Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, sv_writeentitiestoclient_totalentities, sv_writeentitiestoclient_visibleentities, sv_writeentitiestoclient_culled_pvs + sv_writeentitiestoclient_culled_trace, sv_writeentitiestoclient_culled_pvs, sv_writeentitiestoclient_culled_trace);
1177 void SV_CleanupEnts (void)
1182 ent = NEXT_EDICT(sv.edicts);
1183 for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
1184 ent->v->effects = (int)ent->v->effects & ~EF_MUZZLEFLASH;
1189 SV_WriteClientdataToMessage
1193 void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
1204 // send a damage message
1206 if (ent->v->dmg_take || ent->v->dmg_save)
1208 other = PROG_TO_EDICT(ent->v->dmg_inflictor);
1209 MSG_WriteByte (msg, svc_damage);
1210 MSG_WriteByte (msg, ent->v->dmg_save);
1211 MSG_WriteByte (msg, ent->v->dmg_take);
1212 for (i=0 ; i<3 ; i++)
1213 MSG_WriteDPCoord (msg, other->v->origin[i] + 0.5*(other->v->mins[i] + other->v->maxs[i]));
1215 ent->v->dmg_take = 0;
1216 ent->v->dmg_save = 0;
1220 // send the current viewpos offset from the view entity
1222 SV_SetIdealPitch (); // how much to look up / down ideally
1224 // a fixangle might get lost in a dropped packet. Oh well.
1225 if ( ent->v->fixangle )
1227 MSG_WriteByte (msg, svc_setangle);
1228 for (i=0 ; i < 3 ; i++)
1229 MSG_WriteAngle (msg, ent->v->angles[i] );
1230 ent->v->fixangle = 0;
1235 if (ent->v->view_ofs[2] != DEFAULT_VIEWHEIGHT)
1236 bits |= SU_VIEWHEIGHT;
1238 if (ent->v->idealpitch)
1239 bits |= SU_IDEALPITCH;
1241 // stuff the sigil bits into the high bits of items for sbar, or else
1243 val = GETEDICTFIELDVALUE(ent, eval_items2);
1246 items = (int)ent->v->items | ((int)val->_float << 23);
1248 items = (int)ent->v->items | ((int)pr_global_struct->serverflags << 28);
1252 if ( (int)ent->v->flags & FL_ONGROUND)
1253 bits |= SU_ONGROUND;
1255 if ( ent->v->waterlevel >= 2)
1258 // PROTOCOL_DARKPLACES
1259 VectorClear(punchvector);
1260 if ((val = GETEDICTFIELDVALUE(ent, eval_punchvector)))
1261 VectorCopy(val->vector, punchvector);
1264 if ((val = GETEDICTFIELDVALUE(ent, eval_viewzoom)))
1266 i = val->_float * 255.0f;
1270 i = bound(0, i, 255);
1274 if (viewzoom != 255)
1275 bits |= SU_VIEWZOOM;
1277 for (i=0 ; i<3 ; i++)
1279 if (ent->v->punchangle[i])
1280 bits |= (SU_PUNCH1<<i);
1281 if (punchvector[i]) // PROTOCOL_DARKPLACES
1282 bits |= (SU_PUNCHVEC1<<i); // PROTOCOL_DARKPLACES
1283 if (ent->v->velocity[i])
1284 bits |= (SU_VELOCITY1<<i);
1287 if (ent->v->weaponframe)
1288 bits |= SU_WEAPONFRAME;
1290 if (ent->v->armorvalue)
1297 if (bits >= 16777216)
1302 MSG_WriteByte (msg, svc_clientdata);
1303 MSG_WriteShort (msg, bits);
1304 if (bits & SU_EXTEND1)
1305 MSG_WriteByte(msg, bits >> 16);
1306 if (bits & SU_EXTEND2)
1307 MSG_WriteByte(msg, bits >> 24);
1309 if (bits & SU_VIEWHEIGHT)
1310 MSG_WriteChar (msg, ent->v->view_ofs[2]);
1312 if (bits & SU_IDEALPITCH)
1313 MSG_WriteChar (msg, ent->v->idealpitch);
1315 for (i=0 ; i<3 ; i++)
1317 if (bits & (SU_PUNCH1<<i))
1318 MSG_WritePreciseAngle(msg, ent->v->punchangle[i]); // PROTOCOL_DARKPLACES
1319 if (bits & (SU_PUNCHVEC1<<i)) // PROTOCOL_DARKPLACES
1320 MSG_WriteFloat(msg, punchvector[i]); // PROTOCOL_DARKPLACES
1321 if (bits & (SU_VELOCITY1<<i))
1322 MSG_WriteFloat(msg, ent->v->velocity[i]);
1325 // [always sent] if (bits & SU_ITEMS)
1326 MSG_WriteLong (msg, items);
1328 if (bits & SU_WEAPONFRAME)
1329 MSG_WriteByte (msg, ent->v->weaponframe);
1330 if (bits & SU_ARMOR)
1331 MSG_WriteByte (msg, ent->v->armorvalue);
1332 if (bits & SU_WEAPON)
1333 MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v->weaponmodel)));
1335 MSG_WriteShort (msg, ent->v->health);
1336 MSG_WriteByte (msg, ent->v->currentammo);
1337 MSG_WriteByte (msg, ent->v->ammo_shells);
1338 MSG_WriteByte (msg, ent->v->ammo_nails);
1339 MSG_WriteByte (msg, ent->v->ammo_rockets);
1340 MSG_WriteByte (msg, ent->v->ammo_cells);
1342 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_NEXUIZ)
1346 if ( ((int)ent->v->weapon) & (1<<i) )
1348 MSG_WriteByte (msg, i);
1355 MSG_WriteByte (msg, ent->v->weapon);
1358 if (bits & SU_VIEWZOOM)
1359 MSG_WriteByte (msg, viewzoom);
1363 =======================
1364 SV_SendClientDatagram
1365 =======================
1367 static qbyte sv_sendclientdatagram_buf[NET_MAXMESSAGE]; // FIXME?
1368 qboolean SV_SendClientDatagram (client_t *client)
1372 msg.data = sv_sendclientdatagram_buf;
1373 msg.maxsize = (int)bound(50.0, client->netconnection->rate * host_realframetime, (double)sizeof(sv_sendclientdatagram_buf));
1376 MSG_WriteByte (&msg, svc_time);
1377 MSG_WriteFloat (&msg, sv.time);
1379 // add the client specific data to the datagram
1380 SV_WriteClientdataToMessage (client->edict, &msg);
1382 SV_WriteEntitiesToClient (client, client->edict, &msg);
1384 // copy the server datagram if there is space
1385 // FIXME: put in delayed queue of effects to send
1386 if (msg.cursize + sv.datagram.cursize <= msg.maxsize)
1387 SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
1389 // send the datagram
1390 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1392 SV_DropClient (true);// if the message couldn't send, kick off
1400 =======================
1401 SV_UpdateToReliableMessages
1402 =======================
1404 void SV_UpdateToReliableMessages (void)
1411 // check for changes to be sent over the reliable streams
1412 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1414 // update the host_client fields we care about according to the entity fields
1415 sv_player = EDICT_NUM(i+1);
1416 s = PR_GetString(sv_player->v->netname);
1417 if (s != host_client->name)
1421 // point the string back at host_client->name to keep it safe
1422 strlcpy (host_client->name, s, sizeof (host_client->name));
1423 sv_player->v->netname = PR_SetString(host_client->name);
1425 if ((val = GETEDICTFIELDVALUE(sv_player, eval_clientcolors)) && host_client->colors != val->_float)
1426 host_client->colors = val->_float;
1427 host_client->frags = sv_player->v->frags;
1428 if (gamemode == GAME_NEHAHRA)
1429 if ((val = GETEDICTFIELDVALUE(sv_player, eval_pmodel)) && host_client->pmodel != val->_float)
1430 host_client->pmodel = val->_float;
1432 // if the fields changed, send messages about the changes
1433 if (strcmp(host_client->old_name, host_client->name))
1435 strcpy(host_client->old_name, host_client->name);
1436 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1438 if (!client->spawned || !client->netconnection)
1440 MSG_WriteByte (&client->message, svc_updatename);
1441 MSG_WriteByte (&client->message, i);
1442 MSG_WriteString (&client->message, host_client->name);
1445 if (host_client->old_colors != host_client->colors)
1447 host_client->old_colors = host_client->colors;
1448 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1450 if (!client->spawned || !client->netconnection)
1452 MSG_WriteByte (&client->message, svc_updatecolors);
1453 MSG_WriteByte (&client->message, i);
1454 MSG_WriteByte (&client->message, host_client->colors);
1457 if (host_client->old_frags != host_client->frags)
1459 host_client->old_frags = host_client->frags;
1460 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1462 if (!client->spawned || !client->netconnection)
1464 MSG_WriteByte (&client->message, svc_updatefrags);
1465 MSG_WriteByte (&client->message, i);
1466 MSG_WriteShort (&client->message, host_client->frags);
1471 for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
1472 if (client->netconnection)
1473 SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
1475 SZ_Clear (&sv.reliable_datagram);
1480 =======================
1483 Send a nop message without trashing or sending the accumulated client
1485 =======================
1487 void SV_SendNop (client_t *client)
1493 msg.maxsize = sizeof(buf);
1496 MSG_WriteChar (&msg, svc_nop);
1498 if (NetConn_SendUnreliableMessage (client->netconnection, &msg) == -1)
1499 SV_DropClient (true); // if the message couldn't send, kick off
1500 client->last_message = realtime;
1504 =======================
1505 SV_SendClientMessages
1506 =======================
1508 void SV_SendClientMessages (void)
1510 int i, prepared = false;
1512 // update frags, names, etc
1513 SV_UpdateToReliableMessages();
1515 // build individual updates
1516 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1518 if (!host_client->active)
1520 if (!host_client->netconnection)
1522 SZ_Clear(&host_client->message);
1526 if (host_client->deadsocket || host_client->message.overflowed)
1528 SV_DropClient (true); // if the message couldn't send, kick off
1532 if (host_client->spawned)
1537 // only prepare entities once per frame
1538 SV_PrepareEntitiesForSending();
1540 if (!SV_SendClientDatagram (host_client))
1545 // the player isn't totally in the game yet
1546 // send small keepalive messages if too much time has passed
1547 // send a full message when the next signon stage has been requested
1548 // some other message data (name changes, etc) may accumulate
1549 // between signon stages
1550 if (!host_client->sendsignon)
1552 if (realtime - host_client->last_message > 5)
1553 SV_SendNop (host_client);
1554 continue; // don't send out non-signon messages
1558 if (host_client->message.cursize || host_client->dropasap)
1560 if (!NetConn_CanSendMessage (host_client->netconnection))
1563 if (host_client->dropasap)
1564 SV_DropClient (false); // went to another level
1567 if (NetConn_SendReliableMessage (host_client->netconnection, &host_client->message) == -1)
1568 SV_DropClient (true); // if the message couldn't send, kick off
1569 SZ_Clear (&host_client->message);
1570 host_client->last_message = realtime;
1571 host_client->sendsignon = false;
1576 // clear muzzle flashes
1582 ==============================================================================
1586 ==============================================================================
1595 int SV_ModelIndex (const char *name)
1599 if (!name || !name[0])
1602 for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
1603 if (!strcmp(sv.model_precache[i], name))
1605 if (i==MAX_MODELS || !sv.model_precache[i])
1606 Host_Error ("SV_ModelIndex: model %s not precached", name);
1610 #ifdef SV_QUAKEENTITIES
1617 void SV_CreateBaseline (void)
1619 int i, entnum, large;
1622 // LordHavoc: clear *all* states (note just active ones)
1623 for (entnum = 0;entnum < sv.max_edicts;entnum++)
1625 // get the current server version
1626 svent = EDICT_NUM(entnum);
1628 // LordHavoc: always clear state values, whether the entity is in use or not
1629 ClearStateToDefault(&svent->e->baseline);
1633 if (entnum > svs.maxclients && !svent->v->modelindex)
1636 // create entity baseline
1637 VectorCopy (svent->v->origin, svent->e->baseline.origin);
1638 VectorCopy (svent->v->angles, svent->e->baseline.angles);
1639 svent->e->baseline.frame = svent->v->frame;
1640 svent->e->baseline.skin = svent->v->skin;
1641 if (entnum > 0 && entnum <= svs.maxclients)
1643 svent->e->baseline.colormap = entnum;
1644 svent->e->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1648 svent->e->baseline.colormap = 0;
1649 svent->e->baseline.modelindex = svent->v->modelindex;
1653 if (svent->e->baseline.modelindex & 0xFF00 || svent->e->baseline.frame & 0xFF00)
1656 // add to the message
1658 MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
1660 MSG_WriteByte (&sv.signon, svc_spawnbaseline);
1661 MSG_WriteShort (&sv.signon, entnum);
1665 MSG_WriteShort (&sv.signon, svent->e->baseline.modelindex);
1666 MSG_WriteShort (&sv.signon, svent->e->baseline.frame);
1670 MSG_WriteByte (&sv.signon, svent->e->baseline.modelindex);
1671 MSG_WriteByte (&sv.signon, svent->e->baseline.frame);
1673 MSG_WriteByte (&sv.signon, svent->e->baseline.colormap);
1674 MSG_WriteByte (&sv.signon, svent->e->baseline.skin);
1675 for (i=0 ; i<3 ; i++)
1677 MSG_WriteDPCoord(&sv.signon, svent->e->baseline.origin[i]);
1678 MSG_WriteAngle(&sv.signon, svent->e->baseline.angles[i]);
1689 Tell all the clients that the server is changing levels
1692 void SV_SendReconnect (void)
1699 msg.maxsize = sizeof(data);
1701 MSG_WriteChar (&msg, svc_stufftext);
1702 MSG_WriteString (&msg, "reconnect\n");
1703 NetConn_SendToAll (&msg, 5);
1705 if (cls.state != ca_dedicated)
1706 Cmd_ExecuteString ("reconnect\n", src_command);
1714 Grabs the current state of each client for saving across the
1715 transition to another level
1718 void SV_SaveSpawnparms (void)
1722 svs.serverflags = pr_global_struct->serverflags;
1724 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1726 if (!host_client->active)
1729 // call the progs to get default spawn parms for the new client
1730 pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1731 PR_ExecuteProgram (pr_global_struct->SetChangeParms, "QC function SetChangeParms is missing");
1732 for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
1733 host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1737 void SV_IncreaseEdicts(void)
1741 int oldmax_edicts = sv.max_edicts;
1742 void *oldedictsengineprivate = sv.edictsengineprivate;
1743 void *oldedictsfields = sv.edictsfields;
1744 void *oldmoved_edicts = sv.moved_edicts;
1746 if (sv.max_edicts >= MAX_EDICTS)
1749 // links don't survive the transition, so unlink everything
1750 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1753 SV_UnlinkEdict(sv.edicts + i);
1754 memset(&ent->e->areagrid, 0, sizeof(ent->e->areagrid));
1758 sv.max_edicts = min(sv.max_edicts + 256, MAX_EDICTS);
1759 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1760 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1761 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1763 memcpy(sv.edictsengineprivate, oldedictsengineprivate, oldmax_edicts * sizeof(edict_engineprivate_t));
1764 memcpy(sv.edictsfields, oldedictsfields, oldmax_edicts * pr_edict_size);
1766 for (i = 0, ent = sv.edicts;i < sv.max_edicts;i++, ent++)
1768 ent->e = sv.edictsengineprivate + i;
1769 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1770 // link every entity except world
1772 SV_LinkEdict(ent, false);
1775 Mem_Free(oldedictsengineprivate);
1776 Mem_Free(oldedictsfields);
1777 Mem_Free(oldmoved_edicts);
1784 This is called at the start of each level
1787 extern float scr_centertime_off;
1789 void SV_SpawnServer (const char *server)
1795 // let's not have any servers with no name
1796 if (hostname.string[0] == 0)
1797 Cvar_Set ("hostname", "UNNAMED");
1798 scr_centertime_off = 0;
1800 Con_DPrintf("SpawnServer: %s\n",server);
1801 svs.changelevel_issued = false; // now safe to issue another
1804 // tell all connected clients that we are going to a new level
1810 // make sure cvars have been checked before opening the ports
1811 NetConn_ServerFrame();
1812 NetConn_OpenServerPorts(true);
1816 // make cvars consistant
1819 Cvar_SetValue ("deathmatch", 0);
1820 current_skill = bound(0, (int)(skill.value + 0.5), 3);
1822 Cvar_SetValue ("skill", (float)current_skill);
1825 // set up the new server
1827 Host_ClearMemory ();
1829 memset (&sv, 0, sizeof(sv));
1831 strlcpy (sv.name, server, sizeof (sv.name));
1833 // load progs to get entity field count
1836 // allocate server memory
1837 // start out with just enough room for clients and a reasonable estimate of entities
1838 sv.max_edicts = max(svs.maxclients + 1, 512);
1839 sv.max_edicts = min(sv.max_edicts, MAX_EDICTS);
1841 // clear the edict memory pool
1842 Mem_EmptyPool(sv_edicts_mempool);
1843 // edict_t structures (hidden from progs)
1844 sv.edicts = Mem_Alloc(sv_edicts_mempool, MAX_EDICTS * sizeof(edict_t));
1845 // engine private structures (hidden from progs)
1846 sv.edictsengineprivate = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_engineprivate_t));
1847 // progs fields, often accessed by server
1848 sv.edictsfields = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * pr_edict_size);
1849 // used by PushMove to move back pushed entities
1850 sv.moved_edicts = Mem_Alloc(sv_edicts_mempool, sv.max_edicts * sizeof(edict_t *));
1851 for (i = 0;i < sv.max_edicts;i++)
1853 ent = sv.edicts + i;
1854 ent->e = sv.edictsengineprivate + i;
1855 ent->v = (void *)((qbyte *)sv.edictsfields + i * pr_edict_size);
1858 sv.datagram.maxsize = sizeof(sv.datagram_buf);
1859 sv.datagram.cursize = 0;
1860 sv.datagram.data = sv.datagram_buf;
1862 sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1863 sv.reliable_datagram.cursize = 0;
1864 sv.reliable_datagram.data = sv.reliable_datagram_buf;
1866 sv.signon.maxsize = sizeof(sv.signon_buf);
1867 sv.signon.cursize = 0;
1868 sv.signon.data = sv.signon_buf;
1870 // leave slots at start for clients only
1871 sv.num_edicts = svs.maxclients+1;
1873 sv.state = ss_loading;
1880 strlcpy (sv.name, server, sizeof (sv.name));
1881 snprintf (sv.modelname, sizeof (sv.modelname), "maps/%s.bsp", server);
1882 sv.worldmodel = Mod_ForName(sv.modelname, false, true, true);
1885 Con_Printf("Couldn't spawn server %s\n", sv.modelname);
1889 sv.models[1] = sv.worldmodel;
1892 // clear world interaction links
1896 sv.sound_precache[0] = "";
1898 sv.model_precache[0] = "";
1899 sv.model_precache[1] = sv.modelname;
1900 for (i = 1;i < sv.worldmodel->brush.numsubmodels;i++)
1902 sv.model_precache[i+1] = localmodels[i];
1903 sv.models[i+1] = Mod_ForName (localmodels[i], false, false, false);
1907 // load the rest of the entities
1910 memset (ent->v, 0, progs->entityfields * 4);
1911 ent->e->free = false;
1912 ent->v->model = PR_SetString(sv.modelname);
1913 ent->v->modelindex = 1; // world model
1914 ent->v->solid = SOLID_BSP;
1915 ent->v->movetype = MOVETYPE_PUSH;
1918 pr_global_struct->coop = coop.integer;
1920 pr_global_struct->deathmatch = deathmatch.integer;
1922 pr_global_struct->mapname = PR_SetString(sv.name);
1924 // serverflags are for cross level information (sigils)
1925 pr_global_struct->serverflags = svs.serverflags;
1927 // load replacement entity file if found
1929 if (sv_entpatch.integer)
1930 entities = FS_LoadFile(va("maps/%s.ent", sv.name), tempmempool, true);
1933 Con_Printf("Loaded maps/%s.ent\n", sv.name);
1934 ED_LoadFromFile (entities);
1938 ED_LoadFromFile (sv.worldmodel->brush.entities);
1941 // LordHavoc: clear world angles (to fix e3m3.bsp)
1942 VectorClear(sv.edicts->v->angles);
1946 // all setup is completed, any further precache statements are errors
1947 sv.state = ss_active;
1949 // run two frames to allow everything to settle
1950 for (i = 0;i < 2;i++)
1952 sv.frametime = pr_global_struct->frametime = host_frametime = 0.1;
1958 #ifdef QUAKEENTITIES
1959 // create a baseline for more efficient communications
1960 SV_CreateBaseline ();
1963 // send serverinfo to all connected clients
1964 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1965 if (host_client->netconnection)
1966 SV_SendServerinfo(host_client);
1968 Con_DPrint("Server spawned.\n");
1969 NetConn_Heartbeat (2);