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