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