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