zoom: do it entirely client side
[divverent/nexuiz.git] / data / qcsrc / server / cl_client.qc
1 // let's abuse an existing field
2 #define SPAWNPOINT_SCORE frags
3
4 .float wantswelcomemessage;
5 .string netname_previous;
6
7 void spawnfunc_info_player_survivor (void)
8 {
9         spawnfunc_info_player_deathmatch();
10 }
11
12 void spawnfunc_info_player_start (void)
13 {
14         spawnfunc_info_player_deathmatch();
15 }
16
17 void spawnfunc_info_player_deathmatch (void)
18 {
19         self.classname = "info_player_deathmatch";
20         relocate_spawnpoint();
21 }
22
23 void spawnpoint_use()
24 {
25         if(teams_matter)
26         if(have_team_spawns)
27         {
28                 self.team = activator.team;
29                 some_spawn_has_been_used = 1;
30         }
31 };
32
33 // Returns:
34 //   -1 if a spawn can't be used
35 //   otherwise, a weight of the spawnpoint
36 float Spawn_Score(entity spot, entity playerlist, float teamcheck)
37 {
38         float shortest, thisdist;
39         entity player;
40
41         // filter out spots for the wrong team
42         if(teamcheck)
43         if(spot.team != teamcheck)
44                 return -1;
45
46         if(race_spawns)
47                 if(spot.target == "")
48                         return -1;
49
50         // filter out spots for assault
51         if(spot.target != "") {
52                 local entity ent;
53                 float good;
54                 ent = find(world, targetname, spot.target);
55                 while(ent) {
56                         if(ent.classname == "target_objective")
57                         {
58                                 if(ent.health < 0 || ent.health >= ASSAULT_VALUE_INACTIVE)
59                                         return -1;
60                                 good = 1;
61                         }
62                         else if(ent.classname == "trigger_race_checkpoint")
63                         {
64                                 if(self.classname == "player") // spectators may spawn everywhere
65                                 {
66                                         if(ent.race_checkpoint != race_PreviousCheckpoint(self.race_checkpoint))
67                                                 return -1;
68                                         float pl;
69                                         pl = self.race_place;
70                                         if(pl > race_highest_place_spawn)
71                                                 pl = 0;
72                                         if(spot.race_place != pl)
73                                                 return -1;
74                                 }
75                                 good = 1;
76                         }
77                         else
78                         {
79                         }
80                         ent = find(ent, targetname, spot.target);
81                 }
82
83                 if(!good)
84                         return -1;
85         }
86
87         player = playerlist;
88         shortest = vlen(world.maxs - world.mins);
89         for(player = playerlist; player; player = player.chain)
90                 if (player != self)
91                 {
92                         thisdist = vlen(player.origin - spot.origin);
93                         if (thisdist < shortest)
94                                 shortest = thisdist;
95                 }
96         return shortest;
97 }
98
99 float spawn_allbad;
100 float spawn_allgood;
101 entity Spawn_FilterOutBadSpots(entity firstspot, entity playerlist, float mindist, float teamcheck)
102 {
103         local entity spot, spotlist, spotlistend;
104         spawn_allgood = TRUE;
105         spawn_allbad = TRUE;
106
107         spotlist = world;
108         spotlistend = world;
109
110         for(spot = firstspot; spot; spot = spot.chain)
111         {
112                 spot.SPAWNPOINT_SCORE = Spawn_Score(spot, playerlist, teamcheck);
113
114                 if(cvar("spawn_debugview"))
115                 {
116                         setmodel(spot, "models/runematch/rune.mdl");
117                         if(spot.SPAWNPOINT_SCORE < mindist)
118                         {
119                                 spot.colormod = '1 0 0';
120                                 spot.scale = 1;
121                         }
122                         else
123                         {
124                                 spot.colormod = '0 1 0';
125                                 spot.scale = spot.SPAWNPOINT_SCORE / mindist;
126                         }
127                 }
128
129                 if(spot.SPAWNPOINT_SCORE >= 0) // spawning allowed here
130                 {
131                         if(spot.SPAWNPOINT_SCORE < mindist)
132                         {
133                                 // too short distance
134                                 spawn_allgood = FALSE;
135                         }
136                         else 
137                         {
138                                 // perfect
139                                 spawn_allbad = FALSE;
140
141                                 if(spotlistend)
142                                         spotlistend.chain = spot;
143                                 spotlistend = spot;
144                                 if(!spotlist)
145                                         spotlist = spot;
146
147                                 /*
148                                 if(teamcheck)
149                                 if(spot.team != teamcheck)
150                                         error("invalid spawn added");
151
152                                 print("added ", etos(spot), "\n");
153                                 */
154                         }
155                 }
156         }
157         if(spotlistend)
158                 spotlistend.chain = world;
159
160         /*
161                 entity e;
162                 if(teamcheck)
163                         for(e = spotlist; e; e = e.chain)
164                         {
165                                 print("seen ", etos(e), "\n");
166                                 if(e.team != teamcheck)
167                                         error("invalid spawn found");
168                         }
169         */
170
171         return spotlist;
172 }
173
174 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
175 {
176         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
177         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
178         local entity spot;
179
180         RandomSelection_Init();
181         for(spot = firstspot; spot; spot = spot.chain)
182                 RandomSelection_Add(spot, 0, pow(bound(lower, spot.SPAWNPOINT_SCORE, upper), exponent) * spot.cnt, spot.SPAWNPOINT_SCORE >= lower);
183
184         return RandomSelection_chosen_ent;
185 }
186
187 /*
188 =============
189 SelectSpawnPoint
190
191 Finds a point to respawn
192 =============
193 */
194 entity SelectSpawnPoint (float anypoint)
195 {
196         local float teamcheck;
197         local entity firstspot_new;
198         local entity spot, firstspot, playerlist;
199
200         spot = find (world, classname, "testplayerstart");
201         if (spot)
202                 return spot;
203
204         teamcheck = 0;
205
206         if(!anypoint && have_team_spawns)
207                 teamcheck = self.team;
208
209         // get the list of players
210         playerlist = findchain(classname, "player");
211         // get the entire list of spots
212         firstspot = findchain(classname, "info_player_deathmatch");
213         // filter out the bad ones
214         // (note this returns the original list if none survived)
215         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 100, teamcheck);
216         if(!firstspot_new)
217                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, -1, teamcheck);
218         firstspot = firstspot_new;
219
220         // there is 50/50 chance of choosing a random spot or the furthest spot
221         // (this means that roughly every other spawn will be furthest, so you
222         // usually won't get fragged at spawn twice in a row)
223         if (arena_roundbased)
224         {
225                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 800, teamcheck);
226                 if(firstspot_new)
227                         firstspot = firstspot_new;
228                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
229         }
230         else if (random() > cvar("g_spawn_furthest"))
231                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
232         else
233                 spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
234
235         if(cvar("spawn_debugview"))
236         {
237                 print("spot mindistance: ", ftos(spot.SPAWNPOINT_SCORE), "\n");
238
239                 entity e;
240                 if(teamcheck)
241                         for(e = firstspot; e; e = e.chain)
242                                 if(e.team != teamcheck)
243                                         error("invalid spawn found");
244         }
245
246         if (!spot)
247         {
248                 if(cvar("spawn_debug"))
249                         GotoNextMap();
250                 else
251                 {
252                         if(some_spawn_has_been_used)
253                                 return world; // team can't spawn any more, because of actions of other team
254                         else
255                                 error("Cannot find a spawn point - please fix the map!");
256                 }
257         }
258
259         return spot;
260 }
261
262 /*
263 =============
264 CheckPlayerModel
265
266 Checks if the argument string can be a valid playermodel.
267 Returns a valid one in doubt.
268 =============
269 */
270 string FallbackPlayerModel = "models/player/marine.zym";
271 string CheckPlayerModel(string plyermodel) {
272         if(strlen(plyermodel) < 4)
273                 return FallbackPlayerModel;
274         if( substring(plyermodel,0,14) != "models/player/")
275                 return FallbackPlayerModel;
276         else if(cvar("sv_servermodelsonly"))
277         {
278                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".zym")
279                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".dpm")
280                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".md3")
281                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".psk")
282                         return FallbackPlayerModel;
283                 if(!fexists(plyermodel))
284                         return FallbackPlayerModel;
285         }
286         return plyermodel;
287 }
288
289 /*
290 =============
291 Client_customizeentityforclient
292
293 LOD reduction
294 =============
295 */
296 float Client_customizeentityforclient()
297 {
298 #ifdef ALLOW_VARIABLE_LOD
299         // self: me
300         // other: the player viewing me
301         float distance;
302         float f;
303
304         if(self.flags & FL_NOTARGET) // we don't need LOD for spectators
305                 return TRUE;
306
307         if(other.cvar_cl_playerdetailreduction <= 0)
308         {
309                 if(other.cvar_cl_playerdetailreduction <= -2)
310                         self.modelindex = self.modelindex_lod2;
311                 else if(other.cvar_cl_playerdetailreduction <= -1)
312                         self.modelindex = self.modelindex_lod1;
313                 else
314                         self.modelindex = self.modelindex_lod0;
315         }
316         else
317         {
318                 distance = vlen(self.origin - other.origin);
319                 f = (distance + 100.0) * other.cvar_cl_playerdetailreduction;
320                 if(f > 10000)
321                         self.modelindex = self.modelindex_lod2;
322                 else if(f > 5000)
323                         self.modelindex = self.modelindex_lod1;
324                 else
325                         self.modelindex = self.modelindex_lod0;
326         }
327 #endif
328
329         return TRUE;
330 }
331
332 void UpdatePlayerSounds();
333 void setmodel_lod(entity e, string modelname)
334 {
335 #ifdef ALLOW_VARIABLE_LOD
336         string s;
337
338         // FIXME: this only supports 3-letter extensions
339         s = strcat(substring(modelname, 0, strlen(modelname) - 4), "_1", substring(modelname, 0, strlen(modelname) - 4));
340         if(fexists(s))
341         {
342                 precache_model(s);
343                 setmodel(e, s); // players have high precision
344                 self.modelindex_lod1 = self.modelindex;
345         }
346         else
347                 self.modelindex_lod1 = -1;
348
349         s = strcat(substring(modelname, 0, strlen(modelname) - 4), "_2", substring(modelname, 0, strlen(modelname) - 4));
350         if(fexists(s))
351         {
352                 precache_model(s);
353                 setmodel(e, s); // players have high precision
354                 self.modelindex_lod2 = self.modelindex;
355         }
356         else
357                 self.modelindex_lod2 = -1;
358
359         precache_model(modelname);
360         setmodel(e, modelname); // players have high precision
361         self.modelindex_lod0 = self.modelindex;
362
363         if(self.modelindex_lod1 < 0)
364                 self.modelindex_lod1 = self.modelindex;
365
366         if(self.modelindex_lod2 < 0)
367                 self.modelindex_lod2 = self.modelindex;
368 #else
369         precache_model(modelname);
370         setmodel(e, modelname); // players have high precision
371 #endif
372         player_setupanimsformodel();
373         UpdatePlayerSounds();
374 }
375
376 /*
377 =============
378 PutObserverInServer
379
380 putting a client as observer in the server
381 =============
382 */
383 void PutObserverInServer (void)
384 {
385         entity  spot;
386
387         race_PreSpawnObserver();
388
389         spot = SelectSpawnPoint (TRUE);
390         if(!spot)
391                 error("No spawnpoints for observers?!?\n");
392         RemoveGrapplingHook(self); // Wazat's Grappling Hook
393
394         if(clienttype(self) == CLIENTTYPE_REAL)
395         {
396                 msg_entity = self;
397                 WriteByte(MSG_ONE, SVC_SETVIEW);
398                 WriteEntity(MSG_ONE, self);
399         }
400
401         DropAllRunes(self);
402         kh_Key_DropAll(self, TRUE);
403
404         if(self.flagcarried)
405                 DropFlag(self.flagcarried);
406
407         WaypointSprite_PlayerDead();
408         
409         if(self.killcount != -666)
410         {
411                 if(g_lms)
412                 {
413                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
414                                 bprint ("^4", self.netname, "^4 has no more lives left\n");
415                         else
416                                 bprint ("^4", self.netname, "^4 is spectating now\n"); // TODO turn this into a proper forfeit?
417                 }
418                 else
419                         bprint ("^4", self.netname, "^4 is spectating now\n");
420         }
421
422         PlayerScore_Clear(self); // clear scores when needed
423
424         self.spectatortime = time;
425         
426         self.classname = "observer";
427         self.health = -666;
428         self.takedamage = DAMAGE_NO;
429         self.solid = SOLID_NOT;
430         self.movetype = MOVETYPE_NOCLIP;
431         self.flags = FL_CLIENT | FL_NOTARGET;
432         self.armorvalue = 666;
433         self.effects = 0;
434         self.armorvalue = cvar("g_balance_armor_start");
435         self.pauserotarmor_finished = 0;
436         self.pauserothealth_finished = 0;
437         self.pauseregen_finished = 0;
438         self.damageforcescale = 0;
439         self.death_time = 0;
440         self.dead_frame = 0;
441         self.alpha = 0;
442         self.scale = 0;
443         self.fade_time = 0;
444         self.pain_frame = 0;
445         self.pain_finished = 0;
446         self.strength_finished = 0;
447         self.invincible_finished = 0;
448         self.pushltime = 0;
449         self.think = SUB_Null;
450         self.nextthink = 0;
451         self.hook_time = 0;
452         self.runes = 0;
453         self.deadflag = DEAD_NO;
454         self.angles = spot.angles;
455         self.angles_z = 0;
456         self.fixangle = TRUE;
457         self.crouch = FALSE;
458
459         self.view_ofs = PL_VIEW_OFS;
460         setorigin (self, spot.origin);
461         setsize (self, '0 0 0', '0 0 0');
462         self.oldorigin = self.origin;
463         self.items = 0;
464         self.model = "";
465         self.modelindex = 0;
466         self.weapon = 0;
467         self.weaponmodel = "";
468         self.weaponentity = world;
469         self.killcount = -666;
470         self.velocity = '0 0 0';
471         self.avelocity = '0 0 0';
472         self.punchangle = '0 0 0';
473         self.punchvector = '0 0 0';
474         self.oldvelocity = self.velocity;
475         self.customizeentityforclient = Client_customizeentityforclient;
476         self.wantswelcomemessage = 1;
477
478         if(g_arena)
479         {
480                 if(self.version_mismatch)
481                 {
482                         Spawnqueue_Unmark(self);
483                         Spawnqueue_Remove(self);
484                 }
485                 else
486                 {
487                         Spawnqueue_Insert(self);
488                 }
489         }
490         else if(g_lms)
491         {
492                 // Only if the player cannot play at all
493                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
494                         self.frags = -666;
495                 else
496                         self.frags = -667;
497         }
498         else
499                 self.frags = -666;
500 }
501
502 float RestrictSkin(float s)
503 {
504         if(!teams_matter)
505                 return s;
506         if(s == 6)
507                 return 6;
508         return mod(s, 3);
509 }
510
511 void FixPlayermodel()
512 {
513         local string defaultmodel;
514         local float defaultskin;
515         local vector m1, m2;
516
517         defaultmodel = "";
518
519         if(cvar("sv_defaultcharacter") == 1) {
520                 defaultskin = 0;
521
522                 if(teams_matter)
523                 {
524                         defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", Team_ColorNameLowerCase(self.team)));
525                         defaultskin = cvar(strcat("sv_defaultplayerskin_", Team_ColorNameLowerCase(self.team)));
526                 }
527
528                 if(defaultmodel == "")
529                 {
530                         defaultmodel = cvar_string("sv_defaultplayermodel");
531                         defaultskin = cvar("sv_defaultplayerskin");
532                 }
533         }
534
535         if(defaultmodel != "")
536         {
537                 if (defaultmodel != self.model)
538                 {
539                         m1 = self.mins;
540                         m2 = self.maxs;
541                         setmodel_lod (self, defaultmodel);
542                         setsize (self, m1, m2);
543                 }
544
545                 self.skin = defaultskin;
546         } else {
547                 if (self.playermodel != self.model)
548                 {
549                         self.playermodel = CheckPlayerModel(self.playermodel);
550                         m1 = self.mins;
551                         m2 = self.maxs;
552                         setmodel_lod (self, self.playermodel);
553                         setsize (self, m1, m2);
554                 }
555
556                 self.skin = RestrictSkin(stof(self.playerskin));
557         }
558
559         if(!teams_matter)
560                 if(strlen(cvar_string("sv_defaultplayercolors")))
561                         if(self.clientcolors != cvar("sv_defaultplayercolors"))
562                                 setcolor(self, cvar("sv_defaultplayercolors"));
563 }
564
565 /*
566 =============
567 PutClientInServer
568
569 Called when a client spawns in the server
570 =============
571 */
572 //void() ctf_playerchanged;
573 void PutClientInServer (void)
574 {
575         if(clienttype(self) == CLIENTTYPE_BOT)
576         {
577                 self.classname = "player";
578         }
579         else if(clienttype(self) == CLIENTTYPE_REAL)
580         {
581                 msg_entity = self;
582                 WriteByte(MSG_ONE, SVC_SETVIEW);
583                 WriteEntity(MSG_ONE, self);
584         }
585
586         // player is dead and becomes observer
587         // FIXME fix LMS scoring for new system
588         if(g_lms)
589         {
590                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
591                         self.classname = "observer";
592         }
593
594         if(g_arena)
595         if(!self.spawned)
596                 self.classname = "observer";
597
598         if(self.classname == "player") {
599                 entity  spot;
600
601                 race_PreSpawn();
602
603                 spot = SelectSpawnPoint (FALSE);
604                 if(!spot)
605                 {
606                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
607                         return; // spawn failed
608                 }
609
610                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
611
612                 self.classname = "player";
613                 self.iscreature = TRUE;
614                 self.movetype = MOVETYPE_WALK;
615                 self.solid = SOLID_SLIDEBOX;
616                 if(independent_players)
617                         MAKE_INDEPENDENT_PLAYER(self);
618                 self.flags = FL_CLIENT;
619                 self.takedamage = DAMAGE_AIM;
620                 if(g_minstagib)
621                         self.effects = EF_FULLBRIGHT;
622                 else
623                         self.effects = 0;
624                 self.air_finished = time + 12;
625                 self.dmg = 2;
626
627                 self.ammo_shells = start_ammo_shells;
628                 self.ammo_nails = start_ammo_nails;
629                 self.ammo_rockets = start_ammo_rockets;
630                 self.ammo_cells = start_ammo_cells;
631                 self.health = start_health;
632                 self.armorvalue = start_armorvalue;
633                 self.items = start_items;
634                 self.switchweapon = start_switchweapon;
635                 self.cnt = start_switchweapon;
636                 self.weapon = 0;
637                 self.jump_interval = time;
638
639                 self.spawnshieldtime = time + cvar("g_spawnshieldtime");
640                 self.pauserotarmor_finished = time + cvar("g_balance_pause_armor_rot_spawn");
641                 self.pauserothealth_finished = time + cvar("g_balance_pause_health_rot_spawn");
642                 self.pauseregen_finished = time + cvar("g_balance_pause_health_regen_spawn");
643                 //extend the pause of rotting if client was reset at the beginning of the countdown
644                 if(!cvar("sv_ready_restart_after_countdown") && time < restart_countdown) {
645                         self.spawnshieldtime += RESTART_COUNTDOWN;
646                         self.pauserotarmor_finished += RESTART_COUNTDOWN;
647                         self.pauserothealth_finished += RESTART_COUNTDOWN;
648                         self.pauseregen_finished += RESTART_COUNTDOWN;
649                 }
650                 self.damageforcescale = 2;
651                 self.death_time = 0;
652                 self.dead_frame = 0;
653                 self.alpha = 0;
654                 self.scale = 0;
655                 self.fade_time = 0;
656                 self.pain_frame = 0;
657                 self.pain_finished = 0;
658                 self.strength_finished = 0;
659                 self.invincible_finished = 0;
660                 self.pushltime = 0;
661                 //self.speed_finished = 0;
662                 //self.slowmo_finished = 0;
663                 // players have no think function
664                 self.think = SUB_Null;
665                 self.nextthink = 0;
666                 self.hook_time = 0;
667
668                 self.runes = 0;
669
670                 self.deadflag = DEAD_NO;
671
672                 self.angles = spot.angles;
673
674                 self.angles_z = 0; // never spawn tilted even if the spot says to
675                 self.fixangle = TRUE; // turn this way immediately
676                 self.velocity = '0 0 0';
677                 self.avelocity = '0 0 0';
678                 self.punchangle = '0 0 0';
679                 self.punchvector = '0 0 0';
680                 self.oldvelocity = self.velocity;
681
682                 msg_entity = self;
683                 WRITESPECTATABLE_MSG_ONE({
684                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
685                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
686                 });
687
688                 self.customizeentityforclient = Client_customizeentityforclient;
689
690                 self.model = "";
691                 FixPlayermodel();
692
693                 self.crouch = FALSE;
694                 self.view_ofs = PL_VIEW_OFS;
695                 setsize (self, PL_MIN, PL_MAX);
696                 self.spawnorigin = spot.origin;
697                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
698                 // don't reset back to last position, even if new position is stuck in solid
699                 self.oldorigin = self.origin;
700
701                 if(g_arena)
702                 {
703                         Spawnqueue_Remove(self);
704                         Spawnqueue_Mark(self);
705                 }
706
707                 self.event_damage = PlayerDamage;
708
709                 self.bot_attack = TRUE;
710
711                 self.statdraintime = time + 5;
712                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
713
714                 if(self.killcount == -666) {
715                         PlayerScore_Clear(self);
716                         self.killcount = 0;
717                         self.frags = 0;
718                 }
719
720                 self.cnt = WEP_LASER;
721                 self.nixnex_lastchange_id = -1;
722
723                 CL_SpawnWeaponentity();
724                 self.alpha = default_player_alpha;
725                 self.colormod = '1 1 1' * cvar("g_player_brightness");
726                 self.exteriorweaponentity.alpha = default_weapon_alpha;
727
728                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
729                 self.lms_traveled_distance = 0;
730                 self.speedrunning = FALSE;
731
732                 race_PostSpawn(spot);
733
734                 if(cvar("spawn_debug"))
735                 {
736                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
737                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
738                 }
739
740                 //stuffcmd(self, "chase_active 0");
741                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
742
743                 if (cvar("g_spawnsound"))
744                         sound (self, CHAN_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
745
746                 if(g_assault) {
747                         if(self.team == assault_attacker_team)
748                                 centerprint(self, "You are attacking!\n");
749                         else
750                                 centerprint(self, "You are defending!\n");
751                 }
752
753         } else if(self.classname == "observer") {
754                 PutObserverInServer ();
755         }
756
757         //if(g_ctf)
758         //      ctf_playerchanged();
759 }
760
761 /*
762 =============
763 SendCSQCInfo
764
765 Send whatever CSQC needs NOW and cannot wait for SendServerInfo to happen...
766 =============
767 */
768 void SendCSQCInfo(void)
769 {
770         if(clienttype(self) != CLIENTTYPE_REAL)
771                 return;
772         msg_entity = self;
773         WriteByte(MSG_ONE, SVC_TEMPENTITY);
774         WriteByte(MSG_ONE, TE_CSQC_INIT);
775         WriteShort(MSG_ONE, CSQC_REVISION);
776         WriteByte(MSG_ONE, maxclients);
777         WriteByte(MSG_ONE, g_minstagib);
778 }
779
780 /*
781 =============
782 SetNewParms
783 =============
784 */
785 void SetNewParms (void)
786 {
787         // initialize parms for a new player
788         parm1 = -(86400 * 366);
789 }
790
791 /*
792 =============
793 SetChangeParms
794 =============
795 */
796 void SetChangeParms (void)
797 {
798         // save parms for level change
799         parm1 = self.parm_idlesince - time;
800 }
801
802 /*
803 =============
804 DecodeLevelParms
805 =============
806 */
807 void DecodeLevelParms (void)
808 {
809         // load parms
810         self.parm_idlesince = parm1;
811         if(self.parm_idlesince == -(86400 * 366))
812                 self.parm_idlesince = time;
813 }
814
815 /*
816 =============
817 ClientKill
818
819 Called when a client types 'kill' in the console
820 =============
821 */
822
823 void ClientKill_Now_TeamChange()
824 {
825         if(self.killindicator_teamchange == -1)
826         {
827                 self.team = -1;
828                 JoinBestTeam( self, FALSE, FALSE );
829         }
830         else
831         {
832                 SV_ChangeTeam(self.killindicator_teamchange - 1);
833         }
834 }
835
836 void ClientKill_Now()
837 {
838         if(self.killindicator_teamchange)
839                 ClientKill_Now_TeamChange();
840
841         // in any case:
842         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
843
844         if(self.killindicator)
845         {
846                 dprint("Cleaned up after a leaked kill indicator.\n");
847                 remove(self.killindicator);
848                 self.killindicator = world;
849         }
850 }
851 void KillIndicator_Think()
852 {
853         if (!self.owner.modelindex)
854         {
855                 self.owner.killindicator = world;
856                 remove(self);
857                 return;
858         }
859
860         if(self.cnt <= 0)
861         {
862                 self = self.owner;
863                 ClientKill_Now(); // no oldself needed
864                 return;
865         }
866         else
867         {
868                 if(self.cnt <= 10)
869                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
870                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
871                 {
872                         if(self.cnt <= 10)
873                                 announce(self.owner, strcat("announcer/robotic/", ftos(self.cnt), ".ogg"));
874                         if(self.owner.killindicator_teamchange)
875                         {
876                                 if(self.owner.killindicator_teamchange == -1)
877                                         centerprint(self.owner, strcat("Changing team in ", ftos(self.cnt), " seconds"));
878                                 else
879                                         centerprint(self.owner, strcat("Changing to ", ColoredTeamName(self.owner.killindicator_teamchange), " in ", ftos(self.cnt), " seconds"));
880                         }
881                         else
882                                 centerprint(self.owner, strcat("^1Suicide in ", ftos(self.cnt), " seconds"));
883                 }
884                 self.nextthink = time + 1;
885                 self.cnt -= 1;
886         }
887 }
888
889 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto
890 {
891         float killtime;
892         entity e;
893         killtime = cvar("g_balance_kill_delay");
894
895         self.killindicator_teamchange = targetteam;
896
897         if(!self.killindicator)
898         {
899                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
900                 {
901                         ClientKill_Now();
902                 }
903                 else
904                 {
905                         self.killindicator = spawn();
906                         self.killindicator.owner = self;
907                         self.killindicator.scale = 0.5;
908                         setattachment(self.killindicator, self, "");
909                         setorigin(self.killindicator, '0 0 52');
910                         self.killindicator.think = KillIndicator_Think;
911                         self.killindicator.nextthink = time + (self.lip) * 0.05;
912                         self.killindicator.cnt = ceil(killtime);
913                         self.killindicator.count = bound(0, ceil(killtime), 10);
914                         sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
915
916                         for(e = world; (e = find(e, classname, "body")) != world; )
917                         {
918                                 if(e.enemy != self)
919                                         continue;
920                                 e.killindicator = spawn();
921                                 e.killindicator.owner = e;
922                                 e.killindicator.scale = 0.5;
923                                 setattachment(e.killindicator, e, "");
924                                 setorigin(e.killindicator, '0 0 52');
925                                 e.killindicator.think = KillIndicator_Think;
926                                 e.killindicator.nextthink = time + (e.lip) * 0.05;
927                                 e.killindicator.cnt = ceil(killtime);
928                         }
929                         self.lip = 0;
930                 }
931         }
932         if(self.killindicator)
933         {
934                 if(targetteam)
935                         self.killindicator.colormod = TeamColor(targetteam);
936                 else
937                         self.killindicator.colormod = '0 0 0';
938         }
939 }
940
941 void ClientKill (void)
942 {
943         ClientKill_TeamChange(0);
944 }
945
946 void DoTeamChange(float destteam)
947 {
948         float t, c0;
949         if(!cvar("teamplay"))
950         {
951                 if(destteam >= 0)
952                         SetPlayerColors(self, destteam);
953                 return;
954         }
955         if(self.classname == "player")
956         if(destteam == -1)
957         {
958                 CheckAllowedTeams(self);
959                 t = FindSmallestTeam(self, TRUE);
960                 switch(self.team)
961                 {
962                         case COLOR_TEAM1: c0 = c1; break;
963                         case COLOR_TEAM2: c0 = c2; break;
964                         case COLOR_TEAM3: c0 = c3; break;
965                         case COLOR_TEAM4: c0 = c4; break;
966                         default:          c0 = 999;
967                 }
968                 switch(t)
969                 {
970                         case 1:
971                                 if(c0 > c1)
972                                         destteam = COLOR_TEAM1;
973                                 break;
974                         case 2:
975                                 if(c0 > c2)
976                                         destteam = COLOR_TEAM2;
977                                 break;
978                         case 3:
979                                 if(c0 > c3)
980                                         destteam = COLOR_TEAM3;
981                                 break;
982                         case 4:
983                                 if(c0 > c4)
984                                         destteam = COLOR_TEAM4;
985                                 break;
986                 }
987                 if(destteam == -1)
988                         return;
989         }
990         if(destteam == self.team && !self.killindicator)
991                 return;
992         ClientKill_TeamChange(destteam);
993 }
994
995 void FixClientCvars(entity e)
996 {
997         // send prediction settings to the client
998         stuffcmd(e, "\nin_bindmap 0 0\n");
999         /*
1000          * we no longer need to stuff this. Remove this comment block if you feel 
1001          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1002         stuffcmd(e, strcat("cl_gravity ", ftos(cvar("sv_gravity")), "\n"));
1003         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(cvar("sv_accelerate")), "\n"));
1004         stuffcmd(e, strcat("cl_movement_friction ", ftos(cvar("sv_friction")), "\n"));
1005         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(cvar("sv_maxspeed")), "\n"));
1006         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(cvar("sv_airaccelerate")), "\n"));
1007         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(cvar("sv_maxairspeed")), "\n"));
1008         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(cvar("sv_stopspeed")), "\n"));
1009         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(cvar("sv_jumpvelocity")), "\n"));
1010         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(cvar("sv_stepheight")), "\n"));
1011         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(cvar("sv_friction_on_land")), "\n"));
1012         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(cvar("sv_airaccel_qw")), "\n"));
1013         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(cvar("sv_airaccel_sideways_friction")), "\n"));
1014         stuffcmd(e, "cl_movement_edgefriction 1\n");
1015          */
1016 }
1017
1018 /*
1019 =============
1020 ClientConnect
1021
1022 Called when a client connects to the server
1023 =============
1024 */
1025 //void ctf_clientconnect();
1026 string ColoredTeamName(float t);
1027 void DecodeLevelParms (void);
1028 //void dom_player_join_team(entity pl);
1029 void ClientConnect (void)
1030 {
1031         local string s;
1032         float wep;
1033
1034         if(self.flags & FL_CLIENT)
1035         {
1036                 print("Warning: ClientConnect, but already connected!\n");
1037                 return;
1038         }
1039
1040         if(Ban_IsClientBanned(self))
1041         {
1042                 s = strcat("^1NOTE:^7 banned client ", self.netaddress, " just tried to enter\n");
1043                 dropclient(self);
1044                 bprint(s);
1045                 return;
1046         }
1047
1048         DecodeLevelParms();
1049
1050         self.classname = "player_joining";
1051
1052         self.flags = self.flags | FL_CLIENT;
1053         self.version_nagtime = time + 10 + random() * 10;
1054
1055         if(player_count<0)
1056         {
1057                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1058                 player_count = 0;
1059         }
1060
1061         PlayerScore_Attach(self);
1062
1063         bot_clientconnect();
1064
1065         race_PreSpawnObserver();
1066
1067         //if(g_domination)
1068         //      dom_player_join_team(self);
1069
1070         //JoinBestTeam(self, FALSE, FALSE);
1071
1072         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1073                 self.classname = "observer";
1074         } else {
1075                 self.classname = "player";
1076                 campaign_bots_may_start = 1;
1077         }
1078
1079         self.playerid = (playerid_last = playerid_last + 1);
1080         if(cvar("sv_eventlog"))
1081         {
1082                 if(clienttype(self) == CLIENTTYPE_REAL)
1083                         s = "player";
1084                 else
1085                         s = "bot";
1086                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", s, ":", self.netname), TRUE);
1087                 s = strcat(":team:", ftos(self.playerid), ":");
1088                 s = strcat(s, ftos(self.team));
1089                 GameLogEcho(s, FALSE);
1090         }
1091         self.netname_previous = strzone(self.netname);
1092
1093         //stuffcmd(self, "set tmpviewsize $viewsize \n");
1094
1095         bprint ("^4",self.netname);
1096         bprint ("^4 connected");
1097
1098         if(g_domination || g_ctf)
1099         {
1100                 bprint(" and joined the ");
1101                 bprint(ColoredTeamName(self.team));
1102         }
1103
1104         bprint("\n");
1105
1106         self.welcomemessage_time = 0;
1107
1108         stuffcmd(self, strcat(clientstuff, "\n"));
1109         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1110         stuffcmd(self, "cl_particles_reloadeffects\n");
1111
1112         FixClientCvars(self);
1113
1114         // spawnfunc_waypoint sprites
1115         WaypointSprite_InitClient(self);
1116
1117         // Wazat's grappling hook
1118         SetGrappleHookBindings();
1119
1120         // get autoswitch state from player when he toggles it
1121         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1122
1123         // get version info from player
1124         stuffcmd(self, "cmd clientversion $gameversion\n");
1125
1126         // send all weapon info strings
1127         stuffcmd(self, "register_bestweapon clear\n"); // clear the Quake stuff
1128         wep = WEP_FIRST;
1129         while (wep <= WEP_LAST)
1130         {
1131                 weapon_action(wep, WR_REGISTER);
1132                 wep = wep + 1;
1133         }
1134
1135         // get other cvars from player
1136         GetCvars(0);
1137
1138         // set cvar for team scoreboard
1139         if (teams_matter)
1140         {
1141                 local float t;
1142                 t = cvar("teamplay");
1143                 // we have to stuff the correct teamplay value because if this is a listen server, this changes the teamplay mode of the server itself, which is bad
1144                 stuffcmd(self, strcat("set teamplay ", ftos(t), "\n"));
1145         }
1146         else
1147                 stuffcmd(self, "set teamplay 0\n");
1148
1149         // notify about available teams
1150         if(teamplay)
1151         {
1152                 CheckAllowedTeams(self);
1153                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1154                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1155         }
1156         else
1157                 stuffcmd(self, "set _teams_available 0\n");
1158
1159         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1160
1161         if(g_arena)
1162         {
1163                 self.classname = "observer";
1164                 Spawnqueue_Insert(self);
1165         }
1166         /*else if(g_ctf)
1167         {
1168                 ctf_clientconnect();
1169         }*/
1170
1171         if(entcs_start)
1172                 attach_entcs();
1173
1174         bot_relinkplayerlist();
1175
1176         self.spectatortime = time;
1177         if(blockSpectators)
1178         {
1179                 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"));
1180         }
1181
1182         self.jointime = time;
1183         self.allowedTimeouts = cvar("sv_timeout_number");
1184
1185         if(clienttype(self) == CLIENTTYPE_REAL)
1186         {
1187                 sprint(self, strcat("nexuiz-csqc protocol ", ftos(CSQC_REVISION), "\n"));
1188                 SendCSQCInfo();
1189                 msg_entity = self;
1190                 if(mapvote_initialized && !cvar("g_maplist_textonly"))
1191                 {
1192                         MapVote_SendData(MSG_ONE);
1193                         MapVote_UpdateData(MSG_ONE);
1194                 }
1195                 ScoreInfo_Write(MSG_ONE);
1196         }
1197
1198         if(g_lms)
1199         {
1200                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1201                 {
1202                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1203                         self.frags = -666; // FIXME do we still need this?
1204                 }
1205         }
1206 }
1207
1208 /*
1209 =============
1210 ClientDisconnect
1211
1212 Called when a client disconnects from the server
1213 =============
1214 */
1215 void(entity e) DropFlag;
1216 .entity chatbubbleentity;
1217 .entity teambubbleentity;
1218 void ReadyCount();
1219 //void() ctf_clientdisconnect;
1220 void ClientDisconnect (void)
1221 {
1222         float save;
1223
1224         if not(self.flags & FL_CLIENT)
1225         {
1226                 print("Warning: ClientDisconnect without ClientConnect\n");
1227                 return;
1228         }
1229
1230         bot_clientdisconnect();
1231
1232         if(entcs_start)
1233                 detach_entcs();
1234         
1235         if(cvar("sv_eventlog"))
1236                 GameLogEcho(strcat(":part:", ftos(self.playerid)), FALSE);
1237         bprint ("^4",self.netname);
1238         bprint ("^4 disconnected\n");
1239
1240         if (self.chatbubbleentity)
1241         {
1242                 remove (self.chatbubbleentity);
1243                 self.chatbubbleentity = world;
1244         }
1245
1246         if (self.teambubbleentity)
1247         {
1248                 remove (self.teambubbleentity);
1249                 self.teambubbleentity = world;
1250         }
1251
1252         if (self.killindicator)
1253         {
1254                 remove (self.killindicator);
1255                 self.killindicator = world;
1256         }
1257
1258         WaypointSprite_PlayerGone();
1259
1260         DropAllRunes(self);
1261         kh_Key_DropAll(self, TRUE);
1262
1263         if(self.flagcarried)
1264                 DropFlag(self.flagcarried);
1265
1266         save = self.flags;
1267         self.flags = self.flags - (self.flags & FL_CLIENT);
1268         bot_relinkplayerlist();
1269         self.flags = save;
1270
1271         // remove laserdot
1272         if(self.weaponentity)
1273                 if(self.weaponentity.lasertarget)
1274                         remove(self.weaponentity.lasertarget);
1275
1276         if(g_arena)
1277         {
1278                 Spawnqueue_Unmark(self);
1279                 Spawnqueue_Remove(self);
1280         }
1281         /*if(g_ctf)
1282         {
1283                 ctf_clientdisconnect();
1284         }
1285         */
1286
1287         PlayerScore_Detach(self);
1288
1289         if(self.netname_previous)
1290                 strunzone(self.netname_previous);
1291
1292         ClearPlayerSounds();
1293
1294         // free cvars
1295         GetCvars(-1);
1296         self.playerid = 0;
1297
1298         ReadyCount();
1299 }
1300
1301 .float BUTTON_CHAT;
1302 void ChatBubbleThink()
1303 {
1304         self.nextthink = time;
1305         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1306         {
1307                 self.owner.chatbubbleentity = world;
1308                 remove(self);
1309                 return;
1310         }
1311         setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');
1312         if (self.owner.BUTTON_CHAT && !self.owner.deadflag)
1313                 self.model = self.mdl;
1314         else
1315                 self.model = "";
1316 };
1317
1318 void UpdateChatBubble()
1319 {
1320         if (!self.modelindex)
1321                 return;
1322         // spawn a chatbubble entity if needed
1323         if (!self.chatbubbleentity)
1324         {
1325                 self.chatbubbleentity = spawn();
1326                 self.chatbubbleentity.owner = self;
1327                 self.chatbubbleentity.exteriormodeltoclient = self;
1328                 self.chatbubbleentity.think = ChatBubbleThink;
1329                 self.chatbubbleentity.nextthink = time;
1330                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1331                 setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1332                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1333                 self.chatbubbleentity.model = "";
1334                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1335         }
1336 }
1337
1338
1339 void TeamBubbleThink()
1340 {
1341         self.nextthink = time;
1342         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1343         {
1344                 self.owner.teambubbleentity = world;
1345                 remove(self);
1346                 return;
1347         }
1348 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1349         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1350                 self.model = "";
1351         else
1352                 self.model = self.mdl;
1353
1354 };
1355
1356 float TeamBubble_customizeentityforclient()
1357 {
1358         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1359 }
1360
1361 void UpdateTeamBubble()
1362 {
1363         if (!self.modelindex || !cvar("teamplay"))
1364                 return;
1365         // spawn a teambubble entity if needed
1366         if (!self.teambubbleentity && cvar("teamplay"))
1367         {
1368                 self.teambubbleentity = spawn();
1369                 self.teambubbleentity.owner = self;
1370                 self.teambubbleentity.exteriormodeltoclient = self;
1371                 self.teambubbleentity.think = TeamBubbleThink;
1372                 self.teambubbleentity.nextthink = time;
1373                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1374 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1375                 setorigin(self.teambubbleentity, self.teambubbleentity.origin + '0 0 15' + self.maxs_z * '0 0 1');
1376                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1377                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1378                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1379                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1380                 self.teambubbleentity.effects = EF_LOWPRECISION;
1381         }
1382 }
1383
1384 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1385 // added to the model skins
1386 /*void UpdateColorModHack()
1387 {
1388         local float c;
1389         c = self.clientcolors & 15;
1390         // LordHavoc: only bothering to support white, green, red, yellow, blue
1391              if (teamplay == 0) self.colormod = '0 0 0';
1392         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1393         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1394         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1395         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1396         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1397         else self.colormod = '1 1 1';
1398 };*/
1399
1400 void respawn(void)
1401 {
1402         CopyBody(1);
1403         self.effects |= EF_NODRAW; // prevent another CopyBody
1404         PutClientInServer();
1405 }
1406
1407 /**
1408  * When sv_timeout is used this function returs strings like
1409  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1410  * Called by centerprint functions
1411  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1412  */
1413 string getTimeoutText(float addOneSecond) {
1414         if (!cvar("sv_timeout") || !timeoutStatus)
1415                 return "";
1416
1417         local string retStr;
1418         if (timeoutStatus == 1) {
1419                 if (addOneSecond == 1) {
1420                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1421                 }
1422                 else {
1423                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1424                 }
1425                 return retStr;
1426         }
1427         else if (timeoutStatus == 2) {
1428                 if (addOneSecond) {
1429                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1430                         //don't show messages like "Timeout ends in 0 seconds"...
1431                         if ((remainingTimeoutTime + 1) > 0)
1432                                 return retStr;
1433                         else
1434                                 return "";
1435                 }
1436                 else {
1437                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1438                         //don't show messages like "Timeout ends in 0 seconds"...
1439                         if (remainingTimeoutTime > 0)
1440                                 return retStr;
1441                         else
1442                                 return "";
1443                 }
1444         }
1445         else return "";
1446 }
1447
1448 void player_powerups (void)
1449 {
1450         if (g_minstagib)
1451         {
1452                 if (self.items & IT_STRENGTH)
1453                 {
1454                         if (time > self.strength_finished)
1455                         {
1456                                 if (g_minstagib_invis_alpha > 0)
1457                                 {
1458                                         self.alpha = default_player_alpha;
1459                                         self.exteriorweaponentity.alpha = default_weapon_alpha;
1460                                         self.effects = self.effects | EF_FULLBRIGHT;
1461                                 }
1462                                 else
1463                                 {
1464                                         self.effects -= self.effects & EF_NODRAW;
1465                                 }
1466                                 self.items = self.items - (self.items & IT_STRENGTH);
1467                                 sprint(self, "^3Invisibility has worn off\n");
1468                         }
1469                 }
1470                 else
1471                 {
1472                         if (time < self.strength_finished)
1473                         {
1474                                 if (g_minstagib_invis_alpha > 0)
1475                                 {
1476                                         self.alpha = g_minstagib_invis_alpha;
1477                                         self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1478                                         self.effects -= self.effects & EF_FULLBRIGHT;
1479                                 }
1480                                 else
1481                                 {
1482                                         self.effects = self.effects | EF_NODRAW;
1483                                 }
1484                                 self.items = self.items | IT_STRENGTH;
1485                                 sprint(self, "^3You are invisible\n");
1486                         }
1487                 }
1488
1489                 if (self.items & IT_INVINCIBLE)
1490                 {
1491                         if (time > self.invincible_finished)
1492                         {
1493                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1494                                 sprint(self, "^3Speed has worn off\n");
1495                         }
1496                 }
1497                 else
1498                 {
1499                         if (time < self.invincible_finished)
1500                         {
1501                                 self.items = self.items | IT_INVINCIBLE;
1502                                 sprint(self, "^3You are on speed\n");
1503                         }
1504                 }
1505                 return;
1506         }
1507
1508         self.effects = self.effects - (self.effects & (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT));
1509         if (self.items & IT_STRENGTH)
1510         {
1511                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1512                 if (time > self.strength_finished)
1513                 {
1514                         self.items = self.items - (self.items & IT_STRENGTH);
1515                         sprint(self, "^3Strength has worn off\n");
1516                 }
1517         }
1518         else
1519         {
1520                 if (time < self.strength_finished)
1521                 {
1522                         self.items = self.items | IT_STRENGTH;
1523                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1524                 }
1525         }
1526         if (self.items & IT_INVINCIBLE)
1527         {
1528                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1529                 if (time > self.invincible_finished)
1530                 {
1531                         self.items = self.items - (self.items & IT_INVINCIBLE);
1532                         sprint(self, "^3Shield has worn off\n");
1533                 }
1534         }
1535         else
1536         {
1537                 if (time < self.invincible_finished)
1538                 {
1539                         self.items = self.items | IT_INVINCIBLE;
1540                         sprint(self, "^3Shield surrounds you\n");
1541                 }
1542         }
1543
1544         if (cvar("g_fullbrightplayers"))
1545                 self.effects = self.effects | EF_FULLBRIGHT;
1546
1547         // midair gamemode: damage only while in the air
1548         // if in midair mode, being on ground grants temporary invulnerability
1549         // (this is so that multishot weapon don't clear the ground flag on the
1550         // first damage in the frame, leaving the player vulnerable to the
1551         // remaining hits in the same frame)
1552         if (self.flags & FL_ONGROUND)
1553         if (g_midair)
1554                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1555
1556         if (time > restart_countdown)
1557         if (time < self.spawnshieldtime)
1558                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1559 }
1560
1561 float CalcRegen(float current, float stable, float regenfactor)
1562 {
1563         if(current > stable)
1564                 return current;
1565         else if(current > stable - 0.25) // when close enough, "snap"
1566                 return stable;
1567         else
1568                 return min(stable, current + (stable - current) * regenfactor * frametime);
1569 }
1570
1571 void player_regen (void)
1572 {
1573         float maxh, maxa, limith, limita, max_mod, regen_mod, rot_mod, limit_mod;
1574         maxh = cvar("g_balance_health_stable");
1575         maxa = cvar("g_balance_armor_stable");
1576         limith = cvar("g_balance_health_limit");
1577         limita = cvar("g_balance_armor_limit");
1578
1579         if (g_minstagib || (g_lms && !cvar("g_lms_regenerate")))
1580                 return;
1581
1582         max_mod = regen_mod = rot_mod = limit_mod = 1;
1583
1584         if (self.runes & RUNE_REGEN)
1585         {
1586                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1587                 {
1588                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1589                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1590                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1591                 }
1592                 else
1593                 {
1594                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1595                         max_mod = cvar("g_balance_rune_regen_hpmod");
1596                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1597                 }
1598         }
1599         else if (self.runes & CURSE_VENOM)
1600         {
1601                 max_mod = cvar("g_balance_curse_venom_hpmod");
1602                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1603                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1604                 else
1605                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1606                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1607                 //if (!self.runes & RUNE_REGEN)
1608                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1609         }
1610         maxh = maxh * max_mod;
1611         //maxa = maxa * max_mod;
1612         limith = limith * limit_mod;
1613         limita = limita * limit_mod;
1614
1615         if (self.armorvalue > maxa)
1616         {
1617                 if (time > self.pauserotarmor_finished)
1618                 {
1619                         self.armorvalue = max(maxa, self.armorvalue + (maxa - self.armorvalue) * cvar("g_balance_armor_rot") * frametime);
1620                         self.armorvalue = max(maxa, self.armorvalue - cvar("g_balance_armor_rotlinear") * frametime);
1621                 }
1622         }
1623         else if (self.armorvalue < maxa)
1624         {
1625                 if (time > self.pauseregen_finished)
1626                 {
1627                         self.armorvalue = CalcRegen(self.armorvalue, maxa, cvar("g_balance_armor_regen"));
1628                         self.armorvalue = min(maxa, self.armorvalue + cvar("g_balance_armor_regenlinear") * frametime);
1629                 }
1630         }
1631         if (self.health > maxh)
1632         {
1633                 if (time > self.pauserothealth_finished)
1634                 {
1635                         self.health = max(maxh, self.health + (maxh - self.health) * rot_mod*cvar("g_balance_health_rot") * frametime);
1636                         self.health = max(maxh, self.health - rot_mod*cvar("g_balance_health_rotlinear") * frametime);
1637                 }
1638         }
1639         else if (self.health < maxh)
1640         {
1641                 if (time > self.pauseregen_finished)
1642                 {
1643                         self.health = CalcRegen(self.health, maxh, regen_mod * cvar("g_balance_health_regen"));
1644                         self.health = min(maxh, self.health + regen_mod*cvar("g_balance_health_regenlinear") * frametime);
1645                 }
1646         }
1647
1648         if (self.health > limith)
1649                 self.health = limith;
1650         if (self.armorvalue > limita)
1651                 self.armorvalue = limita;
1652
1653         // if player rotted to death...  die!
1654         if(self.health < 1)
1655                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1656 }
1657
1658 /*
1659 ======================
1660 spectate mode routines
1661 ======================
1662 */
1663 void SpectateCopy(entity spectatee) {
1664         self.armortype = spectatee.armortype;
1665         self.armorvalue = spectatee.armorvalue;
1666         self.currentammo = spectatee.currentammo;
1667         self.effects = spectatee.effects;
1668         self.health = spectatee.health;
1669         self.impulse = 0;
1670         self.items = spectatee.items;
1671         self.punchangle = spectatee.punchangle;
1672         self.view_ofs = spectatee.view_ofs;
1673         self.v_angle = spectatee.v_angle;
1674         self.velocity = spectatee.velocity;
1675         self.dmg_take = spectatee.dmg_take;
1676         self.dmg_save = spectatee.dmg_save;
1677         self.dmg_inflictor = spectatee.dmg_inflictor;
1678         self.angles = spectatee.v_angle;
1679         self.fixangle = TRUE;
1680         setorigin(self, spectatee.origin);
1681         setsize(self, spectatee.mins, spectatee.maxs);
1682 }
1683
1684 float SpectateUpdate() {
1685         if(!self.enemy)
1686                 return 0;
1687
1688         if (self == self.enemy)
1689                 return 0;
1690         
1691         if(self.enemy.flags & FL_NOTARGET)
1692                 return 0;
1693
1694         SpectateCopy(self.enemy);
1695
1696         return 1;
1697 }
1698
1699 float SpectateNext() {
1700         other = find(self.enemy, classname, "player");
1701         if (!other) {
1702                 other = find(other, classname, "player");
1703         }
1704         if (other) {
1705                 self.enemy = other;
1706         }
1707         if(self.enemy.classname == "player") {
1708                 msg_entity = self;
1709                 WriteByte(MSG_ONE, SVC_SETVIEW);
1710                 WriteEntity(MSG_ONE, self.enemy);
1711                 self.wantswelcomemessage = 1;
1712                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
1713                 if(!SpectateUpdate())
1714                         PutObserverInServer();
1715                 return 1;
1716         } else {
1717                 return 0;
1718         }
1719 }
1720
1721 /*
1722 =============
1723 ShowRespawnCountdown()
1724
1725 Update a respawn countdown display.
1726 =============
1727 */
1728 void ShowRespawnCountdown()
1729 {
1730         float number;
1731         if(self.deadflag == DEAD_NO) // just respawned?
1732                 return;
1733         else
1734         {
1735                 number = ceil(self.death_time - time);
1736                 if(number <= 0)
1737                         return;
1738                 if(number <= self.respawn_countdown)
1739                 {
1740                         self.respawn_countdown = number - 1;
1741                         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
1742                                 announce(self, strcat("announcer/robotic/", ftos(number), ".ogg"));
1743                 }
1744         }
1745 }
1746
1747 void LeaveSpectatorMode()
1748 {
1749         if(isJoinAllowed()) {
1750                 if(!cvar("teamplay") || cvar("g_campaign") || cvar("g_balance_teams")) {
1751                         self.classname = "player";
1752                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1753                                 JoinBestTeam(self, FALSE, TRUE);
1754                         if(cvar("g_campaign"))
1755                                 campaign_bots_may_start = 1;
1756                         PutClientInServer();
1757                         if(!(self.flags & FL_NOTARGET))
1758                                 bprint ("^4", self.netname, "^4 is playing now\n");
1759                         centerprint(self,"");
1760                         return;
1761                 } else {
1762                         stuffcmd(self,"menu_showteamselect\n");
1763                         return;
1764                 }
1765         }
1766         else {
1767                 //player may not join because of g_maxplayers is set
1768                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
1769         }
1770 }
1771
1772 /**
1773  * Determines whether the player is allowed to join. This depends on cvar
1774  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
1775  * it checks whether the number of currently playing players exceeds g_maxplayers.
1776  * @return bool TRUE if the player is allowed to join, false otherwise
1777  */
1778 float isJoinAllowed() {
1779         if (!cvar("g_maxplayers"))
1780                 return TRUE;
1781
1782         local entity e;
1783         local float currentlyPlaying;
1784         FOR_EACH_REALPLAYER(e) {
1785                 if(e.classname == "player")
1786                         currentlyPlaying += 1;
1787         }
1788         if(currentlyPlaying < cvar("g_maxplayers"))
1789                 return TRUE;
1790
1791         return FALSE;
1792 }
1793
1794 /**
1795  * Checks whether the client is an observer or spectator, if so, he will get kicked after
1796  * g_maxplayers_spectator_blocktime seconds
1797  */
1798 void checkSpectatorBlock() {
1799         if(self.classname == "spectator" || self.classname == "observer") {
1800                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
1801                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
1802                         dropclient(self);
1803                 }
1804         }
1805 }
1806
1807 float vercmp_recursive(string v1, string v2)
1808 {
1809         float dot1, dot2;
1810         string s1, s2;
1811         float r;
1812
1813         dot1 = strstrofs(v1, ".", 0);
1814         dot2 = strstrofs(v2, ".", 0);
1815         if(dot1 == -1)
1816                 s1 = v1;
1817         else
1818                 s1 = substring(v1, 0, dot1);
1819         if(dot2 == -1)
1820                 s2 = v2;
1821         else
1822                 s2 = substring(v2, 0, dot2);
1823
1824         r = stof(s1) - stof(s2);
1825         if(r != 0)
1826                 return r;
1827
1828         r = strcasecmp(s1, s2);
1829         if(r != 0)
1830                 return r;
1831
1832         if(dot1 == -1)
1833                 if(dot2 == -1)
1834                         return 0;
1835                 else
1836                         return -1;
1837         else
1838                 if(dot2 == -1)
1839                         return 1;
1840                 else
1841                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
1842 }
1843
1844 float vercmp(string v1, string v2)
1845 {
1846         if(strcasecmp(v1, v2) == 0) // early out check
1847                 return 0;
1848         return vercmp_recursive(v1, v2);
1849 }
1850
1851 void ObserverThink()
1852 {
1853         if (self.flags & FL_JUMPRELEASED) {
1854                 if (self.BUTTON_JUMP && !self.version_mismatch) {
1855                         self.welcomemessage_time = 0;
1856                         self.flags = self.flags - FL_JUMPRELEASED;
1857                         LeaveSpectatorMode();
1858                         return;
1859                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
1860                         self.welcomemessage_time = 0;
1861                         self.flags = self.flags - FL_JUMPRELEASED;
1862                         if(SpectateNext() == 1) {
1863                                 self.classname = "spectator";
1864                         }
1865                 }
1866         } else {
1867                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
1868                         self.flags = self.flags | FL_JUMPRELEASED;
1869                 }
1870         }
1871         if(self.BUTTON_ZOOM)
1872                 self.wantswelcomemessage = 0;
1873         if(self.wantswelcomemessage)
1874                 PrintWelcomeMessage(self);
1875 }
1876
1877 void SpectatorThink()
1878 {
1879         if (self.flags & FL_JUMPRELEASED) {
1880                 if (self.BUTTON_JUMP && !self.version_mismatch) {
1881                         self.welcomemessage_time = 0;
1882                         self.flags = self.flags - FL_JUMPRELEASED;
1883                         LeaveSpectatorMode();
1884                         return;
1885                 } else if(self.BUTTON_ATCK) {
1886                         self.welcomemessage_time = 0;
1887                         self.flags = self.flags - FL_JUMPRELEASED;
1888                         if(SpectateNext() == 1) {
1889                                 self.classname = "spectator";
1890                         } else {
1891                                 self.classname = "observer";
1892                                 PutClientInServer();
1893                         }
1894                 } else if (self.BUTTON_ATCK2) {
1895                         self.welcomemessage_time = 0;
1896                         self.flags = self.flags - FL_JUMPRELEASED;
1897                         self.classname = "observer";
1898                         PutClientInServer();
1899                 } else {
1900                         if(!SpectateUpdate())
1901                                 PutObserverInServer();
1902                 }
1903         } else {
1904                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
1905                         self.flags = self.flags | FL_JUMPRELEASED;
1906                 }
1907         }
1908         if(self.BUTTON_ZOOM)
1909                 self.wantswelcomemessage = 0;
1910         if(self.wantswelcomemessage)
1911                 PrintWelcomeMessage(self);
1912         self.flags = self.flags | FL_CLIENT | FL_NOTARGET;
1913 }
1914
1915 /*
1916 =============
1917 PlayerPreThink
1918
1919 Called every frame for each client before the physics are run
1920 =============
1921 */
1922 void() ctf_setstatus;
1923 .float vote_nagtime;
1924 .float spectatee_status;
1925 void PlayerPreThink (void)
1926 {
1927         self.stat_sys_ticrate = cvar("sys_ticrate");
1928         if(blockSpectators)
1929                 checkSpectatorBlock();
1930         
1931         if(self.netname_previous != self.netname)
1932         {
1933                 if(cvar("sv_eventlog"))
1934                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname), TRUE);
1935                 if(self.netname_previous)
1936                         strunzone(self.netname_previous);
1937                 self.netname_previous = strzone(self.netname);
1938         }
1939
1940         // version nagging
1941         if(self.version_nagtime)
1942                 if(self.cvar_g_nexuizversion)
1943                         if(time > self.version_nagtime)
1944                         {
1945                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
1946                                 {
1947                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
1948                                         {
1949                                                 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");
1950                                                 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"));
1951                                         }
1952                                         else
1953                                         {
1954                                                 float r;
1955                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
1956                                                 if(r < 0)
1957                                                 {
1958                                                         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");
1959                                                         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"));
1960                                                 }
1961                                                 else if(r > 0)
1962                                                 {
1963                                                         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");
1964                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
1965                                                 }
1966                                         }
1967                                 }
1968                                 self.version_nagtime = 0;
1969                         }
1970
1971         // vote nagging
1972         if(self.cvar_scr_centertime)
1973                 if(time > self.vote_nagtime)
1974                 {
1975                         VoteNag();
1976                         self.vote_nagtime = time + self.cvar_scr_centertime * 0.6;
1977                 }
1978
1979         // GOD MODE info
1980         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
1981         {
1982                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
1983                 self.max_armorvalue = 0;
1984         }
1985
1986         if(frametime)
1987                 antilag_record(self);
1988
1989         if(self.classname == "player") {
1990 //              if(self.netname == "Wazat")
1991 //                      bprint(self.classname, "\n");
1992
1993                 CheckRules_Player();
1994
1995                 if(self.BUTTON_INFO)
1996                         PrintWelcomeMessage(self);
1997
1998                 if(g_lms || !cvar("sv_spectate"))
1999                 if((time - self.jointime) <= cvar("welcome_message_time"))
2000                         PrintWelcomeMessage(self);
2001
2002                 if (intermission_running)
2003                 {
2004                         IntermissionThink ();   // otherwise a button could be missed between
2005                         return;                                 // the think tics
2006                 }
2007
2008                 if(self.teleport_time)
2009                 if(time > self.teleport_time)
2010                 {
2011                         self.teleport_time = 0;
2012                         self.effects = self.effects - (self.effects & EF_NODRAW);
2013                         if(self.weaponentity)
2014                                 self.weaponentity.flags = self.weaponentity.flags - (self.weaponentity.flags & EF_NODRAW);
2015                 }
2016
2017                 Nixnex_GiveCurrentWeapon();
2018
2019                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2020                         UpdateSelectedPlayer();
2021
2022                 //don't allow the player to turn around while game is paused!
2023                 if(timeoutStatus == 2) {
2024                         self.v_angle = self.lastV_angle;
2025                         self.angles = self.lastV_angle;
2026                         self.fixangle = TRUE;
2027                 }
2028
2029                 if (self.deadflag != DEAD_NO)
2030                 {
2031                         float button_pressed, force_respawn;
2032                         player_anim();
2033                         button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2034                         force_respawn = (g_lms || cvar("g_forced_respawn"));
2035                         if (self.deadflag == DEAD_DYING)
2036                         {
2037                                 if(force_respawn)
2038                                         self.deadflag = DEAD_RESPAWNING;
2039                                 else if(!button_pressed)
2040                                         self.deadflag = DEAD_DEAD;
2041                         }
2042                         else if (self.deadflag == DEAD_DEAD)
2043                         {
2044                                 if(button_pressed)
2045                                         self.deadflag = DEAD_RESPAWNABLE;
2046                         }
2047                         else if (self.deadflag == DEAD_RESPAWNABLE)
2048                         {
2049                                 if(!button_pressed)
2050                                         self.deadflag = DEAD_RESPAWNING;
2051                         }
2052                         else if (self.deadflag == DEAD_RESPAWNING)
2053                         {
2054                                 if(time > self.death_time)
2055                                 {
2056                                         self.death_time = time + 1; // only retry once a second
2057                                         respawn();
2058                                 }
2059                         }
2060                         ShowRespawnCountdown();
2061                         return;
2062                 }
2063
2064                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2065                 {
2066                         vector dist;
2067
2068                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2069                         dist = self.oldorigin - self.origin;
2070                         dist_z = 0;
2071                         self.lms_traveled_distance += fabs(vlen(dist));
2072
2073                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < restart_countdown))
2074                         {
2075                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2076                                 self.lms_traveled_distance = 0;
2077                         }
2078
2079                         if(time > self.lms_nextcheck)
2080                         {
2081                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2082                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2083                                 {
2084                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2085                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2086                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2087                                         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');
2088                                 }
2089                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2090                                 self.lms_traveled_distance = 0;
2091                         }
2092                 }
2093
2094                 if (self.BUTTON_CROUCH && !self.hook.state)
2095                 {
2096                         if (!self.crouch)
2097                         {
2098                                 self.crouch = TRUE;
2099                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2100                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2101                                 player_setanim(self.anim_duck, FALSE, TRUE, TRUE);
2102                         }
2103                 }
2104                 else
2105                 {
2106                         if (self.crouch)
2107                         {
2108                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2109                                 if (!trace_startsolid)
2110                                 {
2111                                         self.crouch = FALSE;
2112                                         self.view_ofs = PL_VIEW_OFS;
2113                                         setsize (self, PL_MIN, PL_MAX);
2114                                 }
2115                         }
2116                 }
2117
2118                 FixPlayermodel();
2119
2120                 GrapplingHookFrame();
2121
2122                 W_WeaponFrame();
2123
2124                 player_powerups();
2125                 player_regen();
2126                 player_anim();
2127
2128                 if (g_minstagib)
2129                         minstagib_ammocheck();
2130
2131                 ctf_setstatus();
2132                 kh_setstatus();
2133
2134                 //self.angles_y=self.v_angle_y + 90;   // temp
2135
2136                 //if (TetrisPreFrame()) return;
2137         } else if(gameover) {
2138                 if (intermission_running)
2139                         IntermissionThink ();   // otherwise a button could be missed between
2140                 return;
2141         } else if(self.classname == "observer") {
2142                 ObserverThink();
2143         } else if(self.classname == "spectator") {
2144                 SpectatorThink();
2145         }
2146
2147         float oldspectatee_status;
2148         oldspectatee_status = self.spectatee_status;
2149         if(self.classname == "spectator")
2150                 self.spectatee_status = num_for_edict(self.enemy);
2151         else if(self.classname == "observer")
2152                 self.spectatee_status = num_for_edict(self);
2153         else
2154                 self.spectatee_status = 0;
2155         if(self.spectatee_status != oldspectatee_status)
2156         {
2157                 msg_entity = self;
2158                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2159                 WriteByte(MSG_ONE, TE_CSQC_SPECTATING);
2160                 WriteByte(MSG_ONE, self.spectatee_status);
2161                 if(g_race)
2162                         race_InitSpectator();
2163         }
2164 }
2165
2166
2167 /*
2168 =============
2169 PlayerPostThink
2170
2171 Called every frame for each client after the physics are run
2172 =============
2173 */
2174 .float idlekick_lasttimeleft;
2175 .float race_penalty;
2176 .float race_penalty_nagged;
2177 void PlayerPostThink (void)
2178 {
2179         // Savage: Check for nameless players
2180         if (strlen(self.netname) < 1) {
2181                 self.netname = "Player";
2182                 stuffcmd(self, "seta _cl_name Player\n");
2183         }
2184
2185         if(sv_maxidle)
2186         {
2187                 float timeleft;
2188                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2189                 if(timeleft <= 0)
2190                 {
2191                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2192                         announce(self, "announcer/robotic/terminated.ogg");
2193                         dropclient(self);
2194                         return;
2195                 }
2196                 else if(timeleft <= 10)
2197                 {
2198                         if(timeleft != self.idlekick_lasttimeleft)
2199                         {
2200                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2201                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".ogg"));
2202                         }
2203                 }
2204                 else
2205                 {
2206                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2207                 }
2208                 self.idlekick_lasttimeleft = timeleft;
2209         }
2210
2211         if(self.classname == "player") {
2212                 CheckRules_Player();
2213                 UpdateChatBubble();
2214                 UpdateTeamBubble();
2215                 if (self.impulse)
2216                         ImpulseCommands();
2217                 if (intermission_running)
2218                         return;         // intermission or finale
2219
2220                 //PrintWelcomeMessage(self);
2221                 //if (TetrisPostFrame()) return;
2222
2223                 // restart countdown
2224                 if (restart_countdown) {
2225                         if(time < restart_countdown) {
2226                                 if (!cvar("sv_ready_restart_after_countdown"))
2227                                 {
2228                                         if(self.movement != '0 0 0' && g_race && !g_race_qualifying)
2229                                         {
2230                                                 if(time < restart_countdown - 2)
2231                                                 {
2232                                                         if(!self.race_penalty_nagged)
2233                                                         {
2234                                                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, "^1DO NOT MOVE DURING THE COUNTDOWN.");
2235                                                                 self.race_penalty_nagged = 1;
2236                                                         }
2237                                                 }
2238                                                 else if(!self.race_penalty)
2239                                                 {
2240                                                         centerprint_atprio(self, CENTERPRIO_IDLEKICK, "^1FIVE SECONDS PENALTY.");
2241                                                         self.race_penalty = time + 5;
2242                                                 }
2243                                         }
2244                                         self.movetype = MOVETYPE_NONE;          
2245                                         self.velocity = '0 0 0';
2246                                         self.avelocity = '0 0 0';
2247                                         self.movement = '0 0 0';
2248                                 }
2249                         }
2250                         else if (time < self.race_penalty)
2251                         {
2252                                 self.movetype = MOVETYPE_NONE;          
2253                                 self.velocity = '0 0 0';
2254                                 self.avelocity = '0 0 0';
2255                                 self.movement = '0 0 0';
2256                         }
2257                         else
2258                         {
2259                                 //allow the player to move again if sv_ready_restart_after_countdown is not used and countdown is over
2260                                 if (!cvar("sv_ready_restart_after_countdown"))
2261                                 {
2262                                         if(self.movetype == MOVETYPE_NONE)
2263                                         {
2264                                                 self.movetype = MOVETYPE_WALK;
2265                                         }
2266                                         self.race_penalty = 0;
2267                                         self.race_penalty_nagged = 0;
2268                                 }
2269                         }
2270                 }
2271                 
2272         } else if (self.classname == "observer") {
2273                 //do nothing
2274         } else if (self.classname == "spectator") {
2275                 //do nothing
2276         }
2277
2278         /*
2279         float i;
2280         for(i = 0; i < 1000; ++i)
2281         {
2282                 vector end;
2283                 end = self.origin + '0 0 1024' + 512 * randomvec();
2284                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2285                 if(trace_fraction < 1)
2286                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2287                 {
2288                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2289                         break;
2290                 }
2291         }
2292         */
2293
2294         Arena_Warmup();
2295 }