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