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