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