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