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