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