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