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