]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/client/main.qc
Minor cleanup of client/defs.qh, move replicated cvars to a common location
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / main.qc
1 #include "main.qh"
2
3 #include "defs.qh"
4 #include <client/items/items.qh>
5 #include <common/ent_cs.qh>
6 #include "miscfunctions.qh"
7 #include <common/effects/effect.qh>
8 #include <common/effects/qc/_mod.qh>
9 #include <common/effects/all.qh>
10 #include <common/effects/all.inc>
11 #include "hud/_mod.qh"
12 #include "commands/cl_cmd.qh"
13 #include "mapvoting.qh"
14 #include <client/mutators/_mod.qh>
15 #include "hud/panel/centerprint.qh"
16 #include "hud/panel/scoreboard.qh"
17 #include "hud/panel/quickmenu.qh"
18 #include "shownames.qh"
19 #include "view.qh"
20 #include "weapons/projectile.qh"
21 #include <common/deathtypes/all.qh>
22 #include <common/items/_mod.qh>
23 #include <common/gamemodes/gamemode/nexball/cl_nexball.qh>
24 #include <common/mapinfo.qh>
25 #include <common/minigames/cl_minigames.qh>
26 #include <common/minigames/cl_minigames_hud.qh>
27 #include <common/net_linked.qh>
28 #include <common/net_notice.qh>
29 #include <common/scores.qh>
30 #include <common/mapobjects/_mod.qh>
31 #include <common/vehicles/all.qh>
32 #include <lib/csqcmodel/cl_model.qh>
33 #include <lib/csqcmodel/interpolate.qh>
34 #include <lib/warpzone/client.qh>
35
36 // --------------------------------------------------------------------------
37 // BEGIN REQUIRED CSQC FUNCTIONS
38 //include "main.qh"
39
40 #define DP_CSQC_ENTITY_REMOVE_IS_B0RKED
41
42 // CSQC_Init : Called every time the CSQC code is initialized (essentially at map load)
43 // Useful for precaching things
44
45 void CSQC_Init()
46 {
47         prvm_language = strzone(cvar_string("prvm_language"));
48
49 #ifdef WATERMARK
50         LOG_INFOF("^4CSQC Build information: ^1%s", WATERMARK);
51 #endif
52
53         {
54                 int i = 0;
55                 for ( ; i < 255; ++i)
56                         if (getplayerkeyvalue(i, "viewentity") == "")
57                                 break;
58                 maxclients = i;
59         }
60
61         // needs to be done so early because of the constants they create
62         static_init();
63         static_init_late();
64         static_init_precache();
65
66         binddb = db_create();
67         tempdb = db_create();
68         ClientProgsDB = db_load("client.db");
69
70         draw_endBoldFont();
71
72         //registercommand("hud_configure");
73         //registercommand("hud_save");
74         //registercommand("menu_action");
75
76         ConsoleCommand_macro_init();
77
78         registercvar("hud_usecsqc", "1");
79         registercvar("scoreboard_columns", "default");
80
81         registercvar("cl_nade_type", "3");
82         registercvar("cl_pokenade_type", "zombie");
83
84         registercvar("cl_jumpspeedcap_min", "");
85         registercvar("cl_jumpspeedcap_max", "");
86
87         registercvar("cl_shootfromfixedorigin", "");
88
89         registercvar("cl_multijump", "-1");
90
91         registercvar("cl_dodging", "0");
92
93         registercvar("cl_spawn_near_teammate", "1");
94
95         registercvar("cl_weapon_switch_reload", "1");
96         registercvar("cl_weapon_switch_fallback_to_impulse", "1");
97
98         registercvar("cl_allow_uidranking", "1");
99
100         if(autocvar_cl_lockview)
101                 cvar_set("cl_lockview", "0");
102
103         gametype = NULL;
104
105         postinit = false;
106
107         calledhooks = 0;
108
109         teams = Sort_Spawn();
110         players = Sort_Spawn();
111
112         GetTeam(NUM_SPECTATOR, true); // add specs first
113
114         for (int w = 0; w <= WEP_LAST - WEP_FIRST; ++w)
115                 weapon_accuracy[w] = -1;
116
117         // precaches
118
119         if(autocvar_cl_reticle)
120         {
121                 precache_pic("gfx/reticle_normal");
122                 // weapon reticles are precached in weapon files
123         }
124
125         {
126                 get_mi_min_max_texcoords(1); // try the CLEVER way first
127                 minimapname = strcat("gfx/", mi_shortname, "_radar.tga");
128                 shortmapname = mi_shortname;
129
130                 if (precache_pic(minimapname) == "")
131                 {
132                         // but maybe we have a non-clever minimap
133                         minimapname = strcat("gfx/", mi_shortname, "_mini.tga");
134                         if (precache_pic(minimapname) == "")
135                                 minimapname = ""; // FAIL
136                         else
137                                 get_mi_min_max_texcoords(0); // load new texcoords
138                 }
139
140                 mi_center = (mi_min + mi_max) * 0.5;
141                 mi_scale = mi_max - mi_min;
142                 minimapname = strzone(minimapname);
143         }
144
145         hud_skin_path = strzone(strcat("gfx/hud/", autocvar_hud_skin));
146         LoadMenuSkinValues();
147 }
148
149 // CSQC_Shutdown : Called every time the CSQC code is shutdown (changing maps, quitting, etc)
150 void Shutdown()
151 {
152         WarpZone_Shutdown();
153
154         delete(teams);
155         delete(players);
156         db_close(binddb);
157         db_close(tempdb);
158         if(autocvar_cl_db_saveasdump)
159                 db_dump(ClientProgsDB, "client.db");
160         else
161                 db_save(ClientProgsDB, "client.db");
162         db_close(ClientProgsDB);
163
164         if(camera_active)
165                 cvar_set("chase_active",ftos(chase_active_backup));
166
167         // unset the event chasecam's chase_active
168         if(autocvar_chase_active < 0)
169                 cvar_set("chase_active", "0");
170
171         cvar_set("slowmo", cvar_defstring("slowmo")); // reset it back to 'default'
172
173         if (!isdemo())
174         {
175                 if (!(calledhooks & HOOK_START))
176                         localcmd("\n_cl_hook_gamestart nop\n");
177                 if (!(calledhooks & HOOK_END))
178                         localcmd("\ncl_hook_gameend\n");
179         }
180
181         localcmd("\ncl_hook_shutdown\n");
182
183         localcmd("\n-button12\n");
184
185         deactivate_minigame();
186         HUD_MinigameMenu_Close(NULL, NULL, NULL);
187
188         ReplicateVars(true); // destroy
189 }
190
191 .float has_team;
192 bool SetTeam(entity o, int Team)
193 {
194         TC(int, Team);
195         //devassert_once(Team);
196         entity tm;
197         if(teamplay)
198         {
199                 switch(Team)
200                 {
201                         case -1:
202                         case NUM_TEAM_1:
203                         case NUM_TEAM_2:
204                         case NUM_TEAM_3:
205                         case NUM_TEAM_4:
206                                 break;
207                         default:
208                                 if(GetTeam(Team, false) == NULL)
209                                 {
210                                         LOG_TRACEF("trying to switch to unsupported team %d", Team);
211                                         Team = NUM_SPECTATOR;
212                                 }
213                                 break;
214                 }
215         }
216         else
217         {
218                 switch(Team)
219                 {
220                         case -1:
221                         case 0:
222                                 break;
223                         default:
224                                 if(GetTeam(Team, false) == NULL)
225                                 {
226                                         LOG_TRACEF("trying to switch to unsupported team %d", Team);
227                                         Team = NUM_SPECTATOR;
228                                 }
229                                 break;
230                 }
231         }
232         if(Team == -1) // leave
233         {
234                 if(o.has_team)
235                 {
236                         tm = GetTeam(o.team, false);
237                         tm.team_size -= 1;
238                         o.has_team = 0;
239                         return true;
240                 }
241         }
242         else
243         {
244                 if (!o.has_team)
245                 {
246                         o.team = Team;
247                         tm = GetTeam(Team, true);
248                         tm.team_size += 1;
249                         o.has_team = 1;
250                         return true;
251                 }
252                 else if(Team != o.team)
253                 {
254                         tm = GetTeam(o.team, false);
255                         tm.team_size -= 1;
256                         o.team = Team;
257                         tm = GetTeam(Team, true);
258                         tm.team_size += 1;
259                         return true;
260                 }
261         }
262         return false;
263 }
264
265 void Playerchecker_Think(entity this)
266 {
267         int i;
268         entity e;
269         for(i = 0; i < maxclients; ++i)
270         {
271                 e = playerslots[i];
272                 if(entcs_GetName(i) == "")
273                 {
274                         if(e.sort_prev)
275                         {
276                                 // player disconnected
277                                 SetTeam(e, -1);
278                                 RemovePlayer(e);
279                                 e.sort_prev = NULL;
280                                 //e.gotscores = 0;
281                         }
282                 }
283                 else
284                 {
285                         if (!e.sort_prev)
286                         {
287                                 // player connected
288                                 if (!e)
289                                 {
290                                         playerslots[i] = e = new_pure(playerslot);
291                                 }
292                                 e.sv_entnum = i;
293                                 e.ping = 0;
294                                 e.ping_packetloss = 0;
295                                 e.ping_movementloss = 0;
296                                 //e.gotscores = 0; // we might already have the scores...
297                                 int t = entcs_GetScoreTeam(i);
298                                 if (t) SetTeam(e, t); // will not hurt; later updates come with Scoreboard_UpdatePlayerTeams
299                                 RegisterPlayer(e);
300                                 Scoreboard_UpdatePlayerPos(e);
301                         }
302                 }
303         }
304         this.nextthink = time + 0.2;
305 }
306
307 void PostInit()
308 {
309         entity playerchecker = new_pure(playerchecker);
310         setthink(playerchecker, Playerchecker_Think);
311         playerchecker.nextthink = time + 0.2;
312
313         TrueAim_Init();
314
315         postinit = true;
316 }
317
318 // CSQC_InputEvent : Used to perform actions based on any key pressed, key released and mouse on the client.
319 // Return value should be 1 if CSQC handled the input, otherwise return 0 to have the input passed to the engine.
320 // All keys are in ascii.
321 // bInputType = 0 is key pressed, 1 is key released, 2 and 3 are mouse input.
322 // In the case of keyboard input, nPrimary is the ascii code, and nSecondary is 0.
323 // In the case of mouse input, nPrimary is xdelta, nSecondary is ydelta.
324 // In the case of mouse input after a setcursormode(1) call, nPrimary is xpos, nSecondary is ypos.
325 float CSQC_InputEvent(int bInputType, float nPrimary, float nSecondary)
326 {
327         TC(int, bInputType);
328         bool override = false;
329         override |= HUD_Panel_InputEvent(bInputType, nPrimary, nSecondary);
330         if (override)
331                 return true;
332
333         override |= QuickMenu_InputEvent(bInputType, nPrimary, nSecondary);
334
335         override |= HUD_Radar_InputEvent(bInputType, nPrimary, nSecondary);
336
337         override |= MapVote_InputEvent(bInputType, nPrimary, nSecondary);
338
339         override |= HUD_Minigame_InputEvent(bInputType, nPrimary, nSecondary);
340
341         if(override)
342                 return true;
343
344         return false;
345 }
346
347 // END REQUIRED CSQC FUNCTIONS
348 // --------------------------------------------------------------------------
349
350 // --------------------------------------------------------------------------
351 // BEGIN OPTIONAL CSQC FUNCTIONS
352
353 void Ent_RemovePlayerScore(entity this)
354 {
355         if(this.owner) {
356                 SetTeam(this.owner, -1);
357                 this.owner.gotscores = 0;
358                 FOREACH(Scores, true, {
359                         this.owner.(scores(it)) = 0; // clear all scores
360                 });
361         }
362 }
363
364 NET_HANDLE(ENT_CLIENT_SCORES, bool isnew)
365 {
366         make_pure(this);
367         entity o;
368
369         // damnit -.- don't want to go change every single .sv_entnum in hud.qc AGAIN
370         // (no I've never heard of M-x replace-string, sed, or anything like that)
371         bool isNew = !this.owner; // workaround for DP bug
372         int n = ReadByte()-1;
373
374 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
375         if(!isNew && n != this.sv_entnum)
376         {
377                 //print("A CSQC entity changed its owner!\n");
378                 LOG_INFOF("A CSQC entity changed its owner! (edict: %d, classname: %s)", etof(this), this.classname);
379                 isNew = true;
380                 Ent_Remove(this);
381         }
382 #endif
383
384         this.sv_entnum = n;
385
386         o = playerslots[this.sv_entnum];
387         if (!o)
388         {
389                 o = playerslots[this.sv_entnum] = new_pure(playerslot);
390         }
391         this.owner = o;
392         o.sv_entnum = this.sv_entnum;
393         o.gotscores = 1;
394
395         //if (!o.sort_prev)
396         //      RegisterPlayer(o);
397         //playerchecker will do this for us later, if it has not already done so
398
399         int sf = ReadShort();
400         int lf = ReadShort();
401         FOREACH(Scores, true, {
402                 int p = 1 << (i % 16);
403                 if (sf & p)
404                 {
405                         if (lf & p)
406                                 o.(scores(it)) = ReadInt24_t();
407                         else
408                                 o.(scores(it)) = ReadChar();
409                 }
410         });
411
412         return = true;
413
414         if(o.sort_prev)
415                 Scoreboard_UpdatePlayerPos(o); // if not registered, we cannot do this yet!
416
417         this.entremove = Ent_RemovePlayerScore;
418 }
419
420 NET_HANDLE(ENT_CLIENT_TEAMSCORES, bool isnew)
421 {
422         make_pure(this);
423         int i;
424
425         this.team = ReadByte();
426         entity o = this.owner = GetTeam(this.team, true); // these team numbers can always be trusted
427
428 #if MAX_TEAMSCORE <= 8
429         int sf = ReadByte();
430         int lf = ReadByte();
431 #else
432         int sf = ReadShort();
433         int lf = ReadShort();
434 #endif
435         for(i = 0; i < MAX_TEAMSCORE; ++i)
436                 if(sf & BIT(i))
437                 {
438                         if(lf & BIT(i))
439                                 o.(teamscores(i)) = ReadInt24_t();
440                         else
441                                 o.(teamscores(i)) = ReadChar();
442                 }
443
444         return = true;
445
446         Scoreboard_UpdateTeamPos(o);
447 }
448
449 NET_HANDLE(ENT_CLIENT_CLIENTDATA, bool isnew)
450 {
451         make_pure(this);
452         float newspectatee_status;
453
454         int f = ReadByte();
455
456         scoreboard_showscores_force = (f & BIT(0));
457
458         if(f & BIT(1))
459         {
460                 newspectatee_status = ReadByte();
461                 if(newspectatee_status == player_localnum + 1)
462                         newspectatee_status = -1; // observing
463         }
464         else
465                 newspectatee_status = 0;
466
467         spectatorbutton_zoom = (f & BIT(2));
468
469         if(f & BIT(4))
470         {
471                 num_spectators = ReadByte();
472
473                 float i, slot;
474
475                 for(i = 0; i < MAX_SPECTATORS; ++i)
476                         spectatorlist[i] = 0; // reset list first
477
478                 for(i = 0; i < num_spectators; ++i)
479                 {
480                         slot = ReadByte();
481                         spectatorlist[i] = slot - 1;
482                 }
483         }
484
485         return = true;
486
487         if(newspectatee_status != spectatee_status)
488         {
489                 // clear race stuff
490                 race_laptime = 0;
491                 race_checkpointtime = 0;
492                 hud_dynamic_shake_factor = -1;
493                 spectatee_status_changed_time = time;
494         }
495         if (autocvar_hud_panel_healtharmor_progressbar_gfx)
496         {
497                 if ( (spectatee_status == -1 && newspectatee_status > 0) //before observing, now spectating
498                   || (spectatee_status > 0 && newspectatee_status > 0 && spectatee_status != newspectatee_status) //changed spectated player
499                 )
500                         prev_p_health = -1;
501                 else if(spectatee_status && !newspectatee_status) //before observing/spectating, now playing
502                         prev_health = -1;
503         }
504         spectatee_status = newspectatee_status;
505
506         // we could get rid of spectatee_status, and derive it from player_localentnum and player_localnum
507 }
508
509 NET_HANDLE(ENT_CLIENT_NAGGER, bool isnew)
510 {
511         make_pure(this);
512         int i, j, b, f;
513
514         int nags = ReadByte(); // NAGS NAGS NAGS NAGS NAGS NAGS NADZ NAGS NAGS NAGS
515
516         if(!(nags & BIT(2)))
517         {
518                 strfree(vote_called_vote);
519                 vote_active = 0;
520         }
521         else
522         {
523                 vote_active = 1;
524         }
525
526         if(nags & BIT(6))
527         {
528                 vote_yescount = ReadByte();
529                 vote_nocount = ReadByte();
530                 vote_needed = ReadByte();
531                 vote_highlighted = ReadChar();
532         }
533
534         if(nags & BIT(7))
535         {
536                 strcpy(vote_called_vote, ReadString());
537         }
538
539         if(nags & 1)
540         {
541                 for(j = 0; j < maxclients; ++j)
542                         if(playerslots[j])
543                                 playerslots[j].ready = true;
544                 for(i = 1; i <= maxclients; i += 8)
545                 {
546                         f = ReadByte();
547                         for(j = i-1, b = BIT(0); b < BIT(8); b <<= 1, ++j)
548                                 if (!(f & b))
549                                         if(playerslots[j])
550                                                 playerslots[j].ready = false;
551                 }
552         }
553
554         return = true;
555
556         ready_waiting = (nags & BIT(0));
557         ready_waiting_for_me = (nags & BIT(1));
558         vote_waiting = (nags & BIT(2));
559         vote_waiting_for_me = (nags & BIT(3));
560         warmup_stage = (nags & BIT(4));
561 }
562
563 NET_HANDLE(ENT_CLIENT_ELIMINATEDPLAYERS, bool isnew)
564 {
565         make_pure(this);
566         int sf = 0;
567         serialize(byte, 0, sf);
568         if (sf & 1) {
569                 for (int j = 0; j < maxclients; ++j) {
570                         if (playerslots[j]) {
571                                 playerslots[j].eliminated = true;
572                         }
573                 }
574                 for (int i = 1; i <= maxclients; i += 8) {
575                         int f = 0;
576                         serialize(byte, 0, f);
577                         for (int b = 0; b < 8; ++b) {
578                                 if (f & BIT(b)) continue;
579                                 int j = i - 1 + b;
580                                 if (playerslots[j]) {
581                                         playerslots[j].eliminated = false;
582                                 }
583                         }
584                 }
585         }
586         return true;
587 }
588
589 NET_HANDLE(ENT_CLIENT_RANDOMSEED, bool isnew)
590 {
591         make_pure(this);
592         prandom_debug();
593         float s = ReadShort();
594         psrandom(s);
595         return true;
596 }
597
598 NET_HANDLE(ENT_CLIENT_ACCURACY, bool isnew)
599 {
600         make_pure(this);
601         int sf = ReadInt24_t();
602         if (sf == 0) {
603                 for (int w = 0; w <= WEP_LAST - WEP_FIRST; ++w)
604                         weapon_accuracy[w] = -1;
605                 return true;
606         }
607
608         int f = 1;
609         for (int w = 0; w <= WEP_LAST - WEP_FIRST; ++w) {
610                 if (sf & f) {
611                         int b = ReadByte();
612                         if (b == 0)
613                                 weapon_accuracy[w] = -1;
614                         else if (b == 255)
615                                 weapon_accuracy[w] = 1.0; // no better error handling yet, sorry
616                         else
617                                 weapon_accuracy[w] = (b - 1.0) / 100.0;
618                 }
619                 f = (f == 0x800000) ? 1 : f * 2;
620         }
621         return true;
622 }
623
624 void Spawn_Draw(entity this)
625 {
626         bool dodraw = autocvar_cl_spawn_point_particles;
627         if(dodraw && autocvar_cl_spawn_point_dist_max)
628         {
629                 vector org = getpropertyvec(VF_ORIGIN);
630                 dodraw = vdist(org - this.origin, <, autocvar_cl_spawn_point_dist_max);
631         }
632
633         if(dodraw)
634                 pointparticles(((!teamplay) ? EFFECT_SPAWNPOINT_NEUTRAL : EFFECT_SPAWNPOINT(this.team - 1)), this.origin + '0 0 28', '0 0 2', bound(0, frametime, 0.1));
635 }
636
637 NET_HANDLE(ENT_CLIENT_SPAWNPOINT, bool is_new)
638 {
639         float teamnum = (ReadByte() - 1);
640         vector spn_origin = ReadVector();
641
642         this.team = (teamnum + 1);
643
644         //if(is_new)
645         //{
646                 this.origin = spn_origin;
647                 setsize(this, PL_MIN_CONST, PL_MAX_CONST);
648                 //droptofloor();
649
650                 /*if(autocvar_cl_spawn_point_model) // needs a model first
651                 {
652                         this.mdl = "models/spawnpoint.md3";
653                         this.colormod = Team_ColorRGB(teamnum);
654                         precache_model(this.mdl);
655                         setmodel(this, this.mdl);
656                         this.drawmask = MASK_NORMAL;
657                         //this.move_movetype = MOVETYPE_NOCLIP;
658                         //this.draw = Spawn_Draw;
659                         IL_PUSH(g_drawables, this);
660                 }*/
661                 this.draw = Spawn_Draw;
662                 if (is_new) IL_PUSH(g_drawables, this);
663         //}
664
665         //printf("Ent_ReadSpawnPoint(is_new = %d); origin = %s, team = %d, effect = %d\n", is_new, vtos(this.origin), teamnum, this.cnt);
666         return true;
667 }
668
669 NET_HANDLE(ENT_CLIENT_SPAWNEVENT, bool is_new)
670 {
671         // If entnum is 0, ONLY do the local spawn actions
672         // this way the server can disable the sending of
673         // spawn origin or such to clients if wanted.
674         float entnum = ReadByte();
675
676         if(entnum)
677         {
678                 this.origin = ReadVector();
679
680                 if(is_new)
681                 {
682                         float teamnum = entcs_GetTeam(entnum - 1);
683
684                         if(autocvar_cl_spawn_event_particles)
685                         {
686                                 switch(teamnum)
687                                 {
688                                         case NUM_TEAM_1: pointparticles(EFFECT_SPAWN_RED, this.origin, '0 0 0', 1); break;
689                                         case NUM_TEAM_2: pointparticles(EFFECT_SPAWN_BLUE, this.origin, '0 0 0', 1); break;
690                                         case NUM_TEAM_3: pointparticles(EFFECT_SPAWN_YELLOW, this.origin, '0 0 0', 1); break;
691                                         case NUM_TEAM_4: pointparticles(EFFECT_SPAWN_PINK, this.origin, '0 0 0', 1); break;
692                                         default: pointparticles(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1); break;
693                                 }
694                         }
695                         if(autocvar_cl_spawn_event_sound)
696                         {
697                                 sound(this, CH_TRIGGER, SND_SPAWN, VOL_BASE, ATTEN_NORM);
698                         }
699                 }
700         }
701         return = true;
702
703         // local spawn actions
704         if(is_new && (!entnum || (entnum == player_localentnum)))
705         {
706                 if(autocvar_cl_spawnzoom && !autocvar_cl_lockview)
707                 {
708                         zoomin_effect = 1;
709                         current_viewzoom = (1 / bound(1, autocvar_cl_spawnzoom_factor, 16));
710                 }
711
712                 if(autocvar_cl_unpress_zoom_on_spawn)
713                 {
714                         localcmd("-zoom\n");
715                         button_zoom = false;
716                 }
717                 HUD_Radar_Hide_Maximized();
718         }
719         //printf("Ent_ReadSpawnEvent(is_new = %d); origin = %s, entnum = %d, localentnum = %d\n", is_new, vtos(this.origin), entnum, player_localentnum);
720 }
721
722 // CSQC_Ent_Update : Called every frame that the server has indicated an update to the SSQC / CSQC entity has occured.
723 // The only parameter reflects if the entity is "new" to the client, meaning it just came into the client's PVS.
724 void CSQC_Ent_Update(entity this, bool isnew)
725 {
726         this.sourceLoc = __FILE__":"STR(__LINE__);
727         int t = ReadByte();
728
729         // set up the "time" global for received entities to be correct for interpolation purposes
730         float savetime = time;
731         if(servertime)
732         {
733                 time = servertime;
734         }
735         else
736         {
737                 serverprevtime = time;
738                 serverdeltatime = STAT(MOVEVARS_TICRATE) * STAT(MOVEVARS_TIMESCALE);
739                 time = serverprevtime + serverdeltatime;
740         }
741
742 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
743         if (this.enttype)
744         {
745                 if (t != this.enttype || isnew)
746                 {
747                         LOG_INFOF("A CSQC entity changed its type! (edict: %d, server: %d, type: %d -> %d)", etof(this), this.entnum, this.enttype, t);
748                         Ent_Remove(this);
749                         clearentity(this);
750                         isnew = true;
751                 }
752         }
753         else
754         {
755                 if (!isnew)
756                 {
757                         LOG_INFOF("A CSQC entity appeared out of nowhere! (edict: %d, server: %d, type: %d)", etof(this), this.entnum, t);
758                         isnew = true;
759                 }
760         }
761 #endif
762         this.enttype = t;
763         bool done = false;
764         FOREACH(LinkedEntities, it.m_id == t, {
765                 if (isnew) this.classname = it.netname;
766                 if (autocvar_developer_csqcentities)
767             LOG_INFOF("CSQC_Ent_Update(%d) at %f with this=%i {.entnum=%d, .enttype=%d} t=%s (%d)", isnew, savetime, this, this.entnum, this.enttype, this.classname, t);
768                 done = it.m_read(this, NULL, isnew);
769                 MUTATOR_CALLHOOK(Ent_Update, this, isnew);
770                 break;
771         });
772         time = savetime;
773         if (!done)
774         {
775                 LOG_FATALF("CSQC_Ent_Update(%d) at %f with this=%i {.entnum=%d, .enttype=%d} t=%s (%d)", isnew, savetime, this, this.entnum, this.enttype, this.classname, t);
776         }
777 }
778
779 // Destructor, but does NOT deallocate the entity by calling remove(). Also
780 // used when an entity changes its type. For an entity that someone interacts
781 // with others, make sure it can no longer do so.
782 void Ent_Remove(entity this)
783 {
784         if(this.entremove) this.entremove(this);
785
786         if(this.skeletonindex)
787         {
788                 skel_delete(this.skeletonindex);
789                 this.skeletonindex = 0;
790         }
791
792         if(this.snd_looping > 0)
793         {
794                 sound(this, this.snd_looping, SND_Null, VOL_BASE, autocvar_cl_jetpack_attenuation);
795                 this.snd_looping = 0;
796         }
797
798         this.enttype = 0;
799         this.classname = "";
800         this.draw = func_null;
801         this.entremove = func_null;
802         // TODO possibly set more stuff to defaults
803 }
804 // CSQC_Ent_Remove : Called when the server requests a SSQC / CSQC entity to be removed.  Essentially call remove(this) as well.
805 void CSQC_Ent_Remove(entity this)
806 {
807         if (autocvar_developer_csqcentities) LOG_INFOF("CSQC_Ent_Remove() with this=%i {.entnum=%d, .enttype=%d}", this, this.entnum, this.enttype);
808         if (wasfreed(this))
809         {
810                 LOG_WARN("CSQC_Ent_Remove called for already removed entity. Packet loss?");
811                 return;
812         }
813         if (this.enttype) Ent_Remove(this);
814         delete(this);
815 }
816
817 void Gamemode_Init()
818 {
819         if (!isdemo())
820         {
821                 if(!(calledhooks & HOOK_START))
822                         localcmd("\n_cl_hook_gamestart ", MapInfo_Type_ToString(gametype), "\n");
823                 calledhooks |= HOOK_START;
824         }
825 }
826 // 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.
827 void CSQC_Parse_StuffCmd(string strMessage)
828 {
829         if (autocvar_developer_csqcentities) LOG_INFOF("CSQC_Parse_StuffCmd(\"%s\")", strMessage);
830         localcmd(strMessage);
831 }
832 // 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.
833 void CSQC_Parse_Print(string strMessage)
834 {
835         if (autocvar_developer_csqcentities) LOG_INFOF("CSQC_Parse_Print(\"%s\")", strMessage);
836         print(ColorTranslateRGB(strMessage));
837 }
838
839 // CSQC_Parse_CenterPrint : Provides the centerprint_AddStandard string in the first parameter that the server provided.
840 void CSQC_Parse_CenterPrint(string strMessage)
841 {
842         if (autocvar_developer_csqcentities) LOG_INFOF("CSQC_Parse_CenterPrint(\"%s\")", strMessage);
843         centerprint_AddStandard(strMessage);
844 }
845
846 // CSQC_Parse_TempEntity : Handles all temporary entity network data in the CSQC layer.
847 // You must ALWAYS first acquire the temporary ID, which is sent as a byte.
848 // Return value should be 1 if CSQC handled the temporary entity, otherwise return 0 to have the engine process the event.
849 bool CSQC_Parse_TempEntity()
850 {
851         // Acquire TE ID
852         int nTEID = ReadByte();
853
854         FOREACH(TempEntities, it.m_id == nTEID, {
855                 if (autocvar_developer_csqcentities)
856                         LOG_INFOF("CSQC_Parse_TempEntity() nTEID=%s (%d)", it.netname, nTEID);
857                 return it.m_read(NULL, NULL, true);
858         });
859
860         if (autocvar_developer_csqcentities)
861                 LOG_INFOF("CSQC_Parse_TempEntity() with nTEID=%d", nTEID);
862
863         // No special logic for this temporary entity; return 0 so the engine can handle it
864         return false;
865 }
866
867 string forcefog;
868 void Fog_Force()
869 {
870         if (autocvar_cl_orthoview && autocvar_cl_orthoview_nofog)
871                 localcmd("\nr_drawfog 0\n");
872         else if (forcefog != "")
873                 localcmd(sprintf("\nfog %s\nr_fog_exp2 0\nr_drawfog 1\n", forcefog));
874 }
875
876 NET_HANDLE(ENT_CLIENT_SCORES_INFO, bool isnew)
877 {
878         make_pure(this);
879         gametype = ReadRegistered(Gametypes);
880         teamplay = _MapInfo_GetTeamPlayBool(gametype);
881         HUD_ModIcons_SetFunc();
882         FOREACH(Scores, true, {
883                 strcpy(scores_label(it), ReadString());
884                 scores_flags(it) = ReadByte();
885         });
886         for (int i = 0; i < MAX_TEAMSCORE; ++i)
887         {
888                 strcpy(teamscores_label(i), ReadString());
889                 teamscores_flags(i) = ReadByte();
890         }
891         return = true;
892         Scoreboard_InitScores();
893         Gamemode_Init();
894 }
895
896 NET_HANDLE(ENT_CLIENT_INIT, bool isnew)
897 {
898         nb_pb_period = ReadByte() / 32; //Accuracy of 1/32th
899
900         hook_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
901         hook_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
902         hook_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
903         hook_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
904         arc_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
905         arc_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
906         arc_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
907         arc_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
908
909         strcpy(forcefog, ReadString());
910
911         armorblockpercent = ReadByte() / 255.0;
912         damagepush_speedfactor = ReadByte() / 255.0;
913
914         serverflags = ReadByte();
915
916         g_trueaim_minrange = ReadCoord();
917
918         return = true;
919
920         MUTATOR_CALLHOOK(Ent_Init);
921
922         if (!postinit) PostInit();
923 }
924
925 float GetSpeedUnitFactor(int speed_unit)
926 {
927         switch(speed_unit)
928         {
929                 default:
930                 case 1: return 1.0;
931                 case 2: return 0.0254;
932                 case 3: return 0.0254 * 3.6;
933                 case 4: return 0.0254 * 3.6 * 0.6213711922;
934                 case 5: return 0.0254 * 1.943844492; // 1 m/s = 1.943844492 knots, because 1 knot = 1.852 km/h
935         }
936 }
937
938 string GetSpeedUnit(int speed_unit)
939 {
940         switch(speed_unit)
941         {
942                 // translator-friendly strings without the initial space
943                 default:
944                 case 1: return strcat(" ", _("qu/s"));
945                 case 2: return strcat(" ", _("m/s"));
946                 case 3: return strcat(" ", _("km/h"));
947                 case 4: return strcat(" ", _("mph"));
948                 case 5: return strcat(" ", _("knots"));
949         }
950 }
951
952 NET_HANDLE(TE_CSQC_RACE, bool isNew)
953 {
954         int b = ReadByte();
955
956         switch (b)
957         {
958                 case RACE_NET_CHECKPOINT_HIT_QUALIFYING:
959                         race_checkpoint = ReadByte();
960                         race_time = ReadInt24_t();
961                         race_previousbesttime = ReadInt24_t();
962                         race_mypreviousbesttime = ReadInt24_t();
963                         string pbestname = ReadString();
964                         if(autocvar_cl_race_cptimes_onlyself)
965                         {
966                                 race_previousbesttime = race_mypreviousbesttime;
967                                 race_mypreviousbesttime = 0;
968                                 strcpy(race_previousbestname, "");
969                         }
970                         else
971                                 strcpy(race_previousbestname, pbestname);
972
973                         race_checkpointtime = time;
974
975                         if(race_checkpoint == 0 || race_checkpoint == 254)
976                         {
977                                 race_penaltyaccumulator = 0;
978                                 race_laptime = time; // valid
979                         }
980                         break;
981
982                 case RACE_NET_CHECKPOINT_CLEAR:
983                         race_laptime = 0;
984                         race_checkpointtime = 0;
985                         break;
986
987                 case RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING:
988                         race_laptime = ReadCoord();
989                         race_checkpointtime = -99999;
990                         // fall through
991                 case RACE_NET_CHECKPOINT_NEXT_QUALIFYING:
992                         race_nextcheckpoint = ReadByte();
993
994                         race_nextbesttime = ReadInt24_t();
995                         if(b != RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING) // not while spectating (matches server)
996                                 race_mybesttime = ReadInt24_t();
997                         string newname = ReadString();
998                         if(autocvar_cl_race_cptimes_onlyself && b != RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING)
999                         {
1000                                 race_nextbesttime = race_mybesttime;
1001                                 race_mybesttime = 0;
1002                                 strcpy(race_nextbestname, "");
1003                         }
1004                         else
1005                                 strcpy(race_nextbestname, newname);
1006                         break;
1007
1008                 case RACE_NET_CHECKPOINT_HIT_RACE:
1009                         race_mycheckpoint = ReadByte();
1010                         race_mycheckpointtime = time;
1011                         race_mycheckpointdelta = ReadInt24_t();
1012                         race_mycheckpointlapsdelta = ReadByte();
1013                         if(race_mycheckpointlapsdelta >= 128)
1014                                 race_mycheckpointlapsdelta -= 256;
1015                         int who = ReadByte();
1016                         if(who)
1017                                 strcpy(race_mycheckpointenemy, entcs_GetName(who - 1));
1018                         else
1019                                 strcpy(race_mycheckpointenemy, ""); // TODO: maybe string_null works fine here?
1020                         break;
1021
1022                 case RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT:
1023                         race_othercheckpoint = ReadByte();
1024                         race_othercheckpointtime = time;
1025                         race_othercheckpointdelta = ReadInt24_t();
1026                         race_othercheckpointlapsdelta = ReadByte();
1027                         if(race_othercheckpointlapsdelta >= 128)
1028                                 race_othercheckpointlapsdelta -= 256;
1029                         int what = ReadByte();
1030                         if(what)
1031                                 strcpy(race_othercheckpointenemy, entcs_GetName(what - 1));
1032                         else
1033                                 strcpy(race_othercheckpointenemy, ""); // TODO: maybe string_null works fine here?
1034                         break;
1035
1036                 case RACE_NET_PENALTY_RACE:
1037                 case RACE_NET_PENALTY_QUALIFYING:
1038                         race_penaltyeventtime = time;
1039                         race_penaltytime = ReadShort();
1040                         string reason = ReadString();
1041                         if (reason == "missing a checkpoint")
1042                                 reason = _("missing a checkpoint");
1043                         strcpy(race_penaltyreason, reason);
1044                         if (b == RACE_NET_PENALTY_QUALIFYING)
1045                                 race_penaltyaccumulator += race_penaltytime;
1046                         break;
1047
1048                 case RACE_NET_SERVER_RECORD:
1049                         race_server_record = ReadInt24_t();
1050                         break;
1051                 case RACE_NET_SPEED_AWARD:
1052                         race_speedaward = ReadInt24_t() * GetSpeedUnitFactor(autocvar_hud_panel_physics_speed_unit);
1053                         strcpy(race_speedaward_holder, ReadString());
1054                         strcpy(race_speedaward_unit, GetSpeedUnit(autocvar_hud_panel_physics_speed_unit));
1055                         break;
1056                 case RACE_NET_SPEED_AWARD_BEST:
1057                         race_speedaward_alltimebest = ReadInt24_t() * GetSpeedUnitFactor(autocvar_hud_panel_physics_speed_unit);
1058                         strcpy(race_speedaward_alltimebest_holder, ReadString());
1059                         strcpy(race_speedaward_alltimebest_unit, GetSpeedUnit(autocvar_hud_panel_physics_speed_unit));
1060                         break;
1061                 case RACE_NET_RANKINGS_CNT:
1062                         RANKINGS_DISPLAY_CNT = ReadByte();
1063                         break;
1064                 case RACE_NET_SERVER_RANKINGS:
1065                         float prevpos, del;
1066                         int pos = ReadShort();
1067                         prevpos = ReadShort();
1068                         del = ReadShort();
1069
1070                         // move other rankings out of the way
1071                         int i;
1072                         if (prevpos) {
1073                                 int m = min(prevpos, RANKINGS_DISPLAY_CNT);
1074                                 for (i=m-1; i>pos-1; --i) {
1075                                         grecordtime[i] = grecordtime[i-1];
1076                                         strcpy(grecordholder[i], grecordholder[i-1]);
1077                                 }
1078                         } else if (del) { // a record has been deleted by the admin
1079                                 for (i=pos-1; i<= RANKINGS_DISPLAY_CNT-1; ++i) {
1080                                         if (i == RANKINGS_DISPLAY_CNT-1) { // clear out last record
1081                                                 grecordtime[i] = 0;
1082                                                 strfree(grecordholder[i]);
1083                                         }
1084                                         else {
1085                                                 grecordtime[i] = grecordtime[i+1];
1086                                                 strcpy(grecordholder[i], grecordholder[i+1]);
1087                                         }
1088                                 }
1089                         } else { // player has no ranked record yet
1090                                 for (i=RANKINGS_DISPLAY_CNT-1;i>pos-1;--i) {
1091                                         grecordtime[i] = grecordtime[i-1];
1092                                         strcpy(grecordholder[i], grecordholder[i-1]);
1093                                 }
1094                         }
1095
1096                         if (grecordtime[RANKINGS_DISPLAY_CNT]) {
1097                                 // kick off the player who fell from the last displayed position
1098                                 grecordtime[RANKINGS_DISPLAY_CNT] = 0;
1099                                 strfree(grecordholder[RANKINGS_DISPLAY_CNT]);
1100                         }
1101
1102                         // store new ranking
1103                         strcpy(grecordholder[pos-1], ReadString());
1104                         grecordtime[pos-1] = ReadInt24_t();
1105                         if(strdecolorize(grecordholder[pos-1]) == strdecolorize(entcs_GetName(player_localnum)))
1106                                 race_myrank = pos;
1107                         break;
1108                 case RACE_NET_SERVER_STATUS:
1109                         race_status = ReadShort();
1110                         strcpy(race_status_name, ReadString());
1111         }
1112         return true;
1113 }
1114
1115 NET_HANDLE(TE_CSQC_TEAMNAGGER, bool isNew)
1116 {
1117         teamnagger = 1;
1118         return true;
1119 }
1120
1121 NET_HANDLE(TE_CSQC_PINGPLREPORT, bool isNew)
1122 {
1123         int i = ReadByte();
1124         int pi = ReadShort();
1125         int pl = ReadByte();
1126         int ml = ReadByte();
1127         return = true;
1128         entity e = playerslots[i];
1129         if (!e) return;
1130         e.ping = pi;
1131         e.ping_packetloss = pl / 255.0;
1132         e.ping_movementloss = ml / 255.0;
1133 }
1134
1135 NET_HANDLE(TE_CSQC_WEAPONCOMPLAIN, bool isNew)
1136 {
1137         int weapon_id = ReadByte();
1138         complain_weapon = REGISTRY_GET(Weapons, weapon_id);
1139         complain_weapon_type = ReadByte();
1140         return = true;
1141
1142         complain_weapon_time = time;
1143         weapontime = time; // ping the weapon panel
1144
1145         switch(complain_weapon_type)
1146         {
1147                 case 0: Local_Notification(MSG_MULTI, ITEM_WEAPON_NOAMMO, weapon_id); break;
1148                 case 1: Local_Notification(MSG_MULTI, ITEM_WEAPON_DONTHAVE, weapon_id); break;
1149                 default: Local_Notification(MSG_MULTI, ITEM_WEAPON_UNAVAILABLE, weapon_id); break;
1150         }
1151 }
1152
1153 string _getcommandkey(string cmd_name, string command, bool forcename)
1154 {
1155         string keys;
1156         float n, j, k, l = 0;
1157
1158         if (!autocvar_hud_showbinds)
1159                 return cmd_name;
1160
1161         keys = db_get(binddb, command);
1162         if (keys == "")
1163         {
1164                 bool joy_active = cvar("joy_active");
1165                 n = tokenize(findkeysforcommand(command, 0)); // uses '...' strings
1166                 for(j = 0; j < n; ++j)
1167                 {
1168                         k = stof(argv(j));
1169                         if(k != -1)
1170                         {
1171                                 string key = keynumtostring(k);
1172                                 if(!joy_active && substring(key, 0, 3) == "JOY")
1173                                         continue;
1174
1175                                 key = translate_key(key);
1176
1177                                 if (keys == "")
1178                                         keys = key;
1179                                 else
1180                                         keys = strcat(keys, ", ", key);
1181
1182                                 ++l;
1183                                 if (autocvar_hud_showbinds_limit > 0 && autocvar_hud_showbinds_limit <= l)
1184                                         break;
1185                         }
1186
1187                 }
1188                 if (keys == "")
1189                         keys = "NO_KEY";
1190                 db_put(binddb, command, keys);
1191         }
1192
1193         if (keys == "NO_KEY") {
1194                 if (autocvar_hud_showbinds > 1)
1195                         return sprintf(_("%s (not bound)"), cmd_name);
1196                 else
1197                         return cmd_name;
1198         }
1199         else if (autocvar_hud_showbinds > 1 || forcename)
1200                 return sprintf("%s (%s)", cmd_name, keys);
1201         else
1202                 return keys;
1203 }