Patch by Spaceman: Allow viewing the accuracy stats of spectated players (client...
[divverent/nexuiz.git] / data / qcsrc / client / Main.qc
1 // --------------------------------------------------------------------------
2 // BEGIN REQUIRED CSQC FUNCTIONS
3 //include "main.qh"
4
5 #define DP_CSQC_ENTITY_REMOVE_IS_B0RKED
6
7 void cvar_clientsettemp(string cv, string val)
8 {
9         entity e;
10         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
11                 if(e.netname == cv)
12                         goto saved;
13         e = spawn();
14         e.classname = "saved_cvar_value";
15         e.netname = strzone(cv);
16         e.message = strzone(cvar_string(cv));
17 :saved
18         cvar_set(cv, val);
19 }
20
21 void cvar_clientsettemp_restore()
22 {
23         entity e;
24         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
25                         cvar_set(e.netname, e.message);
26 }
27
28 void() menu_show_error =
29 {
30         drawstring('0 200 0', "ERROR - MENU IS VISIBLE BUT NO MENU WAS DEFINED!", '8 8 0', '1 0 0', 1, 0);
31 };
32
33 // CSQC_Init : Called every time the CSQC code is initialized (essentially at map load)
34 // Useful for precaching things
35
36 void() menu_sub_null =
37 {
38 };
39
40 #ifdef USE_FTE
41 float __engine_check;
42 #endif
43
44 string forcefog;
45 void WaypointSprite_Load();
46 void CSQC_Init(void)
47 {
48 #ifdef USE_FTE
49 #pragma target ID
50         __engine_check = checkextension("DP_SV_WRITEPICTURE");
51         if(!__engine_check)
52         {
53                 print("^3Your engine build is outdated\n^3This Server uses a newer QC VM. Please update!\n");
54                 localcmd("\ndisconnect\n");
55                 return;
56         }
57 #pragma target FTE
58 #endif
59         
60         check_unacceptable_compiler_bugs();
61
62         float i;
63         CSQC_CheckEngine();
64         dprint_load();
65
66         binddb = db_create();
67         tempdb = db_create();
68         ClientProgsDB = db_load("client.db");
69         compressShortVector_init();
70
71         drawfont = 0;
72         menu_visible = FALSE;
73         menu_show = menu_show_error;
74         menu_action = menu_sub_null;
75
76         for(i = 0; i < 255; ++i)
77                 if(getplayerkey(i, "viewentity") == "")
78                         break;
79         maxclients = i;
80
81         //ctf_temp_1 = "";
82         // localcmd("alias order \"cmd order $*\""); enable if ctf-command thingy is used
83         //registercmd("ctf_menu");
84         registercmd("ons_map");
85         //registercmd("menu_action");
86
87         registercmd("+button3");
88         registercmd("-button3");
89         registercmd("+button4");
90         registercmd("-button4");
91         registercmd("+showaccuracy");registercmd("-showaccuracy");
92
93 #ifndef CAMERATEST
94         if(isdemo())
95         {
96 #endif
97                 registercmd("+forward");registercmd("-forward");
98                 registercmd("+back");registercmd("-back");
99                 registercmd("+moveup");registercmd("-moveup");
100                 registercmd("+movedown");registercmd("-movedown");
101                 registercmd("+moveright");registercmd("-moveright");
102                 registercmd("+moveleft");registercmd("-moveleft");
103                 registercmd("+roll_right");registercmd("-roll_right");
104                 registercmd("+roll_left");registercmd("-roll_left");
105 #ifndef CAMERATEST
106         }
107 #endif
108         registercvar("sbar_usecsqc", "1");
109         registercvar("sbar_columns", "default", CVAR_SAVE);
110
111         gametype = 0;
112
113         // sbar_fields uses strunzone on the titles!
114         for(i = 0; i < MAX_SBAR_FIELDS; ++i)
115                 sbar_title[i] = strzone("(null)");
116
117         postinit = false;
118
119         calledhooks = 0;
120
121         teams = Sort_Spawn();
122         players = Sort_Spawn();
123
124         GetTeam(COLOR_SPECTATOR, true); // add specs first
125
126         cvar_clientsettemp("_supports_weaponpriority", "1");
127
128         RegisterWeapons();
129
130         WaypointSprite_Load();
131
132         Projectile_Precache();
133         GibSplash_Precache();
134         Casings_Precache();
135         DamageInfo_Precache();
136         Announcer_Precache();
137         Tuba_Precache();
138
139         get_mi_min_max_texcoords(1); // try the CLEVER way first
140         minimapname = strcat("gfx/", mi_shortname, "_radar.tga");
141         shortmapname = mi_shortname;
142
143         if(precache_pic(minimapname) == "")
144         {
145                 // but maybe we have a non-clever minimap
146                 minimapname = strcat("gfx/", mi_shortname, "_mini.tga");
147                 if(precache_pic(minimapname) == "")
148                         minimapname = ""; // FAIL
149                 else
150                         get_mi_min_max_texcoords(0); // load new texcoords
151         }
152
153         mi_center = (mi_min + mi_max) * 0.5;
154         mi_scale = mi_max - mi_min;
155         minimapname = strzone(minimapname);
156 }
157
158 // CSQC_Shutdown : Called every time the CSQC code is shutdown (changing maps, quitting, etc)
159 void CSQC_Shutdown(void)
160 {
161 #ifdef USE_FTE
162 #pragma TARGET id
163         if(!__engine_check)
164                 return 0;
165 #pragma TARGET fte
166 #endif
167
168         remove(teams);
169         remove(players);
170         db_close(binddb);
171         db_close(tempdb);
172         db_save(ClientProgsDB, "client.db");
173         db_close(ClientProgsDB);
174
175         cvar_clientsettemp_restore();
176
177         if(camera_active)
178                 cvar_set("chase_active",ftos(chase_active_backup));
179
180         if not(isdemo())
181         {
182                 if not(calledhooks & HOOK_START)
183                         localcmd("\n_cl_hook_gamestart nop;");
184                 if not(calledhooks & HOOK_END)
185                         localcmd("\ncl_hook_gameend;");
186         }
187 }
188
189 .float has_team;
190 float SetTeam(entity o, float Team)
191 {
192         entity tm;
193         if(teamplay)
194         {
195                 switch(Team)
196                 {
197                         case -1:
198                         case COLOR_TEAM1:
199                         case COLOR_TEAM2:
200                         case COLOR_TEAM3:
201                         case COLOR_TEAM4:
202                                 break;
203                         default:
204                                 if(GetTeam(Team, false) == NULL)
205                                 {
206                                         print("trying to switch to unsupported team ", ftos(Team), "\n");
207                                         Team = COLOR_SPECTATOR;
208                                 }
209                                 break;
210                 }
211         }
212         else
213         {
214                 switch(Team)
215                 {
216                         case -1:
217                         case 0:
218                                 break;
219                         default:
220                                 if(GetTeam(Team, false) == NULL)
221                                 {
222                                         print("trying to switch to unsupported team ", ftos(Team), "\n");
223                                         Team = COLOR_SPECTATOR;
224                                 }
225                                 break;
226                 }
227         }
228         if(Team == -1) // leave
229         {
230                 if(o.has_team)
231                 {
232                         //print("(DISCONNECT) leave team ", ftos(o.team), "\n");
233                         tm = GetTeam(o.team, false);
234                         tm.team_size -= 1;
235                         o.has_team = 0;
236                         return TRUE;
237                 }
238         }
239         else
240         {
241                 if not(o.has_team)
242                 {
243                         //print("(CONNECT) enter team ", ftos(o.team), "\n");
244                         o.team = Team;
245                         tm = GetTeam(Team, true);
246                         tm.team_size += 1;
247                         o.has_team = 1;
248                         return TRUE;
249                 }
250                 else if(Team != o.team)
251                 {
252                         //print("(CHANGE) leave team ", ftos(o.team), "\n");
253                         tm = GetTeam(o.team, false);
254                         tm.team_size -= 1;
255                         o.team = Team;
256                         //print("(CHANGE) enter team ", ftos(o.team), "\n");
257                         tm = GetTeam(Team, true);
258                         tm.team_size += 1;
259                         return TRUE;
260                 }
261         }
262         return FALSE;
263 }
264
265 void Playerchecker_Think()
266 {
267         float i;
268         entity e;
269         for(i = 0; i < maxclients; ++i)
270         {
271                 e = playerslots[i];
272                 if(GetPlayerName(i) == "")
273                 {
274                         if(e.sort_prev)
275                         {
276                                 //print("playerchecker: KILL KILL KILL\n");
277                                 // player disconnected
278                                 SetTeam(e, -1);
279                                 RemovePlayer(e);
280                                 e.sort_prev = world;
281                                 //e.gotscores = 0;
282                         }
283                 }
284                 else
285                 {
286                         if not(e.sort_prev)
287                         {
288                                 //print("playerchecker: SPAWN SPAWN SPAWN\n");
289                                 // player connected
290                                 if not(e)
291                                         playerslots[i] = e = spawn();
292                                 e.sv_entnum = i;
293                                 //e.gotscores = 0; // we might already have the scores...
294                                 SetTeam(e, GetPlayerColor(i)); // will not hurt; later updates come with Sbar_UpdatePlayerTeams
295                                 RegisterPlayer(e);
296                                 Sbar_UpdatePlayerPos(e);
297                         }
298                 }
299         }
300         self.nextthink = time + 0.2;
301 }
302
303 void Porto_Init();
304 void TrueAim_Init();
305 void PostInit(void)
306 {
307         print(strcat("PostInit\n    maxclients = ", ftos(maxclients), "\n"));
308         localcmd(strcat("\nsbar_columns_set ", cvar_string("sbar_columns"), ";\n"));
309
310         entity playerchecker;
311         playerchecker = spawn();
312         playerchecker.think = Playerchecker_Think;
313         playerchecker.nextthink = time + 0.2;
314
315         Porto_Init();
316         TrueAim_Init();
317
318         postinit = true;
319 }
320
321 // CSQC_ConsoleCommand : Used to parse commands in the console that have been registered with the "registercmd" function
322 // Return value should be 1 if CSQC handled the command, otherwise return 0 to have the engine handle it.
323 float button_zoom;
324 void Cmd_Sbar_SetFields(float);
325 void Cmd_Sbar_Help(float);
326 float CSQC_ConsoleCommand(string strMessage)
327 {
328         float argc;
329         // Tokenize String
330         //argc = tokenize(strMessage);
331         argc = tokenize_console(strMessage);
332
333         // Acquire Command
334         local string strCmd;
335         strCmd = argv(0);
336
337         if(strCmd == "+button4") { // zoom
338                 // return false, because the message shall be sent to the server anyway (for demos/speccing)
339                 if(ignore_plus_zoom)
340                 {
341                         --ignore_plus_zoom;
342                         return false;
343                 }
344                 button_zoom = 1;
345                 return true;
346         } else if(strCmd == "-button4") { // zoom
347                 if(ignore_minus_zoom)
348                 {
349                         --ignore_minus_zoom;
350                         return false;
351                 }
352                 button_zoom = 0;
353                 return true;
354         } else if(strCmd == "+button3") { // secondary
355                 button_attack2 = 1;
356                 return false;
357         } else if(strCmd == "-button3") { // secondary
358                 button_attack2 = 0;
359                 return false;
360         } else if(strCmd == "+showscores") {
361                 sb_showscores = true;
362                 return true;
363         } else if(strCmd == "-showscores") {
364                 sb_showscores = false;
365                 return true;
366         } else if(strCmd == "+showaccuracy") {
367                 sb_showaccuracy = true;
368                 return true;
369         } else if(strCmd == "-showaccuracy") {
370                 sb_showaccuracy = false;
371                 return true;
372         }
373
374         if(camera_active)
375         if(strCmd == "+forward" || strCmd == "-back") {
376                 ++camera_direction_x;
377                 return true;
378         } else if(strCmd == "-forward" || strCmd == "+back") {
379                 --camera_direction_x;
380                 return true;
381         } else if(strCmd == "+moveright" || strCmd == "-moveleft") {
382                 --camera_direction_y;
383                 return true;
384         } else if(strCmd == "-moveright" || strCmd == "+moveleft") {
385                 ++camera_direction_y;
386                 return true;
387         } else if(strCmd == "+moveup" || strCmd == "-movedown") {
388                 ++camera_direction_z;
389                 return true;
390         } else if(strCmd == "-moveup" || strCmd == "+movedown") {
391                 --camera_direction_z;
392                 return true;
393         } else if(strCmd == "+roll_right" || strCmd == "-roll_left") {
394                 ++camera_roll;
395                 return true;
396         } else if(strCmd == "+roll_left" || strCmd == "-roll_right") {
397                 --camera_roll;
398                 return true;
399         }
400
401         return false;
402 }
403
404 .vector view_ofs;
405 entity debug_shotorg;
406 void ShotOrg_Draw()
407 {
408         self.origin = view_origin + view_forward * self.view_ofs_x + view_right * self.view_ofs_y + view_up * self.view_ofs_z;
409         self.angles = view_angles;
410         self.angles_x = -self.angles_x;
411         if not(self.cnt)
412                 R_AddEntity(self);
413 }
414 void ShotOrg_Draw2D()
415 {
416         vector coord2d_topleft, coord2d_topright, coord2d;
417         string s;
418         vector fs;
419
420         s = vtos(self.view_ofs);
421         s = substring(s, 1, strlen(s) - 2);
422         if(tokenize_console(s) == 3)
423                 s = strcat(argv(0), " ", argv(1), " ", argv(2));
424
425         coord2d_topleft = project_3d_to_2d(self.origin + view_up * 4 - view_right * 4);
426         coord2d_topright = project_3d_to_2d(self.origin + view_up * 4 + view_right * 4);
427
428         fs = '1 1 0' * ((coord2d_topright_x - coord2d_topleft_x) / stringwidth(s, FALSE));
429
430         coord2d = coord2d_topleft;
431         if(fs_x < 8)
432         {
433                 coord2d_x += (coord2d_topright_x - coord2d_topleft_x) * (1 - 8 / fs_x) * 0.5;
434                 fs = '8 8 0';
435         }
436         coord2d_y -= fs_y;
437         coord2d_z = 0;
438         drawstring(coord2d, s, fs, '1 1 1', 1, 0);
439 }
440
441 void ShotOrg_Spawn()
442 {
443         debug_shotorg = spawn();
444         debug_shotorg.draw = ShotOrg_Draw;
445         debug_shotorg.draw2d = ShotOrg_Draw2D;
446         debug_shotorg.renderflags = RF_VIEWMODEL;
447         debug_shotorg.effects = EF_FULLBRIGHT;
448         precache_model("models/shotorg_adjuster.md3");
449         setmodel(debug_shotorg, "models/shotorg_adjuster.md3");
450         debug_shotorg.scale = 2;
451         debug_shotorg.view_ofs = '25 8 -8';
452 }
453
454 void GameCommand(string msg)
455 {
456         float argc;
457         argc = tokenize_console(msg);
458
459         if(argv(0) == "help" || argc == 0)
460         {
461                 print("Usage: cl_cmd COMMAND..., where possible commands are:\n");
462                 print("  settemp cvar value\n");
463                 print("  radar\n");
464                 print("  sbar_columns_set ...\n");
465                 print("  sbar_columns_help\n");
466                 GameCommand_Generic("help");
467                 return;
468         }
469
470         if(GameCommand_Generic(msg))
471                 return;
472
473         string cmd;
474         cmd = argv(0);
475         if(cmd == "mv_download") {
476                 Cmd_MapVote_MapDownload(argc);
477         }
478         else if(cmd == "settemp") {
479                 cvar_clientsettemp(argv(1), argv(2));
480         }
481         else if(cmd == "radar") {
482                 ons_showmap = !ons_showmap;
483         }
484         else if(cmd == "sbar_columns_set") {
485                 Cmd_Sbar_SetFields(argc);
486         }
487         else if(cmd == "sbar_columns_help") {
488                 Cmd_Sbar_Help(argc);
489         }
490 #ifdef BLURTEST
491         else if(cmd == "blurtest") {
492                 blurtest_time0 = time;
493                 blurtest_time1 = time + stof(argv(1));
494                 blurtest_radius = stof(argv(2));
495                 blurtest_power = stof(argv(3));
496         }
497 #endif
498         else if(cmd == "shotorg_move") {
499                 if(!debug_shotorg)
500                         ShotOrg_Spawn();
501                 else
502                         debug_shotorg.view_ofs = debug_shotorg.view_ofs + stov(argv(1));
503                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
504         }
505         else if(cmd == "shotorg_movez") {
506                 if(!debug_shotorg)
507                         ShotOrg_Spawn();
508                 else
509                         debug_shotorg.view_ofs = debug_shotorg.view_ofs + stof(argv(1)) * (debug_shotorg.view_ofs * (1 / debug_shotorg.view_ofs_x)); // closer/farther, same xy pos
510                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
511         }
512         else if(cmd == "shotorg_set") {
513                 if(!debug_shotorg)
514                         ShotOrg_Spawn();
515                 else
516                         debug_shotorg.view_ofs = stov(argv(1));
517                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
518         }
519         else if(cmd == "shotorg_setz") {
520                 if(!debug_shotorg)
521                         ShotOrg_Spawn();
522                 else
523                         debug_shotorg.view_ofs = debug_shotorg.view_ofs * (stof(argv(1)) / debug_shotorg.view_ofs_x); // closer/farther, same xy pos
524                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
525         }
526         else if(cmd == "shotorg_toggle_hide") {
527                 if(debug_shotorg)
528                 {
529                         debug_shotorg.cnt = !debug_shotorg.cnt;
530                 }
531         }
532         else if(cmd == "shotorg_end") {
533                 if(debug_shotorg)
534                 {
535                         print(vtos(debug_shotorg.view_ofs), "\n");
536                         remove(debug_shotorg);
537                         debug_shotorg = world;
538                 }
539                 localcmd("sv_cmd debug_shotorg\n");
540         }
541         else
542         {
543                 print("Invalid command. For a list of supported commands, try cl_cmd help.\n");
544         }
545
546         return;
547 }
548
549 // CSQC_InputEvent : Used to perform actions based on any key pressed, key released and mouse on the client.
550 // Return value should be 1 if CSQC handled the input, otherwise return 0 to have the input passed to the engine.
551 // All keys are in ascii.
552 // bInputType = 0 is key pressed, 1 is key released, 2 is mouse input.
553 // In the case of keyboard input, nPrimary is the ascii code, and nSecondary is 0.
554 // In the case of mouse input, nPrimary is xdelta, nSecondary is ydelta.
555 float CSQC_InputEvent(float bInputType, float nPrimary, float nSecondary)
556 {
557         local float bSkipKey;
558         bSkipKey = false;
559
560         if(menu_visible)
561                 if(menu_action(bInputType, nPrimary, nSecondary))
562                         return TRUE;
563         return bSkipKey;
564 }
565
566 // END REQUIRED CSQC FUNCTIONS
567 // --------------------------------------------------------------------------
568
569 // --------------------------------------------------------------------------
570 // BEGIN OPTIONAL CSQC FUNCTIONS
571 void Ent_ReadEntCS()
572 {
573         InterpolateOrigin_Undo();
574
575         self.classname = "entcs_receiver";
576         self.sv_entnum = ReadByte() - 1;
577         self.origin_x = ReadShort();
578         self.origin_y = ReadShort();
579         self.origin_z = ReadShort();
580         self.angles_y = ReadByte() * 360.0 / 256;
581         self.origin_z = self.angles_x = self.angles_z = 0;
582
583         InterpolateOrigin_Note();
584 }
585
586 void Ent_Remove();
587
588 void Ent_RemovePlayerScore()
589 {
590         float i;
591
592         if(self.owner)
593         {
594                 SetTeam(self.owner, -1);
595                 self.owner.gotscores = 0;
596                 for(i = 0; i < MAX_SCORE; ++i)
597                         self.owner.(scores[i]) = 0; // clear all scores
598         }
599 }
600
601 void Ent_ReadPlayerScore()
602 {
603         float i, n;
604         float isNew;
605         entity o;
606
607         // damnit -.- don't want to go change every single .sv_entnum in sbar.qc AGAIN
608         // (no I've never heard of M-x replace-string, sed, or anything like that)
609         isNew = !self.owner; // workaround for DP bug
610         n = ReadByte()-1;
611
612 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
613         if(!isNew && n != self.sv_entnum)
614         {
615                 print("A CSQC entity changed its owner!\n");
616                 isNew = true;
617                 Ent_Remove();
618                 self.enttype = ENT_CLIENT_SCORES;
619         }
620 #endif
621
622         self.sv_entnum = n;
623
624         if not(playerslots[self.sv_entnum])
625                 playerslots[self.sv_entnum] = spawn();
626         o = self.owner = playerslots[self.sv_entnum];
627         o.sv_entnum = self.sv_entnum;
628         o.gotscores = 1;
629
630         //if not(o.sort_prev)
631         //      RegisterPlayer(o);
632         //playerchecker will do this for us later, if it has not already done so
633
634         float sf, lf;
635 #if MAX_SCORE <= 8
636         sf = ReadByte();
637         lf = ReadByte();
638 #else
639         sf = ReadShort();
640         lf = ReadShort();
641 #endif
642         float p;
643         for(i = 0, p = 1; i < MAX_SCORE; ++i, p *= 2)
644                 if(sf & p)
645                 {
646                         if(lf & p)
647                                 o.(scores[i]) = ReadInt24_t();
648                         else
649                                 o.(scores[i]) = ReadChar();
650                 }
651
652         if(o.sort_prev)
653                 Sbar_UpdatePlayerPos(o); // if not registered, we cannot do this yet!
654
655         self.entremove = Ent_RemovePlayerScore;
656 }
657
658 void Ent_ReadTeamScore()
659 {
660         float i;
661         entity o;
662
663         self.team = ReadByte();
664         o = self.owner = GetTeam(self.team, true); // these team numbers can always be trusted
665
666         float sf, lf;
667 #if MAX_TEAMSCORE <= 8
668         sf = ReadByte();
669         lf = ReadByte();
670 #else
671         sf = ReadShort();
672         lf = ReadShort();
673 #endif
674         float p;
675         for(i = 0, p = 1; i < MAX_TEAMSCORE; ++i, p *= 2)
676                 if(sf & p)
677                 {
678                         if(lf & p)
679                                 o.(teamscores[i]) = ReadInt24_t();
680                         else
681                                 o.(teamscores[i]) = ReadChar();
682                 }
683
684         Sbar_UpdateTeamPos(o);
685 }
686
687 void Net_Reset()
688 {
689 }
690
691 void Ent_ClientData()
692 {
693         float f;
694         float newspectatee_status;
695
696         f = ReadByte();
697
698         sb_showscores_force = (f & 1);
699
700         if(f & 2)
701         {
702                 newspectatee_status = ReadByte();
703                 if(newspectatee_status == player_localentnum)
704                         newspectatee_status = -1; // observing
705         }
706         else
707                 newspectatee_status = 0;
708
709         spectatorbutton_zoom = (f & 4);
710
711         if(f & 8)
712         {
713                 angles_held_status = 1;
714                 angles_held_x = ReadAngle();
715                 angles_held_y = ReadAngle();
716                 angles_held_z = 0;
717         }
718         else
719                 angles_held_status = 0;
720
721         if(newspectatee_status != spectatee_status)
722         {
723                 float i;
724                 // clear the weapon accuracy stats
725                 for(i = WEP_FIRST; i <= WEP_LAST; ++i) {
726                         weapon_hits[i] = 0;
727                         weapon_fired[i] = 0;
728                 }
729
730                 // clear race stuff
731                 race_laptime = 0;
732                 race_checkpointtime = 0;
733         }
734         spectatee_status = newspectatee_status;
735 }
736
737 void Ent_Nagger()
738 {
739         float nags, i, j, b, f;
740
741         nags = ReadByte();
742
743         if(nags & 128)
744         {
745                 if(vote_called_vote)
746                         strunzone(vote_called_vote);
747                 vote_called_vote = strzone(ColorTranslateRGB(ReadString()));
748         }
749
750         if(nags & 1)
751         {
752                 for(j = 0; j < maxclients; ++j)
753                         if(playerslots[j])
754                                 playerslots[j].ready = 1;
755                 for(i = 1; i <= maxclients; i += 8)
756                 {
757                         f = ReadByte();
758                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
759                                 if not(f & b)
760                                         if(playerslots[j])
761                                                 playerslots[j].ready = 0;
762                 }
763         }
764
765         ready_waiting = (nags & 1);
766         ready_waiting_for_me = (nags & 2);
767         vote_waiting = (nags & 4);
768         vote_waiting_for_me = (nags & 8);
769         warmup_stage = (nags & 16);
770 }
771
772 void Ent_RandomSeed()
773 {
774         float s;
775         prandom_debug();
776         s = ReadShort();
777         psrandom(s);
778 }
779
780 // CSQC_Ent_Update : Called every frame that the server has indicated an update to the SSQC / CSQC entity has occured.
781 // The only parameter reflects if the entity is "new" to the client, meaning it just came into the client's PVS.
782 void Ent_RadarLink();
783 void Ent_Init();
784 void Ent_ScoresInfo();
785 void(float bIsNewEntity) CSQC_Ent_Update =
786 {
787         float t;
788         float savetime;
789         t = ReadByte();
790
791         // set up the "time" global for received entities to be correct for interpolation purposes
792         savetime = time;
793         if(servertime)
794         {
795                 time = servertime;
796         }
797         else
798         {
799                 serverprevtime = time;
800                 serverdeltatime = getstatf(STAT_MOVEVARS_TICRATE) * getstatf(STAT_MOVEVARS_TIMESCALE);
801                 time = serverprevtime + serverdeltatime;
802         }
803
804 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
805         if(self.enttype)
806                 if(t != self.enttype)
807                 {
808                         print("A CSQC entity changed its type!\n");
809                         Ent_Remove();
810                         bIsNewEntity = 1;
811                 }
812 #endif
813         self.enttype = t;
814         switch(t)
815         {
816                 case ENT_CLIENT_ENTCS: Ent_ReadEntCS(); break;
817                 case ENT_CLIENT_SCORES: Ent_ReadPlayerScore(); break;
818                 case ENT_CLIENT_TEAMSCORES: Ent_ReadTeamScore(); break;
819                 case ENT_CLIENT_POINTPARTICLES: Ent_PointParticles(); break;
820                 case ENT_CLIENT_RAINSNOW: Ent_RainOrSnow(); break;
821                 case ENT_CLIENT_LASER: Ent_Laser(); break;
822                 case ENT_CLIENT_NAGGER: Ent_Nagger(); break;
823                 case ENT_CLIENT_WAYPOINT: Ent_WaypointSprite(); break;
824                 case ENT_CLIENT_RADARLINK: Ent_RadarLink(); break;
825                 case ENT_CLIENT_PROJECTILE: Ent_Projectile(); break;
826                 case ENT_CLIENT_GIBSPLASH: Ent_GibSplash(bIsNewEntity); break;
827                 case ENT_CLIENT_DAMAGEINFO: Ent_DamageInfo(bIsNewEntity); break;
828                 case ENT_CLIENT_CASING: Ent_Casing(bIsNewEntity); break;
829                 case ENT_CLIENT_INIT: Ent_Init(); break;
830                 case ENT_CLIENT_SCORES_INFO: Ent_ScoresInfo(); break;
831                 case ENT_CLIENT_MAPVOTE: Ent_MapVote(); break;
832                 case ENT_CLIENT_CLIENTDATA: Ent_ClientData(); break;
833                 case ENT_CLIENT_RANDOMSEED: Ent_RandomSeed(); break;
834                 case ENT_CLIENT_WALL: Ent_Wall(); break;
835                 case ENT_CLIENT_MODELEFFECT: Ent_ModelEffect(bIsNewEntity); break;
836                 case ENT_CLIENT_TUBANOTE: Ent_TubaNote(bIsNewEntity); break;
837                 default:
838                         error(strcat("unknown entity type in CSQC_Ent_Update: ", ftos(self.enttype), "\n"));
839                         break;
840         }
841
842         time = savetime;
843 };
844 // Destructor, but does NOT deallocate the entity by calling remove(). Also
845 // used when an entity changes its type. For an entity that someone interacts
846 // with others, make sure it can no longer do so.
847 void Ent_Remove()
848 {
849         if(self.entremove)
850                 self.entremove();
851
852         self.enttype = 0;
853         self.classname = "";
854         self.draw = menu_sub_null;
855         self.entremove = menu_sub_null;
856         // TODO possibly set more stuff to defaults
857 }
858 // CSQC_Ent_Remove : Called when the server requests a SSQC / CSQC entity to be removed.  Essentially call remove(self) as well.
859 void CSQC_Ent_Remove()
860 {
861         if(self.enttype)
862                 Ent_Remove();
863         remove(self);
864 }
865
866 void Gamemode_Init()
867 {
868         if(gametype == GAME_ONSLAUGHT) {
869                 print(strcat("Using ", minimapname, " as minimap.\n"));
870                 precache_pic("gfx/ons-cp-neutral.tga");
871                 precache_pic("gfx/ons-cp-red.tga");
872                 precache_pic("gfx/ons-cp-blue.tga");
873                 precache_pic("gfx/ons-frame.tga");
874                 precache_pic("gfx/ons-frame-team.tga");
875         } else if(gametype == GAME_KEYHUNT) {
876                 precache_pic("gfx/sb_key_carrying");
877                 precache_pic("gfx/sb_key_carrying_outline");
878         }
879
880         if not(isdemo())
881         {
882                 localcmd("\n_cl_hook_gamestart ", GametypeNameFromType(gametype), ";");
883                 calledhooks |= HOOK_START;
884         }
885 }
886 // CSQC_Parse_StuffCmd : Provides the stuffcmd string in the first parameter that the server provided.  To execute standard behavior, simply execute localcmd with the string.
887 void CSQC_Parse_StuffCmd(string strMessage)
888 {
889         localcmd(strMessage);
890 }
891 // CSQC_Parse_Print : Provides the print string in the first parameter that the server provided.  To execute standard behavior, simply execute print with the string.
892 void CSQC_Parse_Print(string strMessage)
893 {
894         print(ColorTranslateRGB(strMessage));
895 }
896
897 // CSQC_Parse_CenterPrint : Provides the centerprint string in the first parameter that the server provided.
898 void CSQC_Parse_CenterPrint(string strMessage)
899 {
900         centerprint(strMessage);
901 }
902
903 void Fog_Force()
904 {
905         // TODO somehow thwart prvm_globalset client ...
906
907         if(forcefog != "")
908                 localcmd(strcat("\nfog ", forcefog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
909 }
910
911 void Gamemode_Init();
912 void Ent_ScoresInfo()
913 {
914         float i;
915         self.classname = "ent_client_scores_info";
916         gametype = ReadByte();
917         for(i = 0; i < MAX_SCORE; ++i)
918         {
919                 scores_label[i] = strzone(ReadString());
920                 scores_flags[i] = ReadByte();
921         }
922         for(i = 0; i < MAX_TEAMSCORE; ++i)
923         {
924                 teamscores_label[i] = strzone(ReadString());
925                 teamscores_flags[i] = ReadByte();
926         }
927         Sbar_InitScores();
928         Gamemode_Init();
929 }
930
931 void Ent_Init()
932 {
933         float i;
934         self.classname = "ent_client_init";
935
936         nb_pb_period = ReadByte() / 32; //Accuracy of 1/32th
937
938         for(i = 0; i < 24; ++i)
939                 weaponimpulse[i] = ReadByte() - 1;
940         hook_shotorigin_x = ReadCoord();
941         hook_shotorigin_y = ReadCoord();
942         hook_shotorigin_z = ReadCoord();
943
944         if(forcefog)
945                 strunzone(forcefog);
946         forcefog = strzone(ReadString());
947
948         armorblockpercent = ReadByte() / 255.0;
949
950         g_weaponswitchdelay = ReadByte() / 255.0;
951
952         if(!postinit)
953                 PostInit();
954 }
955
956 void Net_ReadRace()
957 {
958         float b;
959
960         b = ReadByte();
961
962         switch(b)
963         {
964                 case RACE_NET_CHECKPOINT_HIT_QUALIFYING:
965                         race_checkpoint = ReadByte();
966                         race_time = ReadInt24_t();
967                         race_previousbesttime = ReadInt24_t();
968                         if(race_previousbestname)
969                                 strunzone(race_previousbestname);
970                         race_previousbestname = strzone(ColorTranslateRGB(ReadString()));
971
972                         race_checkpointtime = time;
973
974                         if(race_checkpoint == 0 || race_checkpoint == 254)
975                         {
976                                 race_penaltyaccumulator = 0;
977                                 race_laptime = time; // valid
978                         }
979
980                         break;
981
982                 case RACE_NET_CHECKPOINT_CLEAR:
983                         race_laptime = 0;
984                         race_checkpointtime = 0;
985                         break;
986
987                 case RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING:
988                         race_laptime = ReadCoord();
989                         race_checkpointtime = -99999;
990                         // fall through
991                 case RACE_NET_CHECKPOINT_NEXT_QUALIFYING:
992                         race_nextcheckpoint = ReadByte();
993
994                         race_nextbesttime = ReadInt24_t();
995                         if(race_nextbestname)
996                                 strunzone(race_nextbestname);
997                         race_nextbestname = strzone(ColorTranslateRGB(ReadString()));
998                         break;
999
1000                 case RACE_NET_CHECKPOINT_HIT_RACE:
1001                         race_mycheckpoint = ReadByte();
1002                         race_mycheckpointtime = time;
1003                         race_mycheckpointdelta = ReadInt24_t();
1004                         race_mycheckpointlapsdelta = ReadByte();
1005                         if(race_mycheckpointlapsdelta >= 128)
1006                                 race_mycheckpointlapsdelta -= 256;
1007                         if(race_mycheckpointenemy)
1008                                 strunzone(race_mycheckpointenemy);
1009                         race_mycheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1010                         break;
1011
1012                 case RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT:
1013                         race_othercheckpoint = ReadByte();
1014                         race_othercheckpointtime = time;
1015                         race_othercheckpointdelta = ReadInt24_t();
1016                         race_othercheckpointlapsdelta = ReadByte();
1017                         if(race_othercheckpointlapsdelta >= 128)
1018                                 race_othercheckpointlapsdelta -= 256;
1019                         if(race_othercheckpointenemy)
1020                                 strunzone(race_othercheckpointenemy);
1021                         race_othercheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1022                         break;
1023
1024                 case RACE_NET_PENALTY_RACE:
1025                         race_penaltyeventtime = time;
1026                         race_penaltytime = ReadShort();
1027                         //race_penaltyaccumulator += race_penaltytime;
1028                         if(race_penaltyreason)
1029                                 strunzone(race_penaltyreason);
1030                         race_penaltyreason = strzone(ReadString());
1031                         break;
1032
1033                 case RACE_NET_PENALTY_QUALIFYING:
1034                         race_penaltyeventtime = time;
1035                         race_penaltytime = ReadShort();
1036                         race_penaltyaccumulator += race_penaltytime;
1037                         if(race_penaltyreason)
1038                                 strunzone(race_penaltyreason);
1039                         race_penaltyreason = strzone(ReadString());
1040                         break;
1041
1042                 case RACE_NET_SERVER_RECORD:
1043                         race_server_record = ReadInt24_t();
1044                         break;
1045                 case RACE_NET_SPEED_AWARD:
1046                         race_speedaward = ReadShort();
1047                         race_speedaward_holder = strzone(ReadString());
1048                         break;
1049                 case RACE_NET_SPEED_AWARD_BEST:
1050                         race_speedaward_alltimebest = ReadShort();
1051                         race_speedaward_alltimebest_holder = strzone(ReadString());
1052                         break;
1053         }
1054 }
1055
1056 void Net_ReadSpawn()
1057 {
1058         zoomin_effect = 1;
1059         current_viewzoom = 0.6;
1060 }
1061
1062 void Net_TeamNagger()
1063 {
1064         teamnagger = 1;
1065 }
1066
1067 // CSQC_Parse_TempEntity : Handles all temporary entity network data in the CSQC layer.
1068 // You must ALWAYS first acquire the temporary ID, which is sent as a byte.
1069 // Return value should be 1 if CSQC handled the temporary entity, otherwise return 0 to have the engine process the event.
1070 float CSQC_Parse_TempEntity()
1071 {
1072         local float bHandled;
1073                 bHandled  = true;
1074         // Acquire TE ID
1075         local float nTEID;
1076                 nTEID = ReadByte();
1077
1078                 // NOTE: Could just do return instead of break...
1079         switch(nTEID)
1080         {
1081                 case TE_CSQC_PICTURE:
1082                         Net_MapVote_Picture();
1083                         bHandled = true;
1084                         break;
1085                 case TE_CSQC_RACE:
1086                         Net_ReadRace();
1087                         bHandled = true;
1088                         break;
1089                 case 13: // TE_BEAM
1090                         Net_GrapplingHook();
1091                         bHandled = true;
1092                         break;
1093                 case TE_CSQC_SPAWN:
1094                         Net_ReadSpawn();
1095                         bHandled = true;
1096                         break;
1097                 case TE_CSQC_ZCURVEPARTICLES:
1098                         Net_ReadZCurveParticles();
1099                         bHandled = true;
1100                         break;
1101                 case TE_CSQC_NEXGUNBEAMPARTICLE:
1102                         Net_ReadNexgunBeamParticle();
1103                         bHandled = true;
1104                         break;
1105                 case TE_CSQC_TEAMNAGGER:
1106                         Net_TeamNagger();
1107                         bHandled = true;
1108                         break;
1109         case TE_CSQC_LIGHTNINGARC:
1110             Net_ReadLightningarc();
1111             bHandled = true;
1112             break;
1113                 default:
1114                         // No special logic for this temporary entity; return 0 so the engine can handle it
1115                         bHandled = false;
1116                         break;
1117         }
1118
1119         return bHandled;
1120 }
1121
1122 string getcommandkey(string text, string command)
1123 {
1124         string keys;
1125         float n, j, k, l;
1126
1127         if (!sbar_showbinds)
1128                 return text;
1129
1130         keys = db_get(binddb, command);
1131         if (!keys)
1132         {
1133                 n = tokenize(findkeysforcommand(command)); // uses '...' strings
1134                 for(j = 0; j < n; ++j)
1135                 {
1136                         k = stof(argv(j));
1137                         if(k != -1)
1138                         {
1139                                 if ("" == keys)
1140                                         keys = keynumtostring(k);
1141                                 else
1142                                         keys = strcat(keys, ", ", keynumtostring(k));
1143
1144                                 ++l;
1145                                 if (sbar_showbinds_limit > 0 && sbar_showbinds_limit >= l) break;
1146                         }
1147
1148                 }
1149                 db_put(binddb, command, keys);
1150         }
1151
1152         if ("" == keys) {
1153                 if (sbar_showbinds > 1)
1154                         return strcat(text, " (not bound)");
1155                 else
1156                         return text;
1157         }
1158         else if (sbar_showbinds > 1)
1159                 return strcat(text, " (", keys, ")");
1160         else
1161                 return keys;
1162 }