Merge branch 'master' into Mario/showspecs
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_client.qc
1 #include "waypointsprites.qh"
2
3 #include "cl_impulse.qh"
4 #include "cl_player.qh"
5 #include "ent_cs.qh"
6 #include "g_subs.qh"
7 #include "ipban.qh"
8 #include "miscfunctions.qh"
9 #include "portals.qh"
10 #include "teamplay.qh"
11 #include "playerdemo.qh"
12 #include "secret.qh"
13
14 #include "bot/bot.qh"
15 #include "bot/navigation.qh"
16
17 #include "weapons/hitplot.qh"
18 #include "weapons/weaponsystem.qh"
19
20 #include "../common/net_notice.qh"
21
22 #include "../common/monsters/sv_monsters.qh"
23
24 #include "../warpzonelib/server.qh"
25
26 float c1, c2, c3, c4;
27
28 void send_CSQC_teamnagger() {
29         WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
30         WriteByte(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
31 }
32
33 int CountSpectators(entity player, entity to)
34 {
35         if(!player) { return 0; } // not sure how, but best to be safe
36
37         entity head;
38         float spec_count = 0;
39         FOR_EACH_REALCLIENT(head)
40         {
41                 if(IS_SPEC(head))
42                 if(head != to)
43                 if(head.enemy == player)
44                         spec_count += 1;
45         }
46
47         return spec_count;
48 }
49
50 void WriteSpectators(entity player, entity to)
51 {
52         if(!player) { return; } // not sure how, but best to be safe
53
54         entity head;
55         FOR_EACH_REALCLIENT(head)
56         {
57                 if(IS_SPEC(head))
58                 if(head != to)
59                 if(head.enemy == player)
60                         WriteByte(MSG_ENTITY, num_for_edict(head));
61         }
62 }
63
64 bool ClientData_Send(entity to, int sf)
65 {
66         if(to != self.owner)
67         {
68                 error("wtf");
69                 return false;
70         }
71
72         entity e;
73
74         e = to;
75         if(IS_SPEC(to))
76                 e = to.enemy;
77
78         sf = 0;
79
80         if(e.race_completed)
81                 sf |= 1; // forced scoreboard
82         if(to.spectatee_status)
83                 sf |= 2; // spectator ent number follows
84         if(e.zoomstate)
85                 sf |= 4; // zoomed
86         if(e.porto_v_angle_held)
87                 sf |= 8; // angles held
88         // always check spectators
89         sf |= 16; // spectator handling?
90
91         WriteByte(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
92         WriteByte(MSG_ENTITY, sf);
93
94         if(sf & 2)
95                 WriteByte(MSG_ENTITY, to.spectatee_status);
96
97         if(sf & 8)
98         {
99                 WriteAngle(MSG_ENTITY, e.v_angle.x);
100                 WriteAngle(MSG_ENTITY, e.v_angle.y);
101         }
102
103         if(sf & 16)
104         {
105                 float specs = CountSpectators(e, to);
106                 WriteByte(MSG_ENTITY, specs);
107                 WriteSpectators(e, to);
108         }
109
110         return true;
111 }
112
113 void ClientData_Attach()
114 {
115         Net_LinkEntity(self.clientdata = spawn(), false, 0, ClientData_Send);
116         self.clientdata.drawonlytoclient = self;
117         self.clientdata.owner = self;
118 }
119
120 void ClientData_Detach()
121 {
122         remove(self.clientdata);
123         self.clientdata = world;
124 }
125
126 void ClientData_Touch(entity e)
127 {
128         e.clientdata.SendFlags = 1;
129
130         // make it spectatable
131         entity e2;
132         FOR_EACH_REALCLIENT(e2)
133         {
134                 if(e2 != e)
135                         if(IS_SPEC(e2))
136                                 if(e2.enemy == e)
137                                         e2.clientdata.SendFlags = 1;
138         }
139 }
140
141 .string netname_previous;
142
143 void SetSpectator(entity player, entity spectatee);
144
145
146 /*
147 =============
148 CheckPlayerModel
149
150 Checks if the argument string can be a valid playermodel.
151 Returns a valid one in doubt.
152 =============
153 */
154 string FallbackPlayerModel;
155 string CheckPlayerModel(string plyermodel) {
156         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
157         {
158                 // note: we cannot summon Don Strunzone here, some player may
159                 // still have the model string set. In case anyone manages how
160                 // to change a cvar default, we'll have a small leak here.
161                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
162         }
163         // only in right path
164         if( substring(plyermodel,0,14) != "models/player/")
165                 return FallbackPlayerModel;
166         // only good file extensions
167         if(substring(plyermodel,-4,4) != ".zym")
168         if(substring(plyermodel,-4,4) != ".dpm")
169         if(substring(plyermodel,-4,4) != ".iqm")
170         if(substring(plyermodel,-4,4) != ".md3")
171         if(substring(plyermodel,-4,4) != ".psk")
172                 return FallbackPlayerModel;
173         // forbid the LOD models
174         if(substring(plyermodel, -9,5) == "_lod1")
175                 return FallbackPlayerModel;
176         if(substring(plyermodel, -9,5) == "_lod2")
177                 return FallbackPlayerModel;
178         if(plyermodel != strtolower(plyermodel))
179                 return FallbackPlayerModel;
180         // also, restrict to server models
181         if(autocvar_sv_servermodelsonly)
182         {
183                 if(!fexists(plyermodel))
184                         return FallbackPlayerModel;
185         }
186         return plyermodel;
187 }
188
189 void setplayermodel(entity e, string modelname)
190 {
191         precache_model(modelname);
192         setmodel(e, modelname);
193         player_setupanimsformodel();
194         UpdatePlayerSounds();
195 }
196
197 /*
198 =============
199 PutObserverInServer
200
201 putting a client as observer in the server
202 =============
203 */
204 void FixPlayermodel();
205 void PutObserverInServer (void)
206 {
207         entity spot;
208
209         SetSpectator(self, world);
210
211     self.hud = HUD_NORMAL;
212
213         if(IS_PLAYER(self)) { pointparticles(particleeffectnum("spawn_event_neutral"), self.origin, '0 0 0', 1); }
214
215         spot = SelectSpawnPoint (true);
216         if(!spot)
217                 error("No spawnpoints for observers?!?\n");
218         RemoveGrapplingHook(self); // Wazat's Grappling Hook
219
220         if(IS_REAL_CLIENT(self))
221         {
222                 msg_entity = self;
223                 WriteByte(MSG_ONE, SVC_SETVIEW);
224                 WriteEntity(MSG_ONE, self);
225         }
226
227         self.frags = FRAGS_SPECTATOR;
228
229         MUTATOR_CALLHOOK(MakePlayerObserver);
230
231         Portal_ClearAll(self);
232
233         Unfreeze(self);
234
235         if(self.alivetime)
236         {
237                 if(!warmup_stage)
238                         PS_GR_P_ADDVAL(self, PLAYERSTATS_ALIVETIME, time - self.alivetime);
239                 self.alivetime = 0;
240         }
241
242         if(self.vehicle)
243                 vehicles_exit(VHEF_RELESE);
244
245         WaypointSprite_PlayerDead();
246
247         if (!g_ca)  // don't reset teams when moving a ca player to the spectators
248                 self.team = -1;  // move this as it is needed to log the player spectating in eventlog
249
250         if(self.killcount != -666)
251         {
252                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_SPECTATE, self.netname);
253                 if(autocvar_g_chat_nospectators == 1 || (cvar("g_warmup") && !(warmup_stage || gameover) && autocvar_g_chat_nospectators == 2))
254                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_CHAT_NOSPECTATORS);
255
256                 if(self.just_joined == false) {
257                         LogTeamchange(self.playerid, -1, 4);
258                 } else
259                         self.just_joined = false;
260         }
261
262         PlayerScore_Clear(self); // clear scores when needed
263
264         accuracy_resend(self);
265
266         self.spectatortime = time;
267
268         self.classname = "observer";
269         self.iscreature = false;
270         self.teleportable = TELEPORT_SIMPLE;
271         self.damagedbycontents = false;
272         self.health = -666;
273         self.takedamage = DAMAGE_NO;
274         self.solid = SOLID_NOT;
275         self.movetype = MOVETYPE_FLY_WORLDONLY; // user preference is controlled by playerprethink
276         self.flags = FL_CLIENT | FL_NOTARGET;
277         self.armorvalue = 666;
278         self.effects = 0;
279         self.armorvalue = autocvar_g_balance_armor_start;
280         self.pauserotarmor_finished = 0;
281         self.pauserothealth_finished = 0;
282         self.pauseregen_finished = 0;
283         self.damageforcescale = 0;
284         self.death_time = 0;
285         self.respawn_flags = 0;
286         self.respawn_time = 0;
287         self.stat_respawn_time = 0;
288         self.alpha = 0;
289         self.scale = 0;
290         self.fade_time = 0;
291         self.pain_frame = 0;
292         self.pain_finished = 0;
293         self.strength_finished = 0;
294         self.invincible_finished = 0;
295         self.superweapons_finished = 0;
296         self.pushltime = 0;
297         self.istypefrag = 0;
298         self.think = func_null;
299         self.nextthink = 0;
300         self.hook_time = 0;
301         self.deadflag = DEAD_NO;
302         self.angles = spot.angles;
303         self.angles_z = 0;
304         self.fixangle = true;
305         self.crouch = false;
306         self.revival_time = 0;
307
308         setorigin (self, (spot.origin + PL_VIEW_OFS)); // offset it so that the spectator spawns higher off the ground, looks better this way
309         self.prevorigin = self.origin;
310         self.items = 0;
311         self.weapons = '0 0 0';
312         self.model = "";
313         FixPlayermodel();
314         setmodel(self, "null");
315         self.drawonlytoclient = self;
316
317         setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX); // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
318         self.view_ofs = '0 0 0'; // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
319
320         self.weapon = 0;
321         self.weaponname = "";
322         self.switchingweapon = 0;
323         self.weaponmodel = "";
324         self.weaponentity = world;
325         self.exteriorweaponentity = world;
326         self.killcount = -666;
327         self.velocity = '0 0 0';
328         self.avelocity = '0 0 0';
329         self.punchangle = '0 0 0';
330         self.punchvector = '0 0 0';
331         self.oldvelocity = self.velocity;
332         self.fire_endtime = -1;
333         self.event_damage = func_null;
334 }
335
336 .float model_randomizer;
337 void FixPlayermodel()
338 {
339         string defaultmodel;
340         float defaultskin, chmdl, oldskin, n, i;
341         vector m1, m2;
342
343         defaultmodel = "";
344         defaultskin = 0;
345         chmdl = false;
346
347         if(autocvar_sv_defaultcharacter == 1)
348         {
349                 if(teamplay)
350                 {
351                         string s;
352                         s = Static_Team_ColorName_Lower(self.team);
353                         if(s != "neutral")
354                         {
355                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
356                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
357                         }
358                 }
359
360                 if(defaultmodel == "")
361                 {
362                         defaultmodel = autocvar_sv_defaultplayermodel;
363                         defaultskin = autocvar_sv_defaultplayerskin;
364                 }
365
366                 n = tokenize_console(defaultmodel);
367                 if(n > 0)
368                 {
369                         defaultmodel = argv(floor(n * self.model_randomizer));
370                         // However, do NOT randomize if the player-selected model is in the list.
371                         for (i = 0; i < n; ++i)
372                                 if ((argv(i) == self.playermodel && defaultskin == stof(self.playerskin)) || argv(i) == strcat(self.playermodel, ":", self.playerskin))
373                                         defaultmodel = argv(i);
374                 }
375
376                 i = strstrofs(defaultmodel, ":", 0);
377                 if(i >= 0)
378                 {
379                         defaultskin = stof(substring(defaultmodel, i+1, -1));
380                         defaultmodel = substring(defaultmodel, 0, i);
381                 }
382         }
383
384         if(defaultmodel != "")
385         {
386                 if (defaultmodel != self.model)
387                 {
388                         m1 = self.mins;
389                         m2 = self.maxs;
390                         setplayermodel (self, defaultmodel);
391                         setsize (self, m1, m2);
392                         chmdl = true;
393                 }
394
395                 oldskin = self.skin;
396                 self.skin = defaultskin;
397         } else {
398                 if (self.playermodel != self.model || self.playermodel == "")
399                 {
400                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
401                         m1 = self.mins;
402                         m2 = self.maxs;
403                         setplayermodel (self, self.playermodel);
404                         setsize (self, m1, m2);
405                         chmdl = true;
406                 }
407
408                 oldskin = self.skin;
409                 self.skin = stof(self.playerskin);
410         }
411
412         if(chmdl || oldskin != self.skin) // model or skin has changed
413         {
414                 self.species = player_getspecies(); // update species
415                 UpdatePlayerSounds(); // update skin sounds
416         }
417
418         if(!teamplay)
419                 if(strlen(autocvar_sv_defaultplayercolors))
420                         if(self.clientcolors != stof(autocvar_sv_defaultplayercolors))
421                                 setcolor(self, stof(autocvar_sv_defaultplayercolors));
422 }
423
424 /*
425 =============
426 PutClientInServer
427
428 Called when a client spawns in the server
429 =============
430 */
431 void PutClientInServer (void)
432 {
433         if(IS_BOT_CLIENT(self))
434                 self.classname = "player";
435         else if(IS_REAL_CLIENT(self))
436         {
437                 msg_entity = self;
438                 WriteByte(MSG_ONE, SVC_SETVIEW);
439                 WriteEntity(MSG_ONE, self);
440         }
441
442         SetSpectator(self, world);
443
444         // reset player keys
445         self.itemkeys = 0;
446
447         MUTATOR_CALLHOOK(PutClientInServer);
448
449         if(gameover)
450                 self.classname = "observer";
451
452         if(IS_PLAYER(self))
453         {
454                 entity spot, oldself;
455                 float j;
456
457                 accuracy_resend(self);
458
459                 if(self.team < 0)
460                         JoinBestTeam(self, false, true);
461
462                 spot = SelectSpawnPoint (false);
463                 if(!spot)
464                 {
465                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
466                         return; // spawn failed
467                 }
468
469                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
470
471                 if(self.vehicle)
472                         vehicles_exit(VHEF_RELESE);
473
474                 self.classname = "player";
475                 self.wasplayer = true;
476                 self.iscreature = true;
477                 self.teleportable = TELEPORT_NORMAL;
478                 self.damagedbycontents = true;
479                 self.movetype = MOVETYPE_WALK;
480                 self.solid = SOLID_SLIDEBOX;
481                 self.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
482                 if(autocvar_g_playerclip_collisions)
483                         self.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
484                 if(IS_BOT_CLIENT(self) && autocvar_g_botclip_collisions)
485                         self.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
486                 self.frags = FRAGS_PLAYER;
487                 if(INDEPENDENT_PLAYERS)
488                         MAKE_INDEPENDENT_PLAYER(self);
489                 self.flags = FL_CLIENT;
490                 if(autocvar__notarget)
491                         self.flags |= FL_NOTARGET;
492                 self.takedamage = DAMAGE_AIM;
493                 self.effects = 0;
494                 self.effects |= EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
495                 self.air_finished = time + 12;
496                 self.dmg = 2;
497                 if(WEP_CVAR(vortex, charge))
498                 {
499                         if(WEP_CVAR_SEC(vortex, chargepool))
500                                 self.vortex_chargepool_ammo = 1;
501                         self.vortex_charge = WEP_CVAR(vortex, charge_start);
502                 }
503
504                 if(warmup_stage)
505                 {
506                         self.ammo_shells = warmup_start_ammo_shells;
507                         self.ammo_nails = warmup_start_ammo_nails;
508                         self.ammo_rockets = warmup_start_ammo_rockets;
509                         self.ammo_cells = warmup_start_ammo_cells;
510                         self.ammo_plasma = warmup_start_ammo_plasma;
511                         self.ammo_fuel = warmup_start_ammo_fuel;
512                         self.health = warmup_start_health;
513                         self.armorvalue = warmup_start_armorvalue;
514                         self.weapons = WARMUP_START_WEAPONS;
515                 }
516                 else
517                 {
518                         self.ammo_shells = start_ammo_shells;
519                         self.ammo_nails = start_ammo_nails;
520                         self.ammo_rockets = start_ammo_rockets;
521                         self.ammo_cells = start_ammo_cells;
522                         self.ammo_plasma = start_ammo_plasma;
523                         self.ammo_fuel = start_ammo_fuel;
524                         self.health = start_health;
525                         self.armorvalue = start_armorvalue;
526                         self.weapons = start_weapons;
527                 }
528
529                 if(self.weapons & WEPSET_SUPERWEAPONS)
530                         self.superweapons_finished = time + autocvar_g_balance_superweapons_time;
531                 else
532                         self.superweapons_finished = 0;
533
534                 if(g_weaponarena_random) // WEAPONTODO: more stuff that should be in a mutator. also: rename those cvars
535                 {
536                         if(g_weaponarena_random_with_blaster)
537                                 self.weapons &= ~WEPSET_BLASTER;
538                         W_RandomWeapons(self, g_weaponarena_random);
539                         if(g_weaponarena_random_with_blaster)
540                                 self.weapons |= WEPSET_BLASTER;
541                 }
542
543                 self.items = start_items;
544
545                 self.spawnshieldtime = time + autocvar_g_spawnshieldtime;
546                 self.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
547                 self.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
548                 self.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
549                 self.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
550                 //extend the pause of rotting if client was reset at the beginning of the countdown
551                 if(!autocvar_sv_ready_restart_after_countdown && time < game_starttime) { // TODO why is this cvar NOTted?
552                         self.spawnshieldtime += game_starttime - time;
553                         self.pauserotarmor_finished += game_starttime - time;
554                         self.pauserothealth_finished += game_starttime - time;
555                         self.pauseregen_finished += game_starttime - time;
556                 }
557                 self.damageforcescale = 2;
558                 self.death_time = 0;
559                 self.respawn_flags = 0;
560                 self.respawn_time = 0;
561                 self.stat_respawn_time = 0;
562                 self.scale = 0;
563                 self.fade_time = 0;
564                 self.pain_frame = 0;
565                 self.pain_finished = 0;
566                 self.strength_finished = 0;
567                 self.invincible_finished = 0;
568                 self.pushltime = 0;
569                 // players have no think function
570                 self.think = func_null;
571                 self.nextthink = 0;
572                 self.hook_time = 0;
573                 self.dmg_team = 0;
574                 self.ballistics_density = autocvar_g_ballistics_density_player;
575
576                 self.metertime = 0;
577
578                 self.deadflag = DEAD_NO;
579
580                 self.angles = spot.angles;
581
582                 self.angles_z = 0; // never spawn tilted even if the spot says to
583                 if(IS_BOT_CLIENT(self))
584                         self.v_angle = self.angles;
585                 self.fixangle = true; // turn this way immediately
586                 self.velocity = '0 0 0';
587                 self.avelocity = '0 0 0';
588                 self.punchangle = '0 0 0';
589                 self.punchvector = '0 0 0';
590                 self.oldvelocity = self.velocity;
591                 self.fire_endtime = -1;
592                 self.revival_time = 0;
593
594                 entity spawnevent = spawn();
595                 spawnevent.owner = self;
596                 Net_LinkEntity(spawnevent, false, 0.5, SpawnEvent_Send);
597
598                 // Cut off any still running player sounds.
599                 stopsound(self, CH_PLAYER_SINGLE);
600
601                 self.model = "";
602                 FixPlayermodel();
603                 self.drawonlytoclient = world;
604
605                 self.crouch = false;
606                 self.view_ofs = PL_VIEW_OFS;
607                 setsize (self, PL_MIN, PL_MAX);
608                 self.spawnorigin = spot.origin;
609                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins.z - 24));
610                 // don't reset back to last position, even if new position is stuck in solid
611                 self.oldorigin = self.origin;
612                 self.prevorigin = self.origin;
613                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
614                 self.lastteleporttime = time; // prevent insane speeds due to changing origin
615         self.hud = HUD_NORMAL;
616
617                 self.event_damage = PlayerDamage;
618
619                 self.bot_attack = true;
620                 self.monster_attack = true;
621
622                 self.spider_slowness = 0;
623
624                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
625
626                 if(self.killcount == -666) {
627                         PlayerScore_Clear(self);
628                         self.killcount = 0;
629                 }
630
631                 CL_SpawnWeaponentity();
632                 self.alpha = default_player_alpha;
633                 self.colormod = '1 1 1' * autocvar_g_player_brightness;
634                 self.exteriorweaponentity.alpha = default_weapon_alpha;
635
636                 self.speedrunning = false;
637
638                 //stuffcmd(self, "chase_active 0");
639                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
640
641                 target_voicescript_clear(self);
642
643                 // reset fields the weapons may use
644                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
645                 {
646                         WEP_ACTION(j, WR_RESETPLAYER);
647
648                         // all weapons must be fully loaded when we spawn
649                         entity e = get_weaponinfo(j);
650                         if(e.spawnflags & WEP_FLAG_RELOADABLE) // prevent accessing undefined cvars
651                                 self.(weapon_load[j]) = e.reloading_ammo;
652                 }
653
654                 oldself = self;
655                 self = spot;
656                         activator = oldself;
657                                 string s;
658                                 s = self.target;
659                                 self.target = string_null;
660                                 SUB_UseTargets();
661                                 self.target = s;
662                         activator = world;
663                 self = oldself;
664
665                 Unfreeze(self);
666
667                 spawn_spot = spot;
668                 MUTATOR_CALLHOOK(PlayerSpawn);
669
670                 if(autocvar_spawn_debug)
671                 {
672                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
673                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
674                 }
675
676                 self.switchweapon = w_getbestweapon(self);
677                 self.cnt = -1; // W_LastWeapon will not complain
678                 self.weapon = 0;
679                 self.weaponname = "";
680                 self.switchingweapon = 0;
681
682                 if(!warmup_stage)
683                         if(!self.alivetime)
684                                 self.alivetime = time;
685
686                 antilag_clear(self);
687         }
688         else if(IS_OBSERVER(self))
689         {
690                 PutObserverInServer ();
691         }
692 }
693
694 .float ebouncefactor, ebouncestop; // electro's values
695 // TODO do we need all these fields, or should we stop autodetecting runtime
696 // changes and just have a console command to update this?
697 float ClientInit_SendEntity(entity to, float sf)
698 {
699         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
700         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
701         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[0]));
702         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[1]));
703         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[2]));
704         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[3]));
705         WriteInt24_t(MSG_ENTITY, compressShotOrigin(arc_shotorigin[0]));
706         WriteInt24_t(MSG_ENTITY, compressShotOrigin(arc_shotorigin[1]));
707         WriteInt24_t(MSG_ENTITY, compressShotOrigin(arc_shotorigin[2]));
708         WriteInt24_t(MSG_ENTITY, compressShotOrigin(arc_shotorigin[3]));
709
710         if(sv_foginterval && world.fog != "")
711                 WriteString(MSG_ENTITY, world.fog);
712         else
713                 WriteString(MSG_ENTITY, "");
714         WriteByte(MSG_ENTITY, self.count * 255.0); // g_balance_armor_blockpercent
715         WriteCoord(MSG_ENTITY, self.bouncefactor); // g_balance_mortar_bouncefactor // WEAPONTODO
716         WriteCoord(MSG_ENTITY, self.bouncestop); // g_balance_mortar_bouncestop
717         WriteCoord(MSG_ENTITY, self.ebouncefactor); // g_balance_mortar_bouncefactor
718         WriteCoord(MSG_ENTITY, self.ebouncestop); // g_balance_mortar_bouncestop
719         WriteByte(MSG_ENTITY, WEP_CVAR(vortex, secondary)); // client has to know if it should zoom or not // WEAPONTODO
720         WriteByte(MSG_ENTITY, WEP_CVAR(rifle, secondary)); // client has to know if it should zoom or not // WEAPONTODO
721         WriteByte(MSG_ENTITY, serverflags); // client has to know if it should zoom or not
722         WriteByte(MSG_ENTITY, WEP_CVAR(minelayer, limit)); // minelayer max mines // WEAPONTODO
723         WriteByte(MSG_ENTITY, WEP_CVAR_SEC(hagar, load_max)); // hagar max loadable rockets // WEAPONTODO
724         WriteCoord(MSG_ENTITY, autocvar_g_trueaim_minrange);
725         WriteByte(MSG_ENTITY, WEP_CVAR(porto, secondary)); // WEAPONTODO
726         return true;
727 }
728
729 void ClientInit_CheckUpdate()
730 {
731         self.nextthink = time;
732         if(self.count != autocvar_g_balance_armor_blockpercent)
733         {
734                 self.count = autocvar_g_balance_armor_blockpercent;
735                 self.SendFlags |= 1;
736         }
737         if(self.bouncefactor != autocvar_g_balance_mortar_bouncefactor) // WEAPONTODO
738         {
739                 self.bouncefactor = autocvar_g_balance_mortar_bouncefactor;
740                 self.SendFlags |= 1;
741         }
742         if(self.bouncestop != autocvar_g_balance_mortar_bouncestop)
743         {
744                 self.bouncestop = autocvar_g_balance_mortar_bouncestop;
745                 self.SendFlags |= 1;
746         }
747         if(self.ebouncefactor != autocvar_g_balance_electro_secondary_bouncefactor)
748         {
749                 self.ebouncefactor = autocvar_g_balance_electro_secondary_bouncefactor;
750                 self.SendFlags |= 1;
751         }
752         if(self.ebouncestop != autocvar_g_balance_electro_secondary_bouncestop)
753         {
754                 self.ebouncestop = autocvar_g_balance_electro_secondary_bouncestop;
755                 self.SendFlags |= 1;
756         }
757 }
758
759 void ClientInit_Spawn()
760 {
761         entity o;
762         entity e;
763         e = spawn();
764         e.classname = "clientinit";
765         e.think = ClientInit_CheckUpdate;
766         Net_LinkEntity(e, false, 0, ClientInit_SendEntity);
767
768         o = self;
769         self = e;
770         ClientInit_CheckUpdate();
771         self = o;
772 }
773
774 /*
775 =============
776 SetNewParms
777 =============
778 */
779 void SetNewParms (void)
780 {
781         // initialize parms for a new player
782         parm1 = -(86400 * 366);
783 }
784
785 /*
786 =============
787 SetChangeParms
788 =============
789 */
790 void SetChangeParms (void)
791 {
792         // save parms for level change
793         parm1 = self.parm_idlesince - time;
794 }
795
796 /*
797 =============
798 DecodeLevelParms
799 =============
800 */
801 void DecodeLevelParms (void)
802 {
803         // load parms
804         self.parm_idlesince = parm1;
805         if(self.parm_idlesince == -(86400 * 366))
806                 self.parm_idlesince = time;
807
808         // whatever happens, allow 60 seconds of idling directly after connect for map loading
809         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
810 }
811
812 /*
813 =============
814 ClientKill
815
816 Called when a client types 'kill' in the console
817 =============
818 */
819
820 .float clientkill_nexttime;
821 void ClientKill_Now_TeamChange()
822 {
823         if(self.killindicator_teamchange == -1)
824         {
825                 JoinBestTeam( self, false, true );
826         }
827         else if(self.killindicator_teamchange == -2)
828         {
829                 if(blockSpectators)
830                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
831                 PutObserverInServer();
832         }
833         else
834                 SV_ChangeTeam(self.killindicator_teamchange - 1);
835         self.killindicator_teamchange = 0;
836 }
837
838 void ClientKill_Now()
839 {
840         if(self.vehicle)
841         {
842             vehicles_exit(VHEF_RELESE);
843             if(!self.killindicator_teamchange)
844             {
845             self.vehicle_health = -1;
846             Damage(self, self, self, 1 , DEATH_KILL, self.origin, '0 0 0');
847             }
848         }
849
850         if(self.killindicator && !wasfreed(self.killindicator))
851                 remove(self.killindicator);
852
853         self.killindicator = world;
854
855         if(self.killindicator_teamchange)
856                 ClientKill_Now_TeamChange();
857
858         if(IS_PLAYER(self))
859                 Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
860
861         // now I am sure the player IS dead
862 }
863 void KillIndicator_Think()
864 {
865         if (gameover)
866         {
867                 self.owner.killindicator = world;
868                 remove(self);
869                 return;
870         }
871
872         if (self.owner.alpha < 0 && !self.owner.vehicle)
873         {
874                 self.owner.killindicator = world;
875                 remove(self);
876                 return;
877         }
878
879         if(self.cnt <= 0)
880         {
881                 self = self.owner;
882                 ClientKill_Now(); // no oldself needed
883                 return;
884         }
885     else if(g_cts && self.health == 1) // health == 1 means that it's silent
886     {
887         self.nextthink = time + 1;
888         self.cnt -= 1;
889     }
890         else
891         {
892                 if(self.cnt <= 10)
893                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
894                 if(IS_REAL_CLIENT(self.owner))
895                 {
896                         if(self.cnt <= 10)
897                                 { Send_Notification(NOTIF_ONE, self.owner, MSG_ANNCE, Announcer_PickNumber(CNT_KILL, self.cnt)); }
898                 }
899                 self.nextthink = time + 1;
900                 self.cnt -= 1;
901         }
902 }
903
904 float clientkilltime;
905 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto, -2 = spec
906 {
907         float killtime;
908         float starttime;
909         entity e;
910
911         if (gameover)
912                 return;
913
914         killtime = autocvar_g_balance_kill_delay;
915
916         if(g_race_qualifying || g_cts)
917                 killtime = 0;
918
919     if(g_cts && self.killindicator && self.killindicator.health == 1) // self.killindicator.health == 1 means that the kill indicator was spawned by CTS_ClientKill
920     {
921                 remove(self.killindicator);
922                 self.killindicator = world;
923
924         ClientKill_Now(); // allow instant kill in this case
925         return;
926     }
927
928         self.killindicator_teamchange = targetteam;
929
930     if(!self.killindicator)
931         {
932                 if(self.deadflag == DEAD_NO)
933                 {
934                         killtime = max(killtime, self.clientkill_nexttime - time);
935                         self.clientkill_nexttime = time + killtime + autocvar_g_balance_kill_antispam;
936                 }
937
938                 if(killtime <= 0 || !IS_PLAYER(self) || self.deadflag != DEAD_NO)
939                 {
940                         ClientKill_Now();
941                 }
942                 else
943                 {
944                         starttime = max(time, clientkilltime);
945
946                         self.killindicator = spawn();
947                         self.killindicator.owner = self;
948                         self.killindicator.scale = 0.5;
949                         setattachment(self.killindicator, self, "");
950                         setorigin(self.killindicator, '0 0 52');
951                         self.killindicator.think = KillIndicator_Think;
952                         self.killindicator.nextthink = starttime + (self.lip) * 0.05;
953                         clientkilltime = max(clientkilltime, self.killindicator.nextthink + 0.05);
954                         self.killindicator.cnt = ceil(killtime);
955                         self.killindicator.count = bound(0, ceil(killtime), 10);
956                         //sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
957
958                         for(e = world; (e = find(e, classname, "body")) != world; )
959                         {
960                                 if(e.enemy != self)
961                                         continue;
962                                 e.killindicator = spawn();
963                                 e.killindicator.owner = e;
964                                 e.killindicator.scale = 0.5;
965                                 setattachment(e.killindicator, e, "");
966                                 setorigin(e.killindicator, '0 0 52');
967                                 e.killindicator.think = KillIndicator_Think;
968                                 e.killindicator.nextthink = starttime + (e.lip) * 0.05;
969                                 clientkilltime = max(clientkilltime, e.killindicator.nextthink + 0.05);
970                                 e.killindicator.cnt = ceil(killtime);
971                         }
972                         self.lip = 0;
973                 }
974         }
975         if(self.killindicator)
976         {
977                 if(targetteam == 0) // just die
978                 {
979                         self.killindicator.colormod = '0 0 0';
980                         if(IS_REAL_CLIENT(self))
981                         if(self.killindicator.cnt > 0)
982                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SUICIDE, self.killindicator.cnt);
983                 }
984                 else if(targetteam == -1) // auto
985                 {
986                         self.killindicator.colormod = '0 1 0';
987                         if(IS_REAL_CLIENT(self))
988                         if(self.killindicator.cnt > 0)
989                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_AUTO, self.killindicator.cnt);
990                 }
991                 else if(targetteam == -2) // spectate
992                 {
993                         self.killindicator.colormod = '0.5 0.5 0.5';
994                         if(IS_REAL_CLIENT(self))
995                         if(self.killindicator.cnt > 0)
996                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SPECTATE, self.killindicator.cnt);
997                 }
998                 else
999                 {
1000                         self.killindicator.colormod = Team_ColorRGB(targetteam);
1001                         if(IS_REAL_CLIENT(self))
1002                         if(self.killindicator.cnt > 0)
1003                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, APP_TEAM_NUM_4(targetteam, CENTER_TEAMCHANGE_), self.killindicator.cnt);
1004                 }
1005         }
1006
1007 }
1008
1009 void ClientKill (void)
1010 {
1011         if(gameover) return;
1012         if(self.player_blocked) return;
1013         if(self.frozen) return;
1014
1015         ClientKill_TeamChange(0);
1016 }
1017
1018 void CTS_ClientKill (entity e) // silent version of ClientKill, used when player finishes a CTS run. Useful to prevent cheating by running back to the start line and starting out with more speed
1019 {
1020     e.killindicator = spawn();
1021     e.killindicator.owner = e;
1022     e.killindicator.think = KillIndicator_Think;
1023     e.killindicator.nextthink = time + (e.lip) * 0.05;
1024     e.killindicator.cnt = ceil(autocvar_g_cts_finish_kill_delay);
1025     e.killindicator.health = 1; // this is used to indicate that it should be silent
1026     e.lip = 0;
1027 }
1028
1029 void FixClientCvars(entity e)
1030 {
1031         // send prediction settings to the client
1032         stuffcmd(e, "\nin_bindmap 0 0\n");
1033         if(g_race || g_cts)
1034                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1035         if(autocvar_g_antilag == 3) // client side hitscan
1036                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
1037         if(autocvar_sv_gentle)
1038                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
1039 }
1040
1041 float PlayerInIDList(entity p, string idlist)
1042 {
1043         float n, i;
1044         string s;
1045
1046         // NOTE: we do NOT check crypto_idfp_signed here, an unsigned ID is fine too for this
1047         if (!p.crypto_idfp)
1048                 return 0;
1049
1050         // this function allows abbreviated player IDs too!
1051         n = tokenize_console(idlist);
1052         for(i = 0; i < n; ++i)
1053         {
1054                 s = argv(i);
1055                 if(s == substring(p.crypto_idfp, 0, strlen(s)))
1056                         return 1;
1057         }
1058
1059         return 0;
1060 }
1061
1062 #ifdef DP_EXT_PRECONNECT
1063 /*
1064 =============
1065 ClientPreConnect
1066
1067 Called once (not at each match start) when a client begins a connection to the server
1068 =============
1069 */
1070 void ClientPreConnect (void)
1071 {
1072         if(autocvar_sv_eventlog)
1073         {
1074                 GameLogEcho(sprintf(":connect:%d:%d:%s",
1075                         self.playerid,
1076                         num_for_edict(self),
1077                         ((IS_REAL_CLIENT(self)) ? self.netaddress : "bot")
1078                 ));
1079         }
1080 }
1081 #endif
1082
1083 /*
1084 =============
1085 ClientConnect
1086
1087 Called when a client connects to the server
1088 =============
1089 */
1090 void DecodeLevelParms (void);
1091 //void dom_player_join_team(entity pl);
1092 void set_dom_state(entity e);
1093 void ClientConnect (void)
1094 {
1095         float t;
1096
1097         if(IS_CLIENT(self))
1098         {
1099                 print("Warning: ClientConnect, but already connected!\n");
1100                 return;
1101         }
1102
1103         if(Ban_MaybeEnforceBanOnce(self))
1104                 return;
1105
1106         DecodeLevelParms();
1107
1108 #ifdef WATERMARK
1109         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_WATERMARK, WATERMARK);
1110 #endif
1111
1112         self.classname = "player_joining";
1113
1114         self.flags = FL_CLIENT;
1115         self.version_nagtime = time + 10 + random() * 10;
1116
1117         if(player_count<0)
1118         {
1119                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1120                 player_count = 0;
1121         }
1122
1123         if(IS_REAL_CLIENT(self)) { PlayerStats_PlayerBasic_CheckUpdate(self); }
1124
1125         PlayerScore_Attach(self);
1126         ClientData_Attach();
1127         accuracy_init(self);
1128
1129         bot_clientconnect();
1130
1131         playerdemo_init();
1132
1133         anticheat_init();
1134
1135         // identify the right forced team
1136         if(autocvar_g_campaign)
1137         {
1138                 if(IS_REAL_CLIENT(self)) // only players, not bots
1139                 {
1140                         switch(autocvar_g_campaign_forceteam)
1141                         {
1142                                 case 1: self.team_forced = NUM_TEAM_1; break;
1143                                 case 2: self.team_forced = NUM_TEAM_2; break;
1144                                 case 3: self.team_forced = NUM_TEAM_3; break;
1145                                 case 4: self.team_forced = NUM_TEAM_4; break;
1146                                 default: self.team_forced = 0;
1147                         }
1148                 }
1149         }
1150         else if(PlayerInIDList(self, autocvar_g_forced_team_red))
1151                 self.team_forced = NUM_TEAM_1;
1152         else if(PlayerInIDList(self, autocvar_g_forced_team_blue))
1153                 self.team_forced = NUM_TEAM_2;
1154         else if(PlayerInIDList(self, autocvar_g_forced_team_yellow))
1155                 self.team_forced = NUM_TEAM_3;
1156         else if(PlayerInIDList(self, autocvar_g_forced_team_pink))
1157                 self.team_forced = NUM_TEAM_4;
1158         else if(autocvar_g_forced_team_otherwise == "red")
1159                 self.team_forced = NUM_TEAM_1;
1160         else if(autocvar_g_forced_team_otherwise == "blue")
1161                 self.team_forced = NUM_TEAM_2;
1162         else if(autocvar_g_forced_team_otherwise == "yellow")
1163                 self.team_forced = NUM_TEAM_3;
1164         else if(autocvar_g_forced_team_otherwise == "pink")
1165                 self.team_forced = NUM_TEAM_4;
1166         else if(autocvar_g_forced_team_otherwise == "spectate")
1167                 self.team_forced = -1;
1168         else if(autocvar_g_forced_team_otherwise == "spectator")
1169                 self.team_forced = -1;
1170         else
1171                 self.team_forced = 0;
1172
1173         if(!teamplay)
1174                 if(self.team_forced > 0)
1175                         self.team_forced = 0;
1176
1177         JoinBestTeam(self, false, false); // if the team number is valid, keep it
1178
1179         if((autocvar_sv_spectate == 1) || autocvar_g_campaign || self.team_forced < 0) {
1180                 self.classname = "observer";
1181         } else {
1182                 if(teamplay)
1183                 {
1184                         if(autocvar_g_balance_teams)
1185                         {
1186                                 self.classname = "player";
1187                                 campaign_bots_may_start = 1;
1188                         }
1189                         else
1190                         {
1191                                 self.classname = "observer"; // do it anyway
1192                         }
1193                 }
1194                 else
1195                 {
1196                         self.classname = "player";
1197                         campaign_bots_may_start = 1;
1198                 }
1199         }
1200
1201         self.playerid = (playerid_last = playerid_last + 1);
1202
1203         PlayerStats_GameReport_AddEvent(sprintf("kills-%d", self.playerid));
1204
1205     if(IS_BOT_CLIENT(self))
1206         PlayerStats_GameReport_AddPlayer(self);
1207
1208         if(autocvar_sv_eventlog)
1209                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((IS_REAL_CLIENT(self)) ? self.netaddress : "bot"), ":", self.netname));
1210
1211         LogTeamchange(self.playerid, self.team, 1);
1212
1213         self.just_joined = true;  // stop spamming the eventlog with additional lines when the client connects
1214
1215         self.netname_previous = strzone(self.netname);
1216
1217         if(IS_PLAYER(self) && teamplay)
1218                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(self, INFO_JOIN_CONNECT_TEAM_), self.netname);
1219         else
1220                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_CONNECT, self.netname);
1221
1222         stuffcmd(self, strcat(clientstuff, "\n"));
1223         stuffcmd(self, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1224
1225         FixClientCvars(self);
1226
1227         // spawnfunc_waypoint sprites
1228         WaypointSprite_InitClient(self);
1229
1230         // Wazat's grappling hook
1231         SetGrappleHookBindings();
1232
1233         // Jetpack binds
1234         stuffcmd(self, "alias +jetpack +button10\n");
1235         stuffcmd(self, "alias -jetpack -button10\n");
1236
1237         // get version info from player
1238         stuffcmd(self, "cmd clientversion $gameversion\n");
1239
1240         // get other cvars from player
1241         GetCvars(0);
1242
1243         // notify about available teams
1244         if(teamplay)
1245         {
1246                 CheckAllowedTeams(self);
1247                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1248                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1249         }
1250         else
1251                 stuffcmd(self, "set _teams_available 0\n");
1252
1253         attach_entcs();
1254
1255         bot_relinkplayerlist();
1256
1257         self.spectatortime = time;
1258         if(blockSpectators)
1259         {
1260                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1261         }
1262
1263         self.jointime = time;
1264         self.allowed_timeouts = autocvar_sv_timeout_number;
1265
1266         if(IS_REAL_CLIENT(self))
1267         {
1268                 if(!autocvar_g_campaign)
1269                 {
1270                         self.motd_actived_time = -1;
1271                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
1272                 }
1273
1274                 if(autocvar_g_bugrigs || (g_weaponarena_weapons == WEPSET_TUBA))
1275                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1276         }
1277
1278         if(!sv_foginterval && world.fog != "")
1279                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1280
1281         W_HitPlotOpen(self);
1282
1283         if(autocvar_sv_teamnagger && !(autocvar_bot_vs_human && (c3==-1 && c4==-1)) && !g_ca && !g_cts && !g_race) // teamnagger is currently bad for ca, race & cts
1284                 send_CSQC_teamnagger();
1285
1286         CheatInitClient();
1287
1288         CSQCMODEL_AUTOINIT();
1289
1290         self.model_randomizer = random();
1291
1292         if(IS_REAL_CLIENT(self))
1293                 sv_notice_join();
1294
1295         for (entity e = world; (e = findfloat(e, init_for_player_needed, 1)); ) {
1296                 entity oldself = self;
1297                 self = e;
1298                 e.init_for_player(oldself);
1299                 self = oldself;
1300         }
1301
1302         MUTATOR_CALLHOOK(ClientConnect);
1303 }
1304 /*
1305 =============
1306 ClientDisconnect
1307
1308 Called when a client disconnects from the server
1309 =============
1310 */
1311 .entity chatbubbleentity;
1312 void ReadyCount();
1313 void ClientDisconnect (void)
1314 {
1315         if(self.vehicle)
1316             vehicles_exit(VHEF_RELESE);
1317
1318         if (!IS_CLIENT(self))
1319         {
1320                 print("Warning: ClientDisconnect without ClientConnect\n");
1321                 return;
1322         }
1323
1324         PlayerStats_GameReport_FinalizePlayer(self);
1325
1326         SetSpectator(self, world);
1327
1328         if(IS_PLAYER(self)) { pointparticles(particleeffectnum("spawn_event_neutral"), self.origin, '0 0 0', 1); }
1329
1330         CheatShutdownClient();
1331
1332         W_HitPlotClose(self);
1333
1334         anticheat_report();
1335         anticheat_shutdown();
1336
1337         playerdemo_shutdown();
1338
1339         bot_clientdisconnect();
1340
1341         if(self.entcs)
1342                 detach_entcs();
1343
1344         if(autocvar_sv_eventlog)
1345                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1346
1347         Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_DISCONNECT, self.netname);
1348
1349         MUTATOR_CALLHOOK(ClientDisconnect);
1350
1351         Portal_ClearAll(self);
1352
1353         Unfreeze(self);
1354
1355         RemoveGrapplingHook(self);
1356
1357         // Here, everything has been done that requires this player to be a client.
1358
1359         self.flags &= ~FL_CLIENT;
1360
1361         if (self.chatbubbleentity)
1362                 remove (self.chatbubbleentity);
1363
1364         if (self.killindicator)
1365                 remove (self.killindicator);
1366
1367         WaypointSprite_PlayerGone();
1368
1369         bot_relinkplayerlist();
1370
1371         accuracy_free(self);
1372         ClientData_Detach();
1373         PlayerScore_Detach(self);
1374
1375         if(self.netname_previous)
1376                 strunzone(self.netname_previous);
1377         if(self.clientstatus)
1378                 strunzone(self.clientstatus);
1379         if(self.weaponorder_byimpulse)
1380                 strunzone(self.weaponorder_byimpulse);
1381
1382         ClearPlayerSounds();
1383
1384         if(self.personal)
1385                 remove(self.personal);
1386
1387         self.playerid = 0;
1388         ReadyCount();
1389
1390         // free cvars
1391         GetCvars(-1);
1392 }
1393
1394 .float BUTTON_CHAT;
1395 void ChatBubbleThink()
1396 {
1397         self.nextthink = time;
1398         if ((self.owner.alpha < 0) || self.owner.chatbubbleentity != self)
1399         {
1400                 if(self.owner) // but why can that ever be world?
1401                         self.owner.chatbubbleentity = world;
1402                 remove(self);
1403                 return;
1404         }
1405         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1406 #ifdef TETRIS
1407                 || self.owner.tetris_on
1408 #endif
1409         )
1410                 self.model = self.mdl;
1411         else
1412                 self.model = "";
1413 }
1414
1415 void UpdateChatBubble()
1416 {
1417         if (self.alpha < 0)
1418                 return;
1419         // spawn a chatbubble entity if needed
1420         if (!self.chatbubbleentity)
1421         {
1422                 self.chatbubbleentity = spawn();
1423                 self.chatbubbleentity.owner = self;
1424                 self.chatbubbleentity.exteriormodeltoclient = self;
1425                 self.chatbubbleentity.think = ChatBubbleThink;
1426                 self.chatbubbleentity.nextthink = time;
1427                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1428                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1429                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs.z * '0 0 1');
1430                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1431                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1432                 self.chatbubbleentity.model = "";
1433                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1434         }
1435 }
1436
1437
1438 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1439 // added to the model skins
1440 /*void UpdateColorModHack()
1441 {
1442         float c;
1443         c = self.clientcolors & 15;
1444         // LordHavoc: only bothering to support white, green, red, yellow, blue
1445              if (!teamplay) self.colormod = '0 0 0';
1446         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1447         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1448         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1449         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1450         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1451         else self.colormod = '1 1 1';
1452 }*/
1453
1454 void respawn(void)
1455 {
1456         if(self.alpha >= 0 && autocvar_g_respawn_ghosts)
1457         {
1458                 self.solid = SOLID_NOT;
1459                 self.takedamage = DAMAGE_NO;
1460                 self.movetype = MOVETYPE_FLY;
1461                 self.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1462                 self.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1463                 self.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1464                 pointparticles(particleeffectnum("respawn_ghost"), self.origin, '0 0 0', 1);
1465                 if(autocvar_g_respawn_ghosts_maxtime)
1466                         SUB_SetFade (self, time + autocvar_g_respawn_ghosts_maxtime / 2 + random () * (autocvar_g_respawn_ghosts_maxtime - autocvar_g_respawn_ghosts_maxtime / 2), 1.5);
1467         }
1468
1469         CopyBody(1);
1470
1471         self.effects |= EF_NODRAW; // prevent another CopyBody
1472         PutClientInServer();
1473 }
1474
1475 void play_countdown(float finished, string samp)
1476 {
1477         if(IS_REAL_CLIENT(self))
1478                 if(floor(finished - time - frametime) != floor(finished - time))
1479                         if(finished - time < 6)
1480                                 sound (self, CH_INFO, samp, VOL_BASE, ATTEN_NORM);
1481 }
1482
1483 void player_powerups (void)
1484 {
1485         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1486         olditems = self.items;
1487
1488         if((self.items & IT_USING_JETPACK) && !self.deadflag && !gameover)
1489                 self.modelflags |= MF_ROCKET;
1490         else
1491                 self.modelflags &= ~MF_ROCKET;
1492
1493         self.effects &= ~(EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1494
1495         if((self.alpha < 0 || self.deadflag) && !self.vehicle) // don't apply the flags if the player is gibbed
1496                 return;
1497
1498         Fire_ApplyDamage(self);
1499         Fire_ApplyEffect(self);
1500
1501         if (!g_instagib)
1502         {
1503                 if (self.items & IT_STRENGTH)
1504                 {
1505                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1506                         self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1507                         if (time > self.strength_finished)
1508                         {
1509                                 self.items = self.items - (self.items & IT_STRENGTH);
1510                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_STRENGTH, self.netname);
1511                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_STRENGTH);
1512                         }
1513                 }
1514                 else
1515                 {
1516                         if (time < self.strength_finished)
1517                         {
1518                                 self.items = self.items | IT_STRENGTH;
1519                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_STRENGTH, self.netname);
1520                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_STRENGTH);
1521                         }
1522                 }
1523                 if (self.items & IT_INVINCIBLE)
1524                 {
1525                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1526                         self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1527                         if (time > self.invincible_finished)
1528                         {
1529                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1530                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_SHIELD, self.netname);
1531                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_SHIELD);
1532                         }
1533                 }
1534                 else
1535                 {
1536                         if (time < self.invincible_finished)
1537                         {
1538                                 self.items = self.items | IT_INVINCIBLE;
1539                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_SHIELD, self.netname);
1540                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_SHIELD);
1541                         }
1542                 }
1543                 if (self.items & IT_SUPERWEAPON)
1544                 {
1545                         if (!(self.weapons & WEPSET_SUPERWEAPONS))
1546                         {
1547                                 self.superweapons_finished = 0;
1548                                 self.items = self.items - (self.items & IT_SUPERWEAPON);
1549                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_LOST, self.netname);
1550                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1551                         }
1552                         else if (self.items & IT_UNLIMITED_SUPERWEAPONS)
1553                         {
1554                                 // don't let them run out
1555                         }
1556                         else
1557                         {
1558                                 play_countdown(self.superweapons_finished, "misc/poweroff.wav");
1559                                 if (time > self.superweapons_finished)
1560                                 {
1561                                         self.items = self.items - (self.items & IT_SUPERWEAPON);
1562                                         self.weapons &= ~WEPSET_SUPERWEAPONS;
1563                                         //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_BROKEN, self.netname);
1564                                         Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1565                                 }
1566                         }
1567                 }
1568                 else if(self.weapons & WEPSET_SUPERWEAPONS)
1569                 {
1570                         if (time < self.superweapons_finished || (self.items & IT_UNLIMITED_SUPERWEAPONS))
1571                         {
1572                                 self.items = self.items | IT_SUPERWEAPON;
1573                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_PICKUP, self.netname);
1574                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1575                         }
1576                         else
1577                         {
1578                                 self.superweapons_finished = 0;
1579                                 self.weapons &= ~WEPSET_SUPERWEAPONS;
1580                         }
1581                 }
1582                 else
1583                 {
1584                         self.superweapons_finished = 0;
1585                 }
1586         }
1587
1588         if(autocvar_g_nodepthtestplayers)
1589                 self.effects = self.effects | EF_NODEPTHTEST;
1590
1591         if(autocvar_g_fullbrightplayers)
1592                 self.effects = self.effects | EF_FULLBRIGHT;
1593
1594         if (time >= game_starttime)
1595         if (time < self.spawnshieldtime)
1596                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1597
1598         MUTATOR_CALLHOOK(PlayerPowerups);
1599 }
1600
1601 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1602 {
1603         if(current > stable)
1604                 return current;
1605         else if(current > stable - 0.25) // when close enough, "snap"
1606                 return stable;
1607         else
1608                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1609 }
1610
1611 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1612 {
1613         if(current < stable)
1614                 return current;
1615         else if(current < stable + 0.25) // when close enough, "snap"
1616                 return stable;
1617         else
1618                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1619 }
1620
1621 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1622 {
1623         if(current > rotstable)
1624         {
1625                 if(rotframetime > 0)
1626                 {
1627                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1628                         current = max(rotstable, current - rotlinear * rotframetime);
1629                 }
1630         }
1631         else if(current < regenstable)
1632         {
1633                 if(regenframetime > 0)
1634                 {
1635                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1636                         current = min(regenstable, current + regenlinear * regenframetime);
1637                 }
1638         }
1639
1640         if(current > limit)
1641                 current = limit;
1642
1643         return current;
1644 }
1645
1646 void player_regen (void)
1647 {
1648         float max_mod, regen_mod, rot_mod, limit_mod;
1649         max_mod = regen_mod = rot_mod = limit_mod = 1;
1650         regen_mod_max = max_mod;
1651         regen_mod_regen = regen_mod;
1652         regen_mod_rot = rot_mod;
1653         regen_mod_limit = limit_mod;
1654         if(!MUTATOR_CALLHOOK(PlayerRegen))
1655         if(!self.frozen)
1656         {
1657                 float minh, mina, maxh, maxa, limith, limita;
1658                 maxh = autocvar_g_balance_health_rotstable;
1659                 maxa = autocvar_g_balance_armor_rotstable;
1660                 minh = autocvar_g_balance_health_regenstable;
1661                 mina = autocvar_g_balance_armor_regenstable;
1662                 limith = autocvar_g_balance_health_limit;
1663                 limita = autocvar_g_balance_armor_limit;
1664
1665                 max_mod = regen_mod_max;
1666                 regen_mod = regen_mod_regen;
1667                 rot_mod = regen_mod_rot;
1668                 limit_mod = regen_mod_limit;
1669
1670                 maxh = maxh * max_mod;
1671                 minh = minh * max_mod;
1672                 limith = limith * limit_mod;
1673                 limita = limita * limit_mod;
1674
1675                 self.armorvalue = CalcRotRegen(self.armorvalue, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rot_mod * frametime * (time > self.pauserotarmor_finished), limita);
1676                 self.health = CalcRotRegen(self.health, minh, autocvar_g_balance_health_regen, autocvar_g_balance_health_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxh, autocvar_g_balance_health_rot, autocvar_g_balance_health_rotlinear, rot_mod * frametime * (time > self.pauserothealth_finished), limith);
1677         }
1678
1679         // if player rotted to death...  die!
1680         // check this outside above checks, as player may still be able to rot to death
1681         if(self.health < 1)
1682                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1683
1684         if (!(self.items & IT_UNLIMITED_WEAPON_AMMO))
1685         {
1686                 float minf, maxf, limitf;
1687
1688                 maxf = autocvar_g_balance_fuel_rotstable;
1689                 minf = autocvar_g_balance_fuel_regenstable;
1690                 limitf = autocvar_g_balance_fuel_limit;
1691
1692                 self.ammo_fuel = CalcRotRegen(self.ammo_fuel, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, frametime * (time > self.pauseregen_finished) * ((self.items & IT_FUEL_REGEN) != 0), maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, frametime * (time > self.pauserotfuel_finished), limitf);
1693         }
1694 }
1695
1696 float zoomstate_set;
1697 void SetZoomState(float z)
1698 {
1699         if(z != self.zoomstate)
1700         {
1701                 self.zoomstate = z;
1702                 ClientData_Touch(self);
1703         }
1704         zoomstate_set = 1;
1705 }
1706
1707 void GetPressedKeys(void) {
1708         MUTATOR_CALLHOOK(GetPressedKeys);
1709         if (self.movement.x > 0) // get if movement keys are pressed
1710         {       // forward key pressed
1711                 self.pressedkeys |= KEY_FORWARD;
1712                 self.pressedkeys &= ~KEY_BACKWARD;
1713         }
1714         else if (self.movement.x < 0)
1715         {       // backward key pressed
1716                 self.pressedkeys |= KEY_BACKWARD;
1717                 self.pressedkeys &= ~KEY_FORWARD;
1718         }
1719         else
1720         {       // no x input
1721                 self.pressedkeys &= ~KEY_FORWARD;
1722                 self.pressedkeys &= ~KEY_BACKWARD;
1723         }
1724
1725         if (self.movement.y > 0)
1726         {       // right key pressed
1727                 self.pressedkeys |= KEY_RIGHT;
1728                 self.pressedkeys &= ~KEY_LEFT;
1729         }
1730         else if (self.movement.y < 0)
1731         {       // left key pressed
1732                 self.pressedkeys |= KEY_LEFT;
1733                 self.pressedkeys &= ~KEY_RIGHT;
1734         }
1735         else
1736         {       // no y input
1737                 self.pressedkeys &= ~KEY_RIGHT;
1738                 self.pressedkeys &= ~KEY_LEFT;
1739         }
1740
1741         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
1742                 self.pressedkeys |= KEY_JUMP;
1743         else
1744                 self.pressedkeys &= ~KEY_JUMP;
1745         if (self.BUTTON_CROUCH)
1746                 self.pressedkeys |= KEY_CROUCH;
1747         else
1748                 self.pressedkeys &= ~KEY_CROUCH;
1749
1750         if (self.BUTTON_ATCK)
1751                 self.pressedkeys |= KEY_ATCK;
1752         else
1753                 self.pressedkeys &= ~KEY_ATCK;
1754         if (self.BUTTON_ATCK2)
1755                 self.pressedkeys |= KEY_ATCK2;
1756         else
1757                 self.pressedkeys &= ~KEY_ATCK2;
1758 }
1759
1760 /*
1761 ======================
1762 spectate mode routines
1763 ======================
1764 */
1765
1766 void SpectateCopy(entity spectatee) {
1767         other = spectatee;
1768         MUTATOR_CALLHOOK(SpectateCopy);
1769         self.armortype = spectatee.armortype;
1770         self.armorvalue = spectatee.armorvalue;
1771         self.ammo_cells = spectatee.ammo_cells;
1772         self.ammo_plasma = spectatee.ammo_plasma;
1773         self.ammo_shells = spectatee.ammo_shells;
1774         self.ammo_nails = spectatee.ammo_nails;
1775         self.ammo_rockets = spectatee.ammo_rockets;
1776         self.ammo_fuel = spectatee.ammo_fuel;
1777         self.clip_load = spectatee.clip_load;
1778         self.clip_size = spectatee.clip_size;
1779         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
1780         self.health = spectatee.health;
1781         self.impulse = 0;
1782         self.items = spectatee.items;
1783         self.last_pickup = spectatee.last_pickup;
1784         self.hit_time = spectatee.hit_time;
1785         self.metertime = spectatee.metertime;
1786         self.strength_finished = spectatee.strength_finished;
1787         self.invincible_finished = spectatee.invincible_finished;
1788         self.pressedkeys = spectatee.pressedkeys;
1789         self.weapons = spectatee.weapons;
1790         self.switchweapon = spectatee.switchweapon;
1791         self.switchingweapon = spectatee.switchingweapon;
1792         self.weapon = spectatee.weapon;
1793         self.vortex_charge = spectatee.vortex_charge;
1794         self.vortex_chargepool_ammo = spectatee.vortex_chargepool_ammo;
1795         self.hagar_load = spectatee.hagar_load;
1796         self.arc_heat_percent = spectatee.arc_heat_percent;
1797         self.minelayer_mines = spectatee.minelayer_mines;
1798         self.punchangle = spectatee.punchangle;
1799         self.view_ofs = spectatee.view_ofs;
1800         self.velocity = spectatee.velocity;
1801         self.dmg_take = spectatee.dmg_take;
1802         self.dmg_save = spectatee.dmg_save;
1803         self.dmg_inflictor = spectatee.dmg_inflictor;
1804         self.v_angle = spectatee.v_angle;
1805         self.angles = spectatee.v_angle;
1806         self.frozen = spectatee.frozen;
1807         self.revive_progress = spectatee.revive_progress;
1808         if(!self.BUTTON_USE)
1809                 self.fixangle = true;
1810         setorigin(self, spectatee.origin);
1811         setsize(self, spectatee.mins, spectatee.maxs);
1812         SetZoomState(spectatee.zoomstate);
1813
1814     anticheat_spectatecopy(spectatee);
1815         self.hud = spectatee.hud;
1816         if(spectatee.vehicle)
1817     {
1818         self.fixangle = false;
1819         //self.velocity = spectatee.vehicle.velocity;
1820         self.vehicle_health = spectatee.vehicle_health;
1821         self.vehicle_shield = spectatee.vehicle_shield;
1822         self.vehicle_energy = spectatee.vehicle_energy;
1823         self.vehicle_ammo1 = spectatee.vehicle_ammo1;
1824         self.vehicle_ammo2 = spectatee.vehicle_ammo2;
1825         self.vehicle_reload1 = spectatee.vehicle_reload1;
1826         self.vehicle_reload2 = spectatee.vehicle_reload2;
1827
1828         msg_entity = self;
1829
1830         WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
1831             WriteAngle(MSG_ONE,  spectatee.v_angle.x);
1832             WriteAngle(MSG_ONE,  spectatee.v_angle.y);
1833             WriteAngle(MSG_ONE,  spectatee.v_angle.z);
1834
1835         //WriteByte (MSG_ONE, SVC_SETVIEW);
1836         //    WriteEntity(MSG_ONE, self);
1837         //makevectors(spectatee.v_angle);
1838         //setorigin(self, spectatee.origin - v_forward * 400 + v_up * 300);*/
1839     }
1840 }
1841
1842 float SpectateUpdate()
1843 {
1844         if(!self.enemy)
1845             return 0;
1846
1847         if(!IS_PLAYER(self.enemy) || self == self.enemy)
1848         {
1849                 SetSpectator(self, world);
1850                 return 0;
1851         }
1852
1853         SpectateCopy(self.enemy);
1854
1855         return 1;
1856 }
1857
1858 float SpectateSet()
1859 {
1860         if(!IS_PLAYER(self.enemy))
1861                 return false;
1862
1863         ClientData_Touch(self.enemy);
1864
1865         msg_entity = self;
1866         WriteByte(MSG_ONE, SVC_SETVIEW);
1867         WriteEntity(MSG_ONE, self.enemy);
1868         //stuffcmd(self, "set viewsize $tmpviewsize \n");
1869         self.movetype = MOVETYPE_NONE;
1870         accuracy_resend(self);
1871
1872         if(!SpectateUpdate())
1873                 PutObserverInServer();
1874
1875         return true;
1876 }
1877
1878 void SetSpectator(entity player, entity spectatee)
1879 {
1880         entity old_spectatee = player.enemy;
1881
1882         player.enemy = spectatee;
1883
1884         // WEAPONTODO
1885         // these are required to fix the spectator bug with arc
1886         if(old_spectatee && old_spectatee.arc_beam) { old_spectatee.arc_beam.SendFlags |= ARC_SF_SETTINGS; }
1887         if(player.enemy && player.enemy.arc_beam) { player.enemy.arc_beam.SendFlags |= ARC_SF_SETTINGS; }
1888
1889         // needed to update spectator list
1890         if(old_spectatee) { ClientData_Touch(old_spectatee); }
1891 }
1892
1893 float Spectate(entity pl)
1894 {
1895         if(g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer)
1896         if(DIFF_TEAM(pl, self))
1897                 return 0;
1898
1899         SetSpectator(self, pl);
1900         return SpectateSet();
1901 }
1902
1903 // Returns next available player to spectate if g_ca_spectate_enemies == 0
1904 entity CA_SpectateNext(entity start)
1905 {
1906         if(SAME_TEAM(start, self)) { return start; }
1907
1908         other = start;
1909         // continue from current player
1910         while(other && DIFF_TEAM(other, self))
1911                 other = find(other, classname, "player");
1912
1913         if (!other)
1914         {
1915                 // restart from begining
1916                 other = find(other, classname, "player");
1917                 while(other && DIFF_TEAM(other, self))
1918                         other = find(other, classname, "player");
1919         }
1920
1921         return other;
1922 }
1923
1924 float SpectateNext()
1925 {
1926         other = find(self.enemy, classname, "player");
1927
1928         if (g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer)
1929         {
1930                 // CA and ca players when spectating enemies is forbidden
1931                 other = CA_SpectateNext(other);
1932         }
1933         else
1934         {
1935                 // other modes and ca spectators or spectating enemies is allowed
1936                 if (!other)
1937                         other = find(other, classname, "player");
1938         }
1939
1940         if(other) { SetSpectator(self, other); }
1941
1942         return SpectateSet();
1943 }
1944
1945 float SpectatePrev()
1946 {
1947         // NOTE: chain order is from the highest to the lower entnum (unlike find)
1948         other = findchain(classname, "player");
1949         if (!other) // no player
1950                 return false;
1951
1952         entity first = other;
1953         // skip players until current spectated player
1954         if(self.enemy)
1955         while(other && other != self.enemy)
1956                 other = other.chain;
1957
1958         if (g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer)
1959         {
1960                 do { other = other.chain; }
1961                 while(other && other.team != self.team);
1962
1963                 if (!other)
1964                 {
1965                         other = first;
1966                         while(other.team != self.team)
1967                                 other = other.chain;
1968                         if(other == self.enemy)
1969                                 return true;
1970                 }
1971         }
1972         else
1973         {
1974                 if(other.chain)
1975                         other = other.chain;
1976                 else
1977                         other = first;
1978         }
1979         SetSpectator(self, other);
1980         return SpectateSet();
1981 }
1982
1983 /*
1984 =============
1985 ShowRespawnCountdown()
1986
1987 Update a respawn countdown display.
1988 =============
1989 */
1990 void ShowRespawnCountdown()
1991 {
1992         float number;
1993         if(self.deadflag == DEAD_NO) // just respawned?
1994                 return;
1995         else
1996         {
1997                 number = ceil(self.respawn_time - time);
1998                 if(number <= 0)
1999                         return;
2000                 if(number <= self.respawn_countdown)
2001                 {
2002                         self.respawn_countdown = number - 1;
2003                         if(ceil(self.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
2004                                 { Send_Notification(NOTIF_ONE, self, MSG_ANNCE, Announcer_PickNumber(CNT_RESPAWN, number)); }
2005                 }
2006         }
2007 }
2008
2009 void LeaveSpectatorMode()
2010 {
2011         if(self.caplayer)
2012                 return;
2013         if(nJoinAllowed(self))
2014         {
2015                 if(!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || (self.wasplayer && autocvar_g_changeteam_banned) || self.team_forced > 0)
2016                 {
2017                         self.classname = "player";
2018                         nades_RemoveBonus(self);
2019
2020                         SetSpectator(self, world);
2021
2022                         if(autocvar_g_campaign || autocvar_g_balance_teams)
2023                                 { JoinBestTeam(self, false, true); }
2024
2025                         if(autocvar_g_campaign)
2026                                 { campaign_bots_may_start = 1; }
2027
2028                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_PREVENT_JOIN);
2029
2030                         PutClientInServer();
2031
2032                         if(IS_PLAYER(self)) { Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_PLAY, self.netname); }
2033                 }
2034                 else
2035                         stuffcmd(self, "menu_showteamselect\n");
2036         }
2037         else
2038         {
2039                 // Player may not join because g_maxplayers is set
2040                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_JOIN_PREVENT);
2041         }
2042 }
2043
2044 /**
2045  * Determines whether the player is allowed to join. This depends on cvar
2046  * g_maxplayers, if it isn't used this function always return true, otherwise
2047  * it checks whether the number of currently playing players exceeds g_maxplayers.
2048  * @return int number of free slots for players, 0 if none
2049  */
2050 float nJoinAllowed(entity ignore) {
2051         if(!ignore)
2052         // this is called that way when checking if anyone may be able to join (to build qcstatus)
2053         // so report 0 free slots if restricted
2054         {
2055                 if(autocvar_g_forced_team_otherwise == "spectate")
2056                         return 0;
2057                 if(autocvar_g_forced_team_otherwise == "spectator")
2058                         return 0;
2059         }
2060
2061         if(self.team_forced < 0)
2062                 return 0; // forced spectators can never join
2063
2064         // TODO simplify this
2065         entity e;
2066         float totalClients = 0;
2067         FOR_EACH_CLIENT(e)
2068                 if(e != ignore)
2069                         totalClients += 1;
2070
2071         if (!autocvar_g_maxplayers)
2072                 return maxclients - totalClients;
2073
2074         float currentlyPlaying = 0;
2075         FOR_EACH_REALCLIENT(e)
2076                 if(IS_PLAYER(e) || e.caplayer)
2077                         currentlyPlaying += 1;
2078
2079         if(currentlyPlaying < autocvar_g_maxplayers)
2080                 return min(maxclients - totalClients, autocvar_g_maxplayers - currentlyPlaying);
2081
2082         return 0;
2083 }
2084
2085 /**
2086  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2087  * g_maxplayers_spectator_blocktime seconds
2088  */
2089 void checkSpectatorBlock() {
2090         if(IS_SPEC(self) || IS_OBSERVER(self))
2091         if(!self.caplayer)
2092         if(IS_REAL_CLIENT(self))
2093         {
2094                 if( time > (self.spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
2095                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
2096                         dropclient(self);
2097                 }
2098         }
2099 }
2100
2101 void PrintWelcomeMessage()
2102 {
2103         if(self.motd_actived_time == 0)
2104         {
2105                 if (autocvar_g_campaign) {
2106                         if ((IS_PLAYER(self) && self.BUTTON_INFO) || (!IS_PLAYER(self))) {
2107                                 self.motd_actived_time = time;
2108                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, campaign_message);
2109                         }
2110                 } else {
2111                         if (self.BUTTON_INFO) {
2112                                 self.motd_actived_time = time;
2113                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
2114                         }
2115                 }
2116         }
2117         else if(self.motd_actived_time > 0) // showing MOTD or campaign message
2118         {
2119                 if (autocvar_g_campaign) {
2120                         if (self.BUTTON_INFO)
2121                                 self.motd_actived_time = time;
2122                         else if ((time - self.motd_actived_time > 2) && IS_PLAYER(self)) { // hide it some seconds after BUTTON_INFO has been released
2123                                 self.motd_actived_time = 0;
2124                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2125                         }
2126                 } else {
2127                         if (self.BUTTON_INFO)
2128                                 self.motd_actived_time = time;
2129                         else if (time - self.motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2130                                 self.motd_actived_time = 0;
2131                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2132                         }
2133                 }
2134         }
2135         else //if(self.motd_actived_time < 0) // just connected, motd is active
2136         {
2137                 if(self.BUTTON_INFO) // BUTTON_INFO hides initial MOTD
2138                         self.motd_actived_time = -2; // wait until BUTTON_INFO gets released
2139                 else if(self.motd_actived_time == -2 || IS_PLAYER(self))
2140                 {
2141                         // instanctly hide MOTD
2142                         self.motd_actived_time = 0;
2143                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2144                 }
2145         }
2146 }
2147
2148 void ObserverThink()
2149 {
2150         float prefered_movetype;
2151         if (self.flags & FL_JUMPRELEASED) {
2152                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2153                         self.flags &= ~FL_JUMPRELEASED;
2154                         self.flags |= FL_SPAWNING;
2155                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2156                         self.flags &= ~FL_JUMPRELEASED;
2157                         if(SpectateNext()) {
2158                                 self.classname = "spectator";
2159                         }
2160                 } else {
2161                         prefered_movetype = ((!self.BUTTON_USE ? self.cvar_cl_clippedspectating : !self.cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2162                         if (self.movetype != prefered_movetype)
2163                                 self.movetype = prefered_movetype;
2164                 }
2165         } else {
2166                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2167                         self.flags |= FL_JUMPRELEASED;
2168                         if(self.flags & FL_SPAWNING)
2169                         {
2170                                 self.flags &= ~FL_SPAWNING;
2171                                 LeaveSpectatorMode();
2172                                 return;
2173                         }
2174                 }
2175         }
2176 }
2177
2178 void SpectatorThink()
2179 {
2180         if (self.flags & FL_JUMPRELEASED) {
2181                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2182                         self.flags &= ~FL_JUMPRELEASED;
2183                         self.flags |= FL_SPAWNING;
2184                 } else if(self.BUTTON_ATCK || self.impulse == 10 || self.impulse == 15 || self.impulse == 18 || (self.impulse >= 200 && self.impulse <= 209)) {
2185                         self.flags &= ~FL_JUMPRELEASED;
2186                         if(SpectateNext()) {
2187                                 self.classname = "spectator";
2188                         } else {
2189                                 self.classname = "observer";
2190                                 PutClientInServer();
2191                         }
2192                         self.impulse = 0;
2193                 } else if(self.impulse == 12 || self.impulse == 16  || self.impulse == 19 || (self.impulse >= 220 && self.impulse <= 229)) {
2194                         self.flags &= ~FL_JUMPRELEASED;
2195                         if(SpectatePrev()) {
2196                                 self.classname = "spectator";
2197                         } else {
2198                                 self.classname = "observer";
2199                                 PutClientInServer();
2200                         }
2201                         self.impulse = 0;
2202                 } else if (self.BUTTON_ATCK2) {
2203                         self.flags &= ~FL_JUMPRELEASED;
2204                         self.classname = "observer";
2205                         PutClientInServer();
2206                 } else {
2207                         if(!SpectateUpdate())
2208                                 PutObserverInServer();
2209                 }
2210         } else {
2211                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2212                         self.flags |= FL_JUMPRELEASED;
2213                         if(self.flags & FL_SPAWNING)
2214                         {
2215                                 self.flags &= ~FL_SPAWNING;
2216                                 LeaveSpectatorMode();
2217                                 return;
2218                         }
2219                 }
2220                 if(!SpectateUpdate())
2221                         PutObserverInServer();
2222         }
2223
2224         self.flags |= FL_CLIENT | FL_NOTARGET;
2225 }
2226
2227 void PlayerUseKey()
2228 {
2229         if (!IS_PLAYER(self))
2230                 return;
2231
2232         if(self.vehicle)
2233         {
2234         vehicles_exit(VHEF_NORMAL);
2235         return;
2236         }
2237
2238         // a use key was pressed; call handlers
2239         MUTATOR_CALLHOOK(PlayerUseKey);
2240 }
2241
2242 float isInvisibleString(string s)
2243 {
2244         float i, n, c;
2245         s = strdecolorize(s);
2246         for((i = 0), (n = strlen(s)); i < n; ++i)
2247         {
2248                 c = str2chr(s, i);
2249                 switch(c)
2250                 {
2251                         case 0:
2252                         case 32: // space
2253                                 break;
2254                         case 192: // charmap space
2255                                 if (!autocvar_utf8_enable)
2256                                         break;
2257                                 return false;
2258                         case 160: // space in unicode fonts
2259                         case 0xE000 + 192: // utf8 charmap space
2260                                 if (autocvar_utf8_enable)
2261                                         break;
2262                         default:
2263                                 return false;
2264                 }
2265         }
2266         return true;
2267 }
2268
2269 /*
2270 =============
2271 PlayerPreThink
2272
2273 Called every frame for each client before the physics are run
2274 =============
2275 */
2276 .float usekeypressed;
2277 void() nexball_setstatus;
2278 .int items_added;
2279 void PlayerPreThink (void)
2280 {
2281         WarpZone_PlayerPhysics_FixVAngle();
2282
2283         self.stat_game_starttime = game_starttime;
2284         self.stat_round_starttime = round_starttime;
2285         self.stat_allow_oldvortexbeam = autocvar_g_allow_oldvortexbeam;
2286         self.stat_leadlimit = autocvar_leadlimit;
2287
2288         if(frametime)
2289         {
2290                 // physics frames: update anticheat stuff
2291                 anticheat_prethink();
2292         }
2293
2294         if(blockSpectators && frametime)
2295                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2296                 checkSpectatorBlock();
2297
2298         zoomstate_set = 0;
2299
2300         // Savage: Check for nameless players
2301         if (isInvisibleString(self.netname)) {
2302                 string new_name = strzone(strcat("Player@", ftos(self.playerid)));
2303                 if(autocvar_sv_eventlog)
2304                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", new_name));
2305                 if(self.netname_previous)
2306                         strunzone(self.netname_previous);
2307                 self.netname_previous = strzone(new_name);
2308                 self.netname = self.netname_previous;
2309                 // stuffcmd(self, strcat("name ", self.netname, "\n"));
2310         } else if(self.netname_previous != self.netname) {
2311                 if(autocvar_sv_eventlog)
2312                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2313                 if(self.netname_previous)
2314                         strunzone(self.netname_previous);
2315                 self.netname_previous = strzone(self.netname);
2316         }
2317
2318         // version nagging
2319         if(self.version_nagtime)
2320                 if(self.cvar_g_xonoticversion)
2321                         if(time > self.version_nagtime)
2322                         {
2323                                 // don't notify git users
2324                                 if(strstr(self.cvar_g_xonoticversion, "git", 0) < 0 && strstr(self.cvar_g_xonoticversion, "autobuild", 0) < 0)
2325                                 {
2326                                         if(strstr(autocvar_g_xonoticversion, "git", 0) >= 0 || strstr(autocvar_g_xonoticversion, "autobuild", 0) >= 0)
2327                                         {
2328                                                 // notify release users if connecting to git
2329                                                 dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, " (beta)^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2330                                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2331                                         }
2332                                         else
2333                                         {
2334                                                 float r;
2335                                                 r = vercmp(self.cvar_g_xonoticversion, autocvar_g_xonoticversion);
2336                                                 if(r < 0)
2337                                                 {
2338                                                         // give users new version
2339                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - ^3Xonotic ", autocvar_g_xonoticversion, "^7 is out, and you still have ^3Xonotic ", self.cvar_g_xonoticversion, "^1 - get the update from ^4http://www.xonotic.org/^1!\n");
2340                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2341                                                 }
2342                                                 else if(r > 0)
2343                                                 {
2344                                                         // notify users about old server version
2345                                                         print("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, "^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2346                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2347                                                 }
2348                                         }
2349                                 }
2350                                 self.version_nagtime = 0;
2351                         }
2352
2353         // GOD MODE info
2354         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2355         {
2356                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_GODMODE_OFF, self.max_armorvalue);
2357                 self.max_armorvalue = 0;
2358         }
2359
2360 #ifdef TETRIS
2361         if (TetrisPreFrame())
2362                 return;
2363 #endif
2364
2365         if(self.frozen == 2)
2366         {
2367                 self.revive_progress = bound(0, self.revive_progress + frametime * self.revive_speed, 1);
2368                 self.health = max(1, self.revive_progress * start_health);
2369                 self.iceblock.alpha = bound(0.2, 1 - self.revive_progress, 1);
2370
2371                 if(self.revive_progress >= 1)
2372                         Unfreeze(self);
2373         }
2374         else if(self.frozen == 3)
2375         {
2376                 self.revive_progress = bound(0, self.revive_progress - frametime * self.revive_speed, 1);
2377                 self.health = max(0, autocvar_g_nades_ice_health + (start_health-autocvar_g_nades_ice_health) * self.revive_progress );
2378
2379                 if(self.health < 1)
2380                 {
2381                         if(self.vehicle)
2382                                 vehicles_exit(VHEF_RELESE);
2383                         self.event_damage(self, self.frozen_by, 1, DEATH_NADE_ICE_FREEZE, self.origin, '0 0 0');
2384                 }
2385                 else if ( self.revive_progress <= 0 )
2386                         Unfreeze(self);
2387         }
2388
2389         MUTATOR_CALLHOOK(PlayerPreThink);
2390
2391         if(!self.cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2392         {
2393                 if(self.BUTTON_USE && !self.usekeypressed)
2394                         PlayerUseKey();
2395                 self.usekeypressed = self.BUTTON_USE;
2396         }
2397
2398         if(IS_REAL_CLIENT(self))
2399                 PrintWelcomeMessage();
2400
2401         if(IS_PLAYER(self))
2402         {
2403
2404                 CheckRules_Player();
2405
2406                 if (intermission_running)
2407                 {
2408                         IntermissionThink ();   // otherwise a button could be missed between
2409                         return;                                 // the think tics
2410                 }
2411
2412                 //don't allow the player to turn around while game is paused!
2413                 if(timeout_status == TIMEOUT_ACTIVE) {
2414                         // FIXME turn this into CSQC stuff
2415                         self.v_angle = self.lastV_angle;
2416                         self.angles = self.lastV_angle;
2417                         self.fixangle = true;
2418                 }
2419
2420                 if(frametime)
2421                 {
2422                         if(self.weapon == WEP_VORTEX && WEP_CVAR(vortex, charge))
2423                         {
2424                                 self.weaponentity_glowmod_x = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_half * min(1, self.vortex_charge / WEP_CVAR(vortex, charge_animlimit));
2425                                 self.weaponentity_glowmod_y = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_half * min(1, self.vortex_charge / WEP_CVAR(vortex, charge_animlimit));
2426                                 self.weaponentity_glowmod_z = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_half * min(1, self.vortex_charge / WEP_CVAR(vortex, charge_animlimit));
2427
2428                                 if(self.vortex_charge > WEP_CVAR(vortex, charge_animlimit))
2429                                 {
2430                                         self.weaponentity_glowmod_x = self.weaponentity_glowmod.x + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_full * (self.vortex_charge - WEP_CVAR(vortex, charge_animlimit)) / (1 - WEP_CVAR(vortex, charge_animlimit));
2431                                         self.weaponentity_glowmod_y = self.weaponentity_glowmod.y + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_full * (self.vortex_charge - WEP_CVAR(vortex, charge_animlimit)) / (1 - WEP_CVAR(vortex, charge_animlimit));
2432                                         self.weaponentity_glowmod_z = self.weaponentity_glowmod.z + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_full * (self.vortex_charge - WEP_CVAR(vortex, charge_animlimit)) / (1 - WEP_CVAR(vortex, charge_animlimit));
2433                                 }
2434                         }
2435                         else
2436                                 self.weaponentity_glowmod = colormapPaletteColor(self.clientcolors & 0x0F, true) * 2;
2437
2438                         player_powerups();
2439                 }
2440
2441                 if (self.deadflag != DEAD_NO)
2442                 {
2443                         if(self.personal && g_race_qualifying)
2444                         {
2445                                 if(time > self.respawn_time)
2446                                 {
2447                                         self.respawn_time = time + 1; // only retry once a second
2448                                         self.stat_respawn_time = self.respawn_time;
2449                                         respawn();
2450                                         self.impulse = 141;
2451                                 }
2452                         }
2453                         else
2454                         {
2455                                 float button_pressed;
2456                                 if(frametime)
2457                                         player_anim();
2458                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2459
2460                                 if (self.deadflag == DEAD_DYING)
2461                                 {
2462                                         if((self.respawn_flags & RESPAWN_FORCE) && !autocvar_g_respawn_delay_max)
2463                                                 self.deadflag = DEAD_RESPAWNING;
2464                                         else if(!button_pressed)
2465                                                 self.deadflag = DEAD_DEAD;
2466                                 }
2467                                 else if (self.deadflag == DEAD_DEAD)
2468                                 {
2469                                         if(button_pressed)
2470                                                 self.deadflag = DEAD_RESPAWNABLE;
2471                                         else if(time >= self.respawn_time_max && (self.respawn_flags & RESPAWN_FORCE))
2472                                                 self.deadflag = DEAD_RESPAWNING;
2473                                 }
2474                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2475                                 {
2476                                         if(!button_pressed)
2477                                                 self.deadflag = DEAD_RESPAWNING;
2478                                 }
2479                                 else if (self.deadflag == DEAD_RESPAWNING)
2480                                 {
2481                                         if(time > self.respawn_time)
2482                                         {
2483                                                 self.respawn_time = time + 1; // only retry once a second
2484                                                 self.respawn_time_max = self.respawn_time;
2485                                                 respawn();
2486                                         }
2487                                 }
2488
2489                                 ShowRespawnCountdown();
2490
2491                                 if(self.respawn_flags & RESPAWN_SILENT)
2492                                         self.stat_respawn_time = 0;
2493                                 else if((self.respawn_flags & RESPAWN_FORCE) && autocvar_g_respawn_delay_max)
2494                                         self.stat_respawn_time = self.respawn_time_max;
2495                                 else
2496                                         self.stat_respawn_time = self.respawn_time;
2497                         }
2498
2499                         // if respawning, invert stat_respawn_time to indicate this, the client translates it
2500                         if(self.deadflag == DEAD_RESPAWNING && self.stat_respawn_time > 0)
2501                                 self.stat_respawn_time *= -1;
2502
2503                         return;
2504                 }
2505
2506                 self.prevorigin = self.origin;
2507
2508                 float do_crouch = self.BUTTON_CROUCH;
2509                 if(self.hook.state)
2510                         do_crouch = 0;
2511                 if(self.vehicle)
2512                         do_crouch = 0;
2513                 if(self.frozen)
2514                         do_crouch = 0;
2515
2516                 // WEAPONTODO: THIS SHIT NEEDS TO GO EVENTUALLY
2517                 // It cannot be predicted by the engine!
2518                 if((self.weapon == WEP_SHOCKWAVE || self.weapon == WEP_SHOTGUN) && self.weaponentity.wframe == WFRAME_FIRE2 && time < self.weapon_nextthink)
2519                         do_crouch = 0;
2520
2521                 if (do_crouch)
2522                 {
2523                         if (!self.crouch)
2524                         {
2525                                 self.crouch = true;
2526                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2527                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2528                                 // setanim(self, self.anim_duck, false, true, true); // this anim is BROKEN anyway
2529                         }
2530                 }
2531                 else
2532                 {
2533                         if (self.crouch)
2534                         {
2535                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, false, self);
2536                                 if (!trace_startsolid)
2537                                 {
2538                                         self.crouch = false;
2539                                         self.view_ofs = PL_VIEW_OFS;
2540                                         setsize (self, PL_MIN, PL_MAX);
2541                                 }
2542                         }
2543                 }
2544
2545                 FixPlayermodel();
2546
2547                 GrapplingHookFrame();
2548
2549                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2550                 //if(frametime)
2551                 {
2552                         self.items &= ~self.items_added;
2553
2554                         W_WeaponFrame();
2555
2556                         self.items_added = 0;
2557                         if(self.items & IT_JETPACK)
2558                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2559                                         self.items_added |= IT_FUEL;
2560
2561                         self.items |= self.items_added;
2562                 }
2563
2564                 player_regen();
2565
2566                 // WEAPONTODO: Add a weapon request for this
2567                 // rot vortex charge to the charge limit
2568                 if(WEP_CVAR(vortex, charge_rot_rate) && self.vortex_charge > WEP_CVAR(vortex, charge_limit) && self.vortex_charge_rottime < time)
2569                         self.vortex_charge = bound(WEP_CVAR(vortex, charge_limit), self.vortex_charge - WEP_CVAR(vortex, charge_rot_rate) * frametime / W_TICSPERFRAME, 1);
2570
2571                 if(frametime)
2572                         player_anim();
2573
2574                 // secret status
2575                 secrets_setstatus();
2576
2577                 // monsters status
2578                 monsters_setstatus();
2579
2580                 self.dmg_team = max(0, self.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2581
2582                 //self.angles_y=self.v_angle_y + 90;   // temp
2583         } else if(gameover) {
2584                 if (intermission_running)
2585                         IntermissionThink ();   // otherwise a button could be missed between
2586                 return;
2587         } else if(IS_OBSERVER(self)) {
2588                 ObserverThink();
2589         } else if(IS_SPEC(self)) {
2590                 SpectatorThink();
2591         }
2592
2593         // WEAPONTODO: Add weapon request for this
2594         if(!zoomstate_set)
2595                 SetZoomState(self.BUTTON_ZOOM || self.BUTTON_ZOOMSCRIPT || (self.BUTTON_ATCK2 && self.weapon == WEP_VORTEX) || (self.BUTTON_ATCK2 && self.weapon == WEP_RIFLE && WEP_CVAR(rifle, secondary) == 0)); // WEAPONTODO
2596
2597         float oldspectatee_status;
2598         oldspectatee_status = self.spectatee_status;
2599         if(IS_SPEC(self))
2600                 self.spectatee_status = num_for_edict(self.enemy);
2601         else if(IS_OBSERVER(self))
2602                 self.spectatee_status = num_for_edict(self);
2603         else
2604                 self.spectatee_status = 0;
2605         if(self.spectatee_status != oldspectatee_status)
2606         {
2607                 ClientData_Touch(self);
2608         }
2609
2610         if(self.teamkill_soundtime)
2611         if(time > self.teamkill_soundtime)
2612         {
2613                 self.teamkill_soundtime = 0;
2614
2615                 entity oldpusher, oldself;
2616
2617                 oldself = self; self = self.teamkill_soundsource;
2618                 oldpusher = self.pusher; self.pusher = oldself;
2619
2620                 PlayerSound(playersound_teamshoot, CH_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2621
2622                 self.pusher = oldpusher;
2623                 self = oldself;
2624         }
2625
2626         if(self.taunt_soundtime)
2627         if(time > self.taunt_soundtime)
2628         {
2629                 self.taunt_soundtime = 0;
2630                 PlayerSound(playersound_taunt, CH_VOICE, VOICETYPE_AUTOTAUNT);
2631         }
2632
2633         target_voicescript_next(self);
2634
2635         // WEAPONTODO: Move into weaponsystem somehow
2636         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
2637         if(!self.weapon)
2638                 self.clip_load = self.clip_size = 0;
2639 }
2640
2641 /*
2642 =============
2643 PlayerPostThink
2644
2645 Called every frame for each client after the physics are run
2646 =============
2647 */
2648 .float idlekick_lasttimeleft;
2649 void PlayerPostThink (void)
2650 {
2651         if(sv_maxidle > 0 && frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2652         if(IS_PLAYER(self) || sv_maxidle_spectatorsareidle)
2653         {
2654                 if (time - self.parm_idlesince < 1) // instead of (time == self.parm_idlesince) to support sv_maxidle <= 10
2655                 {
2656                         if(self.idlekick_lasttimeleft)
2657                         {
2658                                 self.idlekick_lasttimeleft = 0;
2659                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_IDLING);
2660                         }
2661                 }
2662                 else
2663                 {
2664                         float timeleft;
2665                         timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2666                         if(timeleft == min(10, sv_maxidle - 1)) // - 1 to support sv_maxidle <= 10
2667                         {
2668                                 if(!self.idlekick_lasttimeleft)
2669                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2670                         }
2671                         if(timeleft <= 0)
2672                         {
2673                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_KICK_IDLING, self.netname);
2674                                 dropclient(self);
2675                                 return;
2676                         }
2677                         else if(timeleft <= 10)
2678                         {
2679                                 if(timeleft != self.idlekick_lasttimeleft)
2680                                         { Send_Notification(NOTIF_ONE, self, MSG_ANNCE, Announcer_PickNumber(CNT_IDLE, timeleft)); }
2681                                 self.idlekick_lasttimeleft = timeleft;
2682                         }
2683                 }
2684         }
2685
2686 #ifdef TETRIS
2687         if(self.impulse == 100)
2688                 ImpulseCommands();
2689         if (!TetrisPostFrame())
2690         {
2691 #endif
2692
2693         CheatFrame();
2694
2695         //CheckPlayerJump();
2696
2697         if(IS_PLAYER(self)) {
2698                 CheckRules_Player();
2699                 UpdateChatBubble();
2700                 if (self.impulse)
2701                         ImpulseCommands();
2702                 if (intermission_running)
2703                         return;         // intermission or finale
2704                 GetPressedKeys();
2705         }
2706
2707 #ifdef TETRIS
2708         }
2709 #endif
2710
2711         /*
2712         float i;
2713         for(i = 0; i < 1000; ++i)
2714         {
2715                 vector end;
2716                 end = self.origin + '0 0 1024' + 512 * randomvec();
2717                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2718                 if(trace_fraction < 1)
2719                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2720                 {
2721                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2722                         break;
2723                 }
2724         }
2725         */
2726
2727         if(self.waypointsprite_attachedforcarrier)
2728                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON));
2729
2730         playerdemo_write();
2731
2732         CSQCMODEL_AUTOUPDATE();
2733 }