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