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