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