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 "bspfile.h"
23 #include "cmd.h"
24 #include "console.h"
25 #include "cvar.h"
26 #include "host.h"
27 #include "model.h"
28 #include "net.h"
29 #include "protocol.h"
30 #include "quakedef.h"
31 #include "screen.h"
32 #include "server.h"
33 #include "sound.h"
34 #include "sys.h"
35 #include "world.h"
36 
37 server_t sv;
38 server_static_t svs;
39 
40 #define MODSTRLEN (sizeof("*" stringify(MAX_MODELS)) / sizeof(char))
41 char localmodels[MAX_MODELS][MODSTRLEN]; // inline model names for precache
42 
43 //============================================================================
44 
45 typedef struct {
46     int version;
47     const char *name;
48     const char *description;
49 } sv_protocol_t;
50 
51 #define PROT(v, n, d) { v, n, d }
52 static sv_protocol_t sv_protocols[] = {
53     {PROTOCOL_VERSION_NQ,   "nq",   "Standard NetQuake protocol"},
54     {PROTOCOL_VERSION_FITZ, "fitz", "FitzQuake protocol"},
55     {PROTOCOL_VERSION_BJP,  "bjp",  "BJP protocol (v1)"},
56     {PROTOCOL_VERSION_BJP2, "bjp2", "BJP protocol (v2)"},
57     {PROTOCOL_VERSION_BJP3, "bjp3", "BJP protocol (v3)"},
58 };
59 
60 static int sv_protocol = PROTOCOL_VERSION_NQ;
61 
SV_Protocol_f(void)62 static void SV_Protocol_f(void)
63 {
64    const char *name = "unknown";
65    int i;
66 
67    if (Cmd_Argc() == 1)
68    {
69       for (i = 0; i < ARRAY_SIZE(sv_protocols); i++)
70       {
71          if (sv_protocols[i].version == sv_protocol)
72          {
73             name = sv_protocols[i].name;
74             break;
75          }
76       }
77       Con_Printf("sv_protocol is %d (%s)\n"
78             "    use 'sv_protocol list' to list available protocols\n",
79             sv_protocol, name);
80    }
81    else if (Cmd_Argc() == 2)
82    {
83       if (!strcasecmp(Cmd_Argv(1), "list"))
84       {
85          Con_Printf("Version  Name  Description\n"
86                "-------  ----  -----------\n");
87          for (i = 0; i < ARRAY_SIZE(sv_protocols); i++)
88          {
89             Con_Printf("%7d  %-4s  %s\n", sv_protocols[i].version,
90                   sv_protocols[i].name, sv_protocols[i].description);
91          }
92       } else {
93          int v = Q_atoi(Cmd_Argv(1));
94          for (i = 0; i < ARRAY_SIZE(sv_protocols); i++) {
95             if (sv_protocols[i].version == v)
96                break;
97             if (!strcasecmp(sv_protocols[i].name, Cmd_Argv(1)))
98                break;
99          }
100          if (i == ARRAY_SIZE(sv_protocols)) {
101             Con_Printf("sv_protocol: unknown protocol version\n");
102             return;
103          }
104          if (sv_protocol != sv_protocols[i].version) {
105             sv_protocol = sv_protocols[i].version;
106             if (sv.active)
107                Con_Printf("change will not take effect until the next "
108                      "level load.\n");
109          }
110       }
111    } else {
112       Con_Printf("Usage: sv_protocol [<version> | <name> | 'list']\n");
113    }
114 }
115 
SV_Protocol_Arg_f(const char * arg)116 static struct stree_root *SV_Protocol_Arg_f(const char *arg)
117 {
118    int i, arg_len;
119    char digits[10];
120    struct stree_root *root;
121 
122    root = (struct stree_root*)Z_Malloc(sizeof(struct stree_root));
123    if (root)
124    {
125       root->entries = 0;
126       root->maxlen = 0;
127       root->minlen = -1;
128       //root->root = {NULL};
129       root->stack = NULL;
130 
131       STree_AllocInit();
132       arg_len = arg ? strlen(arg) : 0;
133       for (i = 0; i < ARRAY_SIZE(sv_protocols); i++)
134       {
135          if (!arg || !strncasecmp(sv_protocols[i].name, arg, arg_len))
136             STree_InsertAlloc(root, sv_protocols[i].name, false);
137          snprintf(digits, sizeof(digits), "%d", sv_protocols[i].version);
138          if (arg_len && !strncmp(digits, arg, arg_len))
139             STree_InsertAlloc(root, digits, true);
140       }
141    }
142    return root;
143 }
144 
145 /*
146 ===============
147 SV_Init
148 ===============
149 */
SV_Init(void)150 void SV_Init(void)
151 {
152     int i;
153 
154     Cvar_RegisterVariable(&sv_maxvelocity);
155     Cvar_RegisterVariable(&sv_gravity);
156     Cvar_RegisterVariable(&sv_friction);
157     Cvar_RegisterVariable(&sv_edgefriction);
158     Cvar_RegisterVariable(&sv_stopspeed);
159     Cvar_RegisterVariable(&sv_maxspeed);
160     Cvar_RegisterVariable(&sv_accelerate);
161     Cvar_RegisterVariable(&sv_idealpitchscale);
162     Cvar_RegisterVariable(&sv_aim);
163     Cvar_RegisterVariable(&sv_nostep);
164 
165     Cmd_AddCommand("sv_protocol", SV_Protocol_f);
166     Cmd_SetCompletion("sv_protocol", SV_Protocol_Arg_f);
167 
168     for (i = 0; i < MAX_MODELS; i++)
169 	sprintf(localmodels[i], "*%i", i);
170 }
171 
172 /*
173 =============================================================================
174 
175 EVENT MESSAGES
176 
177 =============================================================================
178 */
179 
180 /*
181 ==================
182 SV_StartParticle
183 
184 Make sure the event gets sent to all clients
185 ==================
186 */
SV_StartParticle(vec3_t org,vec3_t dir,int color,int count)187 void SV_StartParticle(vec3_t org, vec3_t dir, int color, int count)
188 {
189    int i, v;
190 
191    /*
192     * Drop silently if there is no room
193     * FIXME - does not take into account MTU...
194     */
195    if (sv.datagram.cursize > MAX_DATAGRAM - 12)
196       return;
197 
198    MSG_WriteByte(&sv.datagram, svc_particle);
199    MSG_WriteCoord(&sv.datagram, org[0]);
200    MSG_WriteCoord(&sv.datagram, org[1]);
201    MSG_WriteCoord(&sv.datagram, org[2]);
202    for (i = 0; i < 3; i++)
203    {
204       v = dir[i] * 16;
205       if (v > 127)
206          v = 127;
207       else if (v < -128)
208          v = -128;
209       MSG_WriteChar(&sv.datagram, v);
210    }
211    MSG_WriteByte(&sv.datagram, count);
212    MSG_WriteByte(&sv.datagram, color);
213 }
214 
SV_WriteSoundNum(sizebuf_t * sb,int c,unsigned int bits)215 static void SV_WriteSoundNum(sizebuf_t *sb, int c, unsigned int bits)
216 {
217    switch (sv.protocol)
218    {
219       case PROTOCOL_VERSION_NQ:
220       case PROTOCOL_VERSION_BJP:
221          MSG_WriteByte(sb, c);
222          break;
223       case PROTOCOL_VERSION_BJP2:
224       case PROTOCOL_VERSION_BJP3:
225          MSG_WriteShort(sb, c);
226          break;
227       case PROTOCOL_VERSION_FITZ:
228          if (bits & SND_FITZ_LARGESOUND)
229             MSG_WriteShort(sb, c);
230          else
231             MSG_WriteByte(sb, c);
232          break;
233       default:
234          Host_Error("%s: Unknown protocol version (%d)\n", __func__,
235                sv.protocol);
236    }
237 }
238 
239 /*
240 ==================
241 SV_StartSound
242 
243 Each entity can have eight independant sound sources, like voice,
244 weapon, feet, etc.
245 
246 Channel 0 is an auto-allocate channel, the others override anything
247 allready running on that entity/channel pair.
248 
249 An attenuation of 0 will play full volume everywhere in the level.
250 Larger attenuations will drop off.  (max 4 attenuation)
251 
252 ==================
253 */
SV_StartSound(edict_t * entity,int channel,const char * sample,int volume,float attenuation)254 void SV_StartSound(edict_t *entity, int channel, const char *sample, int volume,
255 	      float attenuation)
256 {
257    int sound_num;
258    int field_mask;
259    int i;
260    int ent;
261    float coord;
262 
263    if (volume < 0 || volume > 255)
264       Sys_Error("%s: volume = %i", __func__, volume);
265 
266    if (attenuation < 0 || attenuation > 4)
267       Sys_Error("%s: attenuation = %f", __func__, attenuation);
268 
269    if (channel < 0 || channel > 7)
270       Sys_Error("%s: channel = %i", __func__, channel);
271 
272    /*
273     * Drop silently if there is no room
274     * FIXME - does not take into account MTU...
275     */
276    if (sv.datagram.cursize > MAX_DATAGRAM - 14)
277       return;
278 
279    // find precache number for sound
280    for (sound_num = 1; sound_num < MAX_SOUNDS
281          && sv.sound_precache[sound_num]; sound_num++)
282       if (!strcmp(sample, sv.sound_precache[sound_num]))
283          break;
284 
285    if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) {
286       Con_Printf("%s: %s not precacheed\n", __func__, sample);
287       return;
288    }
289 
290    ent = NUM_FOR_EDICT(entity);
291 
292    field_mask = 0;
293    if (volume != DEFAULT_SOUND_PACKET_VOLUME)
294       field_mask |= SND_VOLUME;
295    if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
296       field_mask |= SND_ATTENUATION;
297 
298    if (ent >= 8192) {
299       if (sv.protocol != PROTOCOL_VERSION_FITZ)
300          return; /* currently no other protocols can encode these */
301       field_mask |= SND_FITZ_LARGEENTITY;
302    }
303    if (sound_num >= 256 || channel >= 8) {
304       if (sv.protocol != PROTOCOL_VERSION_FITZ)
305          return; /* currently no other protocols can encode these */
306       field_mask |= SND_FITZ_LARGESOUND;
307    }
308 
309    // directed messages go only to the entity the are targeted on
310    MSG_WriteByte(&sv.datagram, svc_sound);
311    MSG_WriteByte(&sv.datagram, field_mask);
312    if (field_mask & SND_VOLUME)
313       MSG_WriteByte(&sv.datagram, volume);
314    if (field_mask & SND_ATTENUATION)
315       MSG_WriteByte(&sv.datagram, attenuation * 64);
316    if (field_mask & SND_FITZ_LARGEENTITY) {
317       MSG_WriteShort(&sv.datagram, ent);
318       MSG_WriteByte(&sv.datagram, channel);
319    } else {
320       MSG_WriteShort(&sv.datagram, (ent << 3) | channel);
321    }
322    SV_WriteSoundNum(&sv.datagram, sound_num, field_mask);
323    for (i = 0; i < 3; i++) {
324       coord = entity->v.origin[i];
325       coord += 0.5 * (entity->v.mins[i] + entity->v.maxs[i]);
326       MSG_WriteCoord(&sv.datagram, coord);
327    }
328 }
329 
330 /*
331 ==============================================================================
332 
333 CLIENT SPAWNING
334 
335 ==============================================================================
336 */
337 
338 /*
339 ================
340 SV_SendServerinfo
341 
342 Sends the first message from the server to a connected client.
343 This will be sent on the initial connection and upon each server load.
344 ================
345 */
SV_SendServerinfo(client_t * client)346 void SV_SendServerinfo(client_t *client)
347 {
348    const char **s;
349 
350    MSG_WriteByte(&client->message, svc_print);
351    MSG_WriteStringf(&client->message,
352          "%c\nVERSION TyrQuake-%s SERVER (%i CRC)",
353          2, stringify(TYR_VERSION), pr_crc);
354 
355    MSG_WriteByte(&client->message, svc_serverinfo);
356    MSG_WriteLong(&client->message, sv.protocol);
357    MSG_WriteByte(&client->message, svs.maxclients);
358 
359    if (!coop.value && deathmatch.value)
360       MSG_WriteByte(&client->message, GAME_DEATHMATCH);
361    else
362       MSG_WriteByte(&client->message, GAME_COOP);
363 
364    MSG_WriteString(&client->message, PR_GetString(sv.edicts->v.message));
365 
366    for (s = sv.model_precache + 1; *s; s++)
367       MSG_WriteString(&client->message, *s);
368    MSG_WriteByte(&client->message, 0);
369 
370    for (s = sv.sound_precache + 1; *s; s++)
371       MSG_WriteString(&client->message, *s);
372    MSG_WriteByte(&client->message, 0);
373 
374    // send music
375    MSG_WriteByte(&client->message, svc_cdtrack);
376    MSG_WriteByte(&client->message, sv.edicts->v.sounds);
377    MSG_WriteByte(&client->message, sv.edicts->v.sounds);
378 
379    // set view
380    MSG_WriteByte(&client->message, svc_setview);
381    MSG_WriteShort(&client->message, NUM_FOR_EDICT(client->edict));
382 
383    MSG_WriteByte(&client->message, svc_signonnum);
384    MSG_WriteByte(&client->message, 1);
385 
386    client->sendsignon = true;
387    client->spawned = false;	// need prespawn, spawn, etc
388 }
389 
390 /*
391 ================
392 SV_ConnectClient
393 
394 Initializes a client_t for a new net connection.  This will only be called
395 once for a player each game, not once for each level change.
396 ================
397 */
SV_ConnectClient(int clientnum)398 void SV_ConnectClient(int clientnum)
399 {
400    edict_t *ent;
401    int edictnum;
402    struct qsocket_s *netconnection;
403    int i;
404    float spawn_parms[NUM_SPAWN_PARMS];
405    client_t *client = svs.clients + clientnum;
406 
407    Con_DPrintf("Client %s connected\n", client->netconnection->address);
408 
409    edictnum = clientnum + 1;
410 
411    ent = EDICT_NUM(edictnum);
412 
413    // set up the client_t
414    netconnection = client->netconnection;
415 
416    if (sv.loadgame)
417       memcpy(spawn_parms, client->spawn_parms, sizeof(spawn_parms));
418    memset(client, 0, sizeof(*client));
419    client->netconnection = netconnection;
420 
421    strcpy(client->name, "unconnected");
422    client->active = true;
423    client->spawned = false;
424    client->edict = ent;
425    client->message.data = client->msgbuf;
426    client->message.maxsize = sizeof(client->msgbuf);
427    client->message.allowoverflow = true;	// we can catch it
428 
429    if (sv.loadgame) {
430       memcpy(client->spawn_parms, spawn_parms, sizeof(spawn_parms));
431    } else {
432       // call the progs to get default spawn parms for the new client
433       PR_ExecuteProgram(pr_global_struct->SetNewParms);
434       for (i = 0; i < NUM_SPAWN_PARMS; i++)
435          client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
436    }
437 
438    SV_SendServerinfo(client);
439 }
440 
441 
442 /*
443 ===================
444 SV_CheckForNewClients
445 
446 ===================
447 */
SV_CheckForNewClients(void)448 void SV_CheckForNewClients(void)
449 {
450    struct qsocket_s *sock;
451    int i;
452 
453    // check for new connections
454    while (1)
455    {
456       sock = NET_CheckNewConnections();
457       if (!sock)
458          break;
459 
460       // init a new client structure
461       for (i = 0; i < svs.maxclients; i++)
462          if (!svs.clients[i].active)
463             break;
464       if (i == svs.maxclients)
465          Sys_Error("%s: no free clients", __func__);
466 
467       svs.clients[i].netconnection = sock;
468       SV_ConnectClient(i);
469 
470       net_activeconnections++;
471    }
472 }
473 
474 
475 
476 /*
477 ===============================================================================
478 
479 FRAME UPDATES
480 
481 ===============================================================================
482 */
483 
484 /*
485 ==================
486 SV_ClearDatagram
487 
488 ==================
489 */
490 void
SV_ClearDatagram(void)491 SV_ClearDatagram(void)
492 {
493     SZ_Clear(&sv.datagram);
494 }
495 
SV_WriteModelIndex(sizebuf_t * sb,int c,unsigned int bits)496 void SV_WriteModelIndex(sizebuf_t *sb, int c, unsigned int bits)
497 {
498    switch (sv.protocol)
499    {
500       case PROTOCOL_VERSION_NQ:
501          MSG_WriteByte(sb, c);
502          break;
503       case PROTOCOL_VERSION_BJP:
504       case PROTOCOL_VERSION_BJP2:
505       case PROTOCOL_VERSION_BJP3:
506          MSG_WriteShort(sb, c);
507          break;
508       case PROTOCOL_VERSION_FITZ:
509          if (bits & B_FITZ_LARGEMODEL)
510             MSG_WriteShort(sb, c);
511          else
512             MSG_WriteByte(sb, c);
513          break;
514       default:
515          Host_Error("%s: Unknown protocol version (%d)\n", __func__,
516                sv.protocol);
517    }
518 }
519 
520 /*
521 =============
522 SV_WriteEntitiesToClient
523 
524 =============
525 */
SV_WriteEntitiesToClient(edict_t * clent,sizebuf_t * msg)526 void SV_WriteEntitiesToClient(edict_t *clent, sizebuf_t *msg)
527 {
528    int e, i;
529    int bits;
530    const leafbits_t *pvs;
531    vec3_t org;
532    float miss;
533    edict_t *ent;
534 
535    // find the client's PVS
536    VectorAdd(clent->v.origin, clent->v.view_ofs, org);
537    pvs = Mod_FatPVS(sv.worldmodel, org);
538 
539    // send over all entities (excpet the client) that touch the pvs
540    ent = NEXT_EDICT(sv.edicts);
541    for (e = 1; e < sv.num_edicts; e++, ent = NEXT_EDICT(ent)) {
542 
543       // clent is ALWAYS sent
544       if (ent != clent) {
545 
546          // ignore ents without visible models
547          if (!ent->v.modelindex || !*PR_GetString(ent->v.model))
548             continue;
549 
550          // ignore if not touching a PV leaf
551          for (i = 0; i < ent->num_leafs; i++)
552             if (Mod_TestLeafBit(pvs, ent->leafnums[i]))
553                break;
554 
555          if (i == ent->num_leafs)
556             continue;	// not visible
557       }
558 
559       if (msg->maxsize - msg->cursize < 16) {
560          Con_Printf("packet overflow\n");
561          return;
562       }
563       // send an update
564       bits = 0;
565 
566       for (i = 0; i < 3; i++) {
567          miss = ent->v.origin[i] - ent->baseline.origin[i];
568          if (miss < -0.1 || miss > 0.1)
569             bits |= U_ORIGIN1 << i;
570       }
571 
572       if (ent->v.angles[0] != ent->baseline.angles[0])
573          bits |= U_ANGLE1;
574 
575       if (ent->v.angles[1] != ent->baseline.angles[1])
576          bits |= U_ANGLE2;
577 
578       if (ent->v.angles[2] != ent->baseline.angles[2])
579          bits |= U_ANGLE3;
580 
581       if (ent->v.movetype == MOVETYPE_STEP)
582          bits |= U_NOLERP;	// don't mess up the step animation
583 
584       if (ent->baseline.colormap != ent->v.colormap)
585          bits |= U_COLORMAP;
586 
587       if (ent->baseline.skinnum != ent->v.skin)
588          bits |= U_SKIN;
589 
590       if (ent->baseline.frame != ent->v.frame)
591          bits |= U_FRAME;
592 
593       if (ent->baseline.effects != ent->v.effects)
594          bits |= U_EFFECTS;
595 
596       if (ent->baseline.modelindex != ent->v.modelindex)
597          bits |= U_MODEL;
598 
599       /* FIXME - TODO: add alpha stuff here */
600 
601       if (sv.protocol == PROTOCOL_VERSION_FITZ) {
602          if ((bits & U_FRAME) && ((int)ent->v.frame & 0xff00))
603             bits |= U_FITZ_FRAME2;
604          if ((bits & U_MODEL) && ((int)ent->v.modelindex & 0xff00))
605             bits |= U_FITZ_MODEL2;
606          /* FIXME - Add the U_LERPFINISH bit */
607          if (bits & 0x00ff0000)
608             bits |= U_FITZ_EXTEND1;
609          if (bits & 0xff000000)
610             bits |= U_FITZ_EXTEND2;
611       }
612 
613       if (e >= 256)
614          bits |= U_LONGENTITY;
615 
616       if (bits >= 256)
617          bits |= U_MOREBITS;
618 
619       //
620       // write the message
621       //
622       MSG_WriteByte(msg, bits | U_SIGNAL);
623 
624       if (bits & U_MOREBITS)
625          MSG_WriteByte(msg, bits >> 8);
626       if (bits & U_FITZ_EXTEND1)
627          MSG_WriteByte(msg, bits >> 16);
628       if (bits & U_FITZ_EXTEND2)
629          MSG_WriteByte(msg, bits >> 24);
630 
631       if (bits & U_LONGENTITY)
632          MSG_WriteShort(msg, e);
633       else
634          MSG_WriteByte(msg, e);
635 
636       if (bits & U_MODEL)
637          SV_WriteModelIndex(msg, ent->v.modelindex, 0);
638       if (bits & U_FRAME)
639          MSG_WriteByte(msg, ent->v.frame);
640       if (bits & U_COLORMAP)
641          MSG_WriteByte(msg, ent->v.colormap);
642       if (bits & U_SKIN)
643          MSG_WriteByte(msg, ent->v.skin);
644       if (bits & U_EFFECTS)
645          MSG_WriteByte(msg, ent->v.effects);
646       if (bits & U_ORIGIN1)
647          MSG_WriteCoord(msg, ent->v.origin[0]);
648       if (bits & U_ANGLE1)
649          MSG_WriteAngle(msg, ent->v.angles[0]);
650       if (bits & U_ORIGIN2)
651          MSG_WriteCoord(msg, ent->v.origin[1]);
652       if (bits & U_ANGLE2)
653          MSG_WriteAngle(msg, ent->v.angles[1]);
654       if (bits & U_ORIGIN3)
655          MSG_WriteCoord(msg, ent->v.origin[2]);
656       if (bits & U_ANGLE3)
657          MSG_WriteAngle(msg, ent->v.angles[2]);
658 #if 0 /* FIXME */
659       if (bits & U_FITZ_ALPHA)
660          MSG_WriteByte(msg, ent->alpha);
661 #endif
662       if (bits & U_FITZ_FRAME2)
663          MSG_WriteByte(msg, (int)ent->v.frame >> 8);
664       if (bits & U_FITZ_MODEL2)
665          MSG_WriteByte(msg, (int)ent->v.modelindex >> 8);
666 #if 0 /* FIXME */
667       if (bits & U_FITZ_LERPFINISH)
668          MSG_WriteByte(msg, (byte)floorf(((ent->v.nextthink - sv.time) * 255.0f) + 0.5f));
669 #endif
670    }
671 }
672 
673 /*
674 =============
675 SV_CleanupEnts
676 
677 =============
678 */
SV_CleanupEnts(void)679 void SV_CleanupEnts(void)
680 {
681    int e;
682    edict_t *ent = NEXT_EDICT(sv.edicts);
683    for (e = 1; e < sv.num_edicts; e++, ent = NEXT_EDICT(ent))
684       ent->v.effects = (int)ent->v.effects & ~EF_MUZZLEFLASH;
685 }
686 
687 /*
688 ==================
689 SV_WriteClientdataToMessage
690 
691 ==================
692 */
SV_WriteClientdataToMessage(edict_t * ent,sizebuf_t * msg)693 void SV_WriteClientdataToMessage(edict_t *ent, sizebuf_t *msg)
694 {
695    int bits;
696    int i;
697    edict_t *other;
698    int items;
699    eval_t *items2;
700    float coord;
701 
702    // send a damage message
703    if (ent->v.dmg_take || ent->v.dmg_save)
704    {
705       other = PROG_TO_EDICT(ent->v.dmg_inflictor);
706       MSG_WriteByte(msg, svc_damage);
707       MSG_WriteByte(msg, ent->v.dmg_save);
708       MSG_WriteByte(msg, ent->v.dmg_take);
709       for (i = 0; i < 3; i++) {
710          coord = other->v.origin[i];
711          coord += 0.5 * (other->v.mins[i] + other->v.maxs[i]);
712          MSG_WriteCoord(msg, coord);
713       }
714       ent->v.dmg_take = 0;
715       ent->v.dmg_save = 0;
716    }
717    //
718    // send the current viewpos offset from the view entity
719    //
720    SV_SetIdealPitch();		// how much to look up / down ideally
721 
722    // a fixangle might get lost in a dropped packet.  Oh well.
723    if (ent->v.fixangle) {
724       MSG_WriteByte(msg, svc_setangle);
725       for (i = 0; i < 3; i++)
726          MSG_WriteAngle(msg, ent->v.angles[i]);
727       ent->v.fixangle = 0;
728    }
729 
730    bits = 0;
731 
732    if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT)
733       bits |= SU_VIEWHEIGHT;
734 
735    if (ent->v.idealpitch)
736       bits |= SU_IDEALPITCH;
737 
738    // stuff the sigil bits into the high bits of items for sbar, or else
739    // mix in items2
740    items = ent->v.items;
741    items2 = GetEdictFieldValue(ent, "items2");
742    if (items2)
743       items |= (int)items2->_float << 23;
744    else
745       items |= (int)pr_global_struct->serverflags << 28;
746 
747    bits |= SU_ITEMS;
748 
749    if ((int)ent->v.flags & FL_ONGROUND)
750       bits |= SU_ONGROUND;
751 
752    if (ent->v.waterlevel >= 2)
753       bits |= SU_INWATER;
754 
755    for (i = 0; i < 3; i++) {
756       if (ent->v.punchangle[i])
757          bits |= (SU_PUNCH1 << i);
758       if (ent->v.velocity[i])
759          bits |= (SU_VELOCITY1 << i);
760    }
761 
762    if (ent->v.weaponframe)
763       bits |= SU_WEAPONFRAME;
764 
765    if (ent->v.armorvalue)
766       bits |= SU_ARMOR;
767 
768    //if (ent->v.weapon)
769    bits |= SU_WEAPON;
770 
771    if (sv.protocol == PROTOCOL_VERSION_FITZ) {
772       if ((bits & SU_WEAPON) &&
773             (SV_ModelIndex(pr_strings + ent->v.weaponmodel) & 0xff00))
774          bits |= SU_FITZ_WEAPON2;
775       if ((int)ent->v.armorvalue & 0xff00)
776          bits |= SU_FITZ_ARMOR2;
777       if ((int)ent->v.currentammo & 0xff00)
778          bits |= SU_FITZ_AMMO2;
779       if ((int)ent->v.ammo_shells & 0xff00)
780          bits |= SU_FITZ_SHELLS2;
781       if ((int)ent->v.ammo_nails & 0xff00)
782          bits |= SU_FITZ_NAILS2;
783       if ((int)ent->v.ammo_rockets & 0xff00)
784          bits |= SU_FITZ_ROCKETS2;
785       if ((int)ent->v.ammo_cells & 0xff00)
786          bits |= SU_FITZ_CELLS2;
787       if ((bits & SU_WEAPONFRAME) &&
788             ((int)ent->v.weaponframe & 0xff00))
789          bits |= SU_FITZ_WEAPONFRAME2;
790 #if 0 /* FIXME - TODO */
791       if ((bits & SU_WEAPON) && ent->alpha != ENTALPHA_DEFAULT)
792          // for now, weaponalpha = client entity alpha
793          bits |= SU_FITZ_WEAPONALPHA;
794 #endif
795       if (bits & 0x00ff0000)
796          bits |= SU_FITZ_EXTEND1;
797       if (bits & 0xff000000)
798          bits |= SU_FITZ_EXTEND2;
799    }
800 
801    // send the data
802 
803    MSG_WriteByte(msg, svc_clientdata);
804    MSG_WriteShort(msg, bits);
805    if (bits & SU_FITZ_EXTEND1)
806       MSG_WriteByte(msg, bits >> 16);
807    if (bits & SU_FITZ_EXTEND2)
808       MSG_WriteByte(msg, bits >> 24);
809 
810    if (bits & SU_VIEWHEIGHT)
811       MSG_WriteChar(msg, ent->v.view_ofs[2]);
812 
813    if (bits & SU_IDEALPITCH)
814       MSG_WriteChar(msg, ent->v.idealpitch);
815 
816    for (i = 0; i < 3; i++) {
817       if (bits & (SU_PUNCH1 << i))
818          MSG_WriteChar(msg, ent->v.punchangle[i]);
819       if (bits & (SU_VELOCITY1 << i))
820          MSG_WriteChar(msg, ent->v.velocity[i] / 16);
821    }
822 
823    // [always sent]        if (bits & SU_ITEMS)
824    MSG_WriteLong(msg, items);
825 
826    if (bits & SU_WEAPONFRAME)
827       MSG_WriteByte(msg, ent->v.weaponframe);
828    if (bits & SU_ARMOR)
829       MSG_WriteByte(msg, ent->v.armorvalue);
830    if (bits & SU_WEAPON)
831       SV_WriteModelIndex(msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel)), 0);
832 
833    MSG_WriteShort(msg, ent->v.health);
834    MSG_WriteByte(msg, ent->v.currentammo);
835    MSG_WriteByte(msg, ent->v.ammo_shells);
836    MSG_WriteByte(msg, ent->v.ammo_nails);
837    MSG_WriteByte(msg, ent->v.ammo_rockets);
838    MSG_WriteByte(msg, ent->v.ammo_cells);
839 
840    if (standard_quake) {
841       MSG_WriteByte(msg, ent->v.weapon);
842    } else {
843       for (i = 0; i < 32; i++) {
844          if (((int)ent->v.weapon) & (1 << i)) {
845             MSG_WriteByte(msg, i);
846             break;
847          }
848       }
849    }
850 
851    /* FITZ protocol stuff */
852    if (bits & SU_FITZ_WEAPON2)
853       MSG_WriteByte(msg, SV_ModelIndex(pr_strings + ent->v.weaponmodel) >> 8);
854    if (bits & SU_FITZ_ARMOR2)
855       MSG_WriteByte(msg, (int)ent->v.armorvalue >> 8);
856    if (bits & SU_FITZ_AMMO2)
857       MSG_WriteByte(msg, (int)ent->v.currentammo >> 8);
858    if (bits & SU_FITZ_SHELLS2)
859       MSG_WriteByte(msg, (int)ent->v.ammo_shells >> 8);
860    if (bits & SU_FITZ_NAILS2)
861       MSG_WriteByte(msg, (int)ent->v.ammo_nails >> 8);
862    if (bits & SU_FITZ_ROCKETS2)
863       MSG_WriteByte(msg, (int)ent->v.ammo_rockets >> 8);
864    if (bits & SU_FITZ_CELLS2)
865       MSG_WriteByte(msg, (int)ent->v.ammo_cells >> 8);
866    if (bits & SU_FITZ_WEAPONFRAME2)
867       MSG_WriteByte(msg, (int)ent->v.weaponframe >> 8);
868 #if 0 /* FIXME - TODO */
869    if (bits & SU_FITZ_WEAPONALPHA)
870       // for now, weaponalpha = client entity alpha
871       MSG_WriteByte(msg, ent->alpha);
872 #endif
873 }
874 
875 /*
876 =======================
877 SV_SendClientDatagram
878 =======================
879 */
SV_SendClientDatagram(client_t * client)880 qboolean SV_SendClientDatagram(client_t *client)
881 {
882    byte buf[MAX_DATAGRAM];
883    sizebuf_t msg;
884    int err;
885 
886    msg.data = buf;
887    msg.maxsize = qmin(MAX_DATAGRAM, client->netconnection->mtu);
888    msg.cursize = 0;
889 
890    MSG_WriteByte(&msg, svc_time);
891    MSG_WriteFloat(&msg, sv.time);
892 
893    // add the client specific data to the datagram
894    SV_WriteClientdataToMessage(client->edict, &msg);
895    SV_WriteEntitiesToClient(client->edict, &msg);
896 
897    // copy the server datagram if there is space
898    if (msg.cursize + sv.datagram.cursize < msg.maxsize)
899       SZ_Write(&msg, sv.datagram.data, sv.datagram.cursize);
900 
901    // send the datagram
902    err = NET_SendUnreliableMessage(client->netconnection, &msg);
903    /* if the message couldn't send, kick the client off */
904    if (err == -1) {
905       SV_DropClient(true);
906       return false;
907    }
908 
909    return true;
910 }
911 
912 /*
913 =======================
914 SV_UpdateToReliableMessages
915 =======================
916 */
SV_UpdateToReliableMessages(void)917 void SV_UpdateToReliableMessages(void)
918 {
919    int i, j;
920    client_t *client;
921 
922    // check for changes to be sent over the reliable streams
923    for (i = 0, host_client = svs.clients; i < svs.maxclients;
924          i++, host_client++) {
925       if (host_client->old_frags != host_client->edict->v.frags) {
926          for (j = 0, client = svs.clients; j < svs.maxclients;
927                j++, client++) {
928             if (!client->active)
929                continue;
930             MSG_WriteByte(&client->message, svc_updatefrags);
931             MSG_WriteByte(&client->message, i);
932             MSG_WriteShort(&client->message, host_client->edict->v.frags);
933          }
934          host_client->old_frags = host_client->edict->v.frags;
935       }
936    }
937 
938    for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) {
939       if (!client->active)
940          continue;
941       SZ_Write(&client->message, sv.reliable_datagram.data,
942             sv.reliable_datagram.cursize);
943    }
944 
945    SZ_Clear(&sv.reliable_datagram);
946 }
947 
948 
949 /*
950 =======================
951 SV_SendNop
952 
953 Send a nop message without trashing or sending the accumulated client
954 message buffer
955 =======================
956 */
SV_SendNop(client_t * client)957 void SV_SendNop(client_t *client)
958 {
959    sizebuf_t msg;
960    byte buf[4];
961    int err;
962 
963    msg.data = buf;
964    msg.maxsize = sizeof(buf);
965    msg.cursize = 0;
966 
967    MSG_WriteChar(&msg, svc_nop);
968 
969    err = NET_SendUnreliableMessage(client->netconnection, &msg);
970    /* if the message couldn't send, kick the client off */
971    if (err == -1)
972       SV_DropClient(true);
973    client->last_message = realtime;
974 }
975 
976 /*
977 =======================
978 SV_SendClientMessages
979 =======================
980 */
SV_SendClientMessages(void)981 void SV_SendClientMessages(void)
982 {
983    int i, err;
984 
985    // update frags, names, etc
986    SV_UpdateToReliableMessages();
987 
988    // build individual updates
989    for (i = 0, host_client = svs.clients; i < svs.maxclients;
990          i++, host_client++) {
991       if (!host_client->active)
992          continue;
993 
994       if (host_client->spawned) {
995          if (!SV_SendClientDatagram(host_client))
996             continue;
997       } else {
998          // the player isn't totally in the game yet
999          // send small keepalive messages if too much time has passed
1000          // send a full message when the next signon stage has been requested
1001          // some other message data (name changes, etc) may accumulate
1002          // between signon stages
1003          if (!host_client->sendsignon) {
1004             if (realtime - host_client->last_message > 5)
1005                SV_SendNop(host_client);
1006             continue;	// don't send out non-signon messages
1007          }
1008       }
1009 
1010       // check for an overflowed message.  Should only happen
1011       // on a very fucked up connection that backs up a lot, then
1012       // changes level
1013       if (host_client->message.overflowed) {
1014          SV_DropClient(true);
1015          host_client->message.overflowed = false;
1016          continue;
1017       }
1018 
1019       if (host_client->message.cursize || host_client->dropasap) {
1020          if (!NET_CanSendMessage(host_client->netconnection))
1021             continue;
1022 
1023          if (host_client->dropasap) {
1024             SV_DropClient(false);	// went to another level
1025          } else {
1026             err = NET_SendMessage(host_client->netconnection,
1027                   &host_client->message);
1028             /* if the message couldn't send, kick the client off */
1029             if (err == -1)
1030                SV_DropClient(true);
1031 
1032             SZ_Clear(&host_client->message);
1033             host_client->last_message = realtime;
1034             host_client->sendsignon = false;
1035          }
1036       }
1037    }
1038 
1039    // clear muzzle flashes
1040    SV_CleanupEnts();
1041 }
1042 
1043 
1044 /*
1045 ==============================================================================
1046 
1047 SERVER SPAWNING
1048 
1049 ==============================================================================
1050 */
1051 
1052 /*
1053 ================
1054 SV_ModelIndex
1055 
1056 ================
1057 */
SV_ModelIndex(const char * name)1058 int SV_ModelIndex(const char *name)
1059 {
1060    int i;
1061 
1062    if (!name || !name[0])
1063       return 0;
1064 
1065    for (i = 0; i < MAX_MODELS && sv.model_precache[i]; i++)
1066       if (!strcmp(sv.model_precache[i], name))
1067          return i;
1068    if (i == MAX_MODELS || !sv.model_precache[i])
1069       Sys_Error("%s: model %s not precached", __func__, name);
1070    return i;
1071 }
1072 
1073 /*
1074 ================
1075 SV_CreateBaseline
1076 
1077 ================
1078 */
SV_CreateBaseline(void)1079 void SV_CreateBaseline(void)
1080 {
1081    int i;
1082    edict_t *svent;
1083    int entnum;
1084    unsigned int bits;
1085 
1086    for (entnum = 0; entnum < sv.num_edicts; entnum++) {
1087       // get the current server version
1088       svent = EDICT_NUM(entnum);
1089       if (svent->free)
1090          continue;
1091       if (entnum > svs.maxclients && !svent->v.modelindex)
1092          continue;
1093 
1094       //
1095       // create entity baseline
1096       //
1097       VectorCopy(svent->v.origin, svent->baseline.origin);
1098       VectorCopy(svent->v.angles, svent->baseline.angles);
1099       svent->baseline.frame = svent->v.frame;
1100       svent->baseline.skinnum = svent->v.skin;
1101       if (entnum > 0 && entnum <= svs.maxclients) {
1102          svent->baseline.colormap = entnum;
1103          svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
1104       } else {
1105          svent->baseline.colormap = 0;
1106          svent->baseline.modelindex =
1107             SV_ModelIndex(PR_GetString(svent->v.model));
1108       }
1109 
1110       bits = 0;
1111       if (sv.protocol == PROTOCOL_VERSION_FITZ) {
1112          if (svent->baseline.modelindex & 0xff00)
1113             bits |= B_FITZ_LARGEMODEL;
1114          if (svent->baseline.frame & 0xff00)
1115             bits |= B_FITZ_LARGEFRAME;
1116 #if 0 /* FIXME - TODO */
1117          if (svent->baseline.alpha != ENTALPHA_DEFAULT)
1118             bits |= B_FITZ_ALPHA
1119 #endif
1120       }
1121 
1122       //
1123       // add to the message
1124       //
1125       if (bits) {
1126          MSG_WriteByte(&sv.signon, svc_fitz_spawnbaseline2);
1127          MSG_WriteShort(&sv.signon, entnum);
1128          MSG_WriteByte(&sv.signon, bits);
1129       } else {
1130          MSG_WriteByte(&sv.signon, svc_spawnbaseline);
1131          MSG_WriteShort(&sv.signon, entnum);
1132       }
1133 
1134       SV_WriteModelIndex(&sv.signon, svent->baseline.modelindex, bits);
1135       if (bits & B_FITZ_LARGEFRAME)
1136          MSG_WriteShort(&sv.signon, svent->baseline.frame);
1137       else
1138          MSG_WriteByte(&sv.signon, svent->baseline.frame);
1139       MSG_WriteByte(&sv.signon, svent->baseline.colormap);
1140       MSG_WriteByte(&sv.signon, svent->baseline.skinnum);
1141       for (i = 0; i < 3; i++) {
1142          MSG_WriteCoord(&sv.signon, svent->baseline.origin[i]);
1143          MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]);
1144       }
1145 
1146 #if 0 /* FIXME - TODO */
1147       if (bits & B_FITZ_ALPHA)
1148          MSG_WriteByte(&sv.signon, svent->baseline.alpha);
1149 #endif
1150    }
1151 }
1152 
1153 
1154 /*
1155 ================
1156 SV_SendReconnect
1157 
1158 Tell all the clients that the server is changing levels
1159 ================
1160 */
SV_SendReconnect(void)1161 void SV_SendReconnect(void)
1162 {
1163    byte data[128];
1164    sizebuf_t msg;
1165 
1166    msg.data = data;
1167    msg.cursize = 0;
1168    msg.maxsize = sizeof(data);
1169 
1170    MSG_WriteChar(&msg, svc_stufftext);
1171    MSG_WriteString(&msg, "reconnect\n");
1172    NET_SendToAll(&msg, 5);
1173 
1174    if (cls.state != ca_dedicated)
1175       Cmd_ExecuteString("reconnect\n", src_command);
1176 }
1177 
1178 
1179 /*
1180 ================
1181 SV_SaveSpawnparms
1182 
1183 Grabs the current state of each client for saving across the
1184 transition to another level
1185 ================
1186 */
SV_SaveSpawnparms(void)1187 void SV_SaveSpawnparms(void)
1188 {
1189    int i, j;
1190 
1191    svs.serverflags = pr_global_struct->serverflags;
1192 
1193    for (i = 0, host_client = svs.clients; i < svs.maxclients;
1194          i++, host_client++) {
1195       if (!host_client->active)
1196          continue;
1197 
1198       // call the progs to get default spawn parms for the new client
1199       pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
1200       PR_ExecuteProgram(pr_global_struct->SetChangeParms);
1201       for (j = 0; j < NUM_SPAWN_PARMS; j++)
1202          host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
1203    }
1204 }
1205 
1206 
1207 /*
1208 ================
1209 SV_SpawnServer
1210 
1211 This is called at the start of each level
1212 ================
1213 */
SV_SpawnServer(char * server)1214 void SV_SpawnServer(char *server)
1215 {
1216    edict_t *ent;
1217    int i;
1218 
1219    // let's not have any servers with no name
1220    if (hostname.string[0] == 0)
1221       Cvar_Set("hostname", "UNNAMED");
1222    scr_centertime_off = 0;
1223 
1224    Con_DPrintf("SpawnServer: %s\n", server);
1225    svs.changelevel_issued = false;	// now safe to issue another
1226 
1227    //
1228    // tell all connected clients that we are going to a new level
1229    //
1230    if (sv.active) {
1231       SV_SendReconnect();
1232    }
1233    //
1234    // make cvars consistant
1235    //
1236    if (coop.value)
1237       Cvar_SetValue("deathmatch", 0);
1238    current_skill = (int)(skill.value + 0.5);
1239    if (current_skill < 0)
1240       current_skill = 0;
1241    if (current_skill > 3)
1242       current_skill = 3;
1243 
1244    Cvar_SetValue("skill", (float)current_skill);
1245 
1246    //
1247    // set up the new server
1248    //
1249    Host_ClearMemory();
1250 
1251    memset(&sv, 0, sizeof(sv));
1252 
1253    strcpy(sv.name, server);
1254 
1255    sv.protocol = sv_protocol;
1256 
1257    // load progs to get entity field count
1258    PR_LoadProgs();
1259 
1260    // allocate server memory
1261    sv.max_edicts = MAX_EDICTS;
1262    sv.edicts = (edict_t*)Hunk_AllocName(sv.max_edicts * pr_edict_size, "edicts");
1263 
1264    sv.datagram.maxsize = sizeof(sv.datagram_buf);
1265    sv.datagram.cursize = 0;
1266    sv.datagram.data = sv.datagram_buf;
1267 
1268    sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
1269    sv.reliable_datagram.cursize = 0;
1270    sv.reliable_datagram.data = sv.reliable_datagram_buf;
1271 
1272    sv.signon.maxsize = sizeof(sv.signon_buf);
1273    sv.signon.cursize = 0;
1274    sv.signon.data = sv.signon_buf;
1275 
1276    // leave slots at start for clients only
1277    sv.num_edicts = svs.maxclients + 1;
1278    for (i = 0; i < svs.maxclients; i++) {
1279       ent = EDICT_NUM(i + 1);
1280       svs.clients[i].edict = ent;
1281    }
1282 
1283    sv.state = ss_loading;
1284    sv.paused = false;
1285 
1286    sv.time = 1.0;
1287 
1288    strcpy(sv.name, server);
1289    sprintf(sv.modelname, "maps/%s.bsp", server);
1290    sv.worldmodel = Mod_ForName(sv.modelname, false);
1291    if (!sv.worldmodel) {
1292       Con_Printf("Couldn't spawn server %s\n", sv.modelname);
1293       sv.active = false;
1294       return;
1295    }
1296    sv.models[1] = sv.worldmodel;
1297 
1298    //
1299    // clear world interaction links
1300    //
1301    SV_ClearWorld();
1302 
1303    sv.sound_precache[0] = pr_strings;
1304 
1305    sv.model_precache[0] = pr_strings;
1306    sv.model_precache[1] = sv.modelname;
1307    for (i = 1; i < sv.worldmodel->numsubmodels; i++) {
1308       sv.model_precache[1 + i] = localmodels[i];
1309       sv.models[i + 1] = Mod_ForName(localmodels[i], false);
1310    }
1311 
1312    //
1313    // load the rest of the entities
1314    //
1315    ent = EDICT_NUM(0);
1316    memset(&ent->v, 0, progs->entityfields * 4);
1317    ent->free = false;
1318    ent->v.model = PR_SetString(sv.worldmodel->name);
1319    ent->v.modelindex = 1;	// world model
1320    ent->v.solid = SOLID_BSP;
1321    ent->v.movetype = MOVETYPE_PUSH;
1322 
1323    if (coop.value)
1324       pr_global_struct->coop = coop.value;
1325    else
1326       pr_global_struct->deathmatch = deathmatch.value;
1327 
1328    pr_global_struct->mapname = PR_SetString(sv.name);
1329 
1330    // serverflags are for cross level information (sigils)
1331    pr_global_struct->serverflags = svs.serverflags;
1332 
1333    ED_LoadFromFile(sv.worldmodel->entities);
1334 
1335    sv.active = true;
1336 
1337    // all setup is completed, any further precache statements are errors
1338    sv.state = ss_active;
1339 
1340    // run two frames to allow everything to settle
1341    /* FIXME - don't do this when loading a saved game */
1342    host_frametime = 0.1;
1343    SV_Physics();
1344    SV_Physics();
1345 
1346    // create a baseline for more efficient communications
1347    SV_CreateBaseline();
1348 
1349    // send serverinfo to all connected clients
1350    for (i = 0, host_client = svs.clients; i < svs.maxclients;
1351          i++, host_client++)
1352       if (host_client->active)
1353          SV_SendServerinfo(host_client);
1354 
1355    Con_DPrintf("Server spawned.\n");
1356 }
1357