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