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