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