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