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