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