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