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