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