298bcdbefefff66e1b26993c8dd3b23a41f1e842
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / main.qc
1 #include "main.qh"
2 #include "_all.qh"
3
4 #include "casings.qh"
5 #include "csqcmodel_hooks.qh"
6 #include "damage.qh"
7 #include "effects.qh"
8 #include "gibs.qh"
9 #include "hook.qh"
10 #include "hud.qh"
11 #include "hud_config.qh"
12 #include "laser.qh"
13 #include "mapvoting.qh"
14 #include "modeleffects.qh"
15 #include "particles.qh"
16 #include "prandom.qh"
17 #include "scoreboard.qh"
18 #include "shownames.qh"
19 #include "sortlist.qh"
20 #include "target_music.qh"
21 #include "tturrets.qh"
22 #include "tuba.qh"
23 #include "t_items.qh"
24 #include "wall.qh"
25 #include "waypointsprites.qh"
26
27 #include "vehicles/bumblebee.qh"
28 #include "vehicles/all.qh"
29
30 #include "weapons/projectile.qh"
31
32 #include "../common/buffs.qh"
33 #include "../common/deathtypes.qh"
34 #include "../common/mapinfo.qh"
35 #include "../common/monsters/all.qh"
36 #include "../common/nades.qh"
37 #include "../common/net_notice.qh"
38 #include "../common/notifications.qh"
39 #include "../common/stats.qh"
40 #include "../common/teams.qh"
41
42 #include "../common/weapons/all.qh"
43
44 #include "../csqcmodellib/cl_model.qh"
45 #include "../csqcmodellib/interpolate.qh"
46
47 #include "../warpzonelib/client.qh"
48
49 // --------------------------------------------------------------------------
50 // BEGIN REQUIRED CSQC FUNCTIONS
51 //include "main.qh"
52
53 entity clearentity_ent;
54 void clearentity(entity e)
55 {
56         if (!clearentity_ent)
57         {
58                 clearentity_ent = spawn();
59                 clearentity_ent.classname = "clearentity";
60         }
61         int n = e.entnum;
62         copyentity(clearentity_ent, e);
63         e.entnum = n;
64 }
65
66 #define DP_CSQC_ENTITY_REMOVE_IS_B0RKED
67 void menu_show_error()
68 {
69         drawstring('0 200 0', _("ERROR - MENU IS VISIBLE BUT NO MENU WAS DEFINED!"), '8 8 0', '1 0 0', 1, 0);
70 }
71
72 // CSQC_Init : Called every time the CSQC code is initialized (essentially at map load)
73 // Useful for precaching things
74
75 void menu_sub_null()
76 {
77 }
78
79 string forcefog;
80 void WaypointSprite_Load();
81 void ConsoleCommand_macro_init();
82 void CSQC_Init(void)
83 {
84         prvm_language = cvar_string("prvm_language");
85
86 #ifdef WATERMARK
87         dprintf("^4CSQC Build information: ^1%s\n", WATERMARK);
88 #endif
89
90         int i;
91
92         binddb = db_create();
93         tempdb = db_create();
94         ClientProgsDB = db_load("client.db");
95         compressShortVector_init();
96
97         draw_endBoldFont();
98         menu_visible = false;
99         menu_show = menu_show_error;
100         menu_action = func_null;
101
102         for(i = 0; i < 255; ++i)
103                 if(getplayerkeyvalue(i, "viewentity") == "")
104                         break;
105         maxclients = i;
106
107         //registercommand("hud_configure");
108         //registercommand("hud_save");
109         //registercommand("menu_action");
110
111         ConsoleCommand_macro_init();
112
113         registercvar("hud_usecsqc", "1");
114         registercvar("scoreboard_columns", "default");
115
116         registercvar("cl_nade_type", "3");
117         registercvar("cl_pokenade_type", "zombie");
118
119         gametype = 0;
120
121         // hud_fields uses strunzone on the titles!
122         for(i = 0; i < MAX_HUD_FIELDS; ++i)
123                 hud_title[i] = strzone("(null)");
124
125         Cmd_HUD_SetFields(0);
126
127         postinit = false;
128
129         calledhooks = 0;
130
131         teams = Sort_Spawn();
132         players = Sort_Spawn();
133
134         GetTeam(NUM_SPECTATOR, true); // add specs first
135
136         // needs to be done so early because of the constants they create
137         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
138         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
139         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
140         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
141         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
142         CALL_ACCUMULATED_FUNCTION(RegisterHUD_Panels);
143         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
144
145         WaypointSprite_Load();
146
147         // precaches
148         precache_model("null");
149         precache_sound("misc/hit.wav");
150         precache_sound("misc/typehit.wav");
151
152         Projectile_Precache();
153         Hook_Precache();
154         GibSplash_Precache();
155         Casings_Precache();
156         Vehicles_Precache();
157         turrets_precache();
158         Tuba_Precache();
159         CSQCPlayer_Precache();
160
161         if(autocvar_cl_reticle)
162         {
163                 precache_pic("gfx/reticle_normal");
164                 // weapon reticles are precached in weapon files
165         }
166
167         get_mi_min_max_texcoords(1); // try the CLEVER way first
168         minimapname = strcat("gfx/", mi_shortname, "_radar.tga");
169         shortmapname = mi_shortname;
170
171         if(precache_pic(minimapname) == "")
172         {
173                 // but maybe we have a non-clever minimap
174                 minimapname = strcat("gfx/", mi_shortname, "_mini.tga");
175                 if(precache_pic(minimapname) == "")
176                         minimapname = ""; // FAIL
177                 else
178                         get_mi_min_max_texcoords(0); // load new texcoords
179         }
180
181         mi_center = (mi_min + mi_max) * 0.5;
182         mi_scale = mi_max - mi_min;
183         minimapname = strzone(minimapname);
184
185         WarpZone_Init();
186
187         hud_skin_path = strzone(strcat("gfx/hud/", autocvar_hud_skin));
188         draw_currentSkin = strzone(strcat("gfx/menu/", cvar_string("menu_skin")));
189 }
190
191 // CSQC_Shutdown : Called every time the CSQC code is shutdown (changing maps, quitting, etc)
192 void Shutdown(void)
193 {
194         WarpZone_Shutdown();
195
196         remove(teams);
197         remove(players);
198         db_close(binddb);
199         db_close(tempdb);
200         if(autocvar_cl_db_saveasdump)
201                 db_dump(ClientProgsDB, "client.db");
202         else
203                 db_save(ClientProgsDB, "client.db");
204         db_close(ClientProgsDB);
205
206         if(camera_active)
207                 cvar_set("chase_active",ftos(chase_active_backup));
208
209         // unset the event chasecam's chase_active
210         if(autocvar_chase_active < 0)
211                 cvar_set("chase_active", "0");
212
213         if (!isdemo())
214         {
215                 if (!(calledhooks & HOOK_START))
216                         localcmd("\n_cl_hook_gamestart nop\n");
217                 if (!(calledhooks & HOOK_END))
218                         localcmd("\ncl_hook_gameend\n");
219         }
220 }
221
222 .float has_team;
223 float SetTeam(entity o, int Team)
224 {
225         entity tm;
226         if(teamplay)
227         {
228                 switch(Team)
229                 {
230                         case -1:
231                         case NUM_TEAM_1:
232                         case NUM_TEAM_2:
233                         case NUM_TEAM_3:
234                         case NUM_TEAM_4:
235                                 break;
236                         default:
237                                 if(GetTeam(Team, false) == world)
238                                 {
239                                         dprintf("trying to switch to unsupported team %d\n", Team);
240                                         Team = NUM_SPECTATOR;
241                                 }
242                                 break;
243                 }
244         }
245         else
246         {
247                 switch(Team)
248                 {
249                         case -1:
250                         case 0:
251                                 break;
252                         default:
253                                 if(GetTeam(Team, false) == world)
254                                 {
255                                         dprintf("trying to switch to unsupported team %d\n", Team);
256                                         Team = NUM_SPECTATOR;
257                                 }
258                                 break;
259                 }
260         }
261         if(Team == -1) // leave
262         {
263                 if(o.has_team)
264                 {
265                         tm = GetTeam(o.team, false);
266                         tm.team_size -= 1;
267                         o.has_team = 0;
268                         return true;
269                 }
270         }
271         else
272         {
273                 if (!o.has_team)
274                 {
275                         o.team = Team;
276                         tm = GetTeam(Team, true);
277                         tm.team_size += 1;
278                         o.has_team = 1;
279                         return true;
280                 }
281                 else if(Team != o.team)
282                 {
283                         tm = GetTeam(o.team, false);
284                         tm.team_size -= 1;
285                         o.team = Team;
286                         tm = GetTeam(Team, true);
287                         tm.team_size += 1;
288                         return true;
289                 }
290         }
291         return false;
292 }
293
294 void Playerchecker_Think()
295 {
296     int i;
297         entity e;
298         for(i = 0; i < maxclients; ++i)
299         {
300                 e = playerslots[i];
301                 if(GetPlayerName(i) == "")
302                 {
303                         if(e.sort_prev)
304                         {
305                                 // player disconnected
306                                 SetTeam(e, -1);
307                                 RemovePlayer(e);
308                                 e.sort_prev = world;
309                                 //e.gotscores = 0;
310                         }
311                 }
312                 else
313                 {
314                         if (!e.sort_prev)
315                         {
316                                 // player connected
317                                 if (!e)
318                                         playerslots[i] = e = spawn();
319                                 e.sv_entnum = i;
320                                 e.ping = 0;
321                                 e.ping_packetloss = 0;
322                                 e.ping_movementloss = 0;
323                                 //e.gotscores = 0; // we might already have the scores...
324                                 SetTeam(e, GetPlayerColor(i)); // will not hurt; later updates come with HUD_UpdatePlayerTeams
325                                 RegisterPlayer(e);
326                                 HUD_UpdatePlayerPos(e);
327                         }
328                 }
329         }
330         self.nextthink = time + 0.2;
331 }
332
333 void Porto_Init();
334 void TrueAim_Init();
335 void PostInit(void)
336 {
337         entity playerchecker;
338         playerchecker = spawn();
339         playerchecker.think = Playerchecker_Think;
340         playerchecker.nextthink = time + 0.2;
341
342         Porto_Init();
343         TrueAim_Init();
344
345         postinit = true;
346 }
347
348 // CSQC_InputEvent : Used to perform actions based on any key pressed, key released and mouse on the client.
349 // Return value should be 1 if CSQC handled the input, otherwise return 0 to have the input passed to the engine.
350 // All keys are in ascii.
351 // bInputType = 0 is key pressed, 1 is key released, 2 and 3 are mouse input.
352 // In the case of keyboard input, nPrimary is the ascii code, and nSecondary is 0.
353 // In the case of mouse input, nPrimary is xdelta, nSecondary is ydelta.
354 // In the case of mouse input after a setcursormode(1) call, nPrimary is xpos, nSecondary is ypos.
355 float CSQC_InputEvent(float bInputType, float nPrimary, float nSecondary)
356 {
357         float bSkipKey;
358         bSkipKey = false;
359
360         if (HUD_Panel_InputEvent(bInputType, nPrimary, nSecondary))
361                 return true;
362
363         if (MapVote_InputEvent(bInputType, nPrimary, nSecondary))
364                 return true;
365
366         if(menu_visible && menu_action)
367                 if(menu_action(bInputType, nPrimary, nSecondary))
368                         return true;
369
370         return bSkipKey;
371 }
372
373 // END REQUIRED CSQC FUNCTIONS
374 // --------------------------------------------------------------------------
375
376 // --------------------------------------------------------------------------
377 // BEGIN OPTIONAL CSQC FUNCTIONS
378 void Ent_RemoveEntCS()
379 {
380         entcs_receiver[self.sv_entnum] = world;
381 }
382 void Ent_ReadEntCS()
383 {
384     int sf;
385         InterpolateOrigin_Undo();
386
387         self.classname = "entcs_receiver";
388         sf = ReadByte();
389
390         if(sf & 1)
391                 self.sv_entnum = ReadByte();
392         if(sf & 2)
393         {
394                 self.origin_x = ReadShort();
395                 self.origin_y = ReadShort();
396                 self.origin_z = ReadShort();
397                 setorigin(self, self.origin);
398         }
399         if(sf & 4)
400         {
401                 self.angles_y = ReadByte() * 360.0 / 256;
402                 self.angles_x = self.angles_z = 0;
403         }
404         if(sf & 8)
405                 self.healthvalue = ReadByte() * 10;
406         if(sf & 16)
407                 self.armorvalue = ReadByte() * 10;
408
409         entcs_receiver[self.sv_entnum] = self;
410         self.entremove = Ent_RemoveEntCS;
411         self.iflags |= IFLAG_ORIGIN;
412
413         InterpolateOrigin_Note();
414 }
415
416 void Ent_Remove();
417
418 void Ent_RemovePlayerScore()
419 {
420         if(self.owner) {
421                 SetTeam(self.owner, -1);
422                 self.owner.gotscores = 0;
423                 for(int i = 0; i < MAX_SCORE; ++i) {
424                         self.owner.(scores[i]) = 0; // clear all scores
425                 }
426         }
427 }
428
429 void Ent_ReadPlayerScore()
430 {
431         int i, n;
432         bool isNew;
433         entity o;
434
435         // damnit -.- don't want to go change every single .sv_entnum in hud.qc AGAIN
436         // (no I've never heard of M-x replace-string, sed, or anything like that)
437         isNew = !self.owner; // workaround for DP bug
438         n = ReadByte()-1;
439
440 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
441         if(!isNew && n != self.sv_entnum)
442         {
443                 //print("A CSQC entity changed its owner!\n");
444                 printf("A CSQC entity changed its owner! (edict: %d, classname: %s)\n", num_for_edict(self), self.classname);
445                 isNew = true;
446                 Ent_Remove();
447                 self.enttype = ENT_CLIENT_SCORES;
448         }
449 #endif
450
451         self.sv_entnum = n;
452
453         if (!(playerslots[self.sv_entnum]))
454                 playerslots[self.sv_entnum] = spawn();
455         o = self.owner = playerslots[self.sv_entnum];
456         o.sv_entnum = self.sv_entnum;
457         o.gotscores = 1;
458
459         //if (!o.sort_prev)
460         //      RegisterPlayer(o);
461         //playerchecker will do this for us later, if it has not already done so
462
463     int sf, lf;
464 #if MAX_SCORE <= 8
465         sf = ReadByte();
466         lf = ReadByte();
467 #else
468         sf = ReadShort();
469         lf = ReadShort();
470 #endif
471     int p;
472         for(i = 0, p = 1; i < MAX_SCORE; ++i, p *= 2)
473                 if(sf & p)
474                 {
475                         if(lf & p)
476                                 o.(scores[i]) = ReadInt24_t();
477                         else
478                                 o.(scores[i]) = ReadChar();
479                 }
480
481         if(o.sort_prev)
482                 HUD_UpdatePlayerPos(o); // if not registered, we cannot do this yet!
483
484         self.entremove = Ent_RemovePlayerScore;
485 }
486
487 void Ent_ReadTeamScore()
488 {
489         int i;
490         entity o;
491
492         self.team = ReadByte();
493         o = self.owner = GetTeam(self.team, true); // these team numbers can always be trusted
494
495     int sf, lf;
496 #if MAX_TEAMSCORE <= 8
497         sf = ReadByte();
498         lf = ReadByte();
499 #else
500         sf = ReadShort();
501         lf = ReadShort();
502 #endif
503         int p;
504         for(i = 0, p = 1; i < MAX_TEAMSCORE; ++i, p *= 2)
505                 if(sf & p)
506                 {
507                         if(lf & p)
508                                 o.(teamscores[i]) = ReadInt24_t();
509                         else
510                                 o.(teamscores[i]) = ReadChar();
511                 }
512
513         HUD_UpdateTeamPos(o);
514 }
515
516 void Ent_ClientData()
517 {
518         float newspectatee_status;
519
520     int f = ReadByte();
521
522         scoreboard_showscores_force = (f & 1);
523
524         if(f & 2)
525         {
526                 newspectatee_status = ReadByte();
527                 if(newspectatee_status == player_localnum + 1)
528                         newspectatee_status = -1; // observing
529         }
530         else
531                 newspectatee_status = 0;
532
533         spectatorbutton_zoom = (f & 4);
534
535         if(f & 8)
536         {
537                 angles_held_status = 1;
538                 angles_held.x = ReadAngle();
539                 angles_held.y = ReadAngle();
540                 angles_held.z = 0;
541         }
542         else
543                 angles_held_status = 0;
544
545         if(newspectatee_status != spectatee_status)
546         {
547                 // clear race stuff
548                 race_laptime = 0;
549                 race_checkpointtime = 0;
550         }
551         if (autocvar_hud_panel_healtharmor_progressbar_gfx)
552         {
553                 if ( (spectatee_status == -1 && newspectatee_status > 0) //before observing, now spectating
554                   || (spectatee_status > 0 && newspectatee_status > 0 && spectatee_status != newspectatee_status) //changed spectated player
555                 )
556                         prev_p_health = -1;
557                 else if(spectatee_status && !newspectatee_status) //before observing/spectating, now playing
558                         prev_health = -1;
559         }
560         spectatee_status = newspectatee_status;
561
562         // we could get rid of spectatee_status, and derive it from player_localentnum and player_localnum
563 }
564
565 void Ent_Nagger()
566 {
567     int i, j, b, f;
568
569     int nags = ReadByte(); // NAGS NAGS NAGS NAGS NAGS NAGS NADZ NAGS NAGS NAGS
570
571         if(!(nags & 4))
572         {
573                 if(vote_called_vote)
574                         strunzone(vote_called_vote);
575                 vote_called_vote = string_null;
576                 vote_active = 0;
577         }
578         else
579         {
580                 vote_active = 1;
581         }
582
583         if(nags & 64)
584         {
585                 vote_yescount = ReadByte();
586                 vote_nocount = ReadByte();
587                 vote_needed = ReadByte();
588                 vote_highlighted = ReadChar();
589         }
590
591         if(nags & 128)
592         {
593                 if(vote_called_vote)
594                         strunzone(vote_called_vote);
595                 vote_called_vote = strzone(ColorTranslateRGB(ReadString()));
596         }
597
598         if(nags & 1)
599         {
600                 for(j = 0; j < maxclients; ++j)
601                         if(playerslots[j])
602                                 playerslots[j].ready = 1;
603                 for(i = 1; i <= maxclients; i += 8)
604                 {
605                         f = ReadByte();
606                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
607                                 if (!(f & b))
608                                         if(playerslots[j])
609                                                 playerslots[j].ready = 0;
610                 }
611         }
612
613         ready_waiting = (nags & 1);
614         ready_waiting_for_me = (nags & 2);
615         vote_waiting = (nags & 4);
616         vote_waiting_for_me = (nags & 8);
617         warmup_stage = (nags & 16);
618 }
619
620 void Ent_EliminatedPlayers()
621 {
622     int i, j, b, f;
623
624     int sf = ReadByte();
625         if(sf & 1)
626         {
627                 for(j = 0; j < maxclients; ++j)
628                         if(playerslots[j])
629                                 playerslots[j].eliminated = 1;
630                 for(i = 1; i <= maxclients; i += 8)
631                 {
632                         f = ReadByte();
633                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
634                                 if (!(f & b))
635                                         if(playerslots[j])
636                                                 playerslots[j].eliminated = 0;
637                 }
638         }
639 }
640
641 void Ent_RandomSeed()
642 {
643         float s;
644         prandom_debug();
645         s = ReadShort();
646         psrandom(s);
647 }
648
649 void Ent_ReadAccuracy(void)
650 {
651     int f, w;
652     int sf = ReadInt24_t();
653         if(sf == 0)
654         {
655                 for(w = 0; w <= WEP_LAST - WEP_FIRST; ++w)
656                         weapon_accuracy[w] = -1;
657                 return;
658         }
659
660         for(w = 0, f = 1; w <= WEP_LAST - WEP_FIRST; ++w)
661         {
662                 if(sf & f)
663                 {
664             int b = ReadByte();
665                         if(b == 0)
666                                 weapon_accuracy[w] = -1;
667                         else if(b == 255)
668                                 weapon_accuracy[w] = 1.0; // no better error handling yet, sorry
669                         else
670                                 weapon_accuracy[w] = (b - 1.0) / 100.0;
671                 }
672                 if(f == 0x800000)
673                         f = 1;
674                 else
675                         f *= 2;
676         }
677 }
678
679 void Spawn_Draw(void)
680 {
681         pointparticles(self.cnt, self.origin + '0 0 28', '0 0 2', bound(0, frametime, 0.1));
682 }
683
684 void Ent_ReadSpawnPoint(float is_new) // entity for spawnpoint
685 {
686         float teamnum = (ReadByte() - 1);
687         vector spn_origin;
688         spn_origin.x = ReadShort();
689         spn_origin.y = ReadShort();
690         spn_origin.z = ReadShort();
691
692         if(is_new)
693         {
694                 self.origin = spn_origin;
695                 setsize(self, PL_MIN, PL_MAX);
696                 droptofloor();
697
698                 /*if(autocvar_cl_spawn_point_model) // needs a model first
699                 {
700                         self.mdl = "models/spawnpoint.md3";
701                         self.colormod = Team_ColorRGB(teamnum);
702                         precache_model(self.mdl);
703                         setmodel(self, self.mdl);
704                         self.drawmask = MASK_NORMAL;
705                         //self.movetype = MOVETYPE_NOCLIP;
706                         //self.draw = Spawn_Draw;
707                 }*/
708                 if(autocvar_cl_spawn_point_particles)
709                 {
710                         if((serverflags & SERVERFLAG_TEAMPLAY))
711                         {
712                                 switch(teamnum)
713                                 {
714                                         case NUM_TEAM_1: self.cnt = particleeffectnum("spawn_point_red"); break;
715                                         case NUM_TEAM_2: self.cnt = particleeffectnum("spawn_point_blue"); break;
716                                         case NUM_TEAM_3: self.cnt = particleeffectnum("spawn_point_yellow"); break;
717                                         case NUM_TEAM_4: self.cnt = particleeffectnum("spawn_point_pink"); break;
718                                         default: self.cnt = particleeffectnum("spawn_point_neutral"); break;
719                                 }
720                         }
721                         else { self.cnt = particleeffectnum("spawn_point_neutral"); }
722
723                         self.draw = Spawn_Draw;
724                 }
725         }
726
727         //printf("Ent_ReadSpawnPoint(is_new = %d); origin = %s, team = %d, effect = %d\n", is_new, vtos(self.origin), teamnum, self.cnt);
728 }
729
730 void Ent_ReadSpawnEvent(float 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                 self.origin_x = ReadShort();
740                 self.origin_y = ReadShort();
741                 self.origin_z = ReadShort();
742
743                 if(is_new)
744                 {
745                         float teamnum = GetPlayerColor(entnum - 1);
746
747                         if(autocvar_cl_spawn_event_particles)
748                         {
749                                 switch(teamnum)
750                                 {
751                                         case NUM_TEAM_1: pointparticles(particleeffectnum("spawn_event_red"), self.origin, '0 0 0', 1); break;
752                                         case NUM_TEAM_2: pointparticles(particleeffectnum("spawn_event_blue"), self.origin, '0 0 0', 1); break;
753                                         case NUM_TEAM_3: pointparticles(particleeffectnum("spawn_event_yellow"), self.origin, '0 0 0', 1); break;
754                                         case NUM_TEAM_4: pointparticles(particleeffectnum("spawn_event_pink"), self.origin, '0 0 0', 1); break;
755                                         default: pointparticles(particleeffectnum("spawn_event_neutral"), self.origin, '0 0 0', 1); break;
756                                 }
757                         }
758                         if(autocvar_cl_spawn_event_sound)
759                         {
760                                 sound(self, CH_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTEN_NORM);
761                         }
762                 }
763         }
764
765         // local spawn actions
766         if(is_new && (!entnum || (entnum == player_localentnum)))
767         {
768                 zoomin_effect = 1;
769                 current_viewzoom = (1 / bound(1, autocvar_cl_spawnzoom_factor, 16));
770
771                 if(autocvar_cl_unpress_zoom_on_spawn)
772                 {
773                         localcmd("-zoom\n");
774                         button_zoom = false;
775                 }
776         }
777
778         //printf("Ent_ReadSpawnEvent(is_new = %d); origin = %s, entnum = %d, localentnum = %d\n", is_new, vtos(self.origin), entnum, player_localentnum);
779 }
780
781 // CSQC_Ent_Update : Called every frame that the server has indicated an update to the SSQC / CSQC entity has occured.
782 // The only parameter reflects if the entity is "new" to the client, meaning it just came into the client's PVS.
783 void Ent_RadarLink();
784 void Ent_Init();
785 void Ent_ScoresInfo();
786 void CSQC_Ent_Update(float bIsNewEntity)
787 {
788         float t;
789         float savetime;
790         t = ReadByte();
791
792         if(autocvar_developer_csqcentities)
793                 printf("CSQC_Ent_Update(%d) with self=%i self.entnum=%d self.enttype=%d t=%d\n", bIsNewEntity, self, self.entnum, self.enttype, t);
794
795         // set up the "time" global for received entities to be correct for interpolation purposes
796         savetime = time;
797         if(servertime)
798         {
799                 time = servertime;
800         }
801         else
802         {
803                 serverprevtime = time;
804                 serverdeltatime = getstatf(STAT_MOVEVARS_TICRATE) * getstatf(STAT_MOVEVARS_TIMESCALE);
805                 time = serverprevtime + serverdeltatime;
806         }
807
808 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
809         if(self.enttype)
810         {
811                 if(t != self.enttype || bIsNewEntity)
812                 {
813                         //print("A CSQC entity changed its type!\n");
814                         printf("A CSQC entity changed its type! (edict: %d, server: %d, type: %d -> %d)\n", num_for_edict(self), self.entnum, self.enttype, t);
815                         Ent_Remove();
816                         clearentity(self);
817                         bIsNewEntity = 1;
818                 }
819         }
820         else
821         {
822                 if(!bIsNewEntity)
823                 {
824                         printf("A CSQC entity appeared out of nowhere! (edict: %d, server: %d, type: %d)\n", num_for_edict(self), self.entnum, t);
825                         bIsNewEntity = 1;
826                 }
827         }
828 #endif
829         self.enttype = t;
830         switch(t)
831         {
832                 case ENT_CLIENT_ENTCS: Ent_ReadEntCS(); break;
833                 case ENT_CLIENT_SCORES: Ent_ReadPlayerScore(); break;
834                 case ENT_CLIENT_TEAMSCORES: Ent_ReadTeamScore(); break;
835                 case ENT_CLIENT_POINTPARTICLES: Ent_PointParticles(); break;
836                 case ENT_CLIENT_RAINSNOW: Ent_RainOrSnow(); break;
837                 case ENT_CLIENT_LASER: Ent_Laser(); break;
838                 case ENT_CLIENT_NAGGER: Ent_Nagger(); break;
839                 case ENT_CLIENT_ELIMINATEDPLAYERS: Ent_EliminatedPlayers(); break;
840                 case ENT_CLIENT_WAYPOINT: Ent_WaypointSprite(); break;
841                 case ENT_CLIENT_RADARLINK: Ent_RadarLink(); break;
842                 case ENT_CLIENT_PROJECTILE: Ent_Projectile(); break;
843                 case ENT_CLIENT_GIBSPLASH: Ent_GibSplash(bIsNewEntity); break;
844                 case ENT_CLIENT_DAMAGEINFO: Ent_DamageInfo(bIsNewEntity); break;
845                 case ENT_CLIENT_CASING: Ent_Casing(bIsNewEntity); break;
846                 case ENT_CLIENT_INIT: Ent_Init(); break;
847                 case ENT_CLIENT_SCORES_INFO: Ent_ScoresInfo(); break;
848                 case ENT_CLIENT_MAPVOTE: Ent_MapVote(); break;
849                 case ENT_CLIENT_CLIENTDATA: Ent_ClientData(); break;
850                 case ENT_CLIENT_RANDOMSEED: Ent_RandomSeed(); break;
851                 case ENT_CLIENT_WALL: Ent_Wall(); break;
852                 case ENT_CLIENT_MODELEFFECT: Ent_ModelEffect(bIsNewEntity); break;
853                 case ENT_CLIENT_TUBANOTE: Ent_TubaNote(bIsNewEntity); break;
854                 case ENT_CLIENT_WARPZONE: WarpZone_Read(bIsNewEntity); break;
855                 case ENT_CLIENT_WARPZONE_CAMERA: WarpZone_Camera_Read(bIsNewEntity); break;
856                 case ENT_CLIENT_WARPZONE_TELEPORTED: WarpZone_Teleported_Read(bIsNewEntity); break;
857                 case ENT_CLIENT_TRIGGER_MUSIC: Ent_ReadTriggerMusic(); break;
858                 case ENT_CLIENT_HOOK: Ent_ReadHook(bIsNewEntity, ENT_CLIENT_HOOK); break;
859                 case ENT_CLIENT_ARC_BEAM: Ent_ReadArcBeam(bIsNewEntity); break;
860                 case ENT_CLIENT_ACCURACY: Ent_ReadAccuracy(); break;
861                 case ENT_CLIENT_AUXILIARYXHAIR: Net_AuXair2(bIsNewEntity); break;
862                 case ENT_CLIENT_TURRET: ent_turret(); break;
863                 case ENT_CLIENT_MODEL: CSQCModel_Read(bIsNewEntity); break;
864                 case ENT_CLIENT_ITEM: ItemRead(bIsNewEntity); break;
865                 case ENT_CLIENT_BUMBLE_RAYGUN: bumble_raygun_read(bIsNewEntity); break;
866                 case ENT_CLIENT_SPAWNPOINT: Ent_ReadSpawnPoint(bIsNewEntity); break;
867                 case ENT_CLIENT_SPAWNEVENT: Ent_ReadSpawnEvent(bIsNewEntity); break;
868                 case ENT_CLIENT_NOTIFICATION: Read_Notification(bIsNewEntity); break;
869                 case ENT_CLIENT_HEALING_ORB: ent_healer(); break;
870
871                 default:
872                         //error(strcat(_("unknown entity type in CSQC_Ent_Update: %d\n"), self.enttype));
873                         error(sprintf("Unknown entity type in CSQC_Ent_Update (enttype: %d, edict: %d, classname: %s)\n", self.enttype, num_for_edict(self), self.classname));
874                         break;
875         }
876
877         time = savetime;
878 }
879 // Destructor, but does NOT deallocate the entity by calling remove(). Also
880 // used when an entity changes its type. For an entity that someone interacts
881 // with others, make sure it can no longer do so.
882 void Ent_Remove()
883 {
884         if(self.entremove)
885                 self.entremove();
886
887         if(self.skeletonindex)
888         {
889                 skel_delete(self.skeletonindex);
890                 self.skeletonindex = 0;
891         }
892
893         if(self.snd_looping > 0)
894         {
895                 sound(self, self.snd_looping, "misc/null.wav", VOL_BASE, autocvar_g_jetpack_attenuation);
896                 self.snd_looping = 0;
897         }
898
899         self.enttype = 0;
900         self.classname = "";
901         self.draw = menu_sub_null;
902         self.entremove = menu_sub_null;
903         // TODO possibly set more stuff to defaults
904 }
905 // CSQC_Ent_Remove : Called when the server requests a SSQC / CSQC entity to be removed.  Essentially call remove(self) as well.
906 void CSQC_Ent_Remove()
907 {
908         if(autocvar_developer_csqcentities)
909                 printf("CSQC_Ent_Remove() with self=%i self.entnum=%d self.enttype=%d\n", self, self.entnum, self.enttype);
910
911         if(wasfreed(self))
912         {
913                 print("WARNING: CSQC_Ent_Remove called for already removed entity. Packet loss?\n");
914                 return;
915         }
916         if(self.enttype)
917                 Ent_Remove();
918         remove(self);
919 }
920
921 void Gamemode_Init()
922 {
923         if (!isdemo())
924         {
925                 if(!(calledhooks & HOOK_START))
926                         localcmd("\n_cl_hook_gamestart ", MapInfo_Type_ToString(gametype), "\n");
927                 calledhooks |= HOOK_START;
928         }
929 }
930 // 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.
931 void CSQC_Parse_StuffCmd(string strMessage)
932 {
933         if(autocvar_developer_csqcentities)
934                 printf("CSQC_Parse_StuffCmd(\"%s\")\n", strMessage);
935
936         localcmd(strMessage);
937 }
938 // 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.
939 void CSQC_Parse_Print(string strMessage)
940 {
941         if(autocvar_developer_csqcentities)
942                 printf("CSQC_Parse_Print(\"%s\")\n", strMessage);
943
944         print(ColorTranslateRGB(strMessage));
945 }
946
947 // CSQC_Parse_CenterPrint : Provides the centerprint_hud string in the first parameter that the server provided.
948 void CSQC_Parse_CenterPrint(string strMessage)
949 {
950         if(autocvar_developer_csqcentities)
951                 printf("CSQC_Parse_CenterPrint(\"%s\")\n", strMessage);
952
953         centerprint_hud(strMessage);
954 }
955
956 string notranslate_fogcmd1 = "\nfog ";
957 string notranslate_fogcmd2 = "\nr_fog_exp2 0\nr_drawfog 1\n";
958 void Fog_Force()
959 {
960         // TODO somehow thwart prvm_globalset client ...
961
962         if(autocvar_cl_orthoview && autocvar_cl_orthoview_nofog)
963                 { localcmd("\nr_drawfog 0\n"); }
964         else if(forcefog != "")
965                 { localcmd(strcat(notranslate_fogcmd1, forcefog, notranslate_fogcmd2)); }
966 }
967
968 void Gamemode_Init();
969 void Ent_ScoresInfo()
970 {
971     int i;
972         self.classname = "ent_client_scores_info";
973         gametype = ReadInt24_t();
974         HUD_ModIcons_SetFunc();
975         for(i = 0; i < MAX_SCORE; ++i)
976         {
977                 if(scores_label[i])
978                         strunzone(scores_label[i]);
979                 scores_label[i] = strzone(ReadString());
980                 scores_flags[i] = ReadByte();
981         }
982         for(i = 0; i < MAX_TEAMSCORE; ++i)
983         {
984                 if(teamscores_label[i])
985                         strunzone(teamscores_label[i]);
986                 teamscores_label[i] = strzone(ReadString());
987                 teamscores_flags[i] = ReadByte();
988         }
989         HUD_InitScores();
990         Gamemode_Init();
991 }
992
993 void Ent_Init()
994 {
995         self.classname = "ent_client_init";
996
997         nb_pb_period = ReadByte() / 32; //Accuracy of 1/32th
998
999         hook_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
1000         hook_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
1001         hook_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
1002         hook_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
1003         arc_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
1004         arc_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
1005         arc_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
1006         arc_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
1007
1008         if(forcefog)
1009                 strunzone(forcefog);
1010         forcefog = strzone(ReadString());
1011
1012         armorblockpercent = ReadByte() / 255.0;
1013
1014         g_balance_mortar_bouncefactor = ReadCoord();
1015         g_balance_mortar_bouncestop = ReadCoord();
1016         g_balance_electro_secondary_bouncefactor = ReadCoord();
1017         g_balance_electro_secondary_bouncestop = ReadCoord();
1018
1019         vortex_scope = !ReadByte();
1020         rifle_scope = !ReadByte();
1021
1022         serverflags = ReadByte();
1023
1024         minelayer_maxmines = ReadByte();
1025
1026         hagar_maxrockets = ReadByte();
1027
1028         g_trueaim_minrange = ReadCoord();
1029         g_balance_porto_secondary = ReadByte();
1030
1031         if(!postinit)
1032                 PostInit();
1033 }
1034
1035 void Net_ReadRace()
1036 {
1037         float b;
1038
1039         b = ReadByte();
1040
1041         switch(b)
1042         {
1043                 case RACE_NET_CHECKPOINT_HIT_QUALIFYING:
1044                         race_checkpoint = ReadByte();
1045                         race_time = ReadInt24_t();
1046                         race_previousbesttime = ReadInt24_t();
1047                         if(race_previousbestname)
1048                                 strunzone(race_previousbestname);
1049                         race_previousbestname = strzone(ColorTranslateRGB(ReadString()));
1050
1051                         race_checkpointtime = time;
1052
1053                         if(race_checkpoint == 0 || race_checkpoint == 254)
1054                         {
1055                                 race_penaltyaccumulator = 0;
1056                                 race_laptime = time; // valid
1057                         }
1058
1059                         break;
1060
1061                 case RACE_NET_CHECKPOINT_CLEAR:
1062                         race_laptime = 0;
1063                         race_checkpointtime = 0;
1064                         break;
1065
1066                 case RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING:
1067                         race_laptime = ReadCoord();
1068                         race_checkpointtime = -99999;
1069                         // fall through
1070                 case RACE_NET_CHECKPOINT_NEXT_QUALIFYING:
1071                         race_nextcheckpoint = ReadByte();
1072
1073                         race_nextbesttime = ReadInt24_t();
1074                         if(race_nextbestname)
1075                                 strunzone(race_nextbestname);
1076                         race_nextbestname = strzone(ColorTranslateRGB(ReadString()));
1077                         break;
1078
1079                 case RACE_NET_CHECKPOINT_HIT_RACE:
1080                         race_mycheckpoint = ReadByte();
1081                         race_mycheckpointtime = time;
1082                         race_mycheckpointdelta = ReadInt24_t();
1083                         race_mycheckpointlapsdelta = ReadByte();
1084                         if(race_mycheckpointlapsdelta >= 128)
1085                                 race_mycheckpointlapsdelta -= 256;
1086                         if(race_mycheckpointenemy)
1087                                 strunzone(race_mycheckpointenemy);
1088                         race_mycheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1089                         break;
1090
1091                 case RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT:
1092                         race_othercheckpoint = ReadByte();
1093                         race_othercheckpointtime = time;
1094                         race_othercheckpointdelta = ReadInt24_t();
1095                         race_othercheckpointlapsdelta = ReadByte();
1096                         if(race_othercheckpointlapsdelta >= 128)
1097                                 race_othercheckpointlapsdelta -= 256;
1098                         if(race_othercheckpointenemy)
1099                                 strunzone(race_othercheckpointenemy);
1100                         race_othercheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1101                         break;
1102
1103                 case RACE_NET_PENALTY_RACE:
1104                         race_penaltyeventtime = time;
1105                         race_penaltytime = ReadShort();
1106                         //race_penaltyaccumulator += race_penaltytime;
1107                         if(race_penaltyreason)
1108                                 strunzone(race_penaltyreason);
1109                         race_penaltyreason = strzone(ReadString());
1110                         break;
1111
1112                 case RACE_NET_PENALTY_QUALIFYING:
1113                         race_penaltyeventtime = time;
1114                         race_penaltytime = ReadShort();
1115                         race_penaltyaccumulator += race_penaltytime;
1116                         if(race_penaltyreason)
1117                                 strunzone(race_penaltyreason);
1118                         race_penaltyreason = strzone(ReadString());
1119                         break;
1120
1121                 case RACE_NET_SERVER_RECORD:
1122                         race_server_record = ReadInt24_t();
1123                         break;
1124                 case RACE_NET_SPEED_AWARD:
1125                         race_speedaward = ReadInt24_t();
1126                         if(race_speedaward_holder)
1127                                 strunzone(race_speedaward_holder);
1128                         race_speedaward_holder = strzone(ReadString());
1129                         break;
1130                 case RACE_NET_SPEED_AWARD_BEST:
1131                         race_speedaward_alltimebest = ReadInt24_t();
1132                         if(race_speedaward_alltimebest_holder)
1133                                 strunzone(race_speedaward_alltimebest_holder);
1134                         race_speedaward_alltimebest_holder = strzone(ReadString());
1135                         break;
1136                 case RACE_NET_SERVER_RANKINGS:
1137                         float prevpos, del;
1138             int pos = ReadShort();
1139                         prevpos = ReadShort();
1140                         del = ReadShort();
1141
1142                         // move other rankings out of the way
1143             int i;
1144                         if (prevpos) {
1145                                 for (i=prevpos-1;i>pos-1;--i) {
1146                                         grecordtime[i] = grecordtime[i-1];
1147                                         if(grecordholder[i])
1148                                                 strunzone(grecordholder[i]);
1149                                         grecordholder[i] = strzone(grecordholder[i-1]);
1150                                 }
1151                         } else if (del) { // a record has been deleted by the admin
1152                                 for (i=pos-1; i<= RANKINGS_CNT-1; ++i) {
1153                                         if (i == RANKINGS_CNT-1) { // clear out last record
1154                                                 grecordtime[i] = 0;
1155                                                 if (grecordholder[i])
1156                                                         strunzone(grecordholder[i]);
1157                                                 grecordholder[i] = string_null;
1158                                         }
1159                                         else {
1160                                                 grecordtime[i] = grecordtime[i+1];
1161                                                 if (grecordholder[i])
1162                                                         strunzone(grecordholder[i]);
1163                                                 grecordholder[i] = strzone(grecordholder[i+1]);
1164                                         }
1165                                 }
1166                         } else { // player has no ranked record yet
1167                                 for (i=RANKINGS_CNT-1;i>pos-1;--i) {
1168                                         grecordtime[i] = grecordtime[i-1];
1169                                         if(grecordholder[i])
1170                                                 strunzone(grecordholder[i]);
1171                                         grecordholder[i] = strzone(grecordholder[i-1]);
1172                                 }
1173                         }
1174
1175                         // store new ranking
1176                         if(grecordholder[pos-1] != "")
1177                                 strunzone(grecordholder[pos-1]);
1178                         grecordholder[pos-1] = strzone(ReadString());
1179                         grecordtime[pos-1] = ReadInt24_t();
1180                         if(grecordholder[pos-1] == GetPlayerName(player_localnum))
1181                                 race_myrank = pos;
1182                         break;
1183                 case RACE_NET_SERVER_STATUS:
1184                         race_status = ReadShort();
1185                         if(race_status_name)
1186                                 strunzone(race_status_name);
1187                         race_status_name = strzone(ReadString());
1188         }
1189 }
1190
1191 void Net_TeamNagger()
1192 {
1193         teamnagger = 1;
1194 }
1195
1196 void Net_ReadPingPLReport()
1197 {
1198         int e, pi, pl, ml;
1199         e = ReadByte();
1200         pi = ReadShort();
1201         pl = ReadByte();
1202         ml = ReadByte();
1203         if (!(playerslots[e]))
1204                 return;
1205         playerslots[e].ping = pi;
1206         playerslots[e].ping_packetloss = pl / 255.0;
1207         playerslots[e].ping_movementloss = ml / 255.0;
1208 }
1209
1210 void Net_WeaponComplain()
1211 {
1212         complain_weapon = ReadByte();
1213
1214         if(complain_weapon_name)
1215                 strunzone(complain_weapon_name);
1216         complain_weapon_name = strzone(WEP_NAME(complain_weapon));
1217
1218         complain_weapon_type = ReadByte();
1219
1220         complain_weapon_time = time;
1221         weapontime = time; // ping the weapon panel
1222
1223         switch(complain_weapon_type)
1224         {
1225                 case 0: Local_Notification(MSG_MULTI, ITEM_WEAPON_NOAMMO, complain_weapon); break;
1226                 case 1: Local_Notification(MSG_MULTI, ITEM_WEAPON_DONTHAVE, complain_weapon); break;
1227                 default: Local_Notification(MSG_MULTI, ITEM_WEAPON_UNAVAILABLE, complain_weapon); break;
1228         }
1229 }
1230
1231 // CSQC_Parse_TempEntity : Handles all temporary entity network data in the CSQC layer.
1232 // You must ALWAYS first acquire the temporary ID, which is sent as a byte.
1233 // Return value should be 1 if CSQC handled the temporary entity, otherwise return 0 to have the engine process the event.
1234 float CSQC_Parse_TempEntity()
1235 {
1236         float bHandled;
1237                 bHandled  = true;
1238         // Acquire TE ID
1239         float nTEID;
1240                 nTEID = ReadByte();
1241
1242         if(autocvar_developer_csqcentities)
1243                 printf("CSQC_Parse_TempEntity() with nTEID=%d\n", nTEID);
1244
1245                 // NOTE: Could just do return instead of break...
1246         switch(nTEID)
1247         {
1248                 case TE_CSQC_TARGET_MUSIC:
1249                         Net_TargetMusic();
1250                         bHandled = true;
1251                         break;
1252                 case TE_CSQC_PICTURE:
1253                         Net_MapVote_Picture();
1254                         bHandled = true;
1255                         break;
1256                 case TE_CSQC_RACE:
1257                         Net_ReadRace();
1258                         bHandled = true;
1259                         break;
1260                 case TE_CSQC_VORTEXBEAMPARTICLE:
1261                         Net_ReadVortexBeamParticle();
1262                         bHandled = true;
1263                         break;
1264                 case TE_CSQC_TEAMNAGGER:
1265                         Net_TeamNagger();
1266                         bHandled = true;
1267                         break;
1268                 case TE_CSQC_ARC:
1269                         Net_ReadArc();
1270                         bHandled = true;
1271                         break;
1272                 case TE_CSQC_PINGPLREPORT:
1273                         Net_ReadPingPLReport();
1274                         bHandled = true;
1275                         break;
1276                 case TE_CSQC_WEAPONCOMPLAIN:
1277                         Net_WeaponComplain();
1278                         bHandled = true;
1279                         break;
1280                 case TE_CSQC_VEHICLESETUP:
1281                         Net_VehicleSetup();
1282                         bHandled = true;
1283                         break;
1284                 case TE_CSQC_SVNOTICE:
1285                         cl_notice_read();
1286                         bHandled = true;
1287                         break;
1288                 case TE_CSQC_SHOCKWAVEPARTICLE:
1289                         Net_ReadShockwaveParticle();
1290                         bHandled = true;
1291                         break;
1292                 default:
1293                         // No special logic for this temporary entity; return 0 so the engine can handle it
1294                         bHandled = false;
1295                         break;
1296         }
1297
1298         return bHandled;
1299 }
1300
1301 string getcommandkey(string text, string command)
1302 {
1303         string keys;
1304         float n, j, k, l = 0;
1305
1306         if (!autocvar_hud_showbinds)
1307                 return text;
1308
1309         keys = db_get(binddb, command);
1310         if (keys == "")
1311         {
1312                 n = tokenize(findkeysforcommand(command, 0)); // uses '...' strings
1313                 for(j = 0; j < n; ++j)
1314                 {
1315                         k = stof(argv(j));
1316                         if(k != -1)
1317                         {
1318                                 if ("" == keys)
1319                                         keys = keynumtostring(k);
1320                                 else
1321                                         keys = strcat(keys, ", ", keynumtostring(k));
1322
1323                                 ++l;
1324                                 if (autocvar_hud_showbinds_limit > 0 && autocvar_hud_showbinds_limit <= l)
1325                                         break;
1326                         }
1327
1328                 }
1329                 if (keys == "")
1330                         keys = "NO_KEY";
1331                 db_put(binddb, command, keys);
1332         }
1333
1334         if (keys == "NO_KEY") {
1335                 if (autocvar_hud_showbinds > 1)
1336                         return sprintf(_("%s (not bound)"), text);
1337                 else
1338                         return text;
1339         }
1340         else if (autocvar_hud_showbinds > 1)
1341                 return sprintf("%s (%s)", text, keys);
1342         else
1343                 return keys;
1344 }