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