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