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