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