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