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