]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/cl_client.qc
Merge branch 'master' into Mario/mutator_minstagib
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_client.qc
1 void race_send_recordtime(float msg);
2 void race_SendRankings(float pos, float prevpos, float del, float msg);
3
4 void send_CSQC_teamnagger() {
5         WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
6         WriteByte(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
7 }
8
9 float ClientData_Send(entity to, float sf)
10 {
11         if(to != self.owner)
12         {
13                 error("wtf");
14                 return FALSE;
15         }
16
17         entity e;
18
19         e = to;
20         if(to.classname == "spectator")
21                 e = to.enemy;
22
23         sf = 0;
24
25         if(e.race_completed)
26                 sf |= 1; // forced scoreboard
27         if(to.spectatee_status)
28                 sf |= 2; // spectator ent number follows
29         if(e.zoomstate)
30                 sf |= 4; // zoomed
31         if(e.porto_v_angle_held)
32                 sf |= 8; // angles held
33
34         WriteByte(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
35         WriteByte(MSG_ENTITY, sf);
36
37         if(sf & 2)
38                 WriteByte(MSG_ENTITY, to.spectatee_status);
39
40         if(sf & 8)
41         {
42                 WriteAngle(MSG_ENTITY, e.v_angle_x);
43                 WriteAngle(MSG_ENTITY, e.v_angle_y);
44         }
45
46         return TRUE;
47 }
48
49 void ClientData_Attach()
50 {
51         Net_LinkEntity(self.clientdata = spawn(), FALSE, 0, ClientData_Send);
52         self.clientdata.drawonlytoclient = self;
53         self.clientdata.owner = self;
54 }
55
56 void ClientData_Detach()
57 {
58         remove(self.clientdata);
59         self.clientdata = world;
60 }
61
62 void ClientData_Touch(entity e)
63 {
64         e.clientdata.SendFlags = 1;
65
66         // make it spectatable
67         entity e2;
68         FOR_EACH_REALCLIENT(e2)
69         {
70                 if(e2 != e)
71                         if(e2.classname == "spectator")
72                                 if(e2.enemy == e)
73                                         e2.clientdata.SendFlags = 1;
74         }
75 }
76
77
78 .vector spawnpoint_score;
79 .string netname_previous;
80
81 void spawnfunc_info_player_survivor (void)
82 {
83         spawnfunc_info_player_deathmatch();
84 }
85
86 void spawnfunc_info_player_start (void)
87 {
88         spawnfunc_info_player_deathmatch();
89 }
90
91 void spawnfunc_info_player_deathmatch (void)
92 {
93         self.classname = "info_player_deathmatch";
94         relocate_spawnpoint();
95 }
96
97 void spawnpoint_use()
98 {
99         if(teamplay)
100         if(have_team_spawns > 0)
101         {
102                 self.team = activator.team;
103                 some_spawn_has_been_used = 1;
104         }
105 }
106
107 // Returns:
108 //   _x: prio (-1 if unusable)
109 //   _y: weight
110 vector Spawn_Score(entity spot, float mindist, float teamcheck)
111 {
112         float shortest, thisdist;
113         float prio;
114         entity player;
115
116         prio = 0;
117
118         // filter out spots for the wrong team
119         if(teamcheck >= 0)
120                 if(spot.team != teamcheck)
121                         return '-1 0 0';
122
123         if(race_spawns)
124                 if(spot.target == "")
125                         return '-1 0 0';
126
127         if(clienttype(self) == CLIENTTYPE_REAL)
128         {
129                 if(spot.restriction == 1)
130                         return '-1 0 0';
131         }
132         else
133         {
134                 if(spot.restriction == 2)
135                         return '-1 0 0';
136         }
137
138         shortest = vlen(world.maxs - world.mins);
139         FOR_EACH_PLAYER(player) if (player != self)
140         {
141                 thisdist = vlen(player.origin - spot.origin);
142                 if (thisdist < shortest)
143                         shortest = thisdist;
144         }
145         if(shortest > mindist)
146                 prio += SPAWN_PRIO_GOOD_DISTANCE;
147
148         spawn_score = prio * '1 0 0' + shortest * '0 1 0';
149         spawn_spot = spot;
150
151         // filter out spots for assault
152         if(spot.target != "") {
153                 entity ent;
154                 float found;
155
156                 found = 0;
157                 for(ent = world; (ent = find(ent, targetname, spot.target)); )
158                 {
159                         ++found;
160                         if(ent.spawn_evalfunc)
161                         {
162                                 entity oldself = self;
163                                 self = ent;
164                                 spawn_score = ent.spawn_evalfunc(oldself, spot, spawn_score);
165                                 self = oldself;
166                                 if(spawn_score_x < 0)
167                                         return spawn_score;
168                         }
169                 }
170
171                 if(!found)
172                 {
173                         dprint("WARNING: spawnpoint at ", vtos(spot.origin), " could not find its target ", spot.target, "\n");
174                         return '-1 0 0';
175                 }
176         }
177
178         MUTATOR_CALLHOOK(Spawn_Score);
179         return spawn_score;
180 }
181
182 void Spawn_ScoreAll(entity firstspot, float mindist, float teamcheck)
183 {
184         entity spot;
185         for(spot = firstspot; spot; spot = spot.chain)
186                 spot.spawnpoint_score = Spawn_Score(spot, mindist, teamcheck);
187 }
188
189 entity Spawn_FilterOutBadSpots(entity firstspot, float mindist, float teamcheck)
190 {
191         entity spot, spotlist, spotlistend;
192
193         spotlist = world;
194         spotlistend = world;
195
196         Spawn_ScoreAll(firstspot, mindist, teamcheck);
197
198         for(spot = firstspot; spot; spot = spot.chain)
199         {
200                 if(spot.spawnpoint_score_x >= 0) // spawning allowed here
201                 {
202                         if(spotlistend)
203                                 spotlistend.chain = spot;
204                         spotlistend = spot;
205                         if(!spotlist)
206                                 spotlist = spot;
207                 }
208         }
209         if(spotlistend)
210                 spotlistend.chain = world;
211
212         return spotlist;
213 }
214
215 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
216 {
217         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
218         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
219         entity spot;
220
221         RandomSelection_Init();
222         for(spot = firstspot; spot; spot = spot.chain)
223                 RandomSelection_Add(spot, 0, string_null, pow(bound(lower, spot.spawnpoint_score_y, upper), exponent) * spot.cnt, (spot.spawnpoint_score_y >= lower) * 0.5 + spot.spawnpoint_score_x);
224
225         return RandomSelection_chosen_ent;
226 }
227
228 /*
229 =============
230 SelectSpawnPoint
231
232 Finds a point to respawn
233 =============
234 */
235 entity SelectSpawnPoint (float anypoint)
236 {
237         float teamcheck;
238         entity spot, firstspot;
239
240         spot = find (world, classname, "testplayerstart");
241         if (spot)
242                 return spot;
243
244         if(anypoint || autocvar_g_spawn_useallspawns)
245                 teamcheck = -1;
246         else if(have_team_spawns > 0)
247         {
248                 if(have_team_spawns_forteam[self.team] == 0)
249                 {
250                         // we request a spawn for a team, and we have team
251                         // spawns, but that team has no spawns?
252                         if(have_team_spawns_forteam[0])
253                                 // try noteam spawns
254                                 teamcheck = 0;
255                         else
256                                 // if not, any spawn has to do
257                                 teamcheck = -1;
258                 }
259                 else
260                         teamcheck = self.team; // MUST be team
261         }
262         else if(have_team_spawns == 0 && have_team_spawns_forteam[0])
263                 teamcheck = 0; // MUST be noteam
264         else
265                 teamcheck = -1;
266                 // if we get here, we either require team spawns but have none, or we require non-team spawns and have none; use any spawn then
267
268
269         // get the entire list of spots
270         firstspot = findchain(classname, "info_player_deathmatch");
271         // filter out the bad ones
272         // (note this returns the original list if none survived)
273         if(anypoint)
274         {
275                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
276         }
277         else
278         {
279                 float mindist;
280                 if (arena_roundbased && !g_ca)
281                         mindist = 800;
282                 else
283                         mindist = 100;
284                 firstspot = Spawn_FilterOutBadSpots(firstspot, mindist, teamcheck);
285
286                 // there is 50/50 chance of choosing a random spot or the furthest spot
287                 // (this means that roughly every other spawn will be furthest, so you
288                 // usually won't get fragged at spawn twice in a row)
289                 if (random() > autocvar_g_spawn_furthest)
290                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
291                 else
292                         spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
293         }
294
295         if (!spot)
296         {
297                 if(autocvar_spawn_debug)
298                         GotoNextMap(0);
299                 else
300                 {
301                         if(some_spawn_has_been_used)
302                                 return world; // team can't spawn any more, because of actions of other team
303                         else
304                                 error("Cannot find a spawn point - please fix the map!");
305                 }
306         }
307
308         return spot;
309 }
310
311 /*
312 =============
313 CheckPlayerModel
314
315 Checks if the argument string can be a valid playermodel.
316 Returns a valid one in doubt.
317 =============
318 */
319 string FallbackPlayerModel;
320 string CheckPlayerModel(string plyermodel) {
321         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
322         {
323                 // note: we cannot summon Don Strunzone here, some player may
324                 // still have the model string set. In case anyone manages how
325                 // to change a cvar default, we'll have a small leak here.
326                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
327         }
328         // only in right path
329         if( substring(plyermodel,0,14) != "models/player/")
330                 return FallbackPlayerModel;
331         // only good file extensions
332         if(substring(plyermodel,-4,4) != ".zym")
333         if(substring(plyermodel,-4,4) != ".dpm")
334         if(substring(plyermodel,-4,4) != ".iqm")
335         if(substring(plyermodel,-4,4) != ".md3")
336         if(substring(plyermodel,-4,4) != ".psk")
337                 return FallbackPlayerModel;
338         // forbid the LOD models
339         if(substring(plyermodel, -9,5) == "_lod1")
340                 return FallbackPlayerModel;
341         if(substring(plyermodel, -9,5) == "_lod2")
342                 return FallbackPlayerModel;
343         if(plyermodel != strtolower(plyermodel))
344                 return FallbackPlayerModel;
345         // also, restrict to server models
346         if(autocvar_sv_servermodelsonly)
347         {
348                 if(!fexists(plyermodel))
349                         return FallbackPlayerModel;
350         }
351         return plyermodel;
352 }
353
354 void setplayermodel(entity e, string modelname)
355 {
356         precache_model(modelname);
357         setmodel(e, modelname);
358         player_setupanimsformodel();
359         UpdatePlayerSounds();
360 }
361
362 /*
363 =============
364 PutObserverInServer
365
366 putting a client as observer in the server
367 =============
368 */
369 void FixPlayermodel();
370 void PutObserverInServer (void)
371 {
372         entity  spot;
373     self.hud = HUD_NORMAL;
374         race_PreSpawnObserver();
375
376         spot = SelectSpawnPoint (TRUE);
377         if(!spot)
378                 error("No spawnpoints for observers?!?\n");
379         RemoveGrapplingHook(self); // Wazat's Grappling Hook
380
381         if(clienttype(self) == CLIENTTYPE_REAL)
382         {
383                 msg_entity = self;
384                 WriteByte(MSG_ONE, SVC_SETVIEW);
385                 WriteEntity(MSG_ONE, self);
386         }
387
388         MUTATOR_CALLHOOK(MakePlayerObserver);
389
390         Portal_ClearAll(self);
391         
392         if(self.alivetime)
393         {
394                 if(!inWarmupStage)
395                         PlayerStats_Event(self, PLAYERSTATS_ALIVETIME, time - self.alivetime);
396                 self.alivetime = 0;
397         }
398
399         if(self.vehicle)
400                 vehicles_exit(VHEF_RELESE);         
401
402         WaypointSprite_PlayerDead();
403
404         if not(g_ca)  // don't reset teams when moving a ca player to the spectators
405                 self.team = -1;  // move this as it is needed to log the player spectating in eventlog
406
407         if(self.killcount != -666) {
408                 if(g_lms) {
409                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0 && self.lms_spectate_warning != 2)
410                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_LMS_NOLIVES, self.netname);
411                         else
412                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_LMS_FORFEIT, self.netname);
413                 } else { Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_SPECTATE, self.netname); }
414
415                 if(self.just_joined == FALSE) {
416                         LogTeamchange(self.playerid, -1, 4);
417                 } else
418                         self.just_joined = FALSE;
419         }
420
421         PlayerScore_Clear(self); // clear scores when needed
422
423         accuracy_resend(self);
424
425         self.spectatortime = time;
426         
427         self.classname = "observer";
428         self.iscreature = FALSE;
429         self.teleportable = TELEPORT_SIMPLE;
430         self.damagedbycontents = FALSE;
431         self.health = -666;
432         self.takedamage = DAMAGE_NO;
433         self.solid = SOLID_NOT;
434         self.movetype = MOVETYPE_FLY_WORLDONLY; // user preference is controlled by playerprethink
435         self.flags = FL_CLIENT | FL_NOTARGET;
436         self.armorvalue = 666;
437         self.effects = 0;
438         self.armorvalue = autocvar_g_balance_armor_start;
439         self.pauserotarmor_finished = 0;
440         self.pauserothealth_finished = 0;
441         self.pauseregen_finished = 0;
442         self.damageforcescale = 0;
443         self.death_time = 0;
444         self.respawn_time = 0;
445         self.alpha = 0;
446         self.scale = 0;
447         self.fade_time = 0;
448         self.pain_frame = 0;
449         self.pain_finished = 0;
450         self.strength_finished = 0;
451         self.invincible_finished = 0;
452         self.superweapons_finished = 0;
453         self.pushltime = 0;
454         self.istypefrag = 0;
455         self.think = func_null;
456         self.nextthink = 0;
457         self.hook_time = 0;
458         self.deadflag = DEAD_NO;
459         self.angles = spot.angles;
460         self.angles_z = 0;
461         self.fixangle = TRUE;
462         self.crouch = FALSE;
463
464         setorigin (self, (spot.origin + PL_VIEW_OFS)); // offset it so that the spectator spawns higher off the ground, looks better this way
465         self.prevorigin = self.origin;
466         self.items = 0;
467         WEPSET_CLEAR_E(self);
468         self.model = "";
469         FixPlayermodel();
470         setmodel(self, "null");
471         self.drawonlytoclient = self;
472
473         setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX); // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
474         self.view_ofs = '0 0 0'; // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
475
476         self.weapon = 0;
477         self.weaponname = "";
478         self.switchingweapon = 0;
479         self.weaponmodel = "";
480         self.weaponentity = world;
481         self.exteriorweaponentity = world;
482         self.killcount = -666;
483         self.velocity = '0 0 0';
484         self.avelocity = '0 0 0';
485         self.punchangle = '0 0 0';
486         self.punchvector = '0 0 0';
487         self.oldvelocity = self.velocity;
488         self.fire_endtime = -1;
489
490         if(g_arena)
491         {
492                 if(self.version_mismatch)
493                 {
494                         self.frags = FRAGS_SPECTATOR;
495                         Spawnqueue_Unmark(self);
496                         Spawnqueue_Remove(self);
497                 }
498                 else
499                 {
500                         self.frags = FRAGS_LMS_LOSER;
501                         Spawnqueue_Insert(self);
502                 }
503         }
504         else if(g_lms)
505         {
506                 // Only if the player cannot play at all
507                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
508                         self.frags = FRAGS_SPECTATOR;
509                 else
510                         self.frags = FRAGS_LMS_LOSER;
511         }
512         else if(g_ca)
513         {
514                 if(self.caplayer)
515                         self.frags = FRAGS_LMS_LOSER;
516                 else
517                         self.frags = FRAGS_SPECTATOR;
518         }
519         else if((g_race && g_race_qualifying) || g_cts)
520         {
521                 if(PlayerScore_Add(self, SP_RACE_FASTEST, 0))
522                         self.frags = FRAGS_LMS_LOSER;
523                 else
524                         self.frags = FRAGS_SPECTATOR;
525         }
526         else
527                 self.frags = FRAGS_SPECTATOR;
528 }
529
530 .float model_randomizer;
531 void FixPlayermodel()
532 {
533         string defaultmodel;
534         float defaultskin, chmdl, oldskin, n, i;
535         vector m1, m2;
536
537         defaultmodel = "";
538         defaultskin = 0;
539         chmdl = FALSE;
540
541         if(autocvar_sv_defaultcharacter == 1)
542         {
543                 if(teamplay)
544                 {
545                         string s;
546                         s = Team_ColorName_Lower(self.team);
547                         if(s != "neutral")
548                         {
549                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
550                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
551                         }
552                 }
553
554                 if(defaultmodel == "")
555                 {
556                         defaultmodel = autocvar_sv_defaultplayermodel;
557                         defaultskin = autocvar_sv_defaultplayerskin;
558                 }
559
560                 n = tokenize_console(defaultmodel);
561                 if(n > 0)
562                         defaultmodel = argv(floor(n * self.model_randomizer));
563
564                 i = strstrofs(defaultmodel, ":", 0);
565                 if(i >= 0)
566                 {
567                         defaultskin = stof(substring(defaultmodel, i+1, -1));
568                         defaultmodel = substring(defaultmodel, 0, i);
569                 }
570         }
571
572         if(defaultmodel != "")
573         {
574                 if (defaultmodel != self.model)
575                 {
576                         m1 = self.mins;
577                         m2 = self.maxs;
578                         setplayermodel (self, defaultmodel);
579                         setsize (self, m1, m2);
580                         chmdl = TRUE;
581                 }
582
583                 oldskin = self.skin;
584                 self.skin = defaultskin;
585         } else {
586                 if (self.playermodel != self.model || self.playermodel == "")
587                 {
588                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
589                         m1 = self.mins;
590                         m2 = self.maxs;
591                         setplayermodel (self, self.playermodel);
592                         setsize (self, m1, m2);
593                         chmdl = TRUE;
594                 }
595
596                 oldskin = self.skin;
597                 self.skin = stof(self.playerskin);
598         }
599
600         if(chmdl || oldskin != self.skin) // model or skin has changed
601         {
602                 self.species = player_getspecies(); // update species
603                 UpdatePlayerSounds(); // update skin sounds
604         }
605
606         if(!teamplay)
607                 if(strlen(autocvar_sv_defaultplayercolors))
608                         if(self.clientcolors != stof(autocvar_sv_defaultplayercolors))
609                                 setcolor(self, stof(autocvar_sv_defaultplayercolors));
610 }
611
612 void PlayerTouchExplode(entity p1, entity p2)
613 {
614         vector org;
615         org = (p1.origin + p2.origin) * 0.5;
616         org_z += (p1.mins_z + p2.mins_z) * 0.5;
617
618         te_explosion(org);
619
620         entity e;
621         e = spawn();
622         setorigin(e, org);
623         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
624         remove(e);
625 }
626
627 /*
628 =============
629 PutClientInServer
630
631 Called when a client spawns in the server
632 =============
633 */
634
635 void PutClientInServer (void)
636 {
637         if(clienttype(self) == CLIENTTYPE_BOT)
638         {
639                 self.classname = "player";
640                 if(g_ca)
641                         self.caplayer = 1;
642         }
643         else if(clienttype(self) == CLIENTTYPE_REAL)
644         {
645                 msg_entity = self;
646                 WriteByte(MSG_ONE, SVC_SETVIEW);
647                 WriteEntity(MSG_ONE, self);
648         }
649
650         // reset player keys
651         self.itemkeys = 0;
652
653         // player is dead and becomes observer
654         // FIXME fix LMS scoring for new system
655         if(g_lms)
656         {
657                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
658                         self.classname = "observer";
659         }
660
661         if((g_arena && !self.spawned) || (g_ca && !allowed_to_spawn))
662                 self.classname = "observer";
663
664         if(gameover)
665                 self.classname = "observer";
666
667         if(self.classname == "player" && (!g_ca || (g_ca && allowed_to_spawn))) {
668                 entity spot, oldself;
669                 float j;
670
671                 accuracy_resend(self);
672
673                 if(self.team < 0)
674                         JoinBestTeam(self, FALSE, TRUE);
675
676                 race_PreSpawn();
677
678                 spot = SelectSpawnPoint (FALSE);
679                 if(!spot)
680                 {
681                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
682                         return; // spawn failed
683                 }
684
685                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
686
687                 self.classname = "player";
688                 self.wasplayer = TRUE;
689                 self.iscreature = TRUE;
690                 self.teleportable = TELEPORT_NORMAL;
691                 self.damagedbycontents = TRUE;
692                 self.movetype = MOVETYPE_WALK;
693                 self.solid = SOLID_SLIDEBOX;
694                 self.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
695                 if(autocvar_g_playerclip_collisions)
696                         self.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
697                 if(clienttype(self) == CLIENTTYPE_BOT && autocvar_g_botclip_collisions)
698                         self.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
699                 self.frags = FRAGS_PLAYER;
700                 if(INDEPENDENT_PLAYERS)
701                         MAKE_INDEPENDENT_PLAYER(self);
702                 self.flags = FL_CLIENT;
703                 if(autocvar__notarget)
704                         self.flags |= FL_NOTARGET;
705                 self.takedamage = DAMAGE_AIM;
706                 self.effects = 0;
707                 self.effects |= EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
708                 self.air_finished = time + 12;
709                 self.dmg = 2;
710                 if(autocvar_g_balance_nex_charge)
711                 {
712                         if(autocvar_g_balance_nex_secondary_chargepool)
713                                 self.nex_chargepool_ammo = 1;
714                         self.nex_charge = autocvar_g_balance_nex_charge_start;
715                 }
716
717                 if(inWarmupStage)
718                 {
719                         self.ammo_shells = warmup_start_ammo_shells;
720                         self.ammo_nails = warmup_start_ammo_nails;
721                         self.ammo_rockets = warmup_start_ammo_rockets;
722                         self.ammo_cells = warmup_start_ammo_cells;
723                         self.ammo_fuel = warmup_start_ammo_fuel;
724                         self.health = warmup_start_health;
725                         self.armorvalue = warmup_start_armorvalue;
726                         WEPSET_COPY_EA(self, warmup_start_weapons);
727                 }
728                 else
729                 {
730                         self.ammo_shells = start_ammo_shells;
731                         self.ammo_nails = start_ammo_nails;
732                         self.ammo_rockets = start_ammo_rockets;
733                         self.ammo_cells = start_ammo_cells;
734                         self.ammo_fuel = start_ammo_fuel;
735                         self.health = start_health;
736                         self.armorvalue = start_armorvalue;
737                         WEPSET_COPY_EA(self, start_weapons);
738                 }
739
740                 if(WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS)) // exception for minstagib, as minstanex is a superweapon
741                         self.superweapons_finished = time + autocvar_g_balance_superweapons_time;
742                 else
743                         self.superweapons_finished = 0;
744
745                 if(g_weaponarena_random)
746                 {
747                         if(g_weaponarena_random_with_laser)
748                                 WEPSET_ANDNOT_EW(self, WEP_LASER);
749                         W_RandomWeapons(self, g_weaponarena_random);
750                         if(g_weaponarena_random_with_laser)
751                                 WEPSET_OR_EW(self, WEP_LASER);
752                 }
753
754                 self.items = start_items;
755
756                 self.spawnshieldtime = time + autocvar_g_spawnshieldtime;
757                 self.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
758                 self.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
759                 self.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
760                 self.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
761                 //extend the pause of rotting if client was reset at the beginning of the countdown
762                 if(!autocvar_sv_ready_restart_after_countdown && time < game_starttime) { // TODO why is this cvar NOTted?
763                         self.spawnshieldtime += game_starttime - time;
764                         self.pauserotarmor_finished += game_starttime - time;
765                         self.pauserothealth_finished += game_starttime - time;
766                         self.pauseregen_finished += game_starttime - time;
767                 }
768                 self.damageforcescale = 2;
769                 self.death_time = 0;
770                 self.respawn_time = 0;
771                 self.scale = 0;
772                 self.fade_time = 0;
773                 self.pain_frame = 0;
774                 self.pain_finished = 0;
775                 self.strength_finished = 0;
776                 self.invincible_finished = 0;
777                 self.pushltime = 0;
778                 // players have no think function
779                 self.think = func_null;
780                 self.nextthink = 0;
781                 self.hook_time = 0;
782                 self.dmg_team = 0;
783                 self.ballistics_density = autocvar_g_ballistics_density_player;
784
785                 self.metertime = 0;
786
787                 self.deadflag = DEAD_NO;
788
789                 self.angles = spot.angles;
790
791                 self.angles_z = 0; // never spawn tilted even if the spot says to
792                 self.fixangle = TRUE; // turn this way immediately
793                 self.velocity = '0 0 0';
794                 self.avelocity = '0 0 0';
795                 self.punchangle = '0 0 0';
796                 self.punchvector = '0 0 0';
797                 self.oldvelocity = self.velocity;
798                 self.fire_endtime = -1;
799
800                 msg_entity = self;
801                 WRITESPECTATABLE_MSG_ONE({
802                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
803                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
804                 });
805
806                 self.model = "";
807                 FixPlayermodel();
808                 self.drawonlytoclient = world;
809
810                 self.crouch = FALSE;
811                 self.view_ofs = PL_VIEW_OFS;
812                 setsize (self, PL_MIN, PL_MAX);
813                 self.spawnorigin = spot.origin;
814                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
815                 // don't reset back to last position, even if new position is stuck in solid
816                 self.oldorigin = self.origin;
817                 self.prevorigin = self.origin;
818                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
819                 self.lastteleporttime = time; // prevent insane speeds due to changing origin
820         self.hud = HUD_NORMAL;
821
822                 if(g_arena)
823                 {
824                         Spawnqueue_Remove(self);
825                         Spawnqueue_Mark(self);
826                 }
827                 else if(g_ca)
828                         self.caplayer = 1;
829
830                 self.event_damage = PlayerDamage;
831
832                 self.bot_attack = TRUE;
833
834                 self.statdraintime = time + 5;
835                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
836
837                 if(self.killcount == -666) {
838                         PlayerScore_Clear(self);
839                         self.killcount = 0;
840                 }
841
842                 CL_SpawnWeaponentity();
843                 self.alpha = default_player_alpha;
844                 self.colormod = '1 1 1' * autocvar_g_player_brightness;
845                 self.exteriorweaponentity.alpha = default_weapon_alpha;
846
847                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
848                 self.lms_traveled_distance = 0;
849                 self.speedrunning = FALSE;
850
851                 race_PostSpawn(spot);
852
853                 //stuffcmd(self, "chase_active 0");
854                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
855
856                 if(g_assault) {
857                         if(self.team == assault_attacker_team)
858                                 Send_Notification(NOTIF_TEAM, self, MSG_CENTER, CENTER_ASSAULT_ATTACKING);
859                         else
860                                 Send_Notification(NOTIF_TEAM, self, MSG_CENTER, CENTER_ASSAULT_DEFENDING);
861                 }
862
863                 target_voicescript_clear(self);
864
865                 // reset fields the weapons may use
866                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
867                 {
868                         weapon_action(j, WR_RESETPLAYER);
869
870                         // all weapons must be fully loaded when we spawn
871                         entity e;
872                         e = get_weaponinfo(j);
873                         if(e.spawnflags & WEP_FLAG_RELOADABLE) // prevent accessing undefined cvars
874                                 self.(weapon_load[j]) = cvar(strcat("g_balance_", e.netname, "_reload_ammo"));
875                 }
876
877                 oldself = self;
878                 self = spot;
879                         activator = oldself;
880                                 string s;
881                                 s = self.target;
882                                 self.target = string_null;
883                                 SUB_UseTargets();
884                                 self.target = s;
885                         activator = world;
886                 self = oldself;
887
888                 spawn_spot = spot;
889                 MUTATOR_CALLHOOK(PlayerSpawn);
890
891                 if(autocvar_spawn_debug)
892                 {
893                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
894                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
895                 }
896
897                 self.switchweapon = w_getbestweapon(self);
898                 self.cnt = -1; // W_LastWeapon will not complain
899                 self.weapon = 0;
900                 self.weaponname = "";
901                 self.switchingweapon = 0;
902
903                 if(!inWarmupStage)
904                         if(!self.alivetime)
905                                 self.alivetime = time;
906
907                 antilag_clear(self);
908
909                 if (autocvar_g_spawnsound)
910                         soundat(world, self.origin, CH_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
911         } else if(self.classname == "observer") {
912                 PutObserverInServer ();
913         }
914 }
915
916 .float ebouncefactor, ebouncestop; // electro's values
917 // TODO do we need all these fields, or should we stop autodetecting runtime
918 // changes and just have a console command to update this?
919 float ClientInit_SendEntity(entity to, float sf)
920 {
921         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
922         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
923         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[0]));
924         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[1]));
925         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[2]));
926         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[3]));
927         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[0]));
928         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[1]));
929         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[2]));
930         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[3]));
931         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[0]));
932         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[1]));
933         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[2]));
934         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[3]));
935         if(sv_foginterval && world.fog != "")
936                 WriteString(MSG_ENTITY, world.fog);
937         else
938                 WriteString(MSG_ENTITY, "");
939         WriteByte(MSG_ENTITY, self.count * 255.0); // g_balance_armor_blockpercent
940         WriteByte(MSG_ENTITY, self.cnt * 255.0); // g_balance_weaponswitchdelay
941         WriteCoord(MSG_ENTITY, self.bouncefactor); // g_balance_grenadelauncher_bouncefactor
942         WriteCoord(MSG_ENTITY, self.bouncestop); // g_balance_grenadelauncher_bouncestop
943         WriteCoord(MSG_ENTITY, self.ebouncefactor); // g_balance_grenadelauncher_bouncefactor
944         WriteCoord(MSG_ENTITY, self.ebouncestop); // g_balance_grenadelauncher_bouncestop
945         WriteByte(MSG_ENTITY, autocvar_g_balance_nex_secondary); // client has to know if it should zoom or not
946         WriteByte(MSG_ENTITY, autocvar_g_balance_rifle_secondary); // client has to know if it should zoom or not
947         WriteByte(MSG_ENTITY, serverflags); // client has to know if it should zoom or not
948         WriteByte(MSG_ENTITY, autocvar_g_balance_minelayer_limit); // minelayer max mines
949         WriteByte(MSG_ENTITY, autocvar_g_balance_hagar_secondary_load_max); // hagar max loadable rockets
950         WriteCoord(MSG_ENTITY, autocvar_g_trueaim_minrange);
951         WriteByte(MSG_ENTITY, autocvar_g_balance_porto_secondary);
952         return TRUE;
953 }
954
955 void ClientInit_CheckUpdate()
956 {
957         self.nextthink = time;
958         if(self.count != autocvar_g_balance_armor_blockpercent)
959         {
960                 self.count = autocvar_g_balance_armor_blockpercent;
961                 self.SendFlags |= 1;
962         }
963         if(self.cnt != autocvar_g_balance_weaponswitchdelay)
964         {
965                 self.cnt = autocvar_g_balance_weaponswitchdelay;
966                 self.SendFlags |= 1;
967         }
968         if(self.bouncefactor != autocvar_g_balance_grenadelauncher_bouncefactor)
969         {
970                 self.bouncefactor = autocvar_g_balance_grenadelauncher_bouncefactor;
971                 self.SendFlags |= 1;
972         }
973         if(self.bouncestop != autocvar_g_balance_grenadelauncher_bouncestop)
974         {
975                 self.bouncestop = autocvar_g_balance_grenadelauncher_bouncestop;
976                 self.SendFlags |= 1;
977         }
978         if(self.ebouncefactor != autocvar_g_balance_electro_secondary_bouncefactor)
979         {
980                 self.ebouncefactor = autocvar_g_balance_electro_secondary_bouncefactor;
981                 self.SendFlags |= 1;
982         }
983         if(self.ebouncestop != autocvar_g_balance_electro_secondary_bouncestop)
984         {
985                 self.ebouncestop = autocvar_g_balance_electro_secondary_bouncestop;
986                 self.SendFlags |= 1;
987         }
988 }
989
990 void ClientInit_Spawn()
991 {
992         entity o;
993         entity e;
994         e = spawn();
995         e.classname = "clientinit";
996         e.think = ClientInit_CheckUpdate;
997         Net_LinkEntity(e, FALSE, 0, ClientInit_SendEntity);
998
999         o = self;
1000         self = e;
1001         ClientInit_CheckUpdate();
1002         self = o;
1003 }
1004
1005 /*
1006 =============
1007 SetNewParms
1008 =============
1009 */
1010 void SetNewParms (void)
1011 {
1012         // initialize parms for a new player
1013         parm1 = -(86400 * 366);
1014 }
1015
1016 /*
1017 =============
1018 SetChangeParms
1019 =============
1020 */
1021 void SetChangeParms (void)
1022 {
1023         // save parms for level change
1024         parm1 = self.parm_idlesince - time;
1025 }
1026
1027 /*
1028 =============
1029 DecodeLevelParms
1030 =============
1031 */
1032 void DecodeLevelParms (void)
1033 {
1034         // load parms
1035         self.parm_idlesince = parm1;
1036         if(self.parm_idlesince == -(86400 * 366))
1037                 self.parm_idlesince = time;
1038
1039         // whatever happens, allow 60 seconds of idling directly after connect for map loading
1040         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
1041 }
1042
1043 /*
1044 =============
1045 ClientKill
1046
1047 Called when a client types 'kill' in the console
1048 =============
1049 */
1050
1051 .float clientkill_nexttime;
1052 void ClientKill_Now_TeamChange()
1053 {
1054         if(self.killindicator_teamchange == -1)
1055         {
1056                 JoinBestTeam( self, FALSE, TRUE );
1057         }
1058         else if(self.killindicator_teamchange == -2)
1059         {
1060                 if(g_ca)
1061                         self.caplayer = 0;
1062                 if(blockSpectators)
1063                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1064                 PutObserverInServer();
1065         }
1066         else
1067                 SV_ChangeTeam(self.killindicator_teamchange - 1);
1068 }
1069
1070 void ClientKill_Now()
1071 {
1072         if(self.vehicle)
1073         {
1074             vehicles_exit(VHEF_RELESE);
1075             if(!self.killindicator_teamchange)
1076             {
1077             self.vehicle_health = -1;
1078             Damage(self, self, self, 1 , DEATH_KILL, self.origin, '0 0 0');             
1079             }
1080         }
1081
1082         if(self.killindicator && !wasfreed(self.killindicator))
1083                 remove(self.killindicator);
1084
1085         self.killindicator = world;
1086
1087         if(self.killindicator_teamchange)
1088                 ClientKill_Now_TeamChange();
1089
1090         // in any case:
1091         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
1092
1093         // now I am sure the player IS dead
1094 }
1095 void KillIndicator_Think()
1096 {
1097         if (gameover)
1098         {
1099                 self.owner.killindicator = world;
1100                 remove(self);
1101                 return;
1102         }
1103
1104         if (self.owner.alpha < 0 && !self.owner.vehicle)
1105         {
1106                 self.owner.killindicator = world;
1107                 remove(self);
1108                 return;
1109         }
1110
1111         if(self.cnt <= 0)
1112         {
1113                 self = self.owner;
1114                 ClientKill_Now(); // no oldself needed
1115                 return;
1116         }
1117     else if(g_cts && self.health == 1) // health == 1 means that it's silent
1118     {
1119         self.nextthink = time + 1;
1120         self.cnt -= 1;
1121     }
1122         else
1123         {
1124                 if(self.cnt <= 10)
1125                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
1126                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
1127                 {
1128                         if(self.cnt <= 10)
1129                                 { Send_Notification(NOTIF_ONE, self.owner, MSG_ANNCE, Announcer_PickNumber(self.cnt)); }
1130                 }
1131                 self.nextthink = time + 1;
1132                 self.cnt -= 1;
1133         }
1134 }
1135
1136 float clientkilltime;
1137 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto, -2 = spec
1138 {
1139         float killtime;
1140         float starttime;
1141         entity e;
1142
1143         if (gameover)
1144                 return;
1145
1146         killtime = autocvar_g_balance_kill_delay;
1147
1148         if(g_race_qualifying || g_cts)
1149                 killtime = 0;
1150
1151     if(g_cts && self.killindicator && self.killindicator.health == 1) // self.killindicator.health == 1 means that the kill indicator was spawned by CTS_ClientKill
1152     {
1153                 remove(self.killindicator);
1154                 self.killindicator = world;
1155
1156         ClientKill_Now(); // allow instant kill in this case
1157         return;
1158     }
1159
1160         self.killindicator_teamchange = targetteam;
1161
1162     if(!self.killindicator)
1163         {
1164                 if(self.deadflag == DEAD_NO)
1165                 {
1166                         killtime = max(killtime, self.clientkill_nexttime - time);
1167                         self.clientkill_nexttime = time + killtime + autocvar_g_balance_kill_antispam;
1168                 }
1169
1170                 if(killtime <= 0 || self.classname != "player" || self.deadflag != DEAD_NO)
1171                 {
1172                         ClientKill_Now();
1173                 }
1174                 else
1175                 {
1176                         starttime = max(time, clientkilltime);
1177
1178                         self.killindicator = spawn();
1179                         self.killindicator.owner = self;
1180                         self.killindicator.scale = 0.5;
1181                         setattachment(self.killindicator, self, "");
1182                         setorigin(self.killindicator, '0 0 52');
1183                         self.killindicator.think = KillIndicator_Think;
1184                         self.killindicator.nextthink = starttime + (self.lip) * 0.05;
1185                         clientkilltime = max(clientkilltime, self.killindicator.nextthink + 0.05);
1186                         self.killindicator.cnt = ceil(killtime);
1187                         self.killindicator.count = bound(0, ceil(killtime), 10);
1188                         //sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1189
1190                         for(e = world; (e = find(e, classname, "body")) != world; )
1191                         {
1192                                 if(e.enemy != self)
1193                                         continue;
1194                                 e.killindicator = spawn();
1195                                 e.killindicator.owner = e;
1196                                 e.killindicator.scale = 0.5;
1197                                 setattachment(e.killindicator, e, "");
1198                                 setorigin(e.killindicator, '0 0 52');
1199                                 e.killindicator.think = KillIndicator_Think;
1200                                 e.killindicator.nextthink = starttime + (e.lip) * 0.05;
1201                                 clientkilltime = max(clientkilltime, e.killindicator.nextthink + 0.05);
1202                                 e.killindicator.cnt = ceil(killtime);
1203                         }
1204                         self.lip = 0;
1205                 }
1206         }
1207         if(self.killindicator)
1208         {
1209                 if(targetteam == 0) // just die
1210                 {
1211                         self.killindicator.colormod = '0 0 0';
1212                         if(clienttype(self) == CLIENTTYPE_REAL)
1213                         if(self.killindicator.cnt > 0)
1214                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SUICIDE, self.killindicator.cnt);
1215                 }
1216                 else if(targetteam == -1) // auto
1217                 {
1218                         self.killindicator.colormod = '0 1 0';
1219                         if(clienttype(self) == CLIENTTYPE_REAL)
1220                         if(self.killindicator.cnt > 0)
1221                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_AUTO, self.killindicator.cnt);
1222                 }
1223                 else if(targetteam == -2) // spectate
1224                 {
1225                         self.killindicator.colormod = '0.5 0.5 0.5';
1226                         if(clienttype(self) == CLIENTTYPE_REAL)
1227                         if(self.killindicator.cnt > 0)
1228                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SPECTATE, self.killindicator.cnt);
1229                 }
1230                 else
1231                 {
1232                         self.killindicator.colormod = Team_ColorRGB(targetteam);
1233                         if(clienttype(self) == CLIENTTYPE_REAL)
1234                         if(self.killindicator.cnt > 0)
1235                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, APP_TEAM_NUM_4(targetteam, CENTER_TEAMCHANGE_), self.killindicator.cnt);
1236                 }
1237         }
1238
1239 }
1240
1241 void ClientKill (void)
1242 {
1243         if (gameover)
1244                 return;
1245
1246         if((g_arena || g_ca) && ((champion && champion.classname == "player" && player_count > 1) || player_count == 1)) // don't allow a kill in this case either
1247         {
1248                 // do nothing
1249         }
1250     else if(self.freezetag_frozen)
1251     {
1252         // do nothing
1253     }
1254         else
1255                 ClientKill_TeamChange(0);
1256 }
1257
1258 void CTS_ClientKill (entity e) // silent version of ClientKill, used when player finishes a CTS run. Useful to prevent cheating by running back to the start line and starting out with more speed
1259 {
1260     e.killindicator = spawn();
1261     e.killindicator.owner = e;
1262     e.killindicator.think = KillIndicator_Think;
1263     e.killindicator.nextthink = time + (e.lip) * 0.05;
1264     e.killindicator.cnt = ceil(autocvar_g_cts_finish_kill_delay);
1265     e.killindicator.health = 1; // this is used to indicate that it should be silent
1266     e.lip = 0;
1267 }
1268
1269 void FixClientCvars(entity e)
1270 {
1271         // send prediction settings to the client
1272         stuffcmd(e, "\nin_bindmap 0 0\n");
1273         if(g_race || g_cts)
1274                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1275         if(autocvar_g_antilag == 3) // client side hitscan
1276                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
1277         if(autocvar_sv_gentle)
1278                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
1279         /*
1280          * we no longer need to stuff this. Remove this comment block if you feel
1281          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1282         stuffcmd(e, strcat("cl_gravity ", ftos(autocvar_sv_gravity), "\n"));
1283         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(autocvar_sv_accelerate), "\n"));
1284         stuffcmd(e, strcat("cl_movement_friction ", ftos(autocvar_sv_friction), "\n"));
1285         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(autocvar_sv_maxspeed), "\n"));
1286         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(autocvar_sv_airaccelerate), "\n"));
1287         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(autocvar_sv_maxairspeed), "\n"));
1288         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(autocvar_sv_stopspeed), "\n"));
1289         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(autocvar_sv_jumpvelocity), "\n"));
1290         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(autocvar_sv_stepheight), "\n"));
1291         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(autocvar_sv_friction_on_land), "\n"));
1292         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(autocvar_sv_airaccel_qw), "\n"));
1293         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(autocvar_sv_airaccel_sideways_friction), "\n"));
1294         stuffcmd(e, "cl_movement_edgefriction 1\n");
1295          */
1296 }
1297
1298 float PlayerInIDList(entity p, string idlist)
1299 {
1300         float n, i;
1301         string s;
1302
1303         // NOTE: we do NOT check crypto_keyfp here, an unsigned ID is fine too for this
1304         if not(p.crypto_idfp)
1305                 return 0;
1306
1307         // this function allows abbreviated player IDs too!
1308         n = tokenize_console(idlist);
1309         for(i = 0; i < n; ++i)
1310         {
1311                 s = argv(i);
1312                 if(s == substring(p.crypto_idfp, 0, strlen(s)))
1313                         return 1;
1314         }
1315
1316         return 0;
1317 }
1318
1319 /*
1320 =============
1321 ClientConnect
1322
1323 Called when a client connects to the server
1324 =============
1325 */
1326 void DecodeLevelParms (void);
1327 //void dom_player_join_team(entity pl);
1328 void set_dom_state(entity e);
1329 void ClientConnect (void)
1330 {
1331         float t;
1332
1333         if(self.flags & FL_CLIENT)
1334         {
1335                 print("Warning: ClientConnect, but already connected!\n");
1336                 return;
1337         }
1338
1339         if(Ban_MaybeEnforceBanOnce(self))
1340                 return;
1341
1342         DecodeLevelParms();
1343
1344 #ifdef WATERMARK
1345         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_WATERMARK, WATERMARK);
1346 #endif
1347
1348         self.classname = "player_joining";
1349
1350         self.flags = FL_CLIENT;
1351         self.version_nagtime = time + 10 + random() * 10;
1352
1353         if(player_count<0)
1354         {
1355                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1356                 player_count = 0;
1357         }
1358
1359         PlayerScore_Attach(self);
1360         ClientData_Attach();
1361         accuracy_init(self);
1362
1363         bot_clientconnect();
1364
1365         playerdemo_init();
1366
1367         anticheat_init();
1368
1369         race_PreSpawnObserver();
1370
1371         // identify the right forced team
1372         if(autocvar_g_campaign)
1373         {
1374                 if(clienttype(self) == CLIENTTYPE_REAL) // only players, not bots
1375                 {
1376                         switch(autocvar_g_campaign_forceteam)
1377                         {
1378                                 case 1: self.team_forced = NUM_TEAM_1; break;
1379                                 case 2: self.team_forced = NUM_TEAM_2; break;
1380                                 case 3: self.team_forced = NUM_TEAM_3; break;
1381                                 case 4: self.team_forced = NUM_TEAM_4; break;
1382                                 default: self.team_forced = 0;
1383                         }
1384                 }
1385         }
1386         else if(PlayerInIDList(self, autocvar_g_forced_team_red))
1387                 self.team_forced = NUM_TEAM_1;
1388         else if(PlayerInIDList(self, autocvar_g_forced_team_blue))
1389                 self.team_forced = NUM_TEAM_2;
1390         else if(PlayerInIDList(self, autocvar_g_forced_team_yellow))
1391                 self.team_forced = NUM_TEAM_3;
1392         else if(PlayerInIDList(self, autocvar_g_forced_team_pink))
1393                 self.team_forced = NUM_TEAM_4;
1394         else if(autocvar_g_forced_team_otherwise == "red")
1395                 self.team_forced = NUM_TEAM_1;
1396         else if(autocvar_g_forced_team_otherwise == "blue")
1397                 self.team_forced = NUM_TEAM_2;
1398         else if(autocvar_g_forced_team_otherwise == "yellow")
1399                 self.team_forced = NUM_TEAM_3;
1400         else if(autocvar_g_forced_team_otherwise == "pink")
1401                 self.team_forced = NUM_TEAM_4;
1402         else if(autocvar_g_forced_team_otherwise == "spectate")
1403                 self.team_forced = -1;
1404         else if(autocvar_g_forced_team_otherwise == "spectator")
1405                 self.team_forced = -1;
1406         else
1407                 self.team_forced = 0;
1408
1409         if(!teamplay)
1410                 if(self.team_forced > 0)
1411                         self.team_forced = 0;
1412
1413         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1414
1415         if((autocvar_sv_spectate == 1 && !g_lms) || autocvar_g_campaign || self.team_forced < 0) {
1416                 self.classname = "observer";
1417         } else {
1418                 if(teamplay)
1419                 {
1420                         if(autocvar_g_balance_teams)
1421                         {
1422                                 self.classname = "player";
1423                                 campaign_bots_may_start = 1;
1424                         }
1425                         else
1426                         {
1427                                 self.classname = "observer"; // do it anyway
1428                         }
1429                 }
1430                 else
1431                 {
1432                         self.classname = "player";
1433                         campaign_bots_may_start = 1;
1434                 }
1435         }
1436
1437         self.playerid = (playerid_last = playerid_last + 1);
1438
1439         PlayerStats_AddEvent(sprintf("kills-%d", self.playerid));
1440
1441     if(clienttype(self) == CLIENTTYPE_BOT)
1442         PlayerStats_AddPlayer(self);
1443
1444         if(autocvar_sv_eventlog)
1445                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1446
1447         LogTeamchange(self.playerid, self.team, 1);
1448
1449         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1450
1451         self.netname_previous = strzone(self.netname);
1452
1453         if((self.classname == STR_PLAYER && teamplay))
1454                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(self, INFO_JOIN_CONNECT_TEAM_), self.netname);
1455         else
1456                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_CONNECT, self.netname);
1457
1458         stuffcmd(self, strcat(clientstuff, "\n"));
1459         stuffcmd(self, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1460
1461         FixClientCvars(self);
1462
1463         // spawnfunc_waypoint sprites
1464         WaypointSprite_InitClient(self);
1465
1466         // Wazat's grappling hook
1467         SetGrappleHookBindings();
1468
1469         // get version info from player
1470         stuffcmd(self, "cmd clientversion $gameversion\n");
1471
1472         // get other cvars from player
1473         GetCvars(0);
1474
1475         // notify about available teams
1476         if(teamplay)
1477         {
1478                 CheckAllowedTeams(self);
1479                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1480                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1481         }
1482         else
1483                 stuffcmd(self, "set _teams_available 0\n");
1484
1485         if(g_arena || g_ca)
1486         {
1487                 self.classname = "observer";
1488                 if(g_arena)
1489                         Spawnqueue_Insert(self);
1490         }
1491
1492         attach_entcs();
1493
1494         bot_relinkplayerlist();
1495
1496         self.spectatortime = time;
1497         if(blockSpectators)
1498         {
1499                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1500         }
1501
1502         self.jointime = time;
1503         self.allowed_timeouts = autocvar_sv_timeout_number;
1504
1505         if(clienttype(self) == CLIENTTYPE_REAL)
1506         {
1507                 if(!autocvar_g_campaign)
1508                 {
1509                         self.motd_actived_time = -1;
1510                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
1511                 }
1512
1513                 if(autocvar_g_bugrigs || WEPSET_EQ_AW(g_weaponarena_weapons, WEP_TUBA))
1514                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1515         }
1516
1517         if(g_lms)
1518         {
1519                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1520                 {
1521                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1522                         self.frags = FRAGS_SPECTATOR;
1523                 }
1524         }
1525
1526         if(!sv_foginterval && world.fog != "")
1527                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1528
1529         if(autocvar_g_hitplots || strstrofs(strcat(" ", autocvar_g_hitplots_individuals, " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1530         {
1531                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1532                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1533         }
1534         else
1535                 self.hitplotfh = -1;
1536
1537         if(g_race || g_cts) {
1538                 string rr;
1539                 if(g_cts)
1540                         rr = CTS_RECORD;
1541                 else
1542                         rr = RACE_RECORD;
1543
1544                 msg_entity = self;
1545                 race_send_recordtime(MSG_ONE);
1546                 race_send_speedaward(MSG_ONE);
1547
1548                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1549                 speedaward_alltimebest_holder = uid2name(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/crypto_idfp")));
1550                 race_send_speedaward_alltimebest(MSG_ONE);
1551
1552                 float i;
1553                 for (i = 1; i <= RANKINGS_CNT; ++i) {
1554                         race_SendRankings(i, 0, 0, MSG_ONE);
1555                 }
1556         }
1557         else if(autocvar_sv_teamnagger && !(autocvar_bot_vs_human && (c3==-1 && c4==-1)) && !g_ca) // teamnagger is currently bad for ca
1558                 send_CSQC_teamnagger();
1559
1560         CheatInitClient();
1561
1562         CSQCMODEL_AUTOINIT();
1563
1564         self.model_randomizer = random();
1565     
1566     if(clienttype(self) != CLIENTTYPE_REAL)
1567         return;
1568         
1569     sv_notice_join();
1570     
1571     MUTATOR_CALLHOOK(ClientConnect);
1572 }
1573 /*
1574 =============
1575 ClientDisconnect
1576
1577 Called when a client disconnects from the server
1578 =============
1579 */
1580 .entity chatbubbleentity;
1581 void ReadyCount();
1582 void ClientDisconnect (void)
1583 {
1584         if(self.vehicle)
1585             vehicles_exit(VHEF_RELESE);
1586
1587         if not(self.flags & FL_CLIENT)
1588         {
1589                 print("Warning: ClientDisconnect without ClientConnect\n");
1590                 return;
1591         }
1592
1593         PlayerStats_AddGlobalInfo(self);
1594
1595         CheatShutdownClient();
1596
1597         if(self.hitplotfh >= 0)
1598         {
1599                 fclose(self.hitplotfh);
1600                 self.hitplotfh = -1;
1601         }
1602
1603         anticheat_report();
1604         anticheat_shutdown();
1605
1606         playerdemo_shutdown();
1607
1608         bot_clientdisconnect();
1609
1610         if(self.entcs)
1611                 detach_entcs();
1612
1613         if(autocvar_sv_eventlog)
1614                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1615                 
1616         Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_DISCONNECT, self.netname);
1617
1618         MUTATOR_CALLHOOK(ClientDisconnect);
1619
1620         Portal_ClearAll(self);
1621
1622         RemoveGrapplingHook(self);
1623
1624         // Here, everything has been done that requires this player to be a client.
1625
1626         self.flags &~= FL_CLIENT;
1627
1628         if (self.chatbubbleentity)
1629                 remove (self.chatbubbleentity);
1630
1631         if (self.killindicator)
1632                 remove (self.killindicator);
1633
1634         WaypointSprite_PlayerGone();
1635
1636         bot_relinkplayerlist();
1637
1638         if(g_arena)
1639         {
1640                 Spawnqueue_Unmark(self);
1641                 Spawnqueue_Remove(self);
1642         }
1643
1644         accuracy_free(self);
1645         ClientData_Detach();
1646         PlayerScore_Detach(self);
1647
1648         if(self.netname_previous)
1649                 strunzone(self.netname_previous);
1650         if(self.clientstatus)
1651                 strunzone(self.clientstatus);
1652         if(self.weaponorder_byimpulse)
1653                 strunzone(self.weaponorder_byimpulse);
1654
1655         ClearPlayerSounds();
1656
1657         if(self.personal)
1658                 remove(self.personal);
1659
1660         self.playerid = 0;
1661         ReadyCount();
1662
1663         // free cvars
1664         GetCvars(-1);
1665 }
1666
1667 .float BUTTON_CHAT;
1668 void ChatBubbleThink()
1669 {
1670         self.nextthink = time;
1671         if ((self.owner.alpha < 0) || self.owner.chatbubbleentity != self)
1672         {
1673                 if(self.owner) // but why can that ever be world?
1674                         self.owner.chatbubbleentity = world;
1675                 remove(self);
1676                 return;
1677         }
1678         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1679 #ifdef TETRIS
1680                 || self.owner.tetris_on
1681 #endif
1682         )
1683                 self.model = self.mdl;
1684         else
1685                 self.model = "";
1686 }
1687
1688 void UpdateChatBubble()
1689 {
1690         if (self.alpha < 0)
1691                 return;
1692         // spawn a chatbubble entity if needed
1693         if (!self.chatbubbleentity)
1694         {
1695                 self.chatbubbleentity = spawn();
1696                 self.chatbubbleentity.owner = self;
1697                 self.chatbubbleentity.exteriormodeltoclient = self;
1698                 self.chatbubbleentity.think = ChatBubbleThink;
1699                 self.chatbubbleentity.nextthink = time;
1700                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1701                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1702                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1703                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1704                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1705                 self.chatbubbleentity.model = "";
1706                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1707         }
1708 }
1709
1710
1711 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1712 // added to the model skins
1713 /*void UpdateColorModHack()
1714 {
1715         float c;
1716         c = self.clientcolors & 15;
1717         // LordHavoc: only bothering to support white, green, red, yellow, blue
1718              if (!teamplay) self.colormod = '0 0 0';
1719         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1720         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1721         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1722         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1723         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1724         else self.colormod = '1 1 1';
1725 }*/
1726
1727 void respawn(void)
1728 {
1729         if(self.alpha >= 0 && autocvar_g_respawn_ghosts)
1730         {
1731                 self.solid = SOLID_NOT;
1732                 self.takedamage = DAMAGE_NO;
1733                 self.movetype = MOVETYPE_FLY;
1734                 self.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1735                 self.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1736                 self.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1737                 pointparticles(particleeffectnum("respawn_ghost"), self.origin, '0 0 0', 1);
1738                 if(autocvar_g_respawn_ghosts_maxtime)
1739                         SUB_SetFade (self, time + autocvar_g_respawn_ghosts_maxtime / 2 + random () * (autocvar_g_respawn_ghosts_maxtime - autocvar_g_respawn_ghosts_maxtime / 2), 1.5);
1740         }
1741
1742         CopyBody(1);
1743
1744         self.effects |= EF_NODRAW; // prevent another CopyBody
1745         PutClientInServer();
1746 }
1747
1748 void play_countdown(float finished, string samp)
1749 {
1750         if(clienttype(self) == CLIENTTYPE_REAL)
1751                 if(floor(finished - time - frametime) != floor(finished - time))
1752                         if(finished - time < 6)
1753                                 sound (self, CH_INFO, samp, VOL_BASE, ATTN_NORM);
1754 }
1755
1756 void player_powerups (void)
1757 {
1758         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1759         olditems = self.items;
1760
1761         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1762                 self.modelflags |= MF_ROCKET;
1763         else
1764                 self.modelflags &~= MF_ROCKET;
1765
1766         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1767
1768         if(self.alpha < 0 || self.deadflag) // don't apply the flags if the player is gibbed
1769                 return;
1770
1771         Fire_ApplyDamage(self);
1772         Fire_ApplyEffect(self);
1773
1774         if not(g_minstagib)
1775         {
1776                 if (self.items & IT_STRENGTH)
1777                 {
1778                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1779                         self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1780                         if (time > self.strength_finished)
1781                         {
1782                                 self.items = self.items - (self.items & IT_STRENGTH);
1783                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_STRENGTH, self.netname);
1784                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_STRENGTH);
1785                         }
1786                 }
1787                 else
1788                 {
1789                         if (time < self.strength_finished)
1790                         {
1791                                 self.items = self.items | IT_STRENGTH;
1792                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_STRENGTH, self.netname);
1793                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_STRENGTH);
1794                         }
1795                 }
1796                 if (self.items & IT_INVINCIBLE)
1797                 {
1798                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1799                         self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1800                         if (time > self.invincible_finished)
1801                         {
1802                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1803                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_SHIELD, self.netname);
1804                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_SHIELD);
1805                         }
1806                 }
1807                 else
1808                 {
1809                         if (time < self.invincible_finished)
1810                         {
1811                                 self.items = self.items | IT_INVINCIBLE;
1812                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_SHIELD, self.netname);
1813                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_SHIELD);
1814                         }
1815                 }
1816                 if (self.items & IT_SUPERWEAPON)
1817                 {
1818                         if (!WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS))
1819                         {
1820                                 self.superweapons_finished = 0;
1821                                 self.items = self.items - (self.items & IT_SUPERWEAPON);
1822                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_LOST, self.netname);
1823                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1824                         }
1825                         else if (self.items & IT_UNLIMITED_SUPERWEAPONS)
1826                         {
1827                                 // don't let them run out
1828                         }
1829                         else
1830                         {
1831                                 play_countdown(self.superweapons_finished, "misc/poweroff.wav");
1832                                 if (time > self.superweapons_finished)
1833                                 {
1834                                         self.items = self.items - (self.items & IT_SUPERWEAPON);
1835                                         WEPSET_ANDNOT_EA(self, WEPBIT_SUPERWEAPONS);
1836                                         //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_BROKEN, self.netname);
1837                                         Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1838                                 }
1839                         }
1840                 }
1841                 else if(WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS))
1842                 {
1843                         if (time < self.superweapons_finished || (self.items & IT_UNLIMITED_SUPERWEAPONS))
1844                         {
1845                                 self.items = self.items | IT_SUPERWEAPON;
1846                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_PICKUP, self.netname);
1847                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1848                         }
1849                         else
1850                         {
1851                                 self.superweapons_finished = 0;
1852                                 WEPSET_ANDNOT_EA(self, WEPBIT_SUPERWEAPONS);
1853                         }
1854                 }
1855                 else
1856                 {
1857                         self.superweapons_finished = 0;
1858                 }
1859         }
1860         
1861         if(autocvar_g_nodepthtestplayers)
1862                 self.effects = self.effects | EF_NODEPTHTEST;
1863
1864         if(autocvar_g_fullbrightplayers)
1865                 self.effects = self.effects | EF_FULLBRIGHT;
1866
1867         // midair gamemode: damage only while in the air
1868         // if in midair mode, being on ground grants temporary invulnerability
1869         // (this is so that multishot weapon don't clear the ground flag on the
1870         // first damage in the frame, leaving the player vulnerable to the
1871         // remaining hits in the same frame)
1872         if (self.flags & FL_ONGROUND)
1873         if (g_midair)
1874                 self.spawnshieldtime = max(self.spawnshieldtime, time + autocvar_g_midair_shieldtime);
1875
1876         if (time >= game_starttime)
1877         if (time < self.spawnshieldtime)
1878                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1879
1880         MUTATOR_CALLHOOK(PlayerPowerups);
1881 }
1882
1883 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1884 {
1885         if(current > stable)
1886                 return current;
1887         else if(current > stable - 0.25) // when close enough, "snap"
1888                 return stable;
1889         else
1890                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1891 }
1892
1893 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1894 {
1895         if(current < stable)
1896                 return current;
1897         else if(current < stable + 0.25) // when close enough, "snap"
1898                 return stable;
1899         else
1900                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1901 }
1902
1903 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1904 {
1905         if(current > rotstable)
1906         {
1907                 if(rotframetime > 0)
1908                 {
1909                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1910                         current = max(rotstable, current - rotlinear * rotframetime);
1911                 }
1912         }
1913         else if(current < regenstable)
1914         {
1915                 if(regenframetime > 0)
1916                 {
1917                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1918                         current = min(regenstable, current + regenlinear * regenframetime);
1919                 }
1920         }
1921
1922         if(current > limit)
1923                 current = limit;
1924
1925         return current;
1926 }
1927
1928 void player_regen (void)
1929 {
1930         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1931         maxh = autocvar_g_balance_health_rotstable;
1932         maxa = autocvar_g_balance_armor_rotstable;
1933         maxf = autocvar_g_balance_fuel_rotstable;
1934         minh = autocvar_g_balance_health_regenstable;
1935         mina = autocvar_g_balance_armor_regenstable;
1936         minf = autocvar_g_balance_fuel_regenstable;
1937         limith = autocvar_g_balance_health_limit;
1938         limita = autocvar_g_balance_armor_limit;
1939         limitf = autocvar_g_balance_fuel_limit;
1940
1941         max_mod = regen_mod = rot_mod = limit_mod = 1;
1942
1943         maxh = maxh * max_mod;
1944         //maxa = maxa * max_mod;
1945         //maxf = maxf * max_mod;
1946         minh = minh * max_mod;
1947         //mina = mina * max_mod;
1948         //minf = minf * max_mod;
1949         limith = limith * limit_mod;
1950         limita = limita * limit_mod;
1951         //limitf = limitf * limit_mod;
1952
1953         if(g_lms && g_ca)
1954                 rot_mod = 0;
1955
1956         if (!g_minstagib && !g_ca && (!g_lms || autocvar_g_lms_regenerate))
1957         {
1958                 self.armorvalue = CalcRotRegen(self.armorvalue, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rot_mod * frametime * (time > self.pauserotarmor_finished), limita);
1959                 self.health = CalcRotRegen(self.health, minh, autocvar_g_balance_health_regen, autocvar_g_balance_health_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxh, autocvar_g_balance_health_rot, autocvar_g_balance_health_rotlinear, rot_mod * frametime * (time > self.pauserothealth_finished), limith);
1960
1961                 // if player rotted to death...  die!
1962                 if(self.health < 1)
1963                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1964         }
1965
1966         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
1967                 self.ammo_fuel = CalcRotRegen(self.ammo_fuel, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished) * (self.items & IT_FUEL_REGEN != 0), maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, rot_mod * frametime * (time > self.pauserotfuel_finished), limitf);
1968 }
1969
1970 float zoomstate_set;
1971 void SetZoomState(float z)
1972 {
1973         if(z != self.zoomstate)
1974         {
1975                 self.zoomstate = z;
1976                 ClientData_Touch(self);
1977         }
1978         zoomstate_set = 1;
1979 }
1980
1981 void GetPressedKeys(void) {
1982         MUTATOR_CALLHOOK(GetPressedKeys);
1983         if (self.movement_x > 0) // get if movement keys are pressed
1984         {       // forward key pressed
1985                 self.pressedkeys |= KEY_FORWARD;
1986                 self.pressedkeys &~= KEY_BACKWARD;
1987         }
1988         else if (self.movement_x < 0)
1989         {       // backward key pressed
1990                 self.pressedkeys |= KEY_BACKWARD;
1991                 self.pressedkeys &~= KEY_FORWARD;
1992         }
1993         else
1994         {       // no x input
1995                 self.pressedkeys &~= KEY_FORWARD;
1996                 self.pressedkeys &~= KEY_BACKWARD;
1997         }
1998
1999         if (self.movement_y > 0)
2000         {       // right key pressed
2001                 self.pressedkeys |= KEY_RIGHT;
2002                 self.pressedkeys &~= KEY_LEFT;
2003         }
2004         else if (self.movement_y < 0)
2005         {       // left key pressed
2006                 self.pressedkeys |= KEY_LEFT;
2007                 self.pressedkeys &~= KEY_RIGHT;
2008         }
2009         else
2010         {       // no y input
2011                 self.pressedkeys &~= KEY_RIGHT;
2012                 self.pressedkeys &~= KEY_LEFT;
2013         }
2014
2015         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2016                 self.pressedkeys |= KEY_JUMP;
2017         else
2018                 self.pressedkeys &~= KEY_JUMP;
2019         if (self.BUTTON_CROUCH)
2020                 self.pressedkeys |= KEY_CROUCH;
2021         else
2022                 self.pressedkeys &~= KEY_CROUCH;
2023
2024         if (self.BUTTON_ATCK)
2025                 self.pressedkeys |= KEY_ATCK;
2026         else
2027                 self.pressedkeys &~= KEY_ATCK;
2028         if (self.BUTTON_ATCK2)
2029                 self.pressedkeys |= KEY_ATCK2;
2030         else
2031                 self.pressedkeys &~= KEY_ATCK2;
2032 }
2033
2034 /*
2035 ======================
2036 spectate mode routines
2037 ======================
2038 */
2039
2040 void SpectateCopy(entity spectatee) {
2041         other = spectatee;
2042         MUTATOR_CALLHOOK(SpectateCopy);
2043         self.armortype = spectatee.armortype;
2044         self.armorvalue = spectatee.armorvalue;
2045         self.ammo_cells = spectatee.ammo_cells;
2046         self.ammo_shells = spectatee.ammo_shells;
2047         self.ammo_nails = spectatee.ammo_nails;
2048         self.ammo_rockets = spectatee.ammo_rockets;
2049         self.ammo_fuel = spectatee.ammo_fuel;
2050         self.clip_load = spectatee.clip_load;
2051         self.clip_size = spectatee.clip_size;
2052         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2053         self.health = spectatee.health;
2054         self.impulse = 0;
2055         self.items = spectatee.items;
2056         self.last_pickup = spectatee.last_pickup;
2057         self.hit_time = spectatee.hit_time;
2058         self.metertime = spectatee.metertime;
2059         self.strength_finished = spectatee.strength_finished;
2060         self.invincible_finished = spectatee.invincible_finished;
2061         self.pressedkeys = spectatee.pressedkeys;
2062         WEPSET_COPY_EE(self, spectatee);
2063         self.switchweapon = spectatee.switchweapon;
2064         self.switchingweapon = spectatee.switchingweapon;
2065         self.weapon = spectatee.weapon;
2066         self.nex_charge = spectatee.nex_charge;
2067         self.nex_chargepool_ammo = spectatee.nex_chargepool_ammo;
2068         self.hagar_load = spectatee.hagar_load;
2069         self.minelayer_mines = spectatee.minelayer_mines;
2070         self.punchangle = spectatee.punchangle;
2071         self.view_ofs = spectatee.view_ofs;
2072         self.velocity = spectatee.velocity;
2073         self.dmg_take = spectatee.dmg_take;
2074         self.dmg_save = spectatee.dmg_save;
2075         self.dmg_inflictor = spectatee.dmg_inflictor;
2076         self.v_angle = spectatee.v_angle;
2077         self.angles = spectatee.v_angle;
2078         self.stat_respawn_time = spectatee.stat_respawn_time;
2079         if(!self.BUTTON_USE)
2080                 self.fixangle = TRUE;
2081         setorigin(self, spectatee.origin);
2082         setsize(self, spectatee.mins, spectatee.maxs);
2083         SetZoomState(spectatee.zoomstate);
2084     
2085     anticheat_spectatecopy(spectatee);
2086         self.hud = spectatee.hud;
2087         if(spectatee.vehicle)
2088     {
2089         self.fixangle = FALSE;
2090         //self.velocity = spectatee.vehicle.velocity;
2091         self.vehicle_health = spectatee.vehicle_health;
2092         self.vehicle_shield = spectatee.vehicle_shield;
2093         self.vehicle_energy = spectatee.vehicle_energy;
2094         self.vehicle_ammo1 = spectatee.vehicle_ammo1;
2095         self.vehicle_ammo2 = spectatee.vehicle_ammo2;
2096         self.vehicle_reload1 = spectatee.vehicle_reload1;
2097         self.vehicle_reload2 = spectatee.vehicle_reload2;
2098
2099         msg_entity = self;
2100         
2101         WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
2102             WriteAngle(MSG_ONE,  spectatee.v_angle_x);
2103             WriteAngle(MSG_ONE,  spectatee.v_angle_y);
2104             WriteAngle(MSG_ONE,  spectatee.v_angle_z);
2105
2106         //WriteByte (MSG_ONE, SVC_SETVIEW);
2107         //    WriteEntity(MSG_ONE, self);            
2108         //makevectors(spectatee.v_angle);
2109         //setorigin(self, spectatee.origin - v_forward * 400 + v_up * 300);*/    
2110     }
2111 }
2112
2113 float SpectateUpdate() {
2114         if(!self.enemy)
2115             return 0;           
2116
2117         if (self == self.enemy)
2118                 return 0;
2119
2120         if(self.enemy.classname != "player")
2121                 return 0;
2122
2123         SpectateCopy(self.enemy);
2124
2125         return 1;
2126 }
2127
2128
2129 // Returns next available player to spectate if g_ca_spectate_enemies == 0
2130 entity CA_SpectateNext(entity start) {
2131         if (start.team == self.team) {
2132                 return start;
2133         }
2134         
2135         other = start;
2136         // continue from current player
2137         while(other && other.team != self.team) {
2138                 other = find(other, classname, "player");
2139         }
2140         
2141         if (!other) {
2142                 // restart from begining
2143                 other = find(other, classname, "player");
2144                 while(other && other.team != self.team) {
2145                         other = find(other, classname, "player");
2146                 }
2147         }
2148         
2149         return other;
2150 }
2151
2152 float SpectateNext(entity _prefer) {
2153         
2154         if(_prefer)
2155                 other = _prefer;        
2156         else
2157                 other = find(self.enemy, classname, "player");
2158         
2159         if (g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer) {
2160                 // CA and ca players when spectating enemies is forbidden
2161                 other = CA_SpectateNext(other);
2162         } else {
2163                 // other modes and ca spectators or spectating enemies is allowed
2164                 if (!other)
2165                         other = find(other, classname, "player");
2166         }
2167         
2168         if (other)
2169                 self.enemy = other;
2170
2171         if(self.enemy.classname == "player") {
2172             /*if(self.enemy.vehicle)
2173             {      
2174             
2175             msg_entity = self;
2176             WriteByte(MSG_ONE, SVC_SETVIEW);
2177             WriteEntity(MSG_ONE, self.enemy);
2178             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2179             
2180             self.movetype = MOVETYPE_NONE;
2181             accuracy_resend(self);
2182             }
2183             else 
2184             {*/         
2185             msg_entity = self;
2186             WriteByte(MSG_ONE, SVC_SETVIEW);
2187             WriteEntity(MSG_ONE, self.enemy);
2188             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2189             self.movetype = MOVETYPE_NONE;
2190             accuracy_resend(self);
2191
2192             if(!SpectateUpdate())
2193                 PutObserverInServer();
2194         //}
2195         return 1;
2196         } else {
2197                 return 0;
2198         }
2199 }
2200
2201 /*
2202 =============
2203 ShowRespawnCountdown()
2204
2205 Update a respawn countdown display.
2206 =============
2207 */
2208 void ShowRespawnCountdown()
2209 {
2210         float number;
2211         if(self.deadflag == DEAD_NO) // just respawned?
2212                 return;
2213         else
2214         {
2215                 number = ceil(self.respawn_time - time);
2216                 if(number <= 0)
2217                         return;
2218                 if(number <= self.respawn_countdown)
2219                 {
2220                         self.respawn_countdown = number - 1;
2221                         if(ceil(self.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
2222                                 Send_Notification(NOTIF_ONE, self, MSG_ANNCE, Announcer_PickNumber(number)); 
2223                 }
2224         }
2225 }
2226
2227 void LeaveSpectatorMode()
2228 {
2229         if(nJoinAllowed(self))
2230         {
2231                 if(!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || (self.wasplayer && autocvar_g_changeteam_banned) || self.team_forced > 0)
2232                 {
2233                         self.classname = "player";
2234
2235                         if(autocvar_g_campaign || autocvar_g_balance_teams)
2236                                 { JoinBestTeam(self, FALSE, TRUE); }
2237
2238                         if(autocvar_g_campaign)
2239                                 { campaign_bots_may_start = 1; }
2240
2241                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_PREVENT_JOIN);
2242
2243                         PutClientInServer();
2244
2245                         if(IS_PLAYER(self)) { Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_PLAY, self.netname); }
2246                 }
2247                 else if not(g_ca && self.caplayer) { stuffcmd(self, "menu_showteamselect\n"); }
2248         }
2249         else
2250         {
2251                 // Player may not join because g_maxplayers is set
2252                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_JOIN_PREVENT);
2253         }
2254 }
2255
2256 /**
2257  * Determines whether the player is allowed to join. This depends on cvar
2258  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2259  * it checks whether the number of currently playing players exceeds g_maxplayers.
2260  * @return int number of free slots for players, 0 if none
2261  */
2262 float nJoinAllowed(entity ignore) {
2263         if(!ignore)
2264         // this is called that way when checking if anyone may be able to join (to build qcstatus)
2265         // so report 0 free slots if restricted
2266         {
2267                 if(autocvar_g_forced_team_otherwise == "spectate")
2268                         return 0;
2269                 if(autocvar_g_forced_team_otherwise == "spectator")
2270                         return 0;
2271         }
2272
2273         if(self.team_forced < 0)
2274                 return 0; // forced spectators can never join
2275
2276         // TODO simplify this
2277         entity e;
2278         float totalClients = 0;
2279         FOR_EACH_CLIENT(e)
2280                 if(e != ignore)
2281                         totalClients += 1;
2282
2283         if (!autocvar_g_maxplayers)
2284                 return maxclients - totalClients;
2285
2286         float currentlyPlaying = 0;
2287         FOR_EACH_REALPLAYER(e)
2288                 currentlyPlaying += 1;
2289
2290         if(currentlyPlaying < autocvar_g_maxplayers)
2291                 return min(maxclients - totalClients, autocvar_g_maxplayers - currentlyPlaying);
2292
2293         return 0;
2294 }
2295
2296 /**
2297  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2298  * g_maxplayers_spectator_blocktime seconds
2299  */
2300 void checkSpectatorBlock() {
2301         if(self.classname == "spectator" || self.classname == "observer") {
2302                 if( time > (self.spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
2303                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
2304                         dropclient(self);
2305                 }
2306         }
2307 }
2308
2309 void PrintWelcomeMessage()
2310 {
2311         if(self.motd_actived_time == 0)
2312         {
2313                 if (autocvar_g_campaign) {
2314                         if ((self.classname == "player" && self.BUTTON_INFO) || (self.classname != "player")) {
2315                                 self.motd_actived_time = time;
2316                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, campaign_message);
2317                         }
2318                 } else {
2319                         if (self.BUTTON_INFO) {
2320                                 self.motd_actived_time = time;
2321                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
2322                         }
2323                 }
2324         }
2325         else if(self.motd_actived_time > 0) // showing MOTD or campaign message
2326         {
2327                 if (autocvar_g_campaign) {
2328                         if (self.BUTTON_INFO)
2329                                 self.motd_actived_time = time;
2330                         else if ((time - self.motd_actived_time > 2) && self.classname == "player") { // hide it some seconds after BUTTON_INFO has been released
2331                                 self.motd_actived_time = 0;
2332                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2333                         }
2334                 } else {
2335                         if (self.BUTTON_INFO)
2336                                 self.motd_actived_time = time;
2337                         else if (time - self.motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2338                                 self.motd_actived_time = 0;
2339                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2340                         }
2341                 }
2342         }
2343         else //if(self.motd_actived_time < 0) // just connected, motd is active
2344         {
2345                 if(self.BUTTON_INFO) // BUTTON_INFO hides initial MOTD
2346                         self.motd_actived_time = -2; // wait until BUTTON_INFO gets released
2347                 else if(self.motd_actived_time == -2 || IS_PLAYER(self) || time - self.jointime > autocvar_welcome_message_time)
2348                 {
2349                         // instanctly hide MOTD
2350                         self.motd_actived_time = 0;
2351                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2352                 }
2353         }
2354 }
2355
2356 void ObserverThink()
2357 {
2358         float prefered_movetype;
2359         if (self.flags & FL_JUMPRELEASED) {
2360                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2361                         self.flags &~= FL_JUMPRELEASED;
2362                         self.flags |= FL_SPAWNING;
2363                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2364                         self.flags &~= FL_JUMPRELEASED;
2365                         if(SpectateNext(world) == 1) {
2366                                 self.classname = "spectator";
2367                         }
2368                 } else {
2369                         prefered_movetype = ((!self.BUTTON_USE ? self.cvar_cl_clippedspectating : !self.cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2370                         if (self.movetype != prefered_movetype)
2371                                 self.movetype = prefered_movetype;
2372                 }
2373         } else {
2374                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2375                         self.flags |= FL_JUMPRELEASED;
2376                         if(self.flags & FL_SPAWNING)
2377                         {
2378                                 self.flags &~= FL_SPAWNING;
2379                                 LeaveSpectatorMode();
2380                                 return;
2381                         }
2382                 }
2383         }
2384 }
2385
2386 void SpectatorThink()
2387 {
2388         if (self.flags & FL_JUMPRELEASED) {
2389                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2390                         self.flags &~= FL_JUMPRELEASED;
2391                         self.flags |= FL_SPAWNING;
2392                 } else if(self.BUTTON_ATCK) {
2393                         self.flags &~= FL_JUMPRELEASED;
2394                         if(SpectateNext(world) == 1) {
2395                                 self.classname = "spectator";
2396                         } else {
2397                                 self.classname = "observer";
2398                                 PutClientInServer();
2399                         }
2400                 } else if (self.BUTTON_ATCK2) {
2401                         self.flags &~= FL_JUMPRELEASED;
2402                         self.classname = "observer";
2403                         PutClientInServer();
2404                 } else {
2405                         if(!SpectateUpdate())
2406                                 PutObserverInServer();
2407                 }
2408         } else {
2409                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2410                         self.flags |= FL_JUMPRELEASED;
2411                         if(self.flags & FL_SPAWNING)
2412                         {
2413                                 self.flags &~= FL_SPAWNING;
2414                                 LeaveSpectatorMode();
2415                                 return;
2416                         }
2417                 }
2418                 if(!SpectateUpdate())
2419                         PutObserverInServer();
2420         }
2421
2422         self.flags |= FL_CLIENT | FL_NOTARGET;
2423 }
2424
2425 void PlayerUseKey()
2426 {
2427         if(self.classname != "player")
2428                 return;
2429
2430         if(self.vehicle)
2431         {
2432         vehicles_exit(VHEF_NORMAL);
2433         return;
2434         }
2435         
2436         // a use key was pressed; call handlers
2437         MUTATOR_CALLHOOK(PlayerUseKey);
2438 }
2439
2440 .float touchexplode_time;
2441
2442 /*
2443 =============
2444 PlayerPreThink
2445
2446 Called every frame for each client before the physics are run
2447 =============
2448 */
2449 .float usekeypressed;
2450 void() nexball_setstatus;
2451 .float items_added;
2452 void PlayerPreThink (void)
2453 {
2454         WarpZone_PlayerPhysics_FixVAngle();
2455
2456         self.stat_game_starttime = game_starttime;
2457         self.stat_allow_oldnexbeam = autocvar_g_allow_oldnexbeam;
2458         self.stat_leadlimit = autocvar_leadlimit;
2459
2460         if(g_arena || (g_ca && !allowed_to_spawn))
2461                 self.stat_respawn_time = 0;
2462         else
2463                 self.stat_respawn_time = self.respawn_time;
2464
2465         if(frametime)
2466         {
2467                 // physics frames: update anticheat stuff
2468                 anticheat_prethink();
2469         }
2470
2471         if(blockSpectators && frametime)
2472                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2473                 checkSpectatorBlock();
2474
2475         zoomstate_set = 0;
2476
2477         if(self.netname_previous != self.netname)
2478         {
2479                 if(autocvar_sv_eventlog)
2480                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2481                 if(self.netname_previous)
2482                         strunzone(self.netname_previous);
2483                 self.netname_previous = strzone(self.netname);
2484         }
2485
2486         // version nagging
2487         if(self.version_nagtime)
2488                 if(self.cvar_g_xonoticversion)
2489                         if(time > self.version_nagtime)
2490                         {
2491                                 // don't notify git users
2492                                 if(strstr(self.cvar_g_xonoticversion, "git", 0) < 0 && strstr(self.cvar_g_xonoticversion, "autobuild", 0) < 0)
2493                                 {
2494                                         if(strstr(autocvar_g_xonoticversion, "git", 0) >= 0 || strstr(autocvar_g_xonoticversion, "autobuild", 0) >= 0)
2495                                         {
2496                                                 // notify release users if connecting to git
2497                                                 dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, " (beta)^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2498                                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2499                                         }
2500                                         else
2501                                         {
2502                                                 float r;
2503                                                 r = vercmp(self.cvar_g_xonoticversion, autocvar_g_xonoticversion);
2504                                                 if(r < 0)
2505                                                 {
2506                                                         // give users new version
2507                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - ^3Xonotic ", autocvar_g_xonoticversion, "^7 is out, and you still have ^3Xonotic ", self.cvar_g_xonoticversion, "^1 - get the update from ^4http://www.xonotic.org/^1!\n");
2508                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2509                                                 }
2510                                                 else if(r > 0)
2511                                                 {
2512                                                         // notify users about old server version
2513                                                         print("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, "^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2514                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2515                                                 }
2516                                         }
2517                                 }
2518                                 self.version_nagtime = 0;
2519                         }
2520
2521         // GOD MODE info
2522         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2523         {
2524                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_GODMODE_OFF, self.max_armorvalue);
2525                 self.max_armorvalue = 0;
2526         }
2527
2528 #ifdef TETRIS
2529         if (TetrisPreFrame())
2530                 return;
2531 #endif
2532
2533         MUTATOR_CALLHOOK(PlayerPreThink);
2534
2535         if(!self.cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2536         {
2537                 if(self.BUTTON_USE && !self.usekeypressed)
2538                         PlayerUseKey();
2539                 self.usekeypressed = self.BUTTON_USE;
2540         }
2541
2542         if(clienttype(self) == CLIENTTYPE_REAL)
2543                 PrintWelcomeMessage();
2544
2545         if(self.classname == "player") {
2546
2547                 CheckRules_Player();
2548
2549                 if (intermission_running)
2550                 {
2551                         IntermissionThink ();   // otherwise a button could be missed between
2552                         return;                                 // the think tics
2553                 }
2554
2555                 //don't allow the player to turn around while game is paused!
2556                 if(timeout_status == TIMEOUT_ACTIVE) {
2557                         // FIXME turn this into CSQC stuff
2558                         self.v_angle = self.lastV_angle;
2559                         self.angles = self.lastV_angle;
2560                         self.fixangle = TRUE;
2561                 }
2562
2563                 if(frametime)
2564                 {
2565                         if(self.weapon == WEP_NEX && autocvar_g_balance_nex_charge)
2566                         {
2567                                 self.weaponentity_glowmod_x = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2568                                 self.weaponentity_glowmod_y = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2569                                 self.weaponentity_glowmod_z = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2570
2571                                 if(self.nex_charge > autocvar_g_balance_nex_charge_animlimit)
2572                                 {
2573                                         self.weaponentity_glowmod_x = self.weaponentity_glowmod_x + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2574                                         self.weaponentity_glowmod_y = self.weaponentity_glowmod_y + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2575                                         self.weaponentity_glowmod_z = self.weaponentity_glowmod_z + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2576                                 }
2577                         }
2578                         else
2579                                 self.weaponentity_glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2580
2581                         player_powerups();
2582                 }
2583
2584                 if (self.deadflag != DEAD_NO)
2585                 {
2586                         float button_pressed, force_respawn;
2587                         if(self.personal && g_race_qualifying)
2588                         {
2589                                 if(time > self.respawn_time)
2590                                 {
2591                                         self.respawn_time = time + 1; // only retry once a second
2592                                         respawn();
2593                                         self.impulse = 141;
2594                                 }
2595                         }
2596                         else
2597                         {
2598                                 if(frametime)
2599                                         player_anim();
2600                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2601                                 force_respawn = (g_lms || g_ca || g_cts || autocvar_g_forced_respawn);
2602                                 if (self.deadflag == DEAD_DYING)
2603                                 {
2604                                         if(force_respawn)
2605                                                 self.deadflag = DEAD_RESPAWNING;
2606                                         else if(!button_pressed)
2607                                                 self.deadflag = DEAD_DEAD;
2608                                 }
2609                                 else if (self.deadflag == DEAD_DEAD)
2610                                 {
2611                                         if(button_pressed)
2612                                                 self.deadflag = DEAD_RESPAWNABLE;
2613                                 }
2614                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2615                                 {
2616                                         if(!button_pressed)
2617                                                 self.deadflag = DEAD_RESPAWNING;
2618                                 }
2619                                 else if (self.deadflag == DEAD_RESPAWNING)
2620                                 {
2621                                         if(time > self.respawn_time)
2622                                         {
2623                                                 self.respawn_time = time + 1; // only retry once a second
2624                                                 respawn();
2625                                         }
2626                                 }
2627                                 ShowRespawnCountdown();
2628                         }
2629
2630                         // if respawning, invert stat_respawn_time to indicate this, the client translates it
2631                         if(self.deadflag == DEAD_RESPAWNING && self.stat_respawn_time > 0)
2632                                 self.stat_respawn_time *= -1;
2633
2634                         return;
2635                 }
2636                 // FIXME from now on self.deadflag is always 0 (and self.health is never < 1)
2637                 // so (self.deadflag == DEAD_NO) is always true in the code below
2638
2639                 if(g_touchexplode)
2640                 if(time > self.touchexplode_time)
2641                 if(self.classname == "player")
2642                 if(self.deadflag == DEAD_NO)
2643                 if not(IS_INDEPENDENT_PLAYER(self))
2644                 FOR_EACH_PLAYER(other) if(self != other)
2645                 {
2646                         if(time > other.touchexplode_time)
2647                         if(other.deadflag == DEAD_NO)
2648                         if not(IS_INDEPENDENT_PLAYER(other))
2649                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2650                         {
2651                                 PlayerTouchExplode(self, other);
2652                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2653                         }
2654                 }
2655
2656                 if(g_lms && !self.deadflag && autocvar_g_lms_campcheck_interval)
2657                 {
2658                         vector dist;
2659
2660                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2661                         dist = self.prevorigin - self.origin;
2662                         dist_z = 0;
2663                         self.lms_traveled_distance += fabs(vlen(dist));
2664
2665                         if((autocvar_g_campaign && !campaign_bots_may_start) || (time < game_starttime))
2666                         {
2667                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
2668                                 self.lms_traveled_distance = 0;
2669                         }
2670
2671                         if(time > self.lms_nextcheck)
2672                         {
2673                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2674                                 if(self.lms_traveled_distance < autocvar_g_lms_campcheck_distance)
2675                                 {
2676                                         Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_LMS_CAMPCHECK);
2677                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2678                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2679                                         Damage(self, self, self, bound(0, autocvar_g_lms_campcheck_damage, self.health + self.armorvalue * autocvar_g_balance_armor_blockpercent + 5), DEATH_CAMP, self.origin, '0 0 0');
2680                                 }
2681                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval;
2682                                 self.lms_traveled_distance = 0;
2683                         }
2684                 }
2685
2686                 self.prevorigin = self.origin;
2687
2688                 float do_crouch = self.BUTTON_CROUCH;
2689                 if(self.hook.state)
2690                         do_crouch = 0;
2691                 if(self.health <= g_bloodloss)
2692                         do_crouch = 1;
2693                 if(self.vehicle)
2694                         do_crouch = 0;
2695                 if(self.freezetag_frozen)
2696                         do_crouch = 0;
2697                 if(self.weapon == WEP_SHOTGUN && self.weaponentity.wframe == WFRAME_FIRE2 && time < self.weapon_nextthink)
2698                         do_crouch = 0;
2699
2700                 if (do_crouch)
2701                 {
2702                         if (!self.crouch)
2703                         {
2704                                 self.crouch = TRUE;
2705                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2706                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2707                                 // setanim(self, self.anim_duck, FALSE, TRUE, TRUE); // this anim is BROKEN anyway
2708                         }
2709                 }
2710                 else
2711                 {
2712                         if (self.crouch)
2713                         {
2714                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2715                                 if (!trace_startsolid)
2716                                 {
2717                                         self.crouch = FALSE;
2718                                         self.view_ofs = PL_VIEW_OFS;
2719                                         setsize (self, PL_MIN, PL_MAX);
2720                                 }
2721                         }
2722                 }
2723
2724                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2725                 {
2726                         if(self.bloodloss_timer < time)
2727                         {
2728                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2729                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2730                         }
2731                 }
2732
2733                 FixPlayermodel();
2734
2735                 GrapplingHookFrame();
2736
2737                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2738                 //if(frametime)
2739                 {
2740                         self.items &~= self.items_added;
2741
2742                         W_WeaponFrame();
2743
2744                         self.items_added = 0;
2745                         if(self.items & IT_JETPACK)
2746                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2747                                         self.items_added |= IT_FUEL;
2748
2749                         self.items |= self.items_added;
2750                 }
2751
2752                 player_regen();
2753
2754                 // rot nex charge to the charge limit
2755                 if(autocvar_g_balance_nex_charge_rot_rate && self.nex_charge > autocvar_g_balance_nex_charge_limit && self.nex_charge_rottime < time)
2756                         self.nex_charge = bound(autocvar_g_balance_nex_charge_limit, self.nex_charge - autocvar_g_balance_nex_charge_rot_rate * frametime / W_TICSPERFRAME, 1);
2757
2758                 if(frametime)
2759                         player_anim();
2760
2761                 if(g_nexball)
2762                         nexball_setstatus();
2763                 
2764                 // secret status
2765                 secrets_setstatus();
2766                 
2767                 self.dmg_team = max(0, self.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2768
2769                 //self.angles_y=self.v_angle_y + 90;   // temp
2770         } else if(gameover) {
2771                 if (intermission_running)
2772                         IntermissionThink ();   // otherwise a button could be missed between
2773                 return;
2774         } else if(self.classname == "observer") {
2775                 ObserverThink();
2776         } else if(self.classname == "spectator") {
2777                 SpectatorThink();
2778         }
2779
2780         if(!zoomstate_set)
2781                 SetZoomState(self.BUTTON_ZOOM || self.BUTTON_ZOOMSCRIPT || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX) || (self.BUTTON_ATCK2 && self.weapon == WEP_RIFLE && autocvar_g_balance_rifle_secondary == 0));
2782
2783         float oldspectatee_status;
2784         oldspectatee_status = self.spectatee_status;
2785         if(self.classname == "spectator")
2786                 self.spectatee_status = num_for_edict(self.enemy);
2787         else if(self.classname == "observer")
2788                 self.spectatee_status = num_for_edict(self);
2789         else
2790                 self.spectatee_status = 0;
2791         if(self.spectatee_status != oldspectatee_status)
2792         {
2793                 ClientData_Touch(self);
2794                 if(g_race || g_cts)
2795                         race_InitSpectator();
2796         }
2797
2798         if(self.teamkill_soundtime)
2799         if(time > self.teamkill_soundtime)
2800         {
2801                 self.teamkill_soundtime = 0;
2802
2803                 entity oldpusher, oldself;
2804
2805                 oldself = self; self = self.teamkill_soundsource;
2806                 oldpusher = self.pusher; self.pusher = oldself;
2807
2808                 PlayerSound(playersound_teamshoot, CH_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2809
2810                 self.pusher = oldpusher;
2811                 self = oldself;
2812         }
2813
2814         if(self.taunt_soundtime)
2815         if(time > self.taunt_soundtime)
2816         {
2817                 self.taunt_soundtime = 0;
2818                 PlayerSound(playersound_taunt, CH_VOICE, VOICETYPE_AUTOTAUNT);
2819         }
2820
2821         target_voicescript_next(self);
2822
2823         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
2824         if(!self.weapon)
2825                 self.clip_load = self.clip_size = 0;
2826 }
2827
2828 float isInvisibleString(string s)
2829 {
2830         float i, n, c;
2831         s = strdecolorize(s);
2832         for((i = 0), (n = strlen(s)); i < n; ++i)
2833         {
2834                 c = str2chr(s, i);
2835                 switch(c)
2836                 {
2837                         case 0:
2838                         case 32: // space
2839                                 break;
2840                         case 192: // charmap space
2841                                 if (!autocvar_utf8_enable)
2842                                         break;
2843                                 return FALSE;
2844                         case 160: // space in unicode fonts
2845                         case 0xE000 + 192: // utf8 charmap space
2846                                 if (autocvar_utf8_enable)
2847                                         break;
2848                         default:
2849                                 return FALSE;
2850                 }
2851         }
2852         return TRUE;
2853 }
2854
2855 /*
2856 =============
2857 PlayerPostThink
2858
2859 Called every frame for each client after the physics are run
2860 =============
2861 */
2862 .float idlekick_lasttimeleft;
2863 void PlayerPostThink (void)
2864 {
2865         // Savage: Check for nameless players
2866         if (isInvisibleString(self.netname)) {
2867                 self.netname = "Player";
2868                 stuffcmd(self, strcat("name ", self.netname, substring(ftos(random()), 2, -1), "\n"));
2869         }
2870
2871         if(sv_maxidle && frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2872         {
2873                 if (time - self.parm_idlesince < 1) // instead of (time == self.parm_idlesince) to support sv_maxidle <= 10
2874                 {
2875                         if(self.idlekick_lasttimeleft) { self.idlekick_lasttimeleft = 0; }
2876                 }
2877                 else
2878                 {
2879                         float timeleft;
2880                         timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2881                         if(timeleft == min(10, sv_maxidle - 1)) // - 1 to support sv_maxidle <= 10
2882                         {
2883                                 if(!self.idlekick_lasttimeleft)
2884                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2885                         }
2886                         if(timeleft <= 0)
2887                         {
2888                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_KICK_IDLING, self.netname);
2889                                 dropclient(self);
2890                                 return;
2891                         }
2892                         else if(timeleft <= 10)
2893                         {
2894                                 if(timeleft != self.idlekick_lasttimeleft)
2895                                         Send_Notification(NOTIF_ONE, self, MSG_ANNCE, Announcer_PickNumber(timeleft));
2896                                 self.idlekick_lasttimeleft = timeleft;
2897                         }
2898                 }
2899         }
2900
2901 #ifdef TETRIS
2902         if(self.impulse == 100)
2903                 ImpulseCommands();
2904         if (!TetrisPostFrame())
2905         {
2906 #endif
2907
2908         CheatFrame();
2909
2910         //CheckPlayerJump();
2911
2912         if(self.classname == "player") {
2913                 CheckRules_Player();
2914                 UpdateChatBubble();
2915                 if (self.impulse)
2916                         ImpulseCommands();
2917                 if (intermission_running)
2918                         return;         // intermission or finale
2919                 GetPressedKeys();
2920         }
2921         
2922 #ifdef TETRIS
2923         }
2924 #endif
2925
2926         /*
2927         float i;
2928         for(i = 0; i < 1000; ++i)
2929         {
2930                 vector end;
2931                 end = self.origin + '0 0 1024' + 512 * randomvec();
2932                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2933                 if(trace_fraction < 1)
2934                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2935                 {
2936                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2937                         break;
2938                 }
2939         }
2940         */
2941
2942         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
2943
2944         if(self.waypointsprite_attachedforcarrier)
2945                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, autocvar_g_balance_armor_blockpercent));
2946
2947         playerdemo_write();
2948
2949         if((g_cts || g_race) && self.cvar_cl_allow_uidtracking == 1 && self.cvar_cl_allow_uid2name == 1)
2950         {
2951                 if not(self.stored_netname)
2952                         self.stored_netname = strzone(uid2name(self.crypto_idfp));
2953                 if(self.stored_netname != self.netname)
2954                 {
2955                         db_put(ServerProgsDB, strcat("/uid2name/", self.crypto_idfp), self.netname);
2956                         strunzone(self.stored_netname);
2957                         self.stored_netname = strzone(self.netname);
2958                 }
2959         }
2960
2961         /*
2962         if(g_race)
2963                 dprint(sprintf("%f %.6f\n", time, race_GetFractionalLapCount(self)));
2964         */
2965
2966         CSQCMODEL_AUTOUPDATE();
2967 }