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