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