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