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