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