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