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