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