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