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