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