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