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