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